blob: 22ae09a983da8316b716c5e9daa69c6096e1a9c9 [file] [log] [blame]
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001# Test enhancements related to descriptors and new-style classes
Tim Peters6d6c1a32001-08-02 04:15:00 +00002
Tim Peters59c9a642001-09-13 05:38:56 +00003from test_support import verify, verbose, TestFailed, TESTFN
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
5
Guido van Rossum4bb1e362001-09-28 23:49:48 +00006def vereq(a, b):
7 if a != b:
8 raise TestFailed, "%r != %r" % (a, b)
9
Tim Peters6d6c1a32001-08-02 04:15:00 +000010def testunop(a, res, expr="len(a)", meth="__len__"):
11 if verbose: print "checking", expr
12 dict = {'a': a}
13 verify(eval(expr, dict) == res)
14 t = type(a)
15 m = getattr(t, meth)
16 verify(m == t.__dict__[meth])
17 verify(m(a) == res)
18 bm = getattr(a, meth)
19 verify(bm() == res)
20
21def testbinop(a, b, res, expr="a+b", meth="__add__"):
22 if verbose: print "checking", expr
23 dict = {'a': a, 'b': b}
24 verify(eval(expr, dict) == res)
25 t = type(a)
26 m = getattr(t, meth)
27 verify(m == t.__dict__[meth])
28 verify(m(a, b) == res)
29 bm = getattr(a, meth)
30 verify(bm(b) == res)
31
32def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
33 if verbose: print "checking", expr
34 dict = {'a': a, 'b': b, 'c': c}
35 verify(eval(expr, dict) == res)
36 t = type(a)
37 m = getattr(t, meth)
38 verify(m == t.__dict__[meth])
39 verify(m(a, b, c) == res)
40 bm = getattr(a, meth)
41 verify(bm(b, c) == res)
42
43def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
44 if verbose: print "checking", stmt
45 dict = {'a': deepcopy(a), 'b': b}
46 exec stmt in dict
47 verify(dict['a'] == res)
48 t = type(a)
49 m = getattr(t, meth)
50 verify(m == t.__dict__[meth])
51 dict['a'] = deepcopy(a)
52 m(dict['a'], b)
53 verify(dict['a'] == res)
54 dict['a'] = deepcopy(a)
55 bm = getattr(dict['a'], meth)
56 bm(b)
57 verify(dict['a'] == res)
58
59def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
60 if verbose: print "checking", stmt
61 dict = {'a': deepcopy(a), 'b': b, 'c': c}
62 exec stmt in dict
63 verify(dict['a'] == res)
64 t = type(a)
65 m = getattr(t, meth)
66 verify(m == t.__dict__[meth])
67 dict['a'] = deepcopy(a)
68 m(dict['a'], b, c)
69 verify(dict['a'] == res)
70 dict['a'] = deepcopy(a)
71 bm = getattr(dict['a'], meth)
72 bm(b, c)
73 verify(dict['a'] == res)
74
75def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
76 if verbose: print "checking", stmt
77 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
78 exec stmt in dict
79 verify(dict['a'] == res)
80 t = type(a)
81 m = getattr(t, meth)
82 verify(m == t.__dict__[meth])
83 dict['a'] = deepcopy(a)
84 m(dict['a'], b, c, d)
85 verify(dict['a'] == res)
86 dict['a'] = deepcopy(a)
87 bm = getattr(dict['a'], meth)
88 bm(b, c, d)
89 verify(dict['a'] == res)
90
91def lists():
92 if verbose: print "Testing list operations..."
93 testbinop([1], [2], [1,2], "a+b", "__add__")
94 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
95 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
96 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
97 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
98 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
99 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
100 testunop([1,2,3], 3, "len(a)", "__len__")
101 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
102 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
103 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
104 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
105
106def dicts():
107 if verbose: print "Testing dict operations..."
108 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
109 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
110 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
111 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
112 d = {1:2,3:4}
113 l1 = []
114 for i in d.keys(): l1.append(i)
115 l = []
116 for i in iter(d): l.append(i)
117 verify(l == l1)
118 l = []
119 for i in d.__iter__(): l.append(i)
120 verify(l == l1)
121 l = []
122 for i in dictionary.__iter__(d): l.append(i)
123 verify(l == l1)
124 d = {1:2, 3:4}
125 testunop(d, 2, "len(a)", "__len__")
126 verify(eval(repr(d), {}) == d)
127 verify(eval(d.__repr__(), {}) == d)
128 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
129
Tim Peters25786c02001-09-02 08:22:48 +0000130def dict_constructor():
131 if verbose:
132 print "Testing dictionary constructor ..."
133 d = dictionary()
134 verify(d == {})
135 d = dictionary({})
136 verify(d == {})
137 d = dictionary(mapping={})
138 verify(d == {})
139 d = dictionary({1: 2, 'a': 'b'})
140 verify(d == {1: 2, 'a': 'b'})
141 for badarg in 0, 0L, 0j, "0", [0], (0,):
142 try:
143 dictionary(badarg)
144 except TypeError:
145 pass
146 else:
147 raise TestFailed("no TypeError from dictionary(%r)" % badarg)
148 try:
149 dictionary(senseless={})
150 except TypeError:
151 pass
152 else:
153 raise TestFailed("no TypeError from dictionary(senseless={}")
154
155 try:
156 dictionary({}, {})
157 except TypeError:
158 pass
159 else:
160 raise TestFailed("no TypeError from dictionary({}, {})")
161
162 class Mapping:
163 dict = {1:2, 3:4, 'a':1j}
164
165 def __getitem__(self, i):
166 return self.dict[i]
167
168 try:
169 dictionary(Mapping())
170 except TypeError:
171 pass
172 else:
173 raise TestFailed("no TypeError from dictionary(incomplete mapping)")
174
175 Mapping.keys = lambda self: self.dict.keys()
176 d = dictionary(mapping=Mapping())
177 verify(d == Mapping.dict)
178
Tim Peters5d2b77c2001-09-03 05:47:38 +0000179def test_dir():
180 if verbose:
181 print "Testing dir() ..."
182 junk = 12
183 verify(dir() == ['junk'])
184 del junk
185
186 # Just make sure these don't blow up!
187 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
188 dir(arg)
189
Tim Peters37a309d2001-09-04 01:20:04 +0000190 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000191 class C:
192 Cdata = 1
193 def Cmethod(self): pass
194
195 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
196 verify(dir(C) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000197 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000198
199 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
200 verify(dir(c) == cstuff)
201
202 c.cdata = 2
203 c.cmethod = lambda self: 0
204 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000205 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000206
207 class A(C):
208 Adata = 1
209 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000210
Tim Peters37a309d2001-09-04 01:20:04 +0000211 astuff = ['Adata', 'Amethod'] + cstuff
212 verify(dir(A) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000213 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000214 a = A()
215 verify(dir(a) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000216 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000217 a.adata = 42
218 a.amethod = lambda self: 3
219 verify(dir(a) == astuff + ['adata', 'amethod'])
220
221 # The same, but with new-style classes. Since these have object as a
222 # base class, a lot more gets sucked in.
223 def interesting(strings):
224 return [s for s in strings if not s.startswith('_')]
225
Tim Peters5d2b77c2001-09-03 05:47:38 +0000226 class C(object):
227 Cdata = 1
228 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000229
230 cstuff = ['Cdata', 'Cmethod']
231 verify(interesting(dir(C)) == cstuff)
232
233 c = C()
234 verify(interesting(dir(c)) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000235 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000236
237 c.cdata = 2
238 c.cmethod = lambda self: 0
239 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000240 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000241
Tim Peters5d2b77c2001-09-03 05:47:38 +0000242 class A(C):
243 Adata = 1
244 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000245
246 astuff = ['Adata', 'Amethod'] + cstuff
247 verify(interesting(dir(A)) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000248 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000249 a = A()
250 verify(interesting(dir(a)) == astuff)
251 a.adata = 42
252 a.amethod = lambda self: 3
253 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000254 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000255
Tim Peterscaaff8d2001-09-10 23:12:14 +0000256 # Try a module subclass.
257 import sys
258 class M(type(sys)):
259 pass
260 minstance = M()
261 minstance.b = 2
262 minstance.a = 1
263 verify(dir(minstance) == ['a', 'b'])
264
265 class M2(M):
266 def getdict(self):
267 return "Not a dict!"
268 __dict__ = property(getdict)
269
270 m2instance = M2()
271 m2instance.b = 2
272 m2instance.a = 1
273 verify(m2instance.__dict__ == "Not a dict!")
274 try:
275 dir(m2instance)
276 except TypeError:
277 pass
278
Tim Peters6d6c1a32001-08-02 04:15:00 +0000279binops = {
280 'add': '+',
281 'sub': '-',
282 'mul': '*',
283 'div': '/',
284 'mod': '%',
285 'divmod': 'divmod',
286 'pow': '**',
287 'lshift': '<<',
288 'rshift': '>>',
289 'and': '&',
290 'xor': '^',
291 'or': '|',
292 'cmp': 'cmp',
293 'lt': '<',
294 'le': '<=',
295 'eq': '==',
296 'ne': '!=',
297 'gt': '>',
298 'ge': '>=',
299 }
300
301for name, expr in binops.items():
302 if expr.islower():
303 expr = expr + "(a, b)"
304 else:
305 expr = 'a %s b' % expr
306 binops[name] = expr
307
308unops = {
309 'pos': '+',
310 'neg': '-',
311 'abs': 'abs',
312 'invert': '~',
313 'int': 'int',
314 'long': 'long',
315 'float': 'float',
316 'oct': 'oct',
317 'hex': 'hex',
318 }
319
320for name, expr in unops.items():
321 if expr.islower():
322 expr = expr + "(a)"
323 else:
324 expr = '%s a' % expr
325 unops[name] = expr
326
327def numops(a, b, skip=[]):
328 dict = {'a': a, 'b': b}
329 for name, expr in binops.items():
330 if name not in skip:
331 name = "__%s__" % name
332 if hasattr(a, name):
333 res = eval(expr, dict)
334 testbinop(a, b, res, expr, name)
335 for name, expr in unops.items():
336 name = "__%s__" % name
337 if hasattr(a, name):
338 res = eval(expr, dict)
339 testunop(a, res, expr, name)
340
341def ints():
342 if verbose: print "Testing int operations..."
343 numops(100, 3)
344
345def longs():
346 if verbose: print "Testing long operations..."
347 numops(100L, 3L)
348
349def floats():
350 if verbose: print "Testing float operations..."
351 numops(100.0, 3.0)
352
353def complexes():
354 if verbose: print "Testing complex operations..."
355 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
356 class Number(complex):
357 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000358 def __new__(cls, *args, **kwds):
359 result = complex.__new__(cls, *args)
360 result.prec = kwds.get('prec', 12)
361 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000362 def __repr__(self):
363 prec = self.prec
364 if self.imag == 0.0:
365 return "%.*g" % (prec, self.real)
366 if self.real == 0.0:
367 return "%.*gj" % (prec, self.imag)
368 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
369 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000370
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371 a = Number(3.14, prec=6)
372 verify(`a` == "3.14")
373 verify(a.prec == 6)
374
Tim Peters3f996e72001-09-13 19:18:27 +0000375 a = Number(a, prec=2)
376 verify(`a` == "3.1")
377 verify(a.prec == 2)
378
379 a = Number(234.5)
380 verify(`a` == "234.5")
381 verify(a.prec == 12)
382
Tim Peters6d6c1a32001-08-02 04:15:00 +0000383def spamlists():
384 if verbose: print "Testing spamlist operations..."
385 import copy, xxsubtype as spam
386 def spamlist(l, memo=None):
387 import xxsubtype as spam
388 return spam.spamlist(l)
389 # This is an ugly hack:
390 copy._deepcopy_dispatch[spam.spamlist] = spamlist
391
392 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
393 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
394 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
395 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
396 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
397 "a[b:c]", "__getslice__")
398 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
399 "a+=b", "__iadd__")
400 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
401 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
402 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
403 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
404 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
405 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
406 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
407 # Test subclassing
408 class C(spam.spamlist):
409 def foo(self): return 1
410 a = C()
411 verify(a == [])
412 verify(a.foo() == 1)
413 a.append(100)
414 verify(a == [100])
415 verify(a.getstate() == 0)
416 a.setstate(42)
417 verify(a.getstate() == 42)
418
419def spamdicts():
420 if verbose: print "Testing spamdict operations..."
421 import copy, xxsubtype as spam
422 def spamdict(d, memo=None):
423 import xxsubtype as spam
424 sd = spam.spamdict()
425 for k, v in d.items(): sd[k] = v
426 return sd
427 # This is an ugly hack:
428 copy._deepcopy_dispatch[spam.spamdict] = spamdict
429
430 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
431 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
432 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
433 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
434 d = spamdict({1:2,3:4})
435 l1 = []
436 for i in d.keys(): l1.append(i)
437 l = []
438 for i in iter(d): l.append(i)
439 verify(l == l1)
440 l = []
441 for i in d.__iter__(): l.append(i)
442 verify(l == l1)
443 l = []
444 for i in type(spamdict({})).__iter__(d): l.append(i)
445 verify(l == l1)
446 straightd = {1:2, 3:4}
447 spamd = spamdict(straightd)
448 testunop(spamd, 2, "len(a)", "__len__")
449 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
450 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
451 "a[b]=c", "__setitem__")
452 # Test subclassing
453 class C(spam.spamdict):
454 def foo(self): return 1
455 a = C()
456 verify(a.items() == [])
457 verify(a.foo() == 1)
458 a['foo'] = 'bar'
459 verify(a.items() == [('foo', 'bar')])
460 verify(a.getstate() == 0)
461 a.setstate(100)
462 verify(a.getstate() == 100)
463
464def pydicts():
465 if verbose: print "Testing Python subclass of dict..."
466 verify(issubclass(dictionary, dictionary))
467 verify(isinstance({}, dictionary))
468 d = dictionary()
469 verify(d == {})
470 verify(d.__class__ is dictionary)
471 verify(isinstance(d, dictionary))
472 class C(dictionary):
473 state = -1
474 def __init__(self, *a, **kw):
475 if a:
476 assert len(a) == 1
477 self.state = a[0]
478 if kw:
479 for k, v in kw.items(): self[v] = k
480 def __getitem__(self, key):
481 return self.get(key, 0)
482 def __setitem__(self, key, value):
483 assert isinstance(key, type(0))
484 dictionary.__setitem__(self, key, value)
485 def setstate(self, state):
486 self.state = state
487 def getstate(self):
488 return self.state
489 verify(issubclass(C, dictionary))
490 a1 = C(12)
491 verify(a1.state == 12)
492 a2 = C(foo=1, bar=2)
493 verify(a2[1] == 'foo' and a2[2] == 'bar')
494 a = C()
495 verify(a.state == -1)
496 verify(a.getstate() == -1)
497 a.setstate(0)
498 verify(a.state == 0)
499 verify(a.getstate() == 0)
500 a.setstate(10)
501 verify(a.state == 10)
502 verify(a.getstate() == 10)
503 verify(a[42] == 0)
504 a[42] = 24
505 verify(a[42] == 24)
506 if verbose: print "pydict stress test ..."
507 N = 50
508 for i in range(N):
509 a[i] = C()
510 for j in range(N):
511 a[i][j] = i*j
512 for i in range(N):
513 for j in range(N):
514 verify(a[i][j] == i*j)
515
516def pylists():
517 if verbose: print "Testing Python subclass of list..."
518 class C(list):
519 def __getitem__(self, i):
520 return list.__getitem__(self, i) + 100
521 def __getslice__(self, i, j):
522 return (i, j)
523 a = C()
524 a.extend([0,1,2])
525 verify(a[0] == 100)
526 verify(a[1] == 101)
527 verify(a[2] == 102)
528 verify(a[100:200] == (100,200))
529
530def metaclass():
531 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000532 class C:
533 __metaclass__ = type
534 def __init__(self):
535 self.__state = 0
536 def getstate(self):
537 return self.__state
538 def setstate(self, state):
539 self.__state = state
540 a = C()
541 verify(a.getstate() == 0)
542 a.setstate(10)
543 verify(a.getstate() == 10)
544 class D:
545 class __metaclass__(type):
546 def myself(cls): return cls
547 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000548 d = D()
549 verify(d.__class__ is D)
550 class M1(type):
551 def __new__(cls, name, bases, dict):
552 dict['__spam__'] = 1
553 return type.__new__(cls, name, bases, dict)
554 class C:
555 __metaclass__ = M1
556 verify(C.__spam__ == 1)
557 c = C()
558 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000559
Guido van Rossum309b5662001-08-17 11:43:17 +0000560 class _instance(object):
561 pass
562 class M2(object):
563 def __new__(cls, name, bases, dict):
564 self = object.__new__(cls)
565 self.name = name
566 self.bases = bases
567 self.dict = dict
568 return self
569 __new__ = staticmethod(__new__)
570 def __call__(self):
571 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000572 # Early binding of methods
573 for key in self.dict:
574 if key.startswith("__"):
575 continue
576 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000577 return it
578 class C:
579 __metaclass__ = M2
580 def spam(self):
581 return 42
582 verify(C.name == 'C')
583 verify(C.bases == ())
584 verify('spam' in C.dict)
585 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000586 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum91ee7982001-08-30 20:52:40 +0000588 # More metaclass examples
589
590 class autosuper(type):
591 # Automatically add __super to the class
592 # This trick only works for dynamic classes
593 # so we force __dynamic__ = 1
594 def __new__(metaclass, name, bases, dict):
595 # XXX Should check that name isn't already a base class name
596 dict["__dynamic__"] = 1
597 cls = super(autosuper, metaclass).__new__(metaclass,
598 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000599 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000600 while name[:1] == "_":
601 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000602 if name:
603 name = "_%s__super" % name
604 else:
605 name = "__super"
606 setattr(cls, name, super(cls))
607 return cls
608 class A:
609 __metaclass__ = autosuper
610 def meth(self):
611 return "A"
612 class B(A):
613 def meth(self):
614 return "B" + self.__super.meth()
615 class C(A):
616 def meth(self):
617 return "C" + self.__super.meth()
618 class D(C, B):
619 def meth(self):
620 return "D" + self.__super.meth()
621 verify(D().meth() == "DCBA")
622 class E(B, C):
623 def meth(self):
624 return "E" + self.__super.meth()
625 verify(E().meth() == "EBCA")
626
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000627 class autoproperty(type):
628 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000629 # named _get_x and/or _set_x are found
630 def __new__(metaclass, name, bases, dict):
631 hits = {}
632 for key, val in dict.iteritems():
633 if key.startswith("_get_"):
634 key = key[5:]
635 get, set = hits.get(key, (None, None))
636 get = val
637 hits[key] = get, set
638 elif key.startswith("_set_"):
639 key = key[5:]
640 get, set = hits.get(key, (None, None))
641 set = val
642 hits[key] = get, set
643 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000644 dict[key] = property(get, set)
645 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000646 name, bases, dict)
647 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000648 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000649 def _get_x(self):
650 return -self.__x
651 def _set_x(self, x):
652 self.__x = -x
653 a = A()
654 verify(not hasattr(a, "x"))
655 a.x = 12
656 verify(a.x == 12)
657 verify(a._A__x == -12)
658
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000659 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000660 # Merge of multiple cooperating metaclasses
661 pass
662 class A:
663 __metaclass__ = multimetaclass
664 def _get_x(self):
665 return "A"
666 class B(A):
667 def _get_x(self):
668 return "B" + self.__super._get_x()
669 class C(A):
670 def _get_x(self):
671 return "C" + self.__super._get_x()
672 class D(C, B):
673 def _get_x(self):
674 return "D" + self.__super._get_x()
675 verify(D().x == "DCBA")
676
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677def pymods():
678 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000680 import sys
681 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 class MM(MT):
683 def __init__(self):
684 MT.__init__(self)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000685 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000687 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 def __setattr__(self, name, value):
689 log.append(("setattr", name, value))
690 MT.__setattr__(self, name, value)
691 def __delattr__(self, name):
692 log.append(("delattr", name))
693 MT.__delattr__(self, name)
694 a = MM()
695 a.foo = 12
696 x = a.foo
697 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000698 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 ("delattr", "foo")], log)
701
702def multi():
703 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704 class C(object):
705 def __init__(self):
706 self.__state = 0
707 def getstate(self):
708 return self.__state
709 def setstate(self, state):
710 self.__state = state
711 a = C()
712 verify(a.getstate() == 0)
713 a.setstate(10)
714 verify(a.getstate() == 10)
715 class D(dictionary, C):
716 def __init__(self):
717 type({}).__init__(self)
718 C.__init__(self)
719 d = D()
720 verify(d.keys() == [])
721 d["hello"] = "world"
722 verify(d.items() == [("hello", "world")])
723 verify(d["hello"] == "world")
724 verify(d.getstate() == 0)
725 d.setstate(10)
726 verify(d.getstate() == 10)
727 verify(D.__mro__ == (D, dictionary, C, object))
728
Guido van Rossume45763a2001-08-10 21:28:46 +0000729 # SF bug #442833
730 class Node(object):
731 def __int__(self):
732 return int(self.foo())
733 def foo(self):
734 return "23"
735 class Frag(Node, list):
736 def foo(self):
737 return "42"
738 verify(Node().__int__() == 23)
739 verify(int(Node()) == 23)
740 verify(Frag().__int__() == 42)
741 verify(int(Frag()) == 42)
742
Tim Peters6d6c1a32001-08-02 04:15:00 +0000743def diamond():
744 if verbose: print "Testing multiple inheritance special cases..."
745 class A(object):
746 def spam(self): return "A"
747 verify(A().spam() == "A")
748 class B(A):
749 def boo(self): return "B"
750 def spam(self): return "B"
751 verify(B().spam() == "B")
752 verify(B().boo() == "B")
753 class C(A):
754 def boo(self): return "C"
755 verify(C().spam() == "A")
756 verify(C().boo() == "C")
757 class D(B, C): pass
758 verify(D().spam() == "B")
759 verify(D().boo() == "B")
760 verify(D.__mro__ == (D, B, C, A, object))
761 class E(C, B): pass
762 verify(E().spam() == "B")
763 verify(E().boo() == "C")
764 verify(E.__mro__ == (E, C, B, A, object))
765 class F(D, E): pass
766 verify(F().spam() == "B")
767 verify(F().boo() == "B")
768 verify(F.__mro__ == (F, D, E, B, C, A, object))
769 class G(E, D): pass
770 verify(G().spam() == "B")
771 verify(G().boo() == "C")
772 verify(G.__mro__ == (G, E, D, C, B, A, object))
773
Guido van Rossum37202612001-08-09 19:45:21 +0000774def objects():
775 if verbose: print "Testing object class..."
776 a = object()
777 verify(a.__class__ == object == type(a))
778 b = object()
779 verify(a is not b)
780 verify(not hasattr(a, "foo"))
781 try:
782 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000783 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000784 pass
785 else:
786 verify(0, "object() should not allow setting a foo attribute")
787 verify(not hasattr(object(), "__dict__"))
788
789 class Cdict(object):
790 pass
791 x = Cdict()
Guido van Rossum3926a632001-09-25 16:25:58 +0000792 verify(x.__dict__ == {})
Guido van Rossum37202612001-08-09 19:45:21 +0000793 x.foo = 1
794 verify(x.foo == 1)
795 verify(x.__dict__ == {'foo': 1})
796
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797def slots():
798 if verbose: print "Testing __slots__..."
799 class C0(object):
800 __slots__ = []
801 x = C0()
802 verify(not hasattr(x, "__dict__"))
803 verify(not hasattr(x, "foo"))
804
805 class C1(object):
806 __slots__ = ['a']
807 x = C1()
808 verify(not hasattr(x, "__dict__"))
809 verify(x.a == None)
810 x.a = 1
811 verify(x.a == 1)
812 del x.a
813 verify(x.a == None)
814
815 class C3(object):
816 __slots__ = ['a', 'b', 'c']
817 x = C3()
818 verify(not hasattr(x, "__dict__"))
819 verify(x.a is None)
820 verify(x.b is None)
821 verify(x.c is None)
822 x.a = 1
823 x.b = 2
824 x.c = 3
825 verify(x.a == 1)
826 verify(x.b == 2)
827 verify(x.c == 3)
828
829def dynamics():
830 if verbose: print "Testing __dynamic__..."
831 verify(object.__dynamic__ == 0)
832 verify(list.__dynamic__ == 0)
833 class S1:
834 __metaclass__ = type
835 verify(S1.__dynamic__ == 0)
836 class S(object):
837 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000838 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 class D(object):
840 __dynamic__ = 1
841 verify(D.__dynamic__ == 1)
842 class E(D, S):
843 pass
844 verify(E.__dynamic__ == 1)
845 class F(S, D):
846 pass
847 verify(F.__dynamic__ == 1)
848 try:
849 S.foo = 1
850 except (AttributeError, TypeError):
851 pass
852 else:
853 verify(0, "assignment to a static class attribute should be illegal")
854 D.foo = 1
855 verify(D.foo == 1)
856 # Test that dynamic attributes are inherited
857 verify(E.foo == 1)
858 verify(F.foo == 1)
859 class SS(D):
860 __dynamic__ = 0
861 verify(SS.__dynamic__ == 0)
862 verify(SS.foo == 1)
863 try:
864 SS.foo = 1
865 except (AttributeError, TypeError):
866 pass
867 else:
868 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000869 # Test dynamic instances
870 class C(object):
871 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000872 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000873 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000874 C.foobar = 2
875 verify(a.foobar == 2)
876 C.method = lambda self: 42
877 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000878 C.__repr__ = lambda self: "C()"
879 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000880 C.__int__ = lambda self: 100
881 verify(int(a) == 100)
882 verify(a.foobar == 2)
883 verify(not hasattr(a, "spam"))
884 def mygetattr(self, name):
885 if name == "spam":
886 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +0000887 raise AttributeError
888 C.__getattr__ = mygetattr
Guido van Rossumd3077402001-08-12 05:24:18 +0000889 verify(a.spam == "spam")
890 a.new = 12
891 verify(a.new == 12)
892 def mysetattr(self, name, value):
893 if name == "spam":
894 raise AttributeError
895 return object.__setattr__(self, name, value)
896 C.__setattr__ = mysetattr
897 try:
898 a.spam = "not spam"
899 except AttributeError:
900 pass
901 else:
902 verify(0, "expected AttributeError")
903 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000904 class D(C):
905 pass
906 d = D()
907 d.foo = 1
908 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000909
Guido van Rossum7e35d572001-09-15 03:14:32 +0000910 # Test handling of int*seq and seq*int
911 class I(int):
912 __dynamic__ = 1
913 verify("a"*I(2) == "aa")
914 verify(I(2)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000915 verify(2*I(3) == 6)
916 verify(I(3)*2 == 6)
917 verify(I(3)*I(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000918
919 # Test handling of long*seq and seq*long
920 class L(long):
921 __dynamic__ = 1
922 verify("a"*L(2L) == "aa")
923 verify(L(2L)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000924 verify(2*L(3) == 6)
925 verify(L(3)*2 == 6)
926 verify(L(3)*L(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000927
Guido van Rossum3d45d8f2001-09-24 18:47:40 +0000928 # Test comparison of classes with dynamic metaclasses
929 class dynamicmetaclass(type):
930 __dynamic__ = 1
931 class someclass:
932 __metaclass__ = dynamicmetaclass
933 verify(someclass != object)
934
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935def errors():
936 if verbose: print "Testing errors..."
937
938 try:
939 class C(list, dictionary):
940 pass
941 except TypeError:
942 pass
943 else:
944 verify(0, "inheritance from both list and dict should be illegal")
945
946 try:
947 class C(object, None):
948 pass
949 except TypeError:
950 pass
951 else:
952 verify(0, "inheritance from non-type should be illegal")
953 class Classic:
954 pass
955
956 try:
957 class C(object, Classic):
958 pass
959 except TypeError:
960 pass
961 else:
962 verify(0, "inheritance from object and Classic should be illegal")
963
964 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000965 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000966 pass
967 except TypeError:
968 pass
969 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000970 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971
972 try:
973 class C(object):
974 __slots__ = 1
975 except TypeError:
976 pass
977 else:
978 verify(0, "__slots__ = 1 should be illegal")
979
980 try:
981 class C(object):
982 __slots__ = [1]
983 except TypeError:
984 pass
985 else:
986 verify(0, "__slots__ = [1] should be illegal")
987
988def classmethods():
989 if verbose: print "Testing class methods..."
990 class C(object):
991 def foo(*a): return a
992 goo = classmethod(foo)
993 c = C()
994 verify(C.goo(1) == (C, 1))
995 verify(c.goo(1) == (C, 1))
996 verify(c.foo(1) == (c, 1))
997 class D(C):
998 pass
999 d = D()
1000 verify(D.goo(1) == (D, 1))
1001 verify(d.goo(1) == (D, 1))
1002 verify(d.foo(1) == (d, 1))
1003 verify(D.foo(d, 1) == (d, 1))
1004
1005def staticmethods():
1006 if verbose: print "Testing static methods..."
1007 class C(object):
1008 def foo(*a): return a
1009 goo = staticmethod(foo)
1010 c = C()
1011 verify(C.goo(1) == (1,))
1012 verify(c.goo(1) == (1,))
1013 verify(c.foo(1) == (c, 1,))
1014 class D(C):
1015 pass
1016 d = D()
1017 verify(D.goo(1) == (1,))
1018 verify(d.goo(1) == (1,))
1019 verify(d.foo(1) == (d, 1))
1020 verify(D.foo(d, 1) == (d, 1))
1021
1022def classic():
1023 if verbose: print "Testing classic classes..."
1024 class C:
1025 def foo(*a): return a
1026 goo = classmethod(foo)
1027 c = C()
1028 verify(C.goo(1) == (C, 1))
1029 verify(c.goo(1) == (C, 1))
1030 verify(c.foo(1) == (c, 1))
1031 class D(C):
1032 pass
1033 d = D()
1034 verify(D.goo(1) == (D, 1))
1035 verify(d.goo(1) == (D, 1))
1036 verify(d.foo(1) == (d, 1))
1037 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001038 class E: # *not* subclassing from C
1039 foo = C.foo
1040 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001041 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042
1043def compattr():
1044 if verbose: print "Testing computed attributes..."
1045 class C(object):
1046 class computed_attribute(object):
1047 def __init__(self, get, set=None):
1048 self.__get = get
1049 self.__set = set
1050 def __get__(self, obj, type=None):
1051 return self.__get(obj)
1052 def __set__(self, obj, value):
1053 return self.__set(obj, value)
1054 def __init__(self):
1055 self.__x = 0
1056 def __get_x(self):
1057 x = self.__x
1058 self.__x = x+1
1059 return x
1060 def __set_x(self, x):
1061 self.__x = x
1062 x = computed_attribute(__get_x, __set_x)
1063 a = C()
1064 verify(a.x == 0)
1065 verify(a.x == 1)
1066 a.x = 10
1067 verify(a.x == 10)
1068 verify(a.x == 11)
1069
1070def newslot():
1071 if verbose: print "Testing __new__ slot override..."
1072 class C(list):
1073 def __new__(cls):
1074 self = list.__new__(cls)
1075 self.foo = 1
1076 return self
1077 def __init__(self):
1078 self.foo = self.foo + 2
1079 a = C()
1080 verify(a.foo == 3)
1081 verify(a.__class__ is C)
1082 class D(C):
1083 pass
1084 b = D()
1085 verify(b.foo == 3)
1086 verify(b.__class__ is D)
1087
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088def altmro():
1089 if verbose: print "Testing mro() and overriding it..."
1090 class A(object):
1091 def f(self): return "A"
1092 class B(A):
1093 pass
1094 class C(A):
1095 def f(self): return "C"
1096 class D(B, C):
1097 pass
1098 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1099 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001100 class PerverseMetaType(type):
1101 def mro(cls):
1102 L = type.mro(cls)
1103 L.reverse()
1104 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105 class X(A,B,C,D):
1106 __metaclass__ = PerverseMetaType
1107 verify(X.__mro__ == (object, A, C, B, D, X))
1108 verify(X().f() == "A")
1109
1110def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001111 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112
1113 class B(object):
1114 "Intermediate class because object doesn't have a __setattr__"
1115
1116 class C(B):
1117
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001118 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 if name == "foo":
1120 return ("getattr", name)
1121 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001122 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 def __setattr__(self, name, value):
1124 if name == "foo":
1125 self.setattr = (name, value)
1126 else:
1127 return B.__setattr__(self, name, value)
1128 def __delattr__(self, name):
1129 if name == "foo":
1130 self.delattr = name
1131 else:
1132 return B.__delattr__(self, name)
1133
1134 def __getitem__(self, key):
1135 return ("getitem", key)
1136 def __setitem__(self, key, value):
1137 self.setitem = (key, value)
1138 def __delitem__(self, key):
1139 self.delitem = key
1140
1141 def __getslice__(self, i, j):
1142 return ("getslice", i, j)
1143 def __setslice__(self, i, j, value):
1144 self.setslice = (i, j, value)
1145 def __delslice__(self, i, j):
1146 self.delslice = (i, j)
1147
1148 a = C()
1149 verify(a.foo == ("getattr", "foo"))
1150 a.foo = 12
1151 verify(a.setattr == ("foo", 12))
1152 del a.foo
1153 verify(a.delattr == "foo")
1154
1155 verify(a[12] == ("getitem", 12))
1156 a[12] = 21
1157 verify(a.setitem == (12, 21))
1158 del a[12]
1159 verify(a.delitem == 12)
1160
1161 verify(a[0:10] == ("getslice", 0, 10))
1162 a[0:10] = "foo"
1163 verify(a.setslice == (0, 10, "foo"))
1164 del a[0:10]
1165 verify(a.delslice == (0, 10))
1166
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001167def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001168 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001169 class C(object):
1170 def __init__(self, x):
1171 self.x = x
1172 def foo(self):
1173 return self.x
1174 c1 = C(1)
1175 verify(c1.foo() == 1)
1176 class D(C):
1177 boo = C.foo
1178 goo = c1.foo
1179 d2 = D(2)
1180 verify(d2.foo() == 2)
1181 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001182 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001183 class E(object):
1184 foo = C.foo
1185 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001186 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001187
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001188def specials():
1189 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001190 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001191 # Test the default behavior for static classes
1192 class C(object):
1193 def __getitem__(self, i):
1194 if 0 <= i < 10: return i
1195 raise IndexError
1196 c1 = C()
1197 c2 = C()
1198 verify(not not c1)
1199 verify(hash(c1) == id(c1))
1200 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1201 verify(c1 == c1)
1202 verify(c1 != c2)
1203 verify(not c1 != c1)
1204 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001205 # Note that the module name appears in str/repr, and that varies
1206 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001207 verify(str(c1).find('C object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001208 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001209 verify(-1 not in c1)
1210 for i in range(10):
1211 verify(i in c1)
1212 verify(10 not in c1)
1213 # Test the default behavior for dynamic classes
1214 class D(object):
1215 __dynamic__ = 1
1216 def __getitem__(self, i):
1217 if 0 <= i < 10: return i
1218 raise IndexError
1219 d1 = D()
1220 d2 = D()
1221 verify(not not d1)
1222 verify(hash(d1) == id(d1))
1223 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1224 verify(d1 == d1)
1225 verify(d1 != d2)
1226 verify(not d1 != d1)
1227 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001228 # Note that the module name appears in str/repr, and that varies
1229 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001230 verify(str(d1).find('D object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001231 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001232 verify(-1 not in d1)
1233 for i in range(10):
1234 verify(i in d1)
1235 verify(10 not in d1)
1236 # Test overridden behavior for static classes
1237 class Proxy(object):
1238 def __init__(self, x):
1239 self.x = x
1240 def __nonzero__(self):
1241 return not not self.x
1242 def __hash__(self):
1243 return hash(self.x)
1244 def __eq__(self, other):
1245 return self.x == other
1246 def __ne__(self, other):
1247 return self.x != other
1248 def __cmp__(self, other):
1249 return cmp(self.x, other.x)
1250 def __str__(self):
1251 return "Proxy:%s" % self.x
1252 def __repr__(self):
1253 return "Proxy(%r)" % self.x
1254 def __contains__(self, value):
1255 return value in self.x
1256 p0 = Proxy(0)
1257 p1 = Proxy(1)
1258 p_1 = Proxy(-1)
1259 verify(not p0)
1260 verify(not not p1)
1261 verify(hash(p0) == hash(0))
1262 verify(p0 == p0)
1263 verify(p0 != p1)
1264 verify(not p0 != p0)
1265 verify(not p0 == p1)
1266 verify(cmp(p0, p1) == -1)
1267 verify(cmp(p0, p0) == 0)
1268 verify(cmp(p0, p_1) == 1)
1269 verify(str(p0) == "Proxy:0")
1270 verify(repr(p0) == "Proxy(0)")
1271 p10 = Proxy(range(10))
1272 verify(-1 not in p10)
1273 for i in range(10):
1274 verify(i in p10)
1275 verify(10 not in p10)
1276 # Test overridden behavior for dynamic classes
1277 class DProxy(object):
1278 __dynamic__ = 1
1279 def __init__(self, x):
1280 self.x = x
1281 def __nonzero__(self):
1282 return not not self.x
1283 def __hash__(self):
1284 return hash(self.x)
1285 def __eq__(self, other):
1286 return self.x == other
1287 def __ne__(self, other):
1288 return self.x != other
1289 def __cmp__(self, other):
1290 return cmp(self.x, other.x)
1291 def __str__(self):
1292 return "DProxy:%s" % self.x
1293 def __repr__(self):
1294 return "DProxy(%r)" % self.x
1295 def __contains__(self, value):
1296 return value in self.x
1297 p0 = DProxy(0)
1298 p1 = DProxy(1)
1299 p_1 = DProxy(-1)
1300 verify(not p0)
1301 verify(not not p1)
1302 verify(hash(p0) == hash(0))
1303 verify(p0 == p0)
1304 verify(p0 != p1)
1305 verify(not p0 != p0)
1306 verify(not p0 == p1)
1307 verify(cmp(p0, p1) == -1)
1308 verify(cmp(p0, p0) == 0)
1309 verify(cmp(p0, p_1) == 1)
1310 verify(str(p0) == "DProxy:0")
1311 verify(repr(p0) == "DProxy(0)")
1312 p10 = DProxy(range(10))
1313 verify(-1 not in p10)
1314 for i in range(10):
1315 verify(i in p10)
1316 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001317 # Safety test for __cmp__
1318 def unsafecmp(a, b):
1319 try:
1320 a.__class__.__cmp__(a, b)
1321 except TypeError:
1322 pass
1323 else:
1324 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1325 a.__class__, a, b)
1326 unsafecmp(u"123", "123")
1327 unsafecmp("123", u"123")
1328 unsafecmp(1, 1.0)
1329 unsafecmp(1.0, 1)
1330 unsafecmp(1, 1L)
1331 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001332
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001333def weakrefs():
1334 if verbose: print "Testing weak references..."
1335 import weakref
1336 class C(object):
1337 pass
1338 c = C()
1339 r = weakref.ref(c)
1340 verify(r() is c)
1341 del c
1342 verify(r() is None)
1343 del r
1344 class NoWeak(object):
1345 __slots__ = ['foo']
1346 no = NoWeak()
1347 try:
1348 weakref.ref(no)
1349 except TypeError, msg:
1350 verify(str(msg).find("weakly") >= 0)
1351 else:
1352 verify(0, "weakref.ref(no) should be illegal")
1353 class Weak(object):
1354 __slots__ = ['foo', '__weakref__']
1355 yes = Weak()
1356 r = weakref.ref(yes)
1357 verify(r() is yes)
1358 del yes
1359 verify(r() is None)
1360 del r
1361
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001362def properties():
1363 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001364 class C(object):
1365 def getx(self):
1366 return self.__x
1367 def setx(self, value):
1368 self.__x = value
1369 def delx(self):
1370 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001371 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001372 a = C()
1373 verify(not hasattr(a, "x"))
1374 a.x = 42
1375 verify(a._C__x == 42)
1376 verify(a.x == 42)
1377 del a.x
1378 verify(not hasattr(a, "x"))
1379 verify(not hasattr(a, "_C__x"))
1380 C.x.__set__(a, 100)
1381 verify(C.x.__get__(a) == 100)
1382## C.x.__set__(a)
1383## verify(not hasattr(a, "x"))
1384
Tim Peters66c1a522001-09-24 21:17:50 +00001385 raw = C.__dict__['x']
1386 verify(isinstance(raw, property))
1387
1388 attrs = dir(raw)
1389 verify("__doc__" in attrs)
1390 verify("fget" in attrs)
1391 verify("fset" in attrs)
1392 verify("fdel" in attrs)
1393
1394 verify(raw.__doc__ == "I'm the x property.")
1395 verify(raw.fget is C.__dict__['getx'])
1396 verify(raw.fset is C.__dict__['setx'])
1397 verify(raw.fdel is C.__dict__['delx'])
1398
1399 for attr in "__doc__", "fget", "fset", "fdel":
1400 try:
1401 setattr(raw, attr, 42)
1402 except TypeError, msg:
1403 if str(msg).find('readonly') < 0:
1404 raise TestFailed("when setting readonly attr %r on a "
1405 "property, got unexpected TypeError "
1406 "msg %r" % (attr, str(msg)))
1407 else:
1408 raise TestFailed("expected TypeError from trying to set "
1409 "readonly %r attr on a property" % attr)
1410
Guido van Rossumc4a18802001-08-24 16:55:27 +00001411def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001412 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001413
1414 class A(object):
1415 def meth(self, a):
1416 return "A(%r)" % a
1417
1418 verify(A().meth(1) == "A(1)")
1419
1420 class B(A):
1421 def __init__(self):
1422 self.__super = super(B, self)
1423 def meth(self, a):
1424 return "B(%r)" % a + self.__super.meth(a)
1425
1426 verify(B().meth(2) == "B(2)A(2)")
1427
1428 class C(A):
1429 __dynamic__ = 1
1430 def meth(self, a):
1431 return "C(%r)" % a + self.__super.meth(a)
1432 C._C__super = super(C)
1433
1434 verify(C().meth(3) == "C(3)A(3)")
1435
1436 class D(C, B):
1437 def meth(self, a):
1438 return "D(%r)" % a + super(D, self).meth(a)
1439
1440 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1441
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001442def inherits():
1443 if verbose: print "Testing inheritance from basic types..."
1444
1445 class hexint(int):
1446 def __repr__(self):
1447 return hex(self)
1448 def __add__(self, other):
1449 return hexint(int.__add__(self, other))
1450 # (Note that overriding __radd__ doesn't work,
1451 # because the int type gets first dibs.)
1452 verify(repr(hexint(7) + 9) == "0x10")
1453 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001454 a = hexint(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001455 verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001456 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001457 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001458 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001459 verify((+a).__class__ is int)
1460 verify((a >> 0).__class__ is int)
1461 verify((a << 0).__class__ is int)
1462 verify((hexint(0) << 12).__class__ is int)
1463 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001464
1465 class octlong(long):
1466 __slots__ = []
1467 def __str__(self):
1468 s = oct(self)
1469 if s[-1] == 'L':
1470 s = s[:-1]
1471 return s
1472 def __add__(self, other):
1473 return self.__class__(super(octlong, self).__add__(other))
1474 __radd__ = __add__
1475 verify(str(octlong(3) + 5) == "010")
1476 # (Note that overriding __radd__ here only seems to work
1477 # because the example uses a short int left argument.)
1478 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001479 a = octlong(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001480 verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001481 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001482 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001483 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001484 verify((+a).__class__ is long)
1485 verify((-a).__class__ is long)
1486 verify((-octlong(0)).__class__ is long)
1487 verify((a >> 0).__class__ is long)
1488 verify((a << 0).__class__ is long)
1489 verify((a - 0).__class__ is long)
1490 verify((a * 1).__class__ is long)
1491 verify((a ** 1).__class__ is long)
1492 verify((a // 1).__class__ is long)
1493 verify((1 * a).__class__ is long)
1494 verify((a | 0).__class__ is long)
1495 verify((a ^ 0).__class__ is long)
1496 verify((a & -1L).__class__ is long)
1497 verify((octlong(0) << 12).__class__ is long)
1498 verify((octlong(0) >> 12).__class__ is long)
1499 verify(abs(octlong(0)).__class__ is long)
1500
1501 # Because octlong overrides __add__, we can't check the absence of +0
1502 # optimizations using octlong.
1503 class longclone(long):
1504 pass
1505 a = longclone(1)
1506 verify((a + 0).__class__ is long)
1507 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001508
1509 class precfloat(float):
1510 __slots__ = ['prec']
1511 def __init__(self, value=0.0, prec=12):
1512 self.prec = int(prec)
1513 float.__init__(value)
1514 def __repr__(self):
1515 return "%.*g" % (self.prec, self)
1516 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001517 a = precfloat(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001518 verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001519 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001520 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001521 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001522 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001523
Tim Peters2400fa42001-09-12 19:12:49 +00001524 class madcomplex(complex):
1525 def __repr__(self):
1526 return "%.17gj%+.17g" % (self.imag, self.real)
1527 a = madcomplex(-3, 4)
1528 verify(repr(a) == "4j-3")
1529 base = complex(-3, 4)
1530 verify(base.__class__ is complex)
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001531 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001532 verify(complex(a) == base)
1533 verify(complex(a).__class__ is complex)
1534 a = madcomplex(a) # just trying another form of the constructor
1535 verify(repr(a) == "4j-3")
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001536 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001537 verify(complex(a) == base)
1538 verify(complex(a).__class__ is complex)
1539 verify(hash(a) == hash(base))
1540 verify((+a).__class__ is complex)
1541 verify((a + 0).__class__ is complex)
1542 verify(a + 0 == base)
1543 verify((a - 0).__class__ is complex)
1544 verify(a - 0 == base)
1545 verify((a * 1).__class__ is complex)
1546 verify(a * 1 == base)
1547 verify((a / 1).__class__ is complex)
1548 verify(a / 1 == base)
1549
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001550 class madtuple(tuple):
1551 _rev = None
1552 def rev(self):
1553 if self._rev is not None:
1554 return self._rev
1555 L = list(self)
1556 L.reverse()
1557 self._rev = self.__class__(L)
1558 return self._rev
1559 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001560 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001561 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1562 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1563 for i in range(512):
1564 t = madtuple(range(i))
1565 u = t.rev()
1566 v = u.rev()
1567 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001568 a = madtuple((1,2,3,4,5))
1569 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001570 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001571 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001572 verify(a[:].__class__ is tuple)
1573 verify((a * 1).__class__ is tuple)
1574 verify((a * 0).__class__ is tuple)
1575 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001576 a = madtuple(())
1577 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001578 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001579 verify((a + a).__class__ is tuple)
1580 verify((a * 0).__class__ is tuple)
1581 verify((a * 1).__class__ is tuple)
1582 verify((a * 2).__class__ is tuple)
1583 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001584
1585 class madstring(str):
1586 _rev = None
1587 def rev(self):
1588 if self._rev is not None:
1589 return self._rev
1590 L = list(self)
1591 L.reverse()
1592 self._rev = self.__class__("".join(L))
1593 return self._rev
1594 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001595 verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001596 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1597 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1598 for i in range(256):
1599 s = madstring("".join(map(chr, range(i))))
1600 t = s.rev()
1601 u = t.rev()
1602 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001603 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001604 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001605 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001606
Tim Peters8fa5dd02001-09-12 02:18:30 +00001607 base = "\x00" * 5
1608 s = madstring(base)
Guido van Rossumbb77e682001-09-24 16:51:54 +00001609 verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001610 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001611 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001612 verify(hash(s) == hash(base))
Guido van Rossumbb77e682001-09-24 16:51:54 +00001613 verify({s: 1}[base] == 1)
1614 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001615 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001616 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001617 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001618 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001619 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001620 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001621 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001622 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001623 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001624 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001625 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001626 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001627 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001628 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001629 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001630 verify(s.strip() == base)
1631 verify(s.lstrip().__class__ is str)
1632 verify(s.lstrip() == base)
1633 verify(s.rstrip().__class__ is str)
1634 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001635 identitytab = ''.join([chr(i) for i in range(256)])
1636 verify(s.translate(identitytab).__class__ is str)
1637 verify(s.translate(identitytab) == base)
1638 verify(s.translate(identitytab, "x").__class__ is str)
1639 verify(s.translate(identitytab, "x") == base)
1640 verify(s.translate(identitytab, "\x00") == "")
1641 verify(s.replace("x", "x").__class__ is str)
1642 verify(s.replace("x", "x") == base)
1643 verify(s.ljust(len(s)).__class__ is str)
1644 verify(s.ljust(len(s)) == base)
1645 verify(s.rjust(len(s)).__class__ is str)
1646 verify(s.rjust(len(s)) == base)
1647 verify(s.center(len(s)).__class__ is str)
1648 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001649 verify(s.lower().__class__ is str)
1650 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001651
Tim Peters111f6092001-09-12 07:54:51 +00001652 s = madstring("x y")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001653 verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001654 verify(intern(s).__class__ is str)
1655 verify(intern(s) is intern("x y"))
1656 verify(intern(s) == "x y")
1657
1658 i = intern("y x")
1659 s = madstring("y x")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001660 verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001661 verify(intern(s).__class__ is str)
1662 verify(intern(s) is i)
1663
1664 s = madstring(i)
1665 verify(intern(s).__class__ is str)
1666 verify(intern(s) is i)
1667
Guido van Rossum91ee7982001-08-30 20:52:40 +00001668 class madunicode(unicode):
1669 _rev = None
1670 def rev(self):
1671 if self._rev is not None:
1672 return self._rev
1673 L = list(self)
1674 L.reverse()
1675 self._rev = self.__class__(u"".join(L))
1676 return self._rev
1677 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001678 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001679 verify(u.rev() == madunicode(u"FEDCBA"))
1680 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001681 base = u"12345"
1682 u = madunicode(base)
1683 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001684 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001685 verify(hash(u) == hash(base))
1686 verify({u: 1}[base] == 1)
1687 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001688 verify(u.strip().__class__ is unicode)
1689 verify(u.strip() == base)
1690 verify(u.lstrip().__class__ is unicode)
1691 verify(u.lstrip() == base)
1692 verify(u.rstrip().__class__ is unicode)
1693 verify(u.rstrip() == base)
1694 verify(u.replace(u"x", u"x").__class__ is unicode)
1695 verify(u.replace(u"x", u"x") == base)
1696 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1697 verify(u.replace(u"xy", u"xy") == base)
1698 verify(u.center(len(u)).__class__ is unicode)
1699 verify(u.center(len(u)) == base)
1700 verify(u.ljust(len(u)).__class__ is unicode)
1701 verify(u.ljust(len(u)) == base)
1702 verify(u.rjust(len(u)).__class__ is unicode)
1703 verify(u.rjust(len(u)) == base)
1704 verify(u.lower().__class__ is unicode)
1705 verify(u.lower() == base)
1706 verify(u.upper().__class__ is unicode)
1707 verify(u.upper() == base)
1708 verify(u.capitalize().__class__ is unicode)
1709 verify(u.capitalize() == base)
1710 verify(u.title().__class__ is unicode)
1711 verify(u.title() == base)
1712 verify((u + u"").__class__ is unicode)
1713 verify(u + u"" == base)
1714 verify((u"" + u).__class__ is unicode)
1715 verify(u"" + u == base)
1716 verify((u * 0).__class__ is unicode)
1717 verify(u * 0 == u"")
1718 verify((u * 1).__class__ is unicode)
1719 verify(u * 1 == base)
1720 verify((u * 2).__class__ is unicode)
1721 verify(u * 2 == base + base)
1722 verify(u[:].__class__ is unicode)
1723 verify(u[:] == base)
1724 verify(u[0:0].__class__ is unicode)
1725 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001726
Tim Peters59c9a642001-09-13 05:38:56 +00001727 class CountedInput(file):
1728 """Counts lines read by self.readline().
1729
1730 self.lineno is the 0-based ordinal of the last line read, up to
1731 a maximum of one greater than the number of lines in the file.
1732
1733 self.ateof is true if and only if the final "" line has been read,
1734 at which point self.lineno stops incrementing, and further calls
1735 to readline() continue to return "".
1736 """
1737
1738 lineno = 0
1739 ateof = 0
1740 def readline(self):
1741 if self.ateof:
1742 return ""
1743 s = file.readline(self)
1744 # Next line works too.
1745 # s = super(CountedInput, self).readline()
1746 self.lineno += 1
1747 if s == "":
1748 self.ateof = 1
1749 return s
1750
Tim Peters561f8992001-09-13 19:36:36 +00001751 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00001752 lines = ['a\n', 'b\n', 'c\n']
1753 try:
1754 f.writelines(lines)
1755 f.close()
1756 f = CountedInput(TESTFN)
1757 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1758 got = f.readline()
1759 verify(expected == got)
1760 verify(f.lineno == i)
1761 verify(f.ateof == (i > len(lines)))
1762 f.close()
1763 finally:
1764 try:
1765 f.close()
1766 except:
1767 pass
1768 try:
1769 import os
1770 os.unlink(TESTFN)
1771 except:
1772 pass
1773
Tim Peters808b94e2001-09-13 19:33:07 +00001774def keywords():
1775 if verbose:
1776 print "Testing keyword args to basic type constructors ..."
1777 verify(int(x=1) == 1)
1778 verify(float(x=2) == 2.0)
1779 verify(long(x=3) == 3L)
1780 verify(complex(imag=42, real=666) == complex(666, 42))
1781 verify(str(object=500) == '500')
1782 verify(unicode(string='abc', errors='strict') == u'abc')
1783 verify(tuple(sequence=range(3)) == (0, 1, 2))
1784 verify(list(sequence=(0, 1, 2)) == range(3))
1785 verify(dictionary(mapping={1: 2}) == {1: 2})
1786
1787 for constructor in (int, float, long, complex, str, unicode,
1788 tuple, list, dictionary, file):
1789 try:
1790 constructor(bogus_keyword_arg=1)
1791 except TypeError:
1792 pass
1793 else:
1794 raise TestFailed("expected TypeError from bogus keyword "
1795 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00001796
Tim Peters8fa45672001-09-13 21:01:29 +00001797def restricted():
1798 import rexec
1799 if verbose:
1800 print "Testing interaction with restricted execution ..."
1801
1802 sandbox = rexec.RExec()
1803
1804 code1 = """f = open(%r, 'w')""" % TESTFN
1805 code2 = """f = file(%r, 'w')""" % TESTFN
1806 code3 = """\
1807f = open(%r)
1808t = type(f) # a sneaky way to get the file() constructor
1809f.close()
1810f = t(%r, 'w') # rexec can't catch this by itself
1811""" % (TESTFN, TESTFN)
1812
1813 f = open(TESTFN, 'w') # Create the file so code3 can find it.
1814 f.close()
1815
1816 try:
1817 for code in code1, code2, code3:
1818 try:
1819 sandbox.r_exec(code)
1820 except IOError, msg:
1821 if str(msg).find("restricted") >= 0:
1822 outcome = "OK"
1823 else:
1824 outcome = "got an exception, but not an expected one"
1825 else:
1826 outcome = "expected a restricted-execution exception"
1827
1828 if outcome != "OK":
1829 raise TestFailed("%s, in %r" % (outcome, code))
1830
1831 finally:
1832 try:
1833 import os
1834 os.unlink(TESTFN)
1835 except:
1836 pass
1837
Tim Peters0ab085c2001-09-14 00:25:33 +00001838def str_subclass_as_dict_key():
1839 if verbose:
1840 print "Testing a str subclass used as dict key .."
1841
1842 class cistr(str):
1843 """Sublcass of str that computes __eq__ case-insensitively.
1844
1845 Also computes a hash code of the string in canonical form.
1846 """
1847
1848 def __init__(self, value):
1849 self.canonical = value.lower()
1850 self.hashcode = hash(self.canonical)
1851
1852 def __eq__(self, other):
1853 if not isinstance(other, cistr):
1854 other = cistr(other)
1855 return self.canonical == other.canonical
1856
1857 def __hash__(self):
1858 return self.hashcode
1859
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001860 verify(cistr('ABC') == 'abc')
1861 verify('aBc' == cistr('ABC'))
Tim Peters0ab085c2001-09-14 00:25:33 +00001862 verify(str(cistr('ABC')) == 'ABC')
1863
1864 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
1865 verify(d[cistr('one')] == 1)
1866 verify(d[cistr('tWo')] == 2)
1867 verify(d[cistr('THrEE')] == 3)
1868 verify(cistr('ONe') in d)
1869 verify(d.get(cistr('thrEE')) == 3)
1870
Guido van Rossumab3b0342001-09-18 20:38:53 +00001871def classic_comparisons():
1872 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00001873 class classic:
1874 pass
1875 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00001876 if verbose: print " (base = %s)" % base
1877 class C(base):
1878 def __init__(self, value):
1879 self.value = int(value)
1880 def __cmp__(self, other):
1881 if isinstance(other, C):
1882 return cmp(self.value, other.value)
1883 if isinstance(other, int) or isinstance(other, long):
1884 return cmp(self.value, other)
1885 return NotImplemented
1886 c1 = C(1)
1887 c2 = C(2)
1888 c3 = C(3)
1889 verify(c1 == 1)
1890 c = {1: c1, 2: c2, 3: c3}
1891 for x in 1, 2, 3:
1892 for y in 1, 2, 3:
1893 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1894 for op in "<", "<=", "==", "!=", ">", ">=":
1895 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1896 "x=%d, y=%d" % (x, y))
1897 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
1898 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1899
Guido van Rossum0639f592001-09-18 21:06:04 +00001900def rich_comparisons():
1901 if verbose:
1902 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00001903 class Z(complex):
1904 pass
1905 z = Z(1)
1906 verify(z == 1+0j)
1907 verify(1+0j == z)
1908 class ZZ(complex):
1909 def __eq__(self, other):
1910 try:
1911 return abs(self - other) <= 1e-6
1912 except:
1913 return NotImplemented
1914 zz = ZZ(1.0000003)
1915 verify(zz == 1+0j)
1916 verify(1+0j == zz)
Tim Peters66c1a522001-09-24 21:17:50 +00001917
Guido van Rossum0639f592001-09-18 21:06:04 +00001918 class classic:
1919 pass
1920 for base in (classic, int, object, list):
1921 if verbose: print " (base = %s)" % base
1922 class C(base):
1923 def __init__(self, value):
1924 self.value = int(value)
1925 def __cmp__(self, other):
1926 raise TestFailed, "shouldn't call __cmp__"
1927 def __eq__(self, other):
1928 if isinstance(other, C):
1929 return self.value == other.value
1930 if isinstance(other, int) or isinstance(other, long):
1931 return self.value == other
1932 return NotImplemented
1933 def __ne__(self, other):
1934 if isinstance(other, C):
1935 return self.value != other.value
1936 if isinstance(other, int) or isinstance(other, long):
1937 return self.value != other
1938 return NotImplemented
1939 def __lt__(self, other):
1940 if isinstance(other, C):
1941 return self.value < other.value
1942 if isinstance(other, int) or isinstance(other, long):
1943 return self.value < other
1944 return NotImplemented
1945 def __le__(self, other):
1946 if isinstance(other, C):
1947 return self.value <= other.value
1948 if isinstance(other, int) or isinstance(other, long):
1949 return self.value <= other
1950 return NotImplemented
1951 def __gt__(self, other):
1952 if isinstance(other, C):
1953 return self.value > other.value
1954 if isinstance(other, int) or isinstance(other, long):
1955 return self.value > other
1956 return NotImplemented
1957 def __ge__(self, other):
1958 if isinstance(other, C):
1959 return self.value >= other.value
1960 if isinstance(other, int) or isinstance(other, long):
1961 return self.value >= other
1962 return NotImplemented
1963 c1 = C(1)
1964 c2 = C(2)
1965 c3 = C(3)
1966 verify(c1 == 1)
1967 c = {1: c1, 2: c2, 3: c3}
1968 for x in 1, 2, 3:
1969 for y in 1, 2, 3:
1970 for op in "<", "<=", "==", "!=", ">", ">=":
1971 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1972 "x=%d, y=%d" % (x, y))
1973 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
1974 "x=%d, y=%d" % (x, y))
1975 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
1976 "x=%d, y=%d" % (x, y))
1977
Guido van Rossum1952e382001-09-19 01:25:16 +00001978def coercions():
1979 if verbose: print "Testing coercions..."
1980 class I(int): pass
1981 coerce(I(0), 0)
1982 coerce(0, I(0))
1983 class L(long): pass
1984 coerce(L(0), 0)
1985 coerce(L(0), 0L)
1986 coerce(0, L(0))
1987 coerce(0L, L(0))
1988 class F(float): pass
1989 coerce(F(0), 0)
1990 coerce(F(0), 0L)
1991 coerce(F(0), 0.)
1992 coerce(0, F(0))
1993 coerce(0L, F(0))
1994 coerce(0., F(0))
1995 class C(complex): pass
1996 coerce(C(0), 0)
1997 coerce(C(0), 0L)
1998 coerce(C(0), 0.)
1999 coerce(C(0), 0j)
2000 coerce(0, C(0))
2001 coerce(0L, C(0))
2002 coerce(0., C(0))
2003 coerce(0j, C(0))
2004
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002005def descrdoc():
2006 if verbose: print "Testing descriptor doc strings..."
2007 def check(descr, what):
2008 verify(descr.__doc__ == what, repr(descr.__doc__))
2009 check(file.closed, "flag set if the file is closed") # getset descriptor
2010 check(file.name, "file name") # member descriptor
2011
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002012def setclass():
2013 if verbose: print "Testing __class__ assignment..."
2014 class C(object): pass
2015 class D(object): pass
2016 class E(object): pass
2017 class F(D, E): pass
2018 for cls in C, D, E, F:
2019 for cls2 in C, D, E, F:
2020 x = cls()
2021 x.__class__ = cls2
2022 verify(x.__class__ is cls2)
2023 x.__class__ = cls
2024 verify(x.__class__ is cls)
2025 def cant(x, C):
2026 try:
2027 x.__class__ = C
2028 except TypeError:
2029 pass
2030 else:
2031 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2032 cant(C(), list)
2033 cant(list(), C)
2034 cant(C(), 1)
2035 cant(C(), object)
2036 cant(object(), list)
2037 cant(list(), object)
2038
Guido van Rossum3926a632001-09-25 16:25:58 +00002039def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002040 if verbose:
2041 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002042 import pickle, cPickle
2043
2044 def sorteditems(d):
2045 L = d.items()
2046 L.sort()
2047 return L
2048
2049 global C
2050 class C(object):
2051 def __init__(self, a, b):
2052 super(C, self).__init__()
2053 self.a = a
2054 self.b = b
2055 def __repr__(self):
2056 return "C(%r, %r)" % (self.a, self.b)
2057
2058 global C1
2059 class C1(list):
2060 def __new__(cls, a, b):
2061 return super(C1, cls).__new__(cls)
2062 def __init__(self, a, b):
2063 self.a = a
2064 self.b = b
2065 def __repr__(self):
2066 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2067
2068 global C2
2069 class C2(int):
2070 def __new__(cls, a, b, val=0):
2071 return super(C2, cls).__new__(cls, val)
2072 def __init__(self, a, b, val=0):
2073 self.a = a
2074 self.b = b
2075 def __repr__(self):
2076 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2077
2078 for p in pickle, cPickle:
2079 for bin in 0, 1:
2080
2081 for cls in C, C1, C2:
2082 s = p.dumps(cls, bin)
2083 cls2 = p.loads(s)
2084 verify(cls2 is cls)
2085
2086 a = C1(1, 2); a.append(42); a.append(24)
2087 b = C2("hello", "world", 42)
2088 s = p.dumps((a, b), bin)
2089 x, y = p.loads(s)
2090 assert x.__class__ == a.__class__
2091 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2092 assert y.__class__ == b.__class__
2093 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2094 assert `x` == `a`
2095 assert `y` == `b`
2096 if verbose:
2097 print "a = x =", a
2098 print "b = y =", b
2099
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002100 # Testing copy.deepcopy()
2101 import copy
2102 for cls in C, C1, C2:
2103 cls2 = copy.deepcopy(cls)
2104 verify(cls2 is cls)
2105
2106 a = C1(1, 2); a.append(42); a.append(24)
2107 b = C2("hello", "world", 42)
2108 x, y = copy.deepcopy((a, b))
2109 assert x.__class__ == a.__class__
2110 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2111 assert y.__class__ == b.__class__
2112 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2113 assert `x` == `a`
2114 assert `y` == `b`
2115 if verbose:
2116 print "a = x =", a
2117 print "b = y =", b
2118
2119def copies():
2120 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2121 import copy
2122 class C(object):
2123 pass
2124
2125 a = C()
2126 a.foo = 12
2127 b = copy.copy(a)
2128 verify(b.__dict__ == a.__dict__)
2129
2130 a.bar = [1,2,3]
2131 c = copy.copy(a)
2132 verify(c.bar == a.bar)
2133 verify(c.bar is a.bar)
2134
2135 d = copy.deepcopy(a)
2136 verify(d.__dict__ == a.__dict__)
2137 a.bar.append(4)
2138 verify(d.bar == [1,2,3])
2139
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002140def binopoverride():
2141 if verbose: print "Testing overrides of binary operations..."
2142 class I(int):
2143 def __repr__(self):
2144 return "I(%r)" % int(self)
2145 def __add__(self, other):
2146 return I(int(self) + int(other))
2147 __radd__ = __add__
2148 def __pow__(self, other, mod=None):
2149 if mod is None:
2150 return I(pow(int(self), int(other)))
2151 else:
2152 return I(pow(int(self), int(other), int(mod)))
2153 def __rpow__(self, other, mod=None):
2154 if mod is None:
2155 return I(pow(int(other), int(self), mod))
2156 else:
2157 return I(pow(int(other), int(self), int(mod)))
2158
2159 vereq(`I(1) + I(2)`, "I(3)")
2160 vereq(`I(1) + 2`, "I(3)")
2161 vereq(`1 + I(2)`, "I(3)")
2162 vereq(`I(2) ** I(3)`, "I(8)")
2163 vereq(`2 ** I(3)`, "I(8)")
2164 vereq(`I(2) ** 3`, "I(8)")
2165 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2166 class S(str):
2167 def __eq__(self, other):
2168 return self.lower() == other.lower()
2169
Tim Peters0ab085c2001-09-14 00:25:33 +00002170
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002171def test_main():
Tim Peters6d6c1a32001-08-02 04:15:00 +00002172 lists()
2173 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00002174 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00002175 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 ints()
2177 longs()
2178 floats()
2179 complexes()
2180 spamlists()
2181 spamdicts()
2182 pydicts()
2183 pylists()
2184 metaclass()
2185 pymods()
2186 multi()
2187 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00002188 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189 slots()
2190 dynamics()
2191 errors()
2192 classmethods()
2193 staticmethods()
2194 classic()
2195 compattr()
2196 newslot()
2197 altmro()
2198 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00002199 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00002200 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002201 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002202 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00002203 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002204 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00002205 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00002206 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00002207 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00002208 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00002209 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00002210 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002211 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002212 setclass()
Guido van Rossum3926a632001-09-25 16:25:58 +00002213 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002214 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002215 binopoverride()
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002216 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002218if __name__ == "__main__":
2219 test_main()