blob: 0357a065be14ec984318eb9c4c75c5c70da25eb9 [file] [log] [blame]
Tim Peters6d6c1a32001-08-02 04:15:00 +00001# Test descriptor-related enhancements
2
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
6def testunop(a, res, expr="len(a)", meth="__len__"):
7 if verbose: print "checking", expr
8 dict = {'a': a}
9 verify(eval(expr, dict) == res)
10 t = type(a)
11 m = getattr(t, meth)
12 verify(m == t.__dict__[meth])
13 verify(m(a) == res)
14 bm = getattr(a, meth)
15 verify(bm() == res)
16
17def testbinop(a, b, res, expr="a+b", meth="__add__"):
18 if verbose: print "checking", expr
19 dict = {'a': a, 'b': b}
20 verify(eval(expr, dict) == res)
21 t = type(a)
22 m = getattr(t, meth)
23 verify(m == t.__dict__[meth])
24 verify(m(a, b) == res)
25 bm = getattr(a, meth)
26 verify(bm(b) == res)
27
28def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b, 'c': c}
31 verify(eval(expr, dict) == res)
32 t = type(a)
33 m = getattr(t, meth)
34 verify(m == t.__dict__[meth])
35 verify(m(a, b, c) == res)
36 bm = getattr(a, meth)
37 verify(bm(b, c) == res)
38
39def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
40 if verbose: print "checking", stmt
41 dict = {'a': deepcopy(a), 'b': b}
42 exec stmt in dict
43 verify(dict['a'] == res)
44 t = type(a)
45 m = getattr(t, meth)
46 verify(m == t.__dict__[meth])
47 dict['a'] = deepcopy(a)
48 m(dict['a'], b)
49 verify(dict['a'] == res)
50 dict['a'] = deepcopy(a)
51 bm = getattr(dict['a'], meth)
52 bm(b)
53 verify(dict['a'] == res)
54
55def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
56 if verbose: print "checking", stmt
57 dict = {'a': deepcopy(a), 'b': b, 'c': c}
58 exec stmt in dict
59 verify(dict['a'] == res)
60 t = type(a)
61 m = getattr(t, meth)
62 verify(m == t.__dict__[meth])
63 dict['a'] = deepcopy(a)
64 m(dict['a'], b, c)
65 verify(dict['a'] == res)
66 dict['a'] = deepcopy(a)
67 bm = getattr(dict['a'], meth)
68 bm(b, c)
69 verify(dict['a'] == res)
70
71def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
72 if verbose: print "checking", stmt
73 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
74 exec stmt in dict
75 verify(dict['a'] == res)
76 t = type(a)
77 m = getattr(t, meth)
78 verify(m == t.__dict__[meth])
79 dict['a'] = deepcopy(a)
80 m(dict['a'], b, c, d)
81 verify(dict['a'] == res)
82 dict['a'] = deepcopy(a)
83 bm = getattr(dict['a'], meth)
84 bm(b, c, d)
85 verify(dict['a'] == res)
86
87def lists():
88 if verbose: print "Testing list operations..."
89 testbinop([1], [2], [1,2], "a+b", "__add__")
90 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
91 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
92 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
93 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
94 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
95 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
96 testunop([1,2,3], 3, "len(a)", "__len__")
97 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
98 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
99 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
100 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
101
102def dicts():
103 if verbose: print "Testing dict operations..."
104 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
105 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
106 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
107 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
108 d = {1:2,3:4}
109 l1 = []
110 for i in d.keys(): l1.append(i)
111 l = []
112 for i in iter(d): l.append(i)
113 verify(l == l1)
114 l = []
115 for i in d.__iter__(): l.append(i)
116 verify(l == l1)
117 l = []
118 for i in dictionary.__iter__(d): l.append(i)
119 verify(l == l1)
120 d = {1:2, 3:4}
121 testunop(d, 2, "len(a)", "__len__")
122 verify(eval(repr(d), {}) == d)
123 verify(eval(d.__repr__(), {}) == d)
124 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
125
Tim Peters25786c02001-09-02 08:22:48 +0000126def dict_constructor():
127 if verbose:
128 print "Testing dictionary constructor ..."
129 d = dictionary()
130 verify(d == {})
131 d = dictionary({})
132 verify(d == {})
133 d = dictionary(mapping={})
134 verify(d == {})
135 d = dictionary({1: 2, 'a': 'b'})
136 verify(d == {1: 2, 'a': 'b'})
137 for badarg in 0, 0L, 0j, "0", [0], (0,):
138 try:
139 dictionary(badarg)
140 except TypeError:
141 pass
142 else:
143 raise TestFailed("no TypeError from dictionary(%r)" % badarg)
144 try:
145 dictionary(senseless={})
146 except TypeError:
147 pass
148 else:
149 raise TestFailed("no TypeError from dictionary(senseless={}")
150
151 try:
152 dictionary({}, {})
153 except TypeError:
154 pass
155 else:
156 raise TestFailed("no TypeError from dictionary({}, {})")
157
158 class Mapping:
159 dict = {1:2, 3:4, 'a':1j}
160
161 def __getitem__(self, i):
162 return self.dict[i]
163
164 try:
165 dictionary(Mapping())
166 except TypeError:
167 pass
168 else:
169 raise TestFailed("no TypeError from dictionary(incomplete mapping)")
170
171 Mapping.keys = lambda self: self.dict.keys()
172 d = dictionary(mapping=Mapping())
173 verify(d == Mapping.dict)
174
Tim Peters5d2b77c2001-09-03 05:47:38 +0000175def test_dir():
176 if verbose:
177 print "Testing dir() ..."
178 junk = 12
179 verify(dir() == ['junk'])
180 del junk
181
182 # Just make sure these don't blow up!
183 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
184 dir(arg)
185
Tim Peters37a309d2001-09-04 01:20:04 +0000186 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000187 class C:
188 Cdata = 1
189 def Cmethod(self): pass
190
191 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
192 verify(dir(C) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000193 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000194
195 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
196 verify(dir(c) == cstuff)
197
198 c.cdata = 2
199 c.cmethod = lambda self: 0
200 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000201 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000202
203 class A(C):
204 Adata = 1
205 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000206
Tim Peters37a309d2001-09-04 01:20:04 +0000207 astuff = ['Adata', 'Amethod'] + cstuff
208 verify(dir(A) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000209 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000210 a = A()
211 verify(dir(a) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000212 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000213 a.adata = 42
214 a.amethod = lambda self: 3
215 verify(dir(a) == astuff + ['adata', 'amethod'])
216
217 # The same, but with new-style classes. Since these have object as a
218 # base class, a lot more gets sucked in.
219 def interesting(strings):
220 return [s for s in strings if not s.startswith('_')]
221
Tim Peters5d2b77c2001-09-03 05:47:38 +0000222 class C(object):
223 Cdata = 1
224 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000225
226 cstuff = ['Cdata', 'Cmethod']
227 verify(interesting(dir(C)) == cstuff)
228
229 c = C()
230 verify(interesting(dir(c)) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000231 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000232
233 c.cdata = 2
234 c.cmethod = lambda self: 0
235 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000236 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000237
Tim Peters5d2b77c2001-09-03 05:47:38 +0000238 class A(C):
239 Adata = 1
240 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000241
242 astuff = ['Adata', 'Amethod'] + cstuff
243 verify(interesting(dir(A)) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000244 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000245 a = A()
246 verify(interesting(dir(a)) == astuff)
247 a.adata = 42
248 a.amethod = lambda self: 3
249 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000250 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000251
Tim Peterscaaff8d2001-09-10 23:12:14 +0000252 # Try a module subclass.
253 import sys
254 class M(type(sys)):
255 pass
256 minstance = M()
257 minstance.b = 2
258 minstance.a = 1
259 verify(dir(minstance) == ['a', 'b'])
260
261 class M2(M):
262 def getdict(self):
263 return "Not a dict!"
264 __dict__ = property(getdict)
265
266 m2instance = M2()
267 m2instance.b = 2
268 m2instance.a = 1
269 verify(m2instance.__dict__ == "Not a dict!")
270 try:
271 dir(m2instance)
272 except TypeError:
273 pass
274
Tim Peters6d6c1a32001-08-02 04:15:00 +0000275binops = {
276 'add': '+',
277 'sub': '-',
278 'mul': '*',
279 'div': '/',
280 'mod': '%',
281 'divmod': 'divmod',
282 'pow': '**',
283 'lshift': '<<',
284 'rshift': '>>',
285 'and': '&',
286 'xor': '^',
287 'or': '|',
288 'cmp': 'cmp',
289 'lt': '<',
290 'le': '<=',
291 'eq': '==',
292 'ne': '!=',
293 'gt': '>',
294 'ge': '>=',
295 }
296
297for name, expr in binops.items():
298 if expr.islower():
299 expr = expr + "(a, b)"
300 else:
301 expr = 'a %s b' % expr
302 binops[name] = expr
303
304unops = {
305 'pos': '+',
306 'neg': '-',
307 'abs': 'abs',
308 'invert': '~',
309 'int': 'int',
310 'long': 'long',
311 'float': 'float',
312 'oct': 'oct',
313 'hex': 'hex',
314 }
315
316for name, expr in unops.items():
317 if expr.islower():
318 expr = expr + "(a)"
319 else:
320 expr = '%s a' % expr
321 unops[name] = expr
322
323def numops(a, b, skip=[]):
324 dict = {'a': a, 'b': b}
325 for name, expr in binops.items():
326 if name not in skip:
327 name = "__%s__" % name
328 if hasattr(a, name):
329 res = eval(expr, dict)
330 testbinop(a, b, res, expr, name)
331 for name, expr in unops.items():
332 name = "__%s__" % name
333 if hasattr(a, name):
334 res = eval(expr, dict)
335 testunop(a, res, expr, name)
336
337def ints():
338 if verbose: print "Testing int operations..."
339 numops(100, 3)
340
341def longs():
342 if verbose: print "Testing long operations..."
343 numops(100L, 3L)
344
345def floats():
346 if verbose: print "Testing float operations..."
347 numops(100.0, 3.0)
348
349def complexes():
350 if verbose: print "Testing complex operations..."
351 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
352 class Number(complex):
353 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000354 def __new__(cls, *args, **kwds):
355 result = complex.__new__(cls, *args)
356 result.prec = kwds.get('prec', 12)
357 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358 def __repr__(self):
359 prec = self.prec
360 if self.imag == 0.0:
361 return "%.*g" % (prec, self.real)
362 if self.real == 0.0:
363 return "%.*gj" % (prec, self.imag)
364 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
365 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000366
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367 a = Number(3.14, prec=6)
368 verify(`a` == "3.14")
369 verify(a.prec == 6)
370
Tim Peters3f996e72001-09-13 19:18:27 +0000371 a = Number(a, prec=2)
372 verify(`a` == "3.1")
373 verify(a.prec == 2)
374
375 a = Number(234.5)
376 verify(`a` == "234.5")
377 verify(a.prec == 12)
378
Tim Peters6d6c1a32001-08-02 04:15:00 +0000379def spamlists():
380 if verbose: print "Testing spamlist operations..."
381 import copy, xxsubtype as spam
382 def spamlist(l, memo=None):
383 import xxsubtype as spam
384 return spam.spamlist(l)
385 # This is an ugly hack:
386 copy._deepcopy_dispatch[spam.spamlist] = spamlist
387
388 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
389 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
390 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
391 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
392 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
393 "a[b:c]", "__getslice__")
394 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
395 "a+=b", "__iadd__")
396 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
397 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
398 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
399 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
400 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
401 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
402 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
403 # Test subclassing
404 class C(spam.spamlist):
405 def foo(self): return 1
406 a = C()
407 verify(a == [])
408 verify(a.foo() == 1)
409 a.append(100)
410 verify(a == [100])
411 verify(a.getstate() == 0)
412 a.setstate(42)
413 verify(a.getstate() == 42)
414
415def spamdicts():
416 if verbose: print "Testing spamdict operations..."
417 import copy, xxsubtype as spam
418 def spamdict(d, memo=None):
419 import xxsubtype as spam
420 sd = spam.spamdict()
421 for k, v in d.items(): sd[k] = v
422 return sd
423 # This is an ugly hack:
424 copy._deepcopy_dispatch[spam.spamdict] = spamdict
425
426 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
427 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
428 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
429 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
430 d = spamdict({1:2,3:4})
431 l1 = []
432 for i in d.keys(): l1.append(i)
433 l = []
434 for i in iter(d): l.append(i)
435 verify(l == l1)
436 l = []
437 for i in d.__iter__(): l.append(i)
438 verify(l == l1)
439 l = []
440 for i in type(spamdict({})).__iter__(d): l.append(i)
441 verify(l == l1)
442 straightd = {1:2, 3:4}
443 spamd = spamdict(straightd)
444 testunop(spamd, 2, "len(a)", "__len__")
445 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
446 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
447 "a[b]=c", "__setitem__")
448 # Test subclassing
449 class C(spam.spamdict):
450 def foo(self): return 1
451 a = C()
452 verify(a.items() == [])
453 verify(a.foo() == 1)
454 a['foo'] = 'bar'
455 verify(a.items() == [('foo', 'bar')])
456 verify(a.getstate() == 0)
457 a.setstate(100)
458 verify(a.getstate() == 100)
459
460def pydicts():
461 if verbose: print "Testing Python subclass of dict..."
462 verify(issubclass(dictionary, dictionary))
463 verify(isinstance({}, dictionary))
464 d = dictionary()
465 verify(d == {})
466 verify(d.__class__ is dictionary)
467 verify(isinstance(d, dictionary))
468 class C(dictionary):
469 state = -1
470 def __init__(self, *a, **kw):
471 if a:
472 assert len(a) == 1
473 self.state = a[0]
474 if kw:
475 for k, v in kw.items(): self[v] = k
476 def __getitem__(self, key):
477 return self.get(key, 0)
478 def __setitem__(self, key, value):
479 assert isinstance(key, type(0))
480 dictionary.__setitem__(self, key, value)
481 def setstate(self, state):
482 self.state = state
483 def getstate(self):
484 return self.state
485 verify(issubclass(C, dictionary))
486 a1 = C(12)
487 verify(a1.state == 12)
488 a2 = C(foo=1, bar=2)
489 verify(a2[1] == 'foo' and a2[2] == 'bar')
490 a = C()
491 verify(a.state == -1)
492 verify(a.getstate() == -1)
493 a.setstate(0)
494 verify(a.state == 0)
495 verify(a.getstate() == 0)
496 a.setstate(10)
497 verify(a.state == 10)
498 verify(a.getstate() == 10)
499 verify(a[42] == 0)
500 a[42] = 24
501 verify(a[42] == 24)
502 if verbose: print "pydict stress test ..."
503 N = 50
504 for i in range(N):
505 a[i] = C()
506 for j in range(N):
507 a[i][j] = i*j
508 for i in range(N):
509 for j in range(N):
510 verify(a[i][j] == i*j)
511
512def pylists():
513 if verbose: print "Testing Python subclass of list..."
514 class C(list):
515 def __getitem__(self, i):
516 return list.__getitem__(self, i) + 100
517 def __getslice__(self, i, j):
518 return (i, j)
519 a = C()
520 a.extend([0,1,2])
521 verify(a[0] == 100)
522 verify(a[1] == 101)
523 verify(a[2] == 102)
524 verify(a[100:200] == (100,200))
525
526def metaclass():
527 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000528 class C:
529 __metaclass__ = type
530 def __init__(self):
531 self.__state = 0
532 def getstate(self):
533 return self.__state
534 def setstate(self, state):
535 self.__state = state
536 a = C()
537 verify(a.getstate() == 0)
538 a.setstate(10)
539 verify(a.getstate() == 10)
540 class D:
541 class __metaclass__(type):
542 def myself(cls): return cls
543 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000544 d = D()
545 verify(d.__class__ is D)
546 class M1(type):
547 def __new__(cls, name, bases, dict):
548 dict['__spam__'] = 1
549 return type.__new__(cls, name, bases, dict)
550 class C:
551 __metaclass__ = M1
552 verify(C.__spam__ == 1)
553 c = C()
554 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000555
Guido van Rossum309b5662001-08-17 11:43:17 +0000556 class _instance(object):
557 pass
558 class M2(object):
559 def __new__(cls, name, bases, dict):
560 self = object.__new__(cls)
561 self.name = name
562 self.bases = bases
563 self.dict = dict
564 return self
565 __new__ = staticmethod(__new__)
566 def __call__(self):
567 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000568 # Early binding of methods
569 for key in self.dict:
570 if key.startswith("__"):
571 continue
572 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000573 return it
574 class C:
575 __metaclass__ = M2
576 def spam(self):
577 return 42
578 verify(C.name == 'C')
579 verify(C.bases == ())
580 verify('spam' in C.dict)
581 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000582 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
Guido van Rossum91ee7982001-08-30 20:52:40 +0000584 # More metaclass examples
585
586 class autosuper(type):
587 # Automatically add __super to the class
588 # This trick only works for dynamic classes
589 # so we force __dynamic__ = 1
590 def __new__(metaclass, name, bases, dict):
591 # XXX Should check that name isn't already a base class name
592 dict["__dynamic__"] = 1
593 cls = super(autosuper, metaclass).__new__(metaclass,
594 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000595 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000596 while name[:1] == "_":
597 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000598 if name:
599 name = "_%s__super" % name
600 else:
601 name = "__super"
602 setattr(cls, name, super(cls))
603 return cls
604 class A:
605 __metaclass__ = autosuper
606 def meth(self):
607 return "A"
608 class B(A):
609 def meth(self):
610 return "B" + self.__super.meth()
611 class C(A):
612 def meth(self):
613 return "C" + self.__super.meth()
614 class D(C, B):
615 def meth(self):
616 return "D" + self.__super.meth()
617 verify(D().meth() == "DCBA")
618 class E(B, C):
619 def meth(self):
620 return "E" + self.__super.meth()
621 verify(E().meth() == "EBCA")
622
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000623 class autoproperty(type):
624 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000625 # named _get_x and/or _set_x are found
626 def __new__(metaclass, name, bases, dict):
627 hits = {}
628 for key, val in dict.iteritems():
629 if key.startswith("_get_"):
630 key = key[5:]
631 get, set = hits.get(key, (None, None))
632 get = val
633 hits[key] = get, set
634 elif key.startswith("_set_"):
635 key = key[5:]
636 get, set = hits.get(key, (None, None))
637 set = val
638 hits[key] = get, set
639 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000640 dict[key] = property(get, set)
641 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000642 name, bases, dict)
643 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000644 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000645 def _get_x(self):
646 return -self.__x
647 def _set_x(self, x):
648 self.__x = -x
649 a = A()
650 verify(not hasattr(a, "x"))
651 a.x = 12
652 verify(a.x == 12)
653 verify(a._A__x == -12)
654
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000655 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000656 # Merge of multiple cooperating metaclasses
657 pass
658 class A:
659 __metaclass__ = multimetaclass
660 def _get_x(self):
661 return "A"
662 class B(A):
663 def _get_x(self):
664 return "B" + self.__super._get_x()
665 class C(A):
666 def _get_x(self):
667 return "C" + self.__super._get_x()
668 class D(C, B):
669 def _get_x(self):
670 return "D" + self.__super._get_x()
671 verify(D().x == "DCBA")
672
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673def pymods():
674 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000676 import sys
677 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000678 class MM(MT):
679 def __init__(self):
680 MT.__init__(self)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000681 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000683 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684 def __setattr__(self, name, value):
685 log.append(("setattr", name, value))
686 MT.__setattr__(self, name, value)
687 def __delattr__(self, name):
688 log.append(("delattr", name))
689 MT.__delattr__(self, name)
690 a = MM()
691 a.foo = 12
692 x = a.foo
693 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000694 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696 ("delattr", "foo")], log)
697
698def multi():
699 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 class C(object):
701 def __init__(self):
702 self.__state = 0
703 def getstate(self):
704 return self.__state
705 def setstate(self, state):
706 self.__state = state
707 a = C()
708 verify(a.getstate() == 0)
709 a.setstate(10)
710 verify(a.getstate() == 10)
711 class D(dictionary, C):
712 def __init__(self):
713 type({}).__init__(self)
714 C.__init__(self)
715 d = D()
716 verify(d.keys() == [])
717 d["hello"] = "world"
718 verify(d.items() == [("hello", "world")])
719 verify(d["hello"] == "world")
720 verify(d.getstate() == 0)
721 d.setstate(10)
722 verify(d.getstate() == 10)
723 verify(D.__mro__ == (D, dictionary, C, object))
724
Guido van Rossume45763a2001-08-10 21:28:46 +0000725 # SF bug #442833
726 class Node(object):
727 def __int__(self):
728 return int(self.foo())
729 def foo(self):
730 return "23"
731 class Frag(Node, list):
732 def foo(self):
733 return "42"
734 verify(Node().__int__() == 23)
735 verify(int(Node()) == 23)
736 verify(Frag().__int__() == 42)
737 verify(int(Frag()) == 42)
738
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739def diamond():
740 if verbose: print "Testing multiple inheritance special cases..."
741 class A(object):
742 def spam(self): return "A"
743 verify(A().spam() == "A")
744 class B(A):
745 def boo(self): return "B"
746 def spam(self): return "B"
747 verify(B().spam() == "B")
748 verify(B().boo() == "B")
749 class C(A):
750 def boo(self): return "C"
751 verify(C().spam() == "A")
752 verify(C().boo() == "C")
753 class D(B, C): pass
754 verify(D().spam() == "B")
755 verify(D().boo() == "B")
756 verify(D.__mro__ == (D, B, C, A, object))
757 class E(C, B): pass
758 verify(E().spam() == "B")
759 verify(E().boo() == "C")
760 verify(E.__mro__ == (E, C, B, A, object))
761 class F(D, E): pass
762 verify(F().spam() == "B")
763 verify(F().boo() == "B")
764 verify(F.__mro__ == (F, D, E, B, C, A, object))
765 class G(E, D): pass
766 verify(G().spam() == "B")
767 verify(G().boo() == "C")
768 verify(G.__mro__ == (G, E, D, C, B, A, object))
769
Guido van Rossum37202612001-08-09 19:45:21 +0000770def objects():
771 if verbose: print "Testing object class..."
772 a = object()
773 verify(a.__class__ == object == type(a))
774 b = object()
775 verify(a is not b)
776 verify(not hasattr(a, "foo"))
777 try:
778 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000779 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000780 pass
781 else:
782 verify(0, "object() should not allow setting a foo attribute")
783 verify(not hasattr(object(), "__dict__"))
784
785 class Cdict(object):
786 pass
787 x = Cdict()
Guido van Rossum3926a632001-09-25 16:25:58 +0000788 verify(x.__dict__ == {})
Guido van Rossum37202612001-08-09 19:45:21 +0000789 x.foo = 1
790 verify(x.foo == 1)
791 verify(x.__dict__ == {'foo': 1})
792
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793def slots():
794 if verbose: print "Testing __slots__..."
795 class C0(object):
796 __slots__ = []
797 x = C0()
798 verify(not hasattr(x, "__dict__"))
799 verify(not hasattr(x, "foo"))
800
801 class C1(object):
802 __slots__ = ['a']
803 x = C1()
804 verify(not hasattr(x, "__dict__"))
805 verify(x.a == None)
806 x.a = 1
807 verify(x.a == 1)
808 del x.a
809 verify(x.a == None)
810
811 class C3(object):
812 __slots__ = ['a', 'b', 'c']
813 x = C3()
814 verify(not hasattr(x, "__dict__"))
815 verify(x.a is None)
816 verify(x.b is None)
817 verify(x.c is None)
818 x.a = 1
819 x.b = 2
820 x.c = 3
821 verify(x.a == 1)
822 verify(x.b == 2)
823 verify(x.c == 3)
824
825def dynamics():
826 if verbose: print "Testing __dynamic__..."
827 verify(object.__dynamic__ == 0)
828 verify(list.__dynamic__ == 0)
829 class S1:
830 __metaclass__ = type
831 verify(S1.__dynamic__ == 0)
832 class S(object):
833 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000834 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 class D(object):
836 __dynamic__ = 1
837 verify(D.__dynamic__ == 1)
838 class E(D, S):
839 pass
840 verify(E.__dynamic__ == 1)
841 class F(S, D):
842 pass
843 verify(F.__dynamic__ == 1)
844 try:
845 S.foo = 1
846 except (AttributeError, TypeError):
847 pass
848 else:
849 verify(0, "assignment to a static class attribute should be illegal")
850 D.foo = 1
851 verify(D.foo == 1)
852 # Test that dynamic attributes are inherited
853 verify(E.foo == 1)
854 verify(F.foo == 1)
855 class SS(D):
856 __dynamic__ = 0
857 verify(SS.__dynamic__ == 0)
858 verify(SS.foo == 1)
859 try:
860 SS.foo = 1
861 except (AttributeError, TypeError):
862 pass
863 else:
864 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000865 # Test dynamic instances
866 class C(object):
867 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000868 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000869 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000870 C.foobar = 2
871 verify(a.foobar == 2)
872 C.method = lambda self: 42
873 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000874 C.__repr__ = lambda self: "C()"
875 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000876 C.__int__ = lambda self: 100
877 verify(int(a) == 100)
878 verify(a.foobar == 2)
879 verify(not hasattr(a, "spam"))
880 def mygetattr(self, name):
881 if name == "spam":
882 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +0000883 raise AttributeError
884 C.__getattr__ = mygetattr
Guido van Rossumd3077402001-08-12 05:24:18 +0000885 verify(a.spam == "spam")
886 a.new = 12
887 verify(a.new == 12)
888 def mysetattr(self, name, value):
889 if name == "spam":
890 raise AttributeError
891 return object.__setattr__(self, name, value)
892 C.__setattr__ = mysetattr
893 try:
894 a.spam = "not spam"
895 except AttributeError:
896 pass
897 else:
898 verify(0, "expected AttributeError")
899 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000900 class D(C):
901 pass
902 d = D()
903 d.foo = 1
904 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000905
Guido van Rossum7e35d572001-09-15 03:14:32 +0000906 # Test handling of int*seq and seq*int
907 class I(int):
908 __dynamic__ = 1
909 verify("a"*I(2) == "aa")
910 verify(I(2)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000911 verify(2*I(3) == 6)
912 verify(I(3)*2 == 6)
913 verify(I(3)*I(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000914
915 # Test handling of long*seq and seq*long
916 class L(long):
917 __dynamic__ = 1
918 verify("a"*L(2L) == "aa")
919 verify(L(2L)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000920 verify(2*L(3) == 6)
921 verify(L(3)*2 == 6)
922 verify(L(3)*L(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000923
Guido van Rossum3d45d8f2001-09-24 18:47:40 +0000924 # Test comparison of classes with dynamic metaclasses
925 class dynamicmetaclass(type):
926 __dynamic__ = 1
927 class someclass:
928 __metaclass__ = dynamicmetaclass
929 verify(someclass != object)
930
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931def errors():
932 if verbose: print "Testing errors..."
933
934 try:
935 class C(list, dictionary):
936 pass
937 except TypeError:
938 pass
939 else:
940 verify(0, "inheritance from both list and dict should be illegal")
941
942 try:
943 class C(object, None):
944 pass
945 except TypeError:
946 pass
947 else:
948 verify(0, "inheritance from non-type should be illegal")
949 class Classic:
950 pass
951
952 try:
953 class C(object, Classic):
954 pass
955 except TypeError:
956 pass
957 else:
958 verify(0, "inheritance from object and Classic should be illegal")
959
960 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000961 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000962 pass
963 except TypeError:
964 pass
965 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000966 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000967
968 try:
969 class C(object):
970 __slots__ = 1
971 except TypeError:
972 pass
973 else:
974 verify(0, "__slots__ = 1 should be illegal")
975
976 try:
977 class C(object):
978 __slots__ = [1]
979 except TypeError:
980 pass
981 else:
982 verify(0, "__slots__ = [1] should be illegal")
983
984def classmethods():
985 if verbose: print "Testing class methods..."
986 class C(object):
987 def foo(*a): return a
988 goo = classmethod(foo)
989 c = C()
990 verify(C.goo(1) == (C, 1))
991 verify(c.goo(1) == (C, 1))
992 verify(c.foo(1) == (c, 1))
993 class D(C):
994 pass
995 d = D()
996 verify(D.goo(1) == (D, 1))
997 verify(d.goo(1) == (D, 1))
998 verify(d.foo(1) == (d, 1))
999 verify(D.foo(d, 1) == (d, 1))
1000
1001def staticmethods():
1002 if verbose: print "Testing static methods..."
1003 class C(object):
1004 def foo(*a): return a
1005 goo = staticmethod(foo)
1006 c = C()
1007 verify(C.goo(1) == (1,))
1008 verify(c.goo(1) == (1,))
1009 verify(c.foo(1) == (c, 1,))
1010 class D(C):
1011 pass
1012 d = D()
1013 verify(D.goo(1) == (1,))
1014 verify(d.goo(1) == (1,))
1015 verify(d.foo(1) == (d, 1))
1016 verify(D.foo(d, 1) == (d, 1))
1017
1018def classic():
1019 if verbose: print "Testing classic classes..."
1020 class C:
1021 def foo(*a): return a
1022 goo = classmethod(foo)
1023 c = C()
1024 verify(C.goo(1) == (C, 1))
1025 verify(c.goo(1) == (C, 1))
1026 verify(c.foo(1) == (c, 1))
1027 class D(C):
1028 pass
1029 d = D()
1030 verify(D.goo(1) == (D, 1))
1031 verify(d.goo(1) == (D, 1))
1032 verify(d.foo(1) == (d, 1))
1033 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001034 class E: # *not* subclassing from C
1035 foo = C.foo
1036 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001037 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038
1039def compattr():
1040 if verbose: print "Testing computed attributes..."
1041 class C(object):
1042 class computed_attribute(object):
1043 def __init__(self, get, set=None):
1044 self.__get = get
1045 self.__set = set
1046 def __get__(self, obj, type=None):
1047 return self.__get(obj)
1048 def __set__(self, obj, value):
1049 return self.__set(obj, value)
1050 def __init__(self):
1051 self.__x = 0
1052 def __get_x(self):
1053 x = self.__x
1054 self.__x = x+1
1055 return x
1056 def __set_x(self, x):
1057 self.__x = x
1058 x = computed_attribute(__get_x, __set_x)
1059 a = C()
1060 verify(a.x == 0)
1061 verify(a.x == 1)
1062 a.x = 10
1063 verify(a.x == 10)
1064 verify(a.x == 11)
1065
1066def newslot():
1067 if verbose: print "Testing __new__ slot override..."
1068 class C(list):
1069 def __new__(cls):
1070 self = list.__new__(cls)
1071 self.foo = 1
1072 return self
1073 def __init__(self):
1074 self.foo = self.foo + 2
1075 a = C()
1076 verify(a.foo == 3)
1077 verify(a.__class__ is C)
1078 class D(C):
1079 pass
1080 b = D()
1081 verify(b.foo == 3)
1082 verify(b.__class__ is D)
1083
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084def altmro():
1085 if verbose: print "Testing mro() and overriding it..."
1086 class A(object):
1087 def f(self): return "A"
1088 class B(A):
1089 pass
1090 class C(A):
1091 def f(self): return "C"
1092 class D(B, C):
1093 pass
1094 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1095 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001096 class PerverseMetaType(type):
1097 def mro(cls):
1098 L = type.mro(cls)
1099 L.reverse()
1100 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 class X(A,B,C,D):
1102 __metaclass__ = PerverseMetaType
1103 verify(X.__mro__ == (object, A, C, B, D, X))
1104 verify(X().f() == "A")
1105
1106def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001107 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108
1109 class B(object):
1110 "Intermediate class because object doesn't have a __setattr__"
1111
1112 class C(B):
1113
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001114 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 if name == "foo":
1116 return ("getattr", name)
1117 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001118 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 def __setattr__(self, name, value):
1120 if name == "foo":
1121 self.setattr = (name, value)
1122 else:
1123 return B.__setattr__(self, name, value)
1124 def __delattr__(self, name):
1125 if name == "foo":
1126 self.delattr = name
1127 else:
1128 return B.__delattr__(self, name)
1129
1130 def __getitem__(self, key):
1131 return ("getitem", key)
1132 def __setitem__(self, key, value):
1133 self.setitem = (key, value)
1134 def __delitem__(self, key):
1135 self.delitem = key
1136
1137 def __getslice__(self, i, j):
1138 return ("getslice", i, j)
1139 def __setslice__(self, i, j, value):
1140 self.setslice = (i, j, value)
1141 def __delslice__(self, i, j):
1142 self.delslice = (i, j)
1143
1144 a = C()
1145 verify(a.foo == ("getattr", "foo"))
1146 a.foo = 12
1147 verify(a.setattr == ("foo", 12))
1148 del a.foo
1149 verify(a.delattr == "foo")
1150
1151 verify(a[12] == ("getitem", 12))
1152 a[12] = 21
1153 verify(a.setitem == (12, 21))
1154 del a[12]
1155 verify(a.delitem == 12)
1156
1157 verify(a[0:10] == ("getslice", 0, 10))
1158 a[0:10] = "foo"
1159 verify(a.setslice == (0, 10, "foo"))
1160 del a[0:10]
1161 verify(a.delslice == (0, 10))
1162
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001163def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001164 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001165 class C(object):
1166 def __init__(self, x):
1167 self.x = x
1168 def foo(self):
1169 return self.x
1170 c1 = C(1)
1171 verify(c1.foo() == 1)
1172 class D(C):
1173 boo = C.foo
1174 goo = c1.foo
1175 d2 = D(2)
1176 verify(d2.foo() == 2)
1177 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001178 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001179 class E(object):
1180 foo = C.foo
1181 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001182 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001183
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001184def specials():
1185 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001186 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001187 # Test the default behavior for static classes
1188 class C(object):
1189 def __getitem__(self, i):
1190 if 0 <= i < 10: return i
1191 raise IndexError
1192 c1 = C()
1193 c2 = C()
1194 verify(not not c1)
1195 verify(hash(c1) == id(c1))
1196 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1197 verify(c1 == c1)
1198 verify(c1 != c2)
1199 verify(not c1 != c1)
1200 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001201 # Note that the module name appears in str/repr, and that varies
1202 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001203 verify(str(c1).find('C object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001204 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001205 verify(-1 not in c1)
1206 for i in range(10):
1207 verify(i in c1)
1208 verify(10 not in c1)
1209 # Test the default behavior for dynamic classes
1210 class D(object):
1211 __dynamic__ = 1
1212 def __getitem__(self, i):
1213 if 0 <= i < 10: return i
1214 raise IndexError
1215 d1 = D()
1216 d2 = D()
1217 verify(not not d1)
1218 verify(hash(d1) == id(d1))
1219 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1220 verify(d1 == d1)
1221 verify(d1 != d2)
1222 verify(not d1 != d1)
1223 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001224 # Note that the module name appears in str/repr, and that varies
1225 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001226 verify(str(d1).find('D object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001227 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001228 verify(-1 not in d1)
1229 for i in range(10):
1230 verify(i in d1)
1231 verify(10 not in d1)
1232 # Test overridden behavior for static classes
1233 class Proxy(object):
1234 def __init__(self, x):
1235 self.x = x
1236 def __nonzero__(self):
1237 return not not self.x
1238 def __hash__(self):
1239 return hash(self.x)
1240 def __eq__(self, other):
1241 return self.x == other
1242 def __ne__(self, other):
1243 return self.x != other
1244 def __cmp__(self, other):
1245 return cmp(self.x, other.x)
1246 def __str__(self):
1247 return "Proxy:%s" % self.x
1248 def __repr__(self):
1249 return "Proxy(%r)" % self.x
1250 def __contains__(self, value):
1251 return value in self.x
1252 p0 = Proxy(0)
1253 p1 = Proxy(1)
1254 p_1 = Proxy(-1)
1255 verify(not p0)
1256 verify(not not p1)
1257 verify(hash(p0) == hash(0))
1258 verify(p0 == p0)
1259 verify(p0 != p1)
1260 verify(not p0 != p0)
1261 verify(not p0 == p1)
1262 verify(cmp(p0, p1) == -1)
1263 verify(cmp(p0, p0) == 0)
1264 verify(cmp(p0, p_1) == 1)
1265 verify(str(p0) == "Proxy:0")
1266 verify(repr(p0) == "Proxy(0)")
1267 p10 = Proxy(range(10))
1268 verify(-1 not in p10)
1269 for i in range(10):
1270 verify(i in p10)
1271 verify(10 not in p10)
1272 # Test overridden behavior for dynamic classes
1273 class DProxy(object):
1274 __dynamic__ = 1
1275 def __init__(self, x):
1276 self.x = x
1277 def __nonzero__(self):
1278 return not not self.x
1279 def __hash__(self):
1280 return hash(self.x)
1281 def __eq__(self, other):
1282 return self.x == other
1283 def __ne__(self, other):
1284 return self.x != other
1285 def __cmp__(self, other):
1286 return cmp(self.x, other.x)
1287 def __str__(self):
1288 return "DProxy:%s" % self.x
1289 def __repr__(self):
1290 return "DProxy(%r)" % self.x
1291 def __contains__(self, value):
1292 return value in self.x
1293 p0 = DProxy(0)
1294 p1 = DProxy(1)
1295 p_1 = DProxy(-1)
1296 verify(not p0)
1297 verify(not not p1)
1298 verify(hash(p0) == hash(0))
1299 verify(p0 == p0)
1300 verify(p0 != p1)
1301 verify(not p0 != p0)
1302 verify(not p0 == p1)
1303 verify(cmp(p0, p1) == -1)
1304 verify(cmp(p0, p0) == 0)
1305 verify(cmp(p0, p_1) == 1)
1306 verify(str(p0) == "DProxy:0")
1307 verify(repr(p0) == "DProxy(0)")
1308 p10 = DProxy(range(10))
1309 verify(-1 not in p10)
1310 for i in range(10):
1311 verify(i in p10)
1312 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001313 # Safety test for __cmp__
1314 def unsafecmp(a, b):
1315 try:
1316 a.__class__.__cmp__(a, b)
1317 except TypeError:
1318 pass
1319 else:
1320 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1321 a.__class__, a, b)
1322 unsafecmp(u"123", "123")
1323 unsafecmp("123", u"123")
1324 unsafecmp(1, 1.0)
1325 unsafecmp(1.0, 1)
1326 unsafecmp(1, 1L)
1327 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001328
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001329def weakrefs():
1330 if verbose: print "Testing weak references..."
1331 import weakref
1332 class C(object):
1333 pass
1334 c = C()
1335 r = weakref.ref(c)
1336 verify(r() is c)
1337 del c
1338 verify(r() is None)
1339 del r
1340 class NoWeak(object):
1341 __slots__ = ['foo']
1342 no = NoWeak()
1343 try:
1344 weakref.ref(no)
1345 except TypeError, msg:
1346 verify(str(msg).find("weakly") >= 0)
1347 else:
1348 verify(0, "weakref.ref(no) should be illegal")
1349 class Weak(object):
1350 __slots__ = ['foo', '__weakref__']
1351 yes = Weak()
1352 r = weakref.ref(yes)
1353 verify(r() is yes)
1354 del yes
1355 verify(r() is None)
1356 del r
1357
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001358def properties():
1359 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001360 class C(object):
1361 def getx(self):
1362 return self.__x
1363 def setx(self, value):
1364 self.__x = value
1365 def delx(self):
1366 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001367 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001368 a = C()
1369 verify(not hasattr(a, "x"))
1370 a.x = 42
1371 verify(a._C__x == 42)
1372 verify(a.x == 42)
1373 del a.x
1374 verify(not hasattr(a, "x"))
1375 verify(not hasattr(a, "_C__x"))
1376 C.x.__set__(a, 100)
1377 verify(C.x.__get__(a) == 100)
1378## C.x.__set__(a)
1379## verify(not hasattr(a, "x"))
1380
Tim Peters66c1a522001-09-24 21:17:50 +00001381 raw = C.__dict__['x']
1382 verify(isinstance(raw, property))
1383
1384 attrs = dir(raw)
1385 verify("__doc__" in attrs)
1386 verify("fget" in attrs)
1387 verify("fset" in attrs)
1388 verify("fdel" in attrs)
1389
1390 verify(raw.__doc__ == "I'm the x property.")
1391 verify(raw.fget is C.__dict__['getx'])
1392 verify(raw.fset is C.__dict__['setx'])
1393 verify(raw.fdel is C.__dict__['delx'])
1394
1395 for attr in "__doc__", "fget", "fset", "fdel":
1396 try:
1397 setattr(raw, attr, 42)
1398 except TypeError, msg:
1399 if str(msg).find('readonly') < 0:
1400 raise TestFailed("when setting readonly attr %r on a "
1401 "property, got unexpected TypeError "
1402 "msg %r" % (attr, str(msg)))
1403 else:
1404 raise TestFailed("expected TypeError from trying to set "
1405 "readonly %r attr on a property" % attr)
1406
Guido van Rossumc4a18802001-08-24 16:55:27 +00001407def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001408 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001409
1410 class A(object):
1411 def meth(self, a):
1412 return "A(%r)" % a
1413
1414 verify(A().meth(1) == "A(1)")
1415
1416 class B(A):
1417 def __init__(self):
1418 self.__super = super(B, self)
1419 def meth(self, a):
1420 return "B(%r)" % a + self.__super.meth(a)
1421
1422 verify(B().meth(2) == "B(2)A(2)")
1423
1424 class C(A):
1425 __dynamic__ = 1
1426 def meth(self, a):
1427 return "C(%r)" % a + self.__super.meth(a)
1428 C._C__super = super(C)
1429
1430 verify(C().meth(3) == "C(3)A(3)")
1431
1432 class D(C, B):
1433 def meth(self, a):
1434 return "D(%r)" % a + super(D, self).meth(a)
1435
1436 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1437
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001438def inherits():
1439 if verbose: print "Testing inheritance from basic types..."
1440
1441 class hexint(int):
1442 def __repr__(self):
1443 return hex(self)
1444 def __add__(self, other):
1445 return hexint(int.__add__(self, other))
1446 # (Note that overriding __radd__ doesn't work,
1447 # because the int type gets first dibs.)
1448 verify(repr(hexint(7) + 9) == "0x10")
1449 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001450 a = hexint(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001451 verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001452 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001453 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001454 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001455 verify((+a).__class__ is int)
1456 verify((a >> 0).__class__ is int)
1457 verify((a << 0).__class__ is int)
1458 verify((hexint(0) << 12).__class__ is int)
1459 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001460
1461 class octlong(long):
1462 __slots__ = []
1463 def __str__(self):
1464 s = oct(self)
1465 if s[-1] == 'L':
1466 s = s[:-1]
1467 return s
1468 def __add__(self, other):
1469 return self.__class__(super(octlong, self).__add__(other))
1470 __radd__ = __add__
1471 verify(str(octlong(3) + 5) == "010")
1472 # (Note that overriding __radd__ here only seems to work
1473 # because the example uses a short int left argument.)
1474 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001475 a = octlong(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001476 verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001477 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001478 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001479 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001480 verify((+a).__class__ is long)
1481 verify((-a).__class__ is long)
1482 verify((-octlong(0)).__class__ is long)
1483 verify((a >> 0).__class__ is long)
1484 verify((a << 0).__class__ is long)
1485 verify((a - 0).__class__ is long)
1486 verify((a * 1).__class__ is long)
1487 verify((a ** 1).__class__ is long)
1488 verify((a // 1).__class__ is long)
1489 verify((1 * a).__class__ is long)
1490 verify((a | 0).__class__ is long)
1491 verify((a ^ 0).__class__ is long)
1492 verify((a & -1L).__class__ is long)
1493 verify((octlong(0) << 12).__class__ is long)
1494 verify((octlong(0) >> 12).__class__ is long)
1495 verify(abs(octlong(0)).__class__ is long)
1496
1497 # Because octlong overrides __add__, we can't check the absence of +0
1498 # optimizations using octlong.
1499 class longclone(long):
1500 pass
1501 a = longclone(1)
1502 verify((a + 0).__class__ is long)
1503 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001504
1505 class precfloat(float):
1506 __slots__ = ['prec']
1507 def __init__(self, value=0.0, prec=12):
1508 self.prec = int(prec)
1509 float.__init__(value)
1510 def __repr__(self):
1511 return "%.*g" % (self.prec, self)
1512 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001513 a = precfloat(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001514 verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001515 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001516 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001517 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001518 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001519
Tim Peters2400fa42001-09-12 19:12:49 +00001520 class madcomplex(complex):
1521 def __repr__(self):
1522 return "%.17gj%+.17g" % (self.imag, self.real)
1523 a = madcomplex(-3, 4)
1524 verify(repr(a) == "4j-3")
1525 base = complex(-3, 4)
1526 verify(base.__class__ is complex)
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001527 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001528 verify(complex(a) == base)
1529 verify(complex(a).__class__ is complex)
1530 a = madcomplex(a) # just trying another form of the constructor
1531 verify(repr(a) == "4j-3")
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001532 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001533 verify(complex(a) == base)
1534 verify(complex(a).__class__ is complex)
1535 verify(hash(a) == hash(base))
1536 verify((+a).__class__ is complex)
1537 verify((a + 0).__class__ is complex)
1538 verify(a + 0 == base)
1539 verify((a - 0).__class__ is complex)
1540 verify(a - 0 == base)
1541 verify((a * 1).__class__ is complex)
1542 verify(a * 1 == base)
1543 verify((a / 1).__class__ is complex)
1544 verify(a / 1 == base)
1545
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001546 class madtuple(tuple):
1547 _rev = None
1548 def rev(self):
1549 if self._rev is not None:
1550 return self._rev
1551 L = list(self)
1552 L.reverse()
1553 self._rev = self.__class__(L)
1554 return self._rev
1555 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001556 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001557 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1558 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1559 for i in range(512):
1560 t = madtuple(range(i))
1561 u = t.rev()
1562 v = u.rev()
1563 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001564 a = madtuple((1,2,3,4,5))
1565 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001566 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001567 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001568 verify(a[:].__class__ is tuple)
1569 verify((a * 1).__class__ is tuple)
1570 verify((a * 0).__class__ is tuple)
1571 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001572 a = madtuple(())
1573 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001574 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001575 verify((a + a).__class__ is tuple)
1576 verify((a * 0).__class__ is tuple)
1577 verify((a * 1).__class__ is tuple)
1578 verify((a * 2).__class__ is tuple)
1579 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001580
1581 class madstring(str):
1582 _rev = None
1583 def rev(self):
1584 if self._rev is not None:
1585 return self._rev
1586 L = list(self)
1587 L.reverse()
1588 self._rev = self.__class__("".join(L))
1589 return self._rev
1590 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001591 verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001592 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1593 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1594 for i in range(256):
1595 s = madstring("".join(map(chr, range(i))))
1596 t = s.rev()
1597 u = t.rev()
1598 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001599 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001600 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001601 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001602
Tim Peters8fa5dd02001-09-12 02:18:30 +00001603 base = "\x00" * 5
1604 s = madstring(base)
Guido van Rossumbb77e682001-09-24 16:51:54 +00001605 verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001606 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001607 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001608 verify(hash(s) == hash(base))
Guido van Rossumbb77e682001-09-24 16:51:54 +00001609 verify({s: 1}[base] == 1)
1610 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001611 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001612 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001613 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001614 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001615 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001616 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001617 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001618 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001619 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001620 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001621 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001622 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001623 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001624 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001625 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001626 verify(s.strip() == base)
1627 verify(s.lstrip().__class__ is str)
1628 verify(s.lstrip() == base)
1629 verify(s.rstrip().__class__ is str)
1630 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001631 identitytab = ''.join([chr(i) for i in range(256)])
1632 verify(s.translate(identitytab).__class__ is str)
1633 verify(s.translate(identitytab) == base)
1634 verify(s.translate(identitytab, "x").__class__ is str)
1635 verify(s.translate(identitytab, "x") == base)
1636 verify(s.translate(identitytab, "\x00") == "")
1637 verify(s.replace("x", "x").__class__ is str)
1638 verify(s.replace("x", "x") == base)
1639 verify(s.ljust(len(s)).__class__ is str)
1640 verify(s.ljust(len(s)) == base)
1641 verify(s.rjust(len(s)).__class__ is str)
1642 verify(s.rjust(len(s)) == base)
1643 verify(s.center(len(s)).__class__ is str)
1644 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001645 verify(s.lower().__class__ is str)
1646 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001647
Tim Peters111f6092001-09-12 07:54:51 +00001648 s = madstring("x y")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001649 verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001650 verify(intern(s).__class__ is str)
1651 verify(intern(s) is intern("x y"))
1652 verify(intern(s) == "x y")
1653
1654 i = intern("y x")
1655 s = madstring("y x")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001656 verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001657 verify(intern(s).__class__ is str)
1658 verify(intern(s) is i)
1659
1660 s = madstring(i)
1661 verify(intern(s).__class__ is str)
1662 verify(intern(s) is i)
1663
Guido van Rossum91ee7982001-08-30 20:52:40 +00001664 class madunicode(unicode):
1665 _rev = None
1666 def rev(self):
1667 if self._rev is not None:
1668 return self._rev
1669 L = list(self)
1670 L.reverse()
1671 self._rev = self.__class__(u"".join(L))
1672 return self._rev
1673 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001674 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001675 verify(u.rev() == madunicode(u"FEDCBA"))
1676 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001677 base = u"12345"
1678 u = madunicode(base)
1679 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001680 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001681 verify(hash(u) == hash(base))
1682 verify({u: 1}[base] == 1)
1683 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001684 verify(u.strip().__class__ is unicode)
1685 verify(u.strip() == base)
1686 verify(u.lstrip().__class__ is unicode)
1687 verify(u.lstrip() == base)
1688 verify(u.rstrip().__class__ is unicode)
1689 verify(u.rstrip() == base)
1690 verify(u.replace(u"x", u"x").__class__ is unicode)
1691 verify(u.replace(u"x", u"x") == base)
1692 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1693 verify(u.replace(u"xy", u"xy") == base)
1694 verify(u.center(len(u)).__class__ is unicode)
1695 verify(u.center(len(u)) == base)
1696 verify(u.ljust(len(u)).__class__ is unicode)
1697 verify(u.ljust(len(u)) == base)
1698 verify(u.rjust(len(u)).__class__ is unicode)
1699 verify(u.rjust(len(u)) == base)
1700 verify(u.lower().__class__ is unicode)
1701 verify(u.lower() == base)
1702 verify(u.upper().__class__ is unicode)
1703 verify(u.upper() == base)
1704 verify(u.capitalize().__class__ is unicode)
1705 verify(u.capitalize() == base)
1706 verify(u.title().__class__ is unicode)
1707 verify(u.title() == base)
1708 verify((u + u"").__class__ is unicode)
1709 verify(u + u"" == base)
1710 verify((u"" + u).__class__ is unicode)
1711 verify(u"" + u == base)
1712 verify((u * 0).__class__ is unicode)
1713 verify(u * 0 == u"")
1714 verify((u * 1).__class__ is unicode)
1715 verify(u * 1 == base)
1716 verify((u * 2).__class__ is unicode)
1717 verify(u * 2 == base + base)
1718 verify(u[:].__class__ is unicode)
1719 verify(u[:] == base)
1720 verify(u[0:0].__class__ is unicode)
1721 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001722
Tim Peters59c9a642001-09-13 05:38:56 +00001723 class CountedInput(file):
1724 """Counts lines read by self.readline().
1725
1726 self.lineno is the 0-based ordinal of the last line read, up to
1727 a maximum of one greater than the number of lines in the file.
1728
1729 self.ateof is true if and only if the final "" line has been read,
1730 at which point self.lineno stops incrementing, and further calls
1731 to readline() continue to return "".
1732 """
1733
1734 lineno = 0
1735 ateof = 0
1736 def readline(self):
1737 if self.ateof:
1738 return ""
1739 s = file.readline(self)
1740 # Next line works too.
1741 # s = super(CountedInput, self).readline()
1742 self.lineno += 1
1743 if s == "":
1744 self.ateof = 1
1745 return s
1746
Tim Peters561f8992001-09-13 19:36:36 +00001747 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00001748 lines = ['a\n', 'b\n', 'c\n']
1749 try:
1750 f.writelines(lines)
1751 f.close()
1752 f = CountedInput(TESTFN)
1753 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1754 got = f.readline()
1755 verify(expected == got)
1756 verify(f.lineno == i)
1757 verify(f.ateof == (i > len(lines)))
1758 f.close()
1759 finally:
1760 try:
1761 f.close()
1762 except:
1763 pass
1764 try:
1765 import os
1766 os.unlink(TESTFN)
1767 except:
1768 pass
1769
Tim Peters808b94e2001-09-13 19:33:07 +00001770def keywords():
1771 if verbose:
1772 print "Testing keyword args to basic type constructors ..."
1773 verify(int(x=1) == 1)
1774 verify(float(x=2) == 2.0)
1775 verify(long(x=3) == 3L)
1776 verify(complex(imag=42, real=666) == complex(666, 42))
1777 verify(str(object=500) == '500')
1778 verify(unicode(string='abc', errors='strict') == u'abc')
1779 verify(tuple(sequence=range(3)) == (0, 1, 2))
1780 verify(list(sequence=(0, 1, 2)) == range(3))
1781 verify(dictionary(mapping={1: 2}) == {1: 2})
1782
1783 for constructor in (int, float, long, complex, str, unicode,
1784 tuple, list, dictionary, file):
1785 try:
1786 constructor(bogus_keyword_arg=1)
1787 except TypeError:
1788 pass
1789 else:
1790 raise TestFailed("expected TypeError from bogus keyword "
1791 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00001792
Tim Peters8fa45672001-09-13 21:01:29 +00001793def restricted():
1794 import rexec
1795 if verbose:
1796 print "Testing interaction with restricted execution ..."
1797
1798 sandbox = rexec.RExec()
1799
1800 code1 = """f = open(%r, 'w')""" % TESTFN
1801 code2 = """f = file(%r, 'w')""" % TESTFN
1802 code3 = """\
1803f = open(%r)
1804t = type(f) # a sneaky way to get the file() constructor
1805f.close()
1806f = t(%r, 'w') # rexec can't catch this by itself
1807""" % (TESTFN, TESTFN)
1808
1809 f = open(TESTFN, 'w') # Create the file so code3 can find it.
1810 f.close()
1811
1812 try:
1813 for code in code1, code2, code3:
1814 try:
1815 sandbox.r_exec(code)
1816 except IOError, msg:
1817 if str(msg).find("restricted") >= 0:
1818 outcome = "OK"
1819 else:
1820 outcome = "got an exception, but not an expected one"
1821 else:
1822 outcome = "expected a restricted-execution exception"
1823
1824 if outcome != "OK":
1825 raise TestFailed("%s, in %r" % (outcome, code))
1826
1827 finally:
1828 try:
1829 import os
1830 os.unlink(TESTFN)
1831 except:
1832 pass
1833
Tim Peters0ab085c2001-09-14 00:25:33 +00001834def str_subclass_as_dict_key():
1835 if verbose:
1836 print "Testing a str subclass used as dict key .."
1837
1838 class cistr(str):
1839 """Sublcass of str that computes __eq__ case-insensitively.
1840
1841 Also computes a hash code of the string in canonical form.
1842 """
1843
1844 def __init__(self, value):
1845 self.canonical = value.lower()
1846 self.hashcode = hash(self.canonical)
1847
1848 def __eq__(self, other):
1849 if not isinstance(other, cistr):
1850 other = cistr(other)
1851 return self.canonical == other.canonical
1852
1853 def __hash__(self):
1854 return self.hashcode
1855
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001856 verify(cistr('ABC') == 'abc')
1857 verify('aBc' == cistr('ABC'))
Tim Peters0ab085c2001-09-14 00:25:33 +00001858 verify(str(cistr('ABC')) == 'ABC')
1859
1860 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
1861 verify(d[cistr('one')] == 1)
1862 verify(d[cistr('tWo')] == 2)
1863 verify(d[cistr('THrEE')] == 3)
1864 verify(cistr('ONe') in d)
1865 verify(d.get(cistr('thrEE')) == 3)
1866
Guido van Rossumab3b0342001-09-18 20:38:53 +00001867def classic_comparisons():
1868 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00001869 class classic:
1870 pass
1871 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00001872 if verbose: print " (base = %s)" % base
1873 class C(base):
1874 def __init__(self, value):
1875 self.value = int(value)
1876 def __cmp__(self, other):
1877 if isinstance(other, C):
1878 return cmp(self.value, other.value)
1879 if isinstance(other, int) or isinstance(other, long):
1880 return cmp(self.value, other)
1881 return NotImplemented
1882 c1 = C(1)
1883 c2 = C(2)
1884 c3 = C(3)
1885 verify(c1 == 1)
1886 c = {1: c1, 2: c2, 3: c3}
1887 for x in 1, 2, 3:
1888 for y in 1, 2, 3:
1889 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1890 for op in "<", "<=", "==", "!=", ">", ">=":
1891 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1892 "x=%d, y=%d" % (x, y))
1893 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
1894 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1895
Guido van Rossum0639f592001-09-18 21:06:04 +00001896def rich_comparisons():
1897 if verbose:
1898 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00001899 class Z(complex):
1900 pass
1901 z = Z(1)
1902 verify(z == 1+0j)
1903 verify(1+0j == z)
1904 class ZZ(complex):
1905 def __eq__(self, other):
1906 try:
1907 return abs(self - other) <= 1e-6
1908 except:
1909 return NotImplemented
1910 zz = ZZ(1.0000003)
1911 verify(zz == 1+0j)
1912 verify(1+0j == zz)
Tim Peters66c1a522001-09-24 21:17:50 +00001913
Guido van Rossum0639f592001-09-18 21:06:04 +00001914 class classic:
1915 pass
1916 for base in (classic, int, object, list):
1917 if verbose: print " (base = %s)" % base
1918 class C(base):
1919 def __init__(self, value):
1920 self.value = int(value)
1921 def __cmp__(self, other):
1922 raise TestFailed, "shouldn't call __cmp__"
1923 def __eq__(self, other):
1924 if isinstance(other, C):
1925 return self.value == other.value
1926 if isinstance(other, int) or isinstance(other, long):
1927 return self.value == other
1928 return NotImplemented
1929 def __ne__(self, other):
1930 if isinstance(other, C):
1931 return self.value != other.value
1932 if isinstance(other, int) or isinstance(other, long):
1933 return self.value != other
1934 return NotImplemented
1935 def __lt__(self, other):
1936 if isinstance(other, C):
1937 return self.value < other.value
1938 if isinstance(other, int) or isinstance(other, long):
1939 return self.value < other
1940 return NotImplemented
1941 def __le__(self, other):
1942 if isinstance(other, C):
1943 return self.value <= other.value
1944 if isinstance(other, int) or isinstance(other, long):
1945 return self.value <= other
1946 return NotImplemented
1947 def __gt__(self, other):
1948 if isinstance(other, C):
1949 return self.value > other.value
1950 if isinstance(other, int) or isinstance(other, long):
1951 return self.value > other
1952 return NotImplemented
1953 def __ge__(self, other):
1954 if isinstance(other, C):
1955 return self.value >= other.value
1956 if isinstance(other, int) or isinstance(other, long):
1957 return self.value >= other
1958 return NotImplemented
1959 c1 = C(1)
1960 c2 = C(2)
1961 c3 = C(3)
1962 verify(c1 == 1)
1963 c = {1: c1, 2: c2, 3: c3}
1964 for x in 1, 2, 3:
1965 for y in 1, 2, 3:
1966 for op in "<", "<=", "==", "!=", ">", ">=":
1967 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1968 "x=%d, y=%d" % (x, y))
1969 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
1970 "x=%d, y=%d" % (x, y))
1971 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
1972 "x=%d, y=%d" % (x, y))
1973
Guido van Rossum1952e382001-09-19 01:25:16 +00001974def coercions():
1975 if verbose: print "Testing coercions..."
1976 class I(int): pass
1977 coerce(I(0), 0)
1978 coerce(0, I(0))
1979 class L(long): pass
1980 coerce(L(0), 0)
1981 coerce(L(0), 0L)
1982 coerce(0, L(0))
1983 coerce(0L, L(0))
1984 class F(float): pass
1985 coerce(F(0), 0)
1986 coerce(F(0), 0L)
1987 coerce(F(0), 0.)
1988 coerce(0, F(0))
1989 coerce(0L, F(0))
1990 coerce(0., F(0))
1991 class C(complex): pass
1992 coerce(C(0), 0)
1993 coerce(C(0), 0L)
1994 coerce(C(0), 0.)
1995 coerce(C(0), 0j)
1996 coerce(0, C(0))
1997 coerce(0L, C(0))
1998 coerce(0., C(0))
1999 coerce(0j, C(0))
2000
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002001def descrdoc():
2002 if verbose: print "Testing descriptor doc strings..."
2003 def check(descr, what):
2004 verify(descr.__doc__ == what, repr(descr.__doc__))
2005 check(file.closed, "flag set if the file is closed") # getset descriptor
2006 check(file.name, "file name") # member descriptor
2007
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002008def setclass():
2009 if verbose: print "Testing __class__ assignment..."
2010 class C(object): pass
2011 class D(object): pass
2012 class E(object): pass
2013 class F(D, E): pass
2014 for cls in C, D, E, F:
2015 for cls2 in C, D, E, F:
2016 x = cls()
2017 x.__class__ = cls2
2018 verify(x.__class__ is cls2)
2019 x.__class__ = cls
2020 verify(x.__class__ is cls)
2021 def cant(x, C):
2022 try:
2023 x.__class__ = C
2024 except TypeError:
2025 pass
2026 else:
2027 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2028 cant(C(), list)
2029 cant(list(), C)
2030 cant(C(), 1)
2031 cant(C(), object)
2032 cant(object(), list)
2033 cant(list(), object)
2034
Guido van Rossum3926a632001-09-25 16:25:58 +00002035def pickles():
2036 if verbose: print "Testing pickling new-style classes and objects..."
2037 import pickle, cPickle
2038
2039 def sorteditems(d):
2040 L = d.items()
2041 L.sort()
2042 return L
2043
2044 global C
2045 class C(object):
2046 def __init__(self, a, b):
2047 super(C, self).__init__()
2048 self.a = a
2049 self.b = b
2050 def __repr__(self):
2051 return "C(%r, %r)" % (self.a, self.b)
2052
2053 global C1
2054 class C1(list):
2055 def __new__(cls, a, b):
2056 return super(C1, cls).__new__(cls)
2057 def __init__(self, a, b):
2058 self.a = a
2059 self.b = b
2060 def __repr__(self):
2061 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2062
2063 global C2
2064 class C2(int):
2065 def __new__(cls, a, b, val=0):
2066 return super(C2, cls).__new__(cls, val)
2067 def __init__(self, a, b, val=0):
2068 self.a = a
2069 self.b = b
2070 def __repr__(self):
2071 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2072
2073 for p in pickle, cPickle:
2074 for bin in 0, 1:
2075
2076 for cls in C, C1, C2:
2077 s = p.dumps(cls, bin)
2078 cls2 = p.loads(s)
2079 verify(cls2 is cls)
2080
2081 a = C1(1, 2); a.append(42); a.append(24)
2082 b = C2("hello", "world", 42)
2083 s = p.dumps((a, b), bin)
2084 x, y = p.loads(s)
2085 assert x.__class__ == a.__class__
2086 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2087 assert y.__class__ == b.__class__
2088 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2089 assert `x` == `a`
2090 assert `y` == `b`
2091 if verbose:
2092 print "a = x =", a
2093 print "b = y =", b
2094
Tim Peters0ab085c2001-09-14 00:25:33 +00002095
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002096def test_main():
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 lists()
2098 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00002099 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00002100 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 ints()
2102 longs()
2103 floats()
2104 complexes()
2105 spamlists()
2106 spamdicts()
2107 pydicts()
2108 pylists()
2109 metaclass()
2110 pymods()
2111 multi()
2112 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00002113 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 slots()
2115 dynamics()
2116 errors()
2117 classmethods()
2118 staticmethods()
2119 classic()
2120 compattr()
2121 newslot()
2122 altmro()
2123 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00002124 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00002125 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002126 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002127 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00002128 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002129 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00002130 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00002131 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00002132 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00002133 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00002134 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00002135 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002136 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002137 setclass()
Guido van Rossum3926a632001-09-25 16:25:58 +00002138 pickles()
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002139 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002141if __name__ == "__main__":
2142 test_main()