blob: 2e6748e34c9ddd984c60bb770c92015b1835639f [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)
193
194 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
195 verify(dir(c) == cstuff)
196
197 c.cdata = 2
198 c.cmethod = lambda self: 0
199 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
200
201 class A(C):
202 Adata = 1
203 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000204
Tim Peters37a309d2001-09-04 01:20:04 +0000205 astuff = ['Adata', 'Amethod'] + cstuff
206 verify(dir(A) == astuff)
207 a = A()
208 verify(dir(a) == astuff)
209 a.adata = 42
210 a.amethod = lambda self: 3
211 verify(dir(a) == astuff + ['adata', 'amethod'])
212
213 # The same, but with new-style classes. Since these have object as a
214 # base class, a lot more gets sucked in.
215 def interesting(strings):
216 return [s for s in strings if not s.startswith('_')]
217
Tim Peters5d2b77c2001-09-03 05:47:38 +0000218 class C(object):
219 Cdata = 1
220 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000221
222 cstuff = ['Cdata', 'Cmethod']
223 verify(interesting(dir(C)) == cstuff)
224
225 c = C()
226 verify(interesting(dir(c)) == cstuff)
227
228 c.cdata = 2
229 c.cmethod = lambda self: 0
230 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
231
Tim Peters5d2b77c2001-09-03 05:47:38 +0000232 class A(C):
233 Adata = 1
234 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000235
236 astuff = ['Adata', 'Amethod'] + cstuff
237 verify(interesting(dir(A)) == astuff)
238 a = A()
239 verify(interesting(dir(a)) == astuff)
240 a.adata = 42
241 a.amethod = lambda self: 3
242 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000243
Tim Peterscaaff8d2001-09-10 23:12:14 +0000244 # Try a module subclass.
245 import sys
246 class M(type(sys)):
247 pass
248 minstance = M()
249 minstance.b = 2
250 minstance.a = 1
251 verify(dir(minstance) == ['a', 'b'])
252
253 class M2(M):
254 def getdict(self):
255 return "Not a dict!"
256 __dict__ = property(getdict)
257
258 m2instance = M2()
259 m2instance.b = 2
260 m2instance.a = 1
261 verify(m2instance.__dict__ == "Not a dict!")
262 try:
263 dir(m2instance)
264 except TypeError:
265 pass
266
Tim Peters6d6c1a32001-08-02 04:15:00 +0000267binops = {
268 'add': '+',
269 'sub': '-',
270 'mul': '*',
271 'div': '/',
272 'mod': '%',
273 'divmod': 'divmod',
274 'pow': '**',
275 'lshift': '<<',
276 'rshift': '>>',
277 'and': '&',
278 'xor': '^',
279 'or': '|',
280 'cmp': 'cmp',
281 'lt': '<',
282 'le': '<=',
283 'eq': '==',
284 'ne': '!=',
285 'gt': '>',
286 'ge': '>=',
287 }
288
289for name, expr in binops.items():
290 if expr.islower():
291 expr = expr + "(a, b)"
292 else:
293 expr = 'a %s b' % expr
294 binops[name] = expr
295
296unops = {
297 'pos': '+',
298 'neg': '-',
299 'abs': 'abs',
300 'invert': '~',
301 'int': 'int',
302 'long': 'long',
303 'float': 'float',
304 'oct': 'oct',
305 'hex': 'hex',
306 }
307
308for name, expr in unops.items():
309 if expr.islower():
310 expr = expr + "(a)"
311 else:
312 expr = '%s a' % expr
313 unops[name] = expr
314
315def numops(a, b, skip=[]):
316 dict = {'a': a, 'b': b}
317 for name, expr in binops.items():
318 if name not in skip:
319 name = "__%s__" % name
320 if hasattr(a, name):
321 res = eval(expr, dict)
322 testbinop(a, b, res, expr, name)
323 for name, expr in unops.items():
324 name = "__%s__" % name
325 if hasattr(a, name):
326 res = eval(expr, dict)
327 testunop(a, res, expr, name)
328
329def ints():
330 if verbose: print "Testing int operations..."
331 numops(100, 3)
332
333def longs():
334 if verbose: print "Testing long operations..."
335 numops(100L, 3L)
336
337def floats():
338 if verbose: print "Testing float operations..."
339 numops(100.0, 3.0)
340
341def complexes():
342 if verbose: print "Testing complex operations..."
343 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
344 class Number(complex):
345 __slots__ = ['prec']
346 def __init__(self, *args, **kwds):
347 self.prec = kwds.get('prec', 12)
348 def __repr__(self):
349 prec = self.prec
350 if self.imag == 0.0:
351 return "%.*g" % (prec, self.real)
352 if self.real == 0.0:
353 return "%.*gj" % (prec, self.imag)
354 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
355 __str__ = __repr__
356 a = Number(3.14, prec=6)
357 verify(`a` == "3.14")
358 verify(a.prec == 6)
359
360def spamlists():
361 if verbose: print "Testing spamlist operations..."
362 import copy, xxsubtype as spam
363 def spamlist(l, memo=None):
364 import xxsubtype as spam
365 return spam.spamlist(l)
366 # This is an ugly hack:
367 copy._deepcopy_dispatch[spam.spamlist] = spamlist
368
369 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
370 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
371 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
372 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
373 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
374 "a[b:c]", "__getslice__")
375 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
376 "a+=b", "__iadd__")
377 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
378 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
379 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
380 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
381 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
382 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
383 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
384 # Test subclassing
385 class C(spam.spamlist):
386 def foo(self): return 1
387 a = C()
388 verify(a == [])
389 verify(a.foo() == 1)
390 a.append(100)
391 verify(a == [100])
392 verify(a.getstate() == 0)
393 a.setstate(42)
394 verify(a.getstate() == 42)
395
396def spamdicts():
397 if verbose: print "Testing spamdict operations..."
398 import copy, xxsubtype as spam
399 def spamdict(d, memo=None):
400 import xxsubtype as spam
401 sd = spam.spamdict()
402 for k, v in d.items(): sd[k] = v
403 return sd
404 # This is an ugly hack:
405 copy._deepcopy_dispatch[spam.spamdict] = spamdict
406
407 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
408 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
409 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
410 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
411 d = spamdict({1:2,3:4})
412 l1 = []
413 for i in d.keys(): l1.append(i)
414 l = []
415 for i in iter(d): l.append(i)
416 verify(l == l1)
417 l = []
418 for i in d.__iter__(): l.append(i)
419 verify(l == l1)
420 l = []
421 for i in type(spamdict({})).__iter__(d): l.append(i)
422 verify(l == l1)
423 straightd = {1:2, 3:4}
424 spamd = spamdict(straightd)
425 testunop(spamd, 2, "len(a)", "__len__")
426 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
427 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
428 "a[b]=c", "__setitem__")
429 # Test subclassing
430 class C(spam.spamdict):
431 def foo(self): return 1
432 a = C()
433 verify(a.items() == [])
434 verify(a.foo() == 1)
435 a['foo'] = 'bar'
436 verify(a.items() == [('foo', 'bar')])
437 verify(a.getstate() == 0)
438 a.setstate(100)
439 verify(a.getstate() == 100)
440
441def pydicts():
442 if verbose: print "Testing Python subclass of dict..."
443 verify(issubclass(dictionary, dictionary))
444 verify(isinstance({}, dictionary))
445 d = dictionary()
446 verify(d == {})
447 verify(d.__class__ is dictionary)
448 verify(isinstance(d, dictionary))
449 class C(dictionary):
450 state = -1
451 def __init__(self, *a, **kw):
452 if a:
453 assert len(a) == 1
454 self.state = a[0]
455 if kw:
456 for k, v in kw.items(): self[v] = k
457 def __getitem__(self, key):
458 return self.get(key, 0)
459 def __setitem__(self, key, value):
460 assert isinstance(key, type(0))
461 dictionary.__setitem__(self, key, value)
462 def setstate(self, state):
463 self.state = state
464 def getstate(self):
465 return self.state
466 verify(issubclass(C, dictionary))
467 a1 = C(12)
468 verify(a1.state == 12)
469 a2 = C(foo=1, bar=2)
470 verify(a2[1] == 'foo' and a2[2] == 'bar')
471 a = C()
472 verify(a.state == -1)
473 verify(a.getstate() == -1)
474 a.setstate(0)
475 verify(a.state == 0)
476 verify(a.getstate() == 0)
477 a.setstate(10)
478 verify(a.state == 10)
479 verify(a.getstate() == 10)
480 verify(a[42] == 0)
481 a[42] = 24
482 verify(a[42] == 24)
483 if verbose: print "pydict stress test ..."
484 N = 50
485 for i in range(N):
486 a[i] = C()
487 for j in range(N):
488 a[i][j] = i*j
489 for i in range(N):
490 for j in range(N):
491 verify(a[i][j] == i*j)
492
493def pylists():
494 if verbose: print "Testing Python subclass of list..."
495 class C(list):
496 def __getitem__(self, i):
497 return list.__getitem__(self, i) + 100
498 def __getslice__(self, i, j):
499 return (i, j)
500 a = C()
501 a.extend([0,1,2])
502 verify(a[0] == 100)
503 verify(a[1] == 101)
504 verify(a[2] == 102)
505 verify(a[100:200] == (100,200))
506
507def metaclass():
508 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000509 class C:
510 __metaclass__ = type
511 def __init__(self):
512 self.__state = 0
513 def getstate(self):
514 return self.__state
515 def setstate(self, state):
516 self.__state = state
517 a = C()
518 verify(a.getstate() == 0)
519 a.setstate(10)
520 verify(a.getstate() == 10)
521 class D:
522 class __metaclass__(type):
523 def myself(cls): return cls
524 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000525 d = D()
526 verify(d.__class__ is D)
527 class M1(type):
528 def __new__(cls, name, bases, dict):
529 dict['__spam__'] = 1
530 return type.__new__(cls, name, bases, dict)
531 class C:
532 __metaclass__ = M1
533 verify(C.__spam__ == 1)
534 c = C()
535 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000536
Guido van Rossum309b5662001-08-17 11:43:17 +0000537 class _instance(object):
538 pass
539 class M2(object):
540 def __new__(cls, name, bases, dict):
541 self = object.__new__(cls)
542 self.name = name
543 self.bases = bases
544 self.dict = dict
545 return self
546 __new__ = staticmethod(__new__)
547 def __call__(self):
548 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000549 # Early binding of methods
550 for key in self.dict:
551 if key.startswith("__"):
552 continue
553 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000554 return it
555 class C:
556 __metaclass__ = M2
557 def spam(self):
558 return 42
559 verify(C.name == 'C')
560 verify(C.bases == ())
561 verify('spam' in C.dict)
562 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000563 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564
Guido van Rossum91ee7982001-08-30 20:52:40 +0000565 # More metaclass examples
566
567 class autosuper(type):
568 # Automatically add __super to the class
569 # This trick only works for dynamic classes
570 # so we force __dynamic__ = 1
571 def __new__(metaclass, name, bases, dict):
572 # XXX Should check that name isn't already a base class name
573 dict["__dynamic__"] = 1
574 cls = super(autosuper, metaclass).__new__(metaclass,
575 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000576 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000577 while name[:1] == "_":
578 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000579 if name:
580 name = "_%s__super" % name
581 else:
582 name = "__super"
583 setattr(cls, name, super(cls))
584 return cls
585 class A:
586 __metaclass__ = autosuper
587 def meth(self):
588 return "A"
589 class B(A):
590 def meth(self):
591 return "B" + self.__super.meth()
592 class C(A):
593 def meth(self):
594 return "C" + self.__super.meth()
595 class D(C, B):
596 def meth(self):
597 return "D" + self.__super.meth()
598 verify(D().meth() == "DCBA")
599 class E(B, C):
600 def meth(self):
601 return "E" + self.__super.meth()
602 verify(E().meth() == "EBCA")
603
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000604 class autoproperty(type):
605 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000606 # named _get_x and/or _set_x are found
607 def __new__(metaclass, name, bases, dict):
608 hits = {}
609 for key, val in dict.iteritems():
610 if key.startswith("_get_"):
611 key = key[5:]
612 get, set = hits.get(key, (None, None))
613 get = val
614 hits[key] = get, set
615 elif key.startswith("_set_"):
616 key = key[5:]
617 get, set = hits.get(key, (None, None))
618 set = val
619 hits[key] = get, set
620 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000621 dict[key] = property(get, set)
622 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000623 name, bases, dict)
624 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000625 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000626 def _get_x(self):
627 return -self.__x
628 def _set_x(self, x):
629 self.__x = -x
630 a = A()
631 verify(not hasattr(a, "x"))
632 a.x = 12
633 verify(a.x == 12)
634 verify(a._A__x == -12)
635
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000636 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000637 # Merge of multiple cooperating metaclasses
638 pass
639 class A:
640 __metaclass__ = multimetaclass
641 def _get_x(self):
642 return "A"
643 class B(A):
644 def _get_x(self):
645 return "B" + self.__super._get_x()
646 class C(A):
647 def _get_x(self):
648 return "C" + self.__super._get_x()
649 class D(C, B):
650 def _get_x(self):
651 return "D" + self.__super._get_x()
652 verify(D().x == "DCBA")
653
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654def pymods():
655 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000657 import sys
658 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 class MM(MT):
660 def __init__(self):
661 MT.__init__(self)
662 def __getattr__(self, name):
663 log.append(("getattr", name))
664 return MT.__getattr__(self, name)
665 def __setattr__(self, name, value):
666 log.append(("setattr", name, value))
667 MT.__setattr__(self, name, value)
668 def __delattr__(self, name):
669 log.append(("delattr", name))
670 MT.__delattr__(self, name)
671 a = MM()
672 a.foo = 12
673 x = a.foo
674 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000675 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677 ("delattr", "foo")], log)
678
679def multi():
680 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681 class C(object):
682 def __init__(self):
683 self.__state = 0
684 def getstate(self):
685 return self.__state
686 def setstate(self, state):
687 self.__state = state
688 a = C()
689 verify(a.getstate() == 0)
690 a.setstate(10)
691 verify(a.getstate() == 10)
692 class D(dictionary, C):
693 def __init__(self):
694 type({}).__init__(self)
695 C.__init__(self)
696 d = D()
697 verify(d.keys() == [])
698 d["hello"] = "world"
699 verify(d.items() == [("hello", "world")])
700 verify(d["hello"] == "world")
701 verify(d.getstate() == 0)
702 d.setstate(10)
703 verify(d.getstate() == 10)
704 verify(D.__mro__ == (D, dictionary, C, object))
705
Guido van Rossume45763a2001-08-10 21:28:46 +0000706 # SF bug #442833
707 class Node(object):
708 def __int__(self):
709 return int(self.foo())
710 def foo(self):
711 return "23"
712 class Frag(Node, list):
713 def foo(self):
714 return "42"
715 verify(Node().__int__() == 23)
716 verify(int(Node()) == 23)
717 verify(Frag().__int__() == 42)
718 verify(int(Frag()) == 42)
719
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720def diamond():
721 if verbose: print "Testing multiple inheritance special cases..."
722 class A(object):
723 def spam(self): return "A"
724 verify(A().spam() == "A")
725 class B(A):
726 def boo(self): return "B"
727 def spam(self): return "B"
728 verify(B().spam() == "B")
729 verify(B().boo() == "B")
730 class C(A):
731 def boo(self): return "C"
732 verify(C().spam() == "A")
733 verify(C().boo() == "C")
734 class D(B, C): pass
735 verify(D().spam() == "B")
736 verify(D().boo() == "B")
737 verify(D.__mro__ == (D, B, C, A, object))
738 class E(C, B): pass
739 verify(E().spam() == "B")
740 verify(E().boo() == "C")
741 verify(E.__mro__ == (E, C, B, A, object))
742 class F(D, E): pass
743 verify(F().spam() == "B")
744 verify(F().boo() == "B")
745 verify(F.__mro__ == (F, D, E, B, C, A, object))
746 class G(E, D): pass
747 verify(G().spam() == "B")
748 verify(G().boo() == "C")
749 verify(G.__mro__ == (G, E, D, C, B, A, object))
750
Guido van Rossum37202612001-08-09 19:45:21 +0000751def objects():
752 if verbose: print "Testing object class..."
753 a = object()
754 verify(a.__class__ == object == type(a))
755 b = object()
756 verify(a is not b)
757 verify(not hasattr(a, "foo"))
758 try:
759 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000760 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000761 pass
762 else:
763 verify(0, "object() should not allow setting a foo attribute")
764 verify(not hasattr(object(), "__dict__"))
765
766 class Cdict(object):
767 pass
768 x = Cdict()
769 verify(x.__dict__ is None)
770 x.foo = 1
771 verify(x.foo == 1)
772 verify(x.__dict__ == {'foo': 1})
773
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774def slots():
775 if verbose: print "Testing __slots__..."
776 class C0(object):
777 __slots__ = []
778 x = C0()
779 verify(not hasattr(x, "__dict__"))
780 verify(not hasattr(x, "foo"))
781
782 class C1(object):
783 __slots__ = ['a']
784 x = C1()
785 verify(not hasattr(x, "__dict__"))
786 verify(x.a == None)
787 x.a = 1
788 verify(x.a == 1)
789 del x.a
790 verify(x.a == None)
791
792 class C3(object):
793 __slots__ = ['a', 'b', 'c']
794 x = C3()
795 verify(not hasattr(x, "__dict__"))
796 verify(x.a is None)
797 verify(x.b is None)
798 verify(x.c is None)
799 x.a = 1
800 x.b = 2
801 x.c = 3
802 verify(x.a == 1)
803 verify(x.b == 2)
804 verify(x.c == 3)
805
806def dynamics():
807 if verbose: print "Testing __dynamic__..."
808 verify(object.__dynamic__ == 0)
809 verify(list.__dynamic__ == 0)
810 class S1:
811 __metaclass__ = type
812 verify(S1.__dynamic__ == 0)
813 class S(object):
814 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000815 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816 class D(object):
817 __dynamic__ = 1
818 verify(D.__dynamic__ == 1)
819 class E(D, S):
820 pass
821 verify(E.__dynamic__ == 1)
822 class F(S, D):
823 pass
824 verify(F.__dynamic__ == 1)
825 try:
826 S.foo = 1
827 except (AttributeError, TypeError):
828 pass
829 else:
830 verify(0, "assignment to a static class attribute should be illegal")
831 D.foo = 1
832 verify(D.foo == 1)
833 # Test that dynamic attributes are inherited
834 verify(E.foo == 1)
835 verify(F.foo == 1)
836 class SS(D):
837 __dynamic__ = 0
838 verify(SS.__dynamic__ == 0)
839 verify(SS.foo == 1)
840 try:
841 SS.foo = 1
842 except (AttributeError, TypeError):
843 pass
844 else:
845 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000846 # Test dynamic instances
847 class C(object):
848 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000849 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000850 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000851 C.foobar = 2
852 verify(a.foobar == 2)
853 C.method = lambda self: 42
854 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000855 C.__repr__ = lambda self: "C()"
856 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000857 C.__int__ = lambda self: 100
858 verify(int(a) == 100)
859 verify(a.foobar == 2)
860 verify(not hasattr(a, "spam"))
861 def mygetattr(self, name):
862 if name == "spam":
863 return "spam"
864 else:
865 return object.__getattr__(self, name)
866 C.__getattr__ = mygetattr
867 verify(a.spam == "spam")
868 a.new = 12
869 verify(a.new == 12)
870 def mysetattr(self, name, value):
871 if name == "spam":
872 raise AttributeError
873 return object.__setattr__(self, name, value)
874 C.__setattr__ = mysetattr
875 try:
876 a.spam = "not spam"
877 except AttributeError:
878 pass
879 else:
880 verify(0, "expected AttributeError")
881 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000882 class D(C):
883 pass
884 d = D()
885 d.foo = 1
886 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887
888def errors():
889 if verbose: print "Testing errors..."
890
891 try:
892 class C(list, dictionary):
893 pass
894 except TypeError:
895 pass
896 else:
897 verify(0, "inheritance from both list and dict should be illegal")
898
899 try:
900 class C(object, None):
901 pass
902 except TypeError:
903 pass
904 else:
905 verify(0, "inheritance from non-type should be illegal")
906 class Classic:
907 pass
908
909 try:
910 class C(object, Classic):
911 pass
912 except TypeError:
913 pass
914 else:
915 verify(0, "inheritance from object and Classic should be illegal")
916
917 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000918 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000919 pass
920 except TypeError:
921 pass
922 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000923 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924
925 try:
926 class C(object):
927 __slots__ = 1
928 except TypeError:
929 pass
930 else:
931 verify(0, "__slots__ = 1 should be illegal")
932
933 try:
934 class C(object):
935 __slots__ = [1]
936 except TypeError:
937 pass
938 else:
939 verify(0, "__slots__ = [1] should be illegal")
940
941def classmethods():
942 if verbose: print "Testing class methods..."
943 class C(object):
944 def foo(*a): return a
945 goo = classmethod(foo)
946 c = C()
947 verify(C.goo(1) == (C, 1))
948 verify(c.goo(1) == (C, 1))
949 verify(c.foo(1) == (c, 1))
950 class D(C):
951 pass
952 d = D()
953 verify(D.goo(1) == (D, 1))
954 verify(d.goo(1) == (D, 1))
955 verify(d.foo(1) == (d, 1))
956 verify(D.foo(d, 1) == (d, 1))
957
958def staticmethods():
959 if verbose: print "Testing static methods..."
960 class C(object):
961 def foo(*a): return a
962 goo = staticmethod(foo)
963 c = C()
964 verify(C.goo(1) == (1,))
965 verify(c.goo(1) == (1,))
966 verify(c.foo(1) == (c, 1,))
967 class D(C):
968 pass
969 d = D()
970 verify(D.goo(1) == (1,))
971 verify(d.goo(1) == (1,))
972 verify(d.foo(1) == (d, 1))
973 verify(D.foo(d, 1) == (d, 1))
974
975def classic():
976 if verbose: print "Testing classic classes..."
977 class C:
978 def foo(*a): return a
979 goo = classmethod(foo)
980 c = C()
981 verify(C.goo(1) == (C, 1))
982 verify(c.goo(1) == (C, 1))
983 verify(c.foo(1) == (c, 1))
984 class D(C):
985 pass
986 d = D()
987 verify(D.goo(1) == (D, 1))
988 verify(d.goo(1) == (D, 1))
989 verify(d.foo(1) == (d, 1))
990 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +0000991 class E: # *not* subclassing from C
992 foo = C.foo
993 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +0000994 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995
996def compattr():
997 if verbose: print "Testing computed attributes..."
998 class C(object):
999 class computed_attribute(object):
1000 def __init__(self, get, set=None):
1001 self.__get = get
1002 self.__set = set
1003 def __get__(self, obj, type=None):
1004 return self.__get(obj)
1005 def __set__(self, obj, value):
1006 return self.__set(obj, value)
1007 def __init__(self):
1008 self.__x = 0
1009 def __get_x(self):
1010 x = self.__x
1011 self.__x = x+1
1012 return x
1013 def __set_x(self, x):
1014 self.__x = x
1015 x = computed_attribute(__get_x, __set_x)
1016 a = C()
1017 verify(a.x == 0)
1018 verify(a.x == 1)
1019 a.x = 10
1020 verify(a.x == 10)
1021 verify(a.x == 11)
1022
1023def newslot():
1024 if verbose: print "Testing __new__ slot override..."
1025 class C(list):
1026 def __new__(cls):
1027 self = list.__new__(cls)
1028 self.foo = 1
1029 return self
1030 def __init__(self):
1031 self.foo = self.foo + 2
1032 a = C()
1033 verify(a.foo == 3)
1034 verify(a.__class__ is C)
1035 class D(C):
1036 pass
1037 b = D()
1038 verify(b.foo == 3)
1039 verify(b.__class__ is D)
1040
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041def altmro():
1042 if verbose: print "Testing mro() and overriding it..."
1043 class A(object):
1044 def f(self): return "A"
1045 class B(A):
1046 pass
1047 class C(A):
1048 def f(self): return "C"
1049 class D(B, C):
1050 pass
1051 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1052 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001053 class PerverseMetaType(type):
1054 def mro(cls):
1055 L = type.mro(cls)
1056 L.reverse()
1057 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058 class X(A,B,C,D):
1059 __metaclass__ = PerverseMetaType
1060 verify(X.__mro__ == (object, A, C, B, D, X))
1061 verify(X().f() == "A")
1062
1063def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001064 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001065
1066 class B(object):
1067 "Intermediate class because object doesn't have a __setattr__"
1068
1069 class C(B):
1070
1071 def __getattr__(self, name):
1072 if name == "foo":
1073 return ("getattr", name)
1074 else:
1075 return B.__getattr__(self, name)
1076 def __setattr__(self, name, value):
1077 if name == "foo":
1078 self.setattr = (name, value)
1079 else:
1080 return B.__setattr__(self, name, value)
1081 def __delattr__(self, name):
1082 if name == "foo":
1083 self.delattr = name
1084 else:
1085 return B.__delattr__(self, name)
1086
1087 def __getitem__(self, key):
1088 return ("getitem", key)
1089 def __setitem__(self, key, value):
1090 self.setitem = (key, value)
1091 def __delitem__(self, key):
1092 self.delitem = key
1093
1094 def __getslice__(self, i, j):
1095 return ("getslice", i, j)
1096 def __setslice__(self, i, j, value):
1097 self.setslice = (i, j, value)
1098 def __delslice__(self, i, j):
1099 self.delslice = (i, j)
1100
1101 a = C()
1102 verify(a.foo == ("getattr", "foo"))
1103 a.foo = 12
1104 verify(a.setattr == ("foo", 12))
1105 del a.foo
1106 verify(a.delattr == "foo")
1107
1108 verify(a[12] == ("getitem", 12))
1109 a[12] = 21
1110 verify(a.setitem == (12, 21))
1111 del a[12]
1112 verify(a.delitem == 12)
1113
1114 verify(a[0:10] == ("getslice", 0, 10))
1115 a[0:10] = "foo"
1116 verify(a.setslice == (0, 10, "foo"))
1117 del a[0:10]
1118 verify(a.delslice == (0, 10))
1119
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001120def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001121 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001122 class C(object):
1123 def __init__(self, x):
1124 self.x = x
1125 def foo(self):
1126 return self.x
1127 c1 = C(1)
1128 verify(c1.foo() == 1)
1129 class D(C):
1130 boo = C.foo
1131 goo = c1.foo
1132 d2 = D(2)
1133 verify(d2.foo() == 2)
1134 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001135 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001136 class E(object):
1137 foo = C.foo
1138 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001139 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001140
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001141def specials():
1142 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001143 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001144 # Test the default behavior for static classes
1145 class C(object):
1146 def __getitem__(self, i):
1147 if 0 <= i < 10: return i
1148 raise IndexError
1149 c1 = C()
1150 c2 = C()
1151 verify(not not c1)
1152 verify(hash(c1) == id(c1))
1153 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1154 verify(c1 == c1)
1155 verify(c1 != c2)
1156 verify(not c1 != c1)
1157 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001158 # Note that the module name appears in str/repr, and that varies
1159 # depending on whether this test is run standalone or from a framework.
1160 verify(str(c1).find('C instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001161 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001162 verify(-1 not in c1)
1163 for i in range(10):
1164 verify(i in c1)
1165 verify(10 not in c1)
1166 # Test the default behavior for dynamic classes
1167 class D(object):
1168 __dynamic__ = 1
1169 def __getitem__(self, i):
1170 if 0 <= i < 10: return i
1171 raise IndexError
1172 d1 = D()
1173 d2 = D()
1174 verify(not not d1)
1175 verify(hash(d1) == id(d1))
1176 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1177 verify(d1 == d1)
1178 verify(d1 != d2)
1179 verify(not d1 != d1)
1180 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001181 # Note that the module name appears in str/repr, and that varies
1182 # depending on whether this test is run standalone or from a framework.
1183 verify(str(d1).find('D instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001184 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001185 verify(-1 not in d1)
1186 for i in range(10):
1187 verify(i in d1)
1188 verify(10 not in d1)
1189 # Test overridden behavior for static classes
1190 class Proxy(object):
1191 def __init__(self, x):
1192 self.x = x
1193 def __nonzero__(self):
1194 return not not self.x
1195 def __hash__(self):
1196 return hash(self.x)
1197 def __eq__(self, other):
1198 return self.x == other
1199 def __ne__(self, other):
1200 return self.x != other
1201 def __cmp__(self, other):
1202 return cmp(self.x, other.x)
1203 def __str__(self):
1204 return "Proxy:%s" % self.x
1205 def __repr__(self):
1206 return "Proxy(%r)" % self.x
1207 def __contains__(self, value):
1208 return value in self.x
1209 p0 = Proxy(0)
1210 p1 = Proxy(1)
1211 p_1 = Proxy(-1)
1212 verify(not p0)
1213 verify(not not p1)
1214 verify(hash(p0) == hash(0))
1215 verify(p0 == p0)
1216 verify(p0 != p1)
1217 verify(not p0 != p0)
1218 verify(not p0 == p1)
1219 verify(cmp(p0, p1) == -1)
1220 verify(cmp(p0, p0) == 0)
1221 verify(cmp(p0, p_1) == 1)
1222 verify(str(p0) == "Proxy:0")
1223 verify(repr(p0) == "Proxy(0)")
1224 p10 = Proxy(range(10))
1225 verify(-1 not in p10)
1226 for i in range(10):
1227 verify(i in p10)
1228 verify(10 not in p10)
1229 # Test overridden behavior for dynamic classes
1230 class DProxy(object):
1231 __dynamic__ = 1
1232 def __init__(self, x):
1233 self.x = x
1234 def __nonzero__(self):
1235 return not not self.x
1236 def __hash__(self):
1237 return hash(self.x)
1238 def __eq__(self, other):
1239 return self.x == other
1240 def __ne__(self, other):
1241 return self.x != other
1242 def __cmp__(self, other):
1243 return cmp(self.x, other.x)
1244 def __str__(self):
1245 return "DProxy:%s" % self.x
1246 def __repr__(self):
1247 return "DProxy(%r)" % self.x
1248 def __contains__(self, value):
1249 return value in self.x
1250 p0 = DProxy(0)
1251 p1 = DProxy(1)
1252 p_1 = DProxy(-1)
1253 verify(not p0)
1254 verify(not not p1)
1255 verify(hash(p0) == hash(0))
1256 verify(p0 == p0)
1257 verify(p0 != p1)
1258 verify(not p0 != p0)
1259 verify(not p0 == p1)
1260 verify(cmp(p0, p1) == -1)
1261 verify(cmp(p0, p0) == 0)
1262 verify(cmp(p0, p_1) == 1)
1263 verify(str(p0) == "DProxy:0")
1264 verify(repr(p0) == "DProxy(0)")
1265 p10 = DProxy(range(10))
1266 verify(-1 not in p10)
1267 for i in range(10):
1268 verify(i in p10)
1269 verify(10 not in p10)
1270
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001271def weakrefs():
1272 if verbose: print "Testing weak references..."
1273 import weakref
1274 class C(object):
1275 pass
1276 c = C()
1277 r = weakref.ref(c)
1278 verify(r() is c)
1279 del c
1280 verify(r() is None)
1281 del r
1282 class NoWeak(object):
1283 __slots__ = ['foo']
1284 no = NoWeak()
1285 try:
1286 weakref.ref(no)
1287 except TypeError, msg:
1288 verify(str(msg).find("weakly") >= 0)
1289 else:
1290 verify(0, "weakref.ref(no) should be illegal")
1291 class Weak(object):
1292 __slots__ = ['foo', '__weakref__']
1293 yes = Weak()
1294 r = weakref.ref(yes)
1295 verify(r() is yes)
1296 del yes
1297 verify(r() is None)
1298 del r
1299
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001300def properties():
1301 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001302 class C(object):
1303 def getx(self):
1304 return self.__x
1305 def setx(self, value):
1306 self.__x = value
1307 def delx(self):
1308 del self.__x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001309 x = property(getx, setx, delx)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001310 a = C()
1311 verify(not hasattr(a, "x"))
1312 a.x = 42
1313 verify(a._C__x == 42)
1314 verify(a.x == 42)
1315 del a.x
1316 verify(not hasattr(a, "x"))
1317 verify(not hasattr(a, "_C__x"))
1318 C.x.__set__(a, 100)
1319 verify(C.x.__get__(a) == 100)
1320## C.x.__set__(a)
1321## verify(not hasattr(a, "x"))
1322
Guido van Rossumc4a18802001-08-24 16:55:27 +00001323def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001324 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001325
1326 class A(object):
1327 def meth(self, a):
1328 return "A(%r)" % a
1329
1330 verify(A().meth(1) == "A(1)")
1331
1332 class B(A):
1333 def __init__(self):
1334 self.__super = super(B, self)
1335 def meth(self, a):
1336 return "B(%r)" % a + self.__super.meth(a)
1337
1338 verify(B().meth(2) == "B(2)A(2)")
1339
1340 class C(A):
1341 __dynamic__ = 1
1342 def meth(self, a):
1343 return "C(%r)" % a + self.__super.meth(a)
1344 C._C__super = super(C)
1345
1346 verify(C().meth(3) == "C(3)A(3)")
1347
1348 class D(C, B):
1349 def meth(self, a):
1350 return "D(%r)" % a + super(D, self).meth(a)
1351
1352 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1353
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001354def inherits():
1355 if verbose: print "Testing inheritance from basic types..."
1356
1357 class hexint(int):
1358 def __repr__(self):
1359 return hex(self)
1360 def __add__(self, other):
1361 return hexint(int.__add__(self, other))
1362 # (Note that overriding __radd__ doesn't work,
1363 # because the int type gets first dibs.)
1364 verify(repr(hexint(7) + 9) == "0x10")
1365 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001366 a = hexint(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001367 #XXX verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001368 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001369 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001370 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001371 verify((+a).__class__ is int)
1372 verify((a >> 0).__class__ is int)
1373 verify((a << 0).__class__ is int)
1374 verify((hexint(0) << 12).__class__ is int)
1375 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001376
1377 class octlong(long):
1378 __slots__ = []
1379 def __str__(self):
1380 s = oct(self)
1381 if s[-1] == 'L':
1382 s = s[:-1]
1383 return s
1384 def __add__(self, other):
1385 return self.__class__(super(octlong, self).__add__(other))
1386 __radd__ = __add__
1387 verify(str(octlong(3) + 5) == "010")
1388 # (Note that overriding __radd__ here only seems to work
1389 # because the example uses a short int left argument.)
1390 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001391 a = octlong(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001392 #XXX verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001393 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001394 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001395 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001396 verify((+a).__class__ is long)
1397 verify((-a).__class__ is long)
1398 verify((-octlong(0)).__class__ is long)
1399 verify((a >> 0).__class__ is long)
1400 verify((a << 0).__class__ is long)
1401 verify((a - 0).__class__ is long)
1402 verify((a * 1).__class__ is long)
1403 verify((a ** 1).__class__ is long)
1404 verify((a // 1).__class__ is long)
1405 verify((1 * a).__class__ is long)
1406 verify((a | 0).__class__ is long)
1407 verify((a ^ 0).__class__ is long)
1408 verify((a & -1L).__class__ is long)
1409 verify((octlong(0) << 12).__class__ is long)
1410 verify((octlong(0) >> 12).__class__ is long)
1411 verify(abs(octlong(0)).__class__ is long)
1412
1413 # Because octlong overrides __add__, we can't check the absence of +0
1414 # optimizations using octlong.
1415 class longclone(long):
1416 pass
1417 a = longclone(1)
1418 verify((a + 0).__class__ is long)
1419 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001420
1421 class precfloat(float):
1422 __slots__ = ['prec']
1423 def __init__(self, value=0.0, prec=12):
1424 self.prec = int(prec)
1425 float.__init__(value)
1426 def __repr__(self):
1427 return "%.*g" % (self.prec, self)
1428 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001429 a = precfloat(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001430 #XXX verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001431 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001432 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001433 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001434 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001435
Tim Peters2400fa42001-09-12 19:12:49 +00001436 class madcomplex(complex):
1437 def __repr__(self):
1438 return "%.17gj%+.17g" % (self.imag, self.real)
1439 a = madcomplex(-3, 4)
1440 verify(repr(a) == "4j-3")
1441 base = complex(-3, 4)
1442 verify(base.__class__ is complex)
Tim Peters4f467e82001-09-12 19:53:15 +00001443 #XXX verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001444 verify(complex(a) == base)
1445 verify(complex(a).__class__ is complex)
1446 a = madcomplex(a) # just trying another form of the constructor
1447 verify(repr(a) == "4j-3")
Tim Peters4f467e82001-09-12 19:53:15 +00001448 #XXX verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001449 verify(complex(a) == base)
1450 verify(complex(a).__class__ is complex)
1451 verify(hash(a) == hash(base))
1452 verify((+a).__class__ is complex)
1453 verify((a + 0).__class__ is complex)
1454 verify(a + 0 == base)
1455 verify((a - 0).__class__ is complex)
1456 verify(a - 0 == base)
1457 verify((a * 1).__class__ is complex)
1458 verify(a * 1 == base)
1459 verify((a / 1).__class__ is complex)
1460 verify(a / 1 == base)
1461
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001462 class madtuple(tuple):
1463 _rev = None
1464 def rev(self):
1465 if self._rev is not None:
1466 return self._rev
1467 L = list(self)
1468 L.reverse()
1469 self._rev = self.__class__(L)
1470 return self._rev
1471 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001472 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001473 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1474 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1475 for i in range(512):
1476 t = madtuple(range(i))
1477 u = t.rev()
1478 v = u.rev()
1479 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001480 a = madtuple((1,2,3,4,5))
1481 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001482 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001483 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001484 verify(a[:].__class__ is tuple)
1485 verify((a * 1).__class__ is tuple)
1486 verify((a * 0).__class__ is tuple)
1487 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001488 a = madtuple(())
1489 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001490 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001491 verify((a + a).__class__ is tuple)
1492 verify((a * 0).__class__ is tuple)
1493 verify((a * 1).__class__ is tuple)
1494 verify((a * 2).__class__ is tuple)
1495 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001496
1497 class madstring(str):
1498 _rev = None
1499 def rev(self):
1500 if self._rev is not None:
1501 return self._rev
1502 L = list(self)
1503 L.reverse()
1504 self._rev = self.__class__("".join(L))
1505 return self._rev
1506 s = madstring("abcdefghijklmnopqrstuvwxyz")
Tim Peters4f467e82001-09-12 19:53:15 +00001507 #XXX verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001508 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1509 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1510 for i in range(256):
1511 s = madstring("".join(map(chr, range(i))))
1512 t = s.rev()
1513 u = t.rev()
1514 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001515 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001516 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001517 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001518
Tim Peters8fa5dd02001-09-12 02:18:30 +00001519 base = "\x00" * 5
1520 s = madstring(base)
Tim Peters4f467e82001-09-12 19:53:15 +00001521 #XXX verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001522 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001523 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001524 verify(hash(s) == hash(base))
1525 verify({s: 1}[base] == 1)
1526 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001527 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001528 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001529 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001530 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001531 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001532 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001533 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001534 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001535 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001536 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001537 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001538 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001539 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001540 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001541 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001542 verify(s.strip() == base)
1543 verify(s.lstrip().__class__ is str)
1544 verify(s.lstrip() == base)
1545 verify(s.rstrip().__class__ is str)
1546 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001547 identitytab = ''.join([chr(i) for i in range(256)])
1548 verify(s.translate(identitytab).__class__ is str)
1549 verify(s.translate(identitytab) == base)
1550 verify(s.translate(identitytab, "x").__class__ is str)
1551 verify(s.translate(identitytab, "x") == base)
1552 verify(s.translate(identitytab, "\x00") == "")
1553 verify(s.replace("x", "x").__class__ is str)
1554 verify(s.replace("x", "x") == base)
1555 verify(s.ljust(len(s)).__class__ is str)
1556 verify(s.ljust(len(s)) == base)
1557 verify(s.rjust(len(s)).__class__ is str)
1558 verify(s.rjust(len(s)) == base)
1559 verify(s.center(len(s)).__class__ is str)
1560 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001561 verify(s.lower().__class__ is str)
1562 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001563
Tim Peters111f6092001-09-12 07:54:51 +00001564 s = madstring("x y")
Tim Peters4f467e82001-09-12 19:53:15 +00001565 #XXX verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001566 verify(intern(s).__class__ is str)
1567 verify(intern(s) is intern("x y"))
1568 verify(intern(s) == "x y")
1569
1570 i = intern("y x")
1571 s = madstring("y x")
Tim Peters4f467e82001-09-12 19:53:15 +00001572 #XXX verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001573 verify(intern(s).__class__ is str)
1574 verify(intern(s) is i)
1575
1576 s = madstring(i)
1577 verify(intern(s).__class__ is str)
1578 verify(intern(s) is i)
1579
Guido van Rossum91ee7982001-08-30 20:52:40 +00001580 class madunicode(unicode):
1581 _rev = None
1582 def rev(self):
1583 if self._rev is not None:
1584 return self._rev
1585 L = list(self)
1586 L.reverse()
1587 self._rev = self.__class__(u"".join(L))
1588 return self._rev
1589 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001590 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001591 verify(u.rev() == madunicode(u"FEDCBA"))
1592 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001593 base = u"12345"
1594 u = madunicode(base)
1595 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001596 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001597 verify(hash(u) == hash(base))
1598 verify({u: 1}[base] == 1)
1599 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001600 verify(u.strip().__class__ is unicode)
1601 verify(u.strip() == base)
1602 verify(u.lstrip().__class__ is unicode)
1603 verify(u.lstrip() == base)
1604 verify(u.rstrip().__class__ is unicode)
1605 verify(u.rstrip() == base)
1606 verify(u.replace(u"x", u"x").__class__ is unicode)
1607 verify(u.replace(u"x", u"x") == base)
1608 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1609 verify(u.replace(u"xy", u"xy") == base)
1610 verify(u.center(len(u)).__class__ is unicode)
1611 verify(u.center(len(u)) == base)
1612 verify(u.ljust(len(u)).__class__ is unicode)
1613 verify(u.ljust(len(u)) == base)
1614 verify(u.rjust(len(u)).__class__ is unicode)
1615 verify(u.rjust(len(u)) == base)
1616 verify(u.lower().__class__ is unicode)
1617 verify(u.lower() == base)
1618 verify(u.upper().__class__ is unicode)
1619 verify(u.upper() == base)
1620 verify(u.capitalize().__class__ is unicode)
1621 verify(u.capitalize() == base)
1622 verify(u.title().__class__ is unicode)
1623 verify(u.title() == base)
1624 verify((u + u"").__class__ is unicode)
1625 verify(u + u"" == base)
1626 verify((u"" + u).__class__ is unicode)
1627 verify(u"" + u == base)
1628 verify((u * 0).__class__ is unicode)
1629 verify(u * 0 == u"")
1630 verify((u * 1).__class__ is unicode)
1631 verify(u * 1 == base)
1632 verify((u * 2).__class__ is unicode)
1633 verify(u * 2 == base + base)
1634 verify(u[:].__class__ is unicode)
1635 verify(u[:] == base)
1636 verify(u[0:0].__class__ is unicode)
1637 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001638
Tim Peters59c9a642001-09-13 05:38:56 +00001639 class CountedInput(file):
1640 """Counts lines read by self.readline().
1641
1642 self.lineno is the 0-based ordinal of the last line read, up to
1643 a maximum of one greater than the number of lines in the file.
1644
1645 self.ateof is true if and only if the final "" line has been read,
1646 at which point self.lineno stops incrementing, and further calls
1647 to readline() continue to return "".
1648 """
1649
1650 lineno = 0
1651 ateof = 0
1652 def readline(self):
1653 if self.ateof:
1654 return ""
1655 s = file.readline(self)
1656 # Next line works too.
1657 # s = super(CountedInput, self).readline()
1658 self.lineno += 1
1659 if s == "":
1660 self.ateof = 1
1661 return s
1662
1663 f = open(TESTFN, 'w')
1664 lines = ['a\n', 'b\n', 'c\n']
1665 try:
1666 f.writelines(lines)
1667 f.close()
1668 f = CountedInput(TESTFN)
1669 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1670 got = f.readline()
1671 verify(expected == got)
1672 verify(f.lineno == i)
1673 verify(f.ateof == (i > len(lines)))
1674 f.close()
1675 finally:
1676 try:
1677 f.close()
1678 except:
1679 pass
1680 try:
1681 import os
1682 os.unlink(TESTFN)
1683 except:
1684 pass
1685
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686def all():
1687 lists()
1688 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00001689 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00001690 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 ints()
1692 longs()
1693 floats()
1694 complexes()
1695 spamlists()
1696 spamdicts()
1697 pydicts()
1698 pylists()
1699 metaclass()
1700 pymods()
1701 multi()
1702 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001703 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 slots()
1705 dynamics()
1706 errors()
1707 classmethods()
1708 staticmethods()
1709 classic()
1710 compattr()
1711 newslot()
1712 altmro()
1713 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001714 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001715 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001716 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001717 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00001718 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001719 inherits()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720
1721all()
1722
1723if verbose: print "All OK"