blob: 7095f0b5d49cd9932284a0a5b44687fbeb27a368 [file] [log] [blame]
Tim Peters6d6c1a32001-08-02 04:15:00 +00001# Test descriptor-related enhancements
2
Tim Peters25786c02001-09-02 08:22:48 +00003from test_support import verify, verbose, TestFailed
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)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001367 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001368 verify(int(a).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001369
1370 class octlong(long):
1371 __slots__ = []
1372 def __str__(self):
1373 s = oct(self)
1374 if s[-1] == 'L':
1375 s = s[:-1]
1376 return s
1377 def __add__(self, other):
1378 return self.__class__(super(octlong, self).__add__(other))
1379 __radd__ = __add__
1380 verify(str(octlong(3) + 5) == "010")
1381 # (Note that overriding __radd__ here only seems to work
1382 # because the example uses a short int left argument.)
1383 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001384 a = octlong(12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001385 verify(long(a) == 12345L)
Tim Peters64b5ce32001-09-10 20:52:51 +00001386 verify(long(a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001387
1388 class precfloat(float):
1389 __slots__ = ['prec']
1390 def __init__(self, value=0.0, prec=12):
1391 self.prec = int(prec)
1392 float.__init__(value)
1393 def __repr__(self):
1394 return "%.*g" % (self.prec, self)
1395 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001396 a = precfloat(12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001397 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001398 verify(float(a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001399
1400 class madtuple(tuple):
1401 _rev = None
1402 def rev(self):
1403 if self._rev is not None:
1404 return self._rev
1405 L = list(self)
1406 L.reverse()
1407 self._rev = self.__class__(L)
1408 return self._rev
1409 a = madtuple((1,2,3,4,5,6,7,8,9,0))
1410 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1411 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1412 for i in range(512):
1413 t = madtuple(range(i))
1414 u = t.rev()
1415 v = u.rev()
1416 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001417 a = madtuple((1,2,3,4,5))
1418 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001419 verify(tuple(a).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001420 a = madtuple(())
1421 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001422 verify(tuple(a).__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001423
1424 class madstring(str):
1425 _rev = None
1426 def rev(self):
1427 if self._rev is not None:
1428 return self._rev
1429 L = list(self)
1430 L.reverse()
1431 self._rev = self.__class__("".join(L))
1432 return self._rev
1433 s = madstring("abcdefghijklmnopqrstuvwxyz")
1434 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1435 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1436 for i in range(256):
1437 s = madstring("".join(map(chr, range(i))))
1438 t = s.rev()
1439 u = t.rev()
1440 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001441 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001442 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001443 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001444
Tim Petersc636f562001-09-11 01:52:02 +00001445 s = madstring("\x00" * 5)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001446 verify(str(s) == "\x00" * 5)
Tim Petersc636f562001-09-11 01:52:02 +00001447 verify(str(s).__class__ is str)
1448
Guido van Rossum91ee7982001-08-30 20:52:40 +00001449 class madunicode(unicode):
1450 _rev = None
1451 def rev(self):
1452 if self._rev is not None:
1453 return self._rev
1454 L = list(self)
1455 L.reverse()
1456 self._rev = self.__class__(u"".join(L))
1457 return self._rev
1458 u = madunicode("ABCDEF")
1459 verify(u.rev() == madunicode(u"FEDCBA"))
1460 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters64b5ce32001-09-10 20:52:51 +00001461 u = madunicode(u"12345")
1462 verify(unicode(u) == u"12345")
Tim Peters78e0fc72001-09-11 03:07:38 +00001463 verify(unicode(u).__class__ is unicode)
Guido van Rossum91ee7982001-08-30 20:52:40 +00001464
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465def all():
1466 lists()
1467 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00001468 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00001469 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 ints()
1471 longs()
1472 floats()
1473 complexes()
1474 spamlists()
1475 spamdicts()
1476 pydicts()
1477 pylists()
1478 metaclass()
1479 pymods()
1480 multi()
1481 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001482 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001483 slots()
1484 dynamics()
1485 errors()
1486 classmethods()
1487 staticmethods()
1488 classic()
1489 compattr()
1490 newslot()
1491 altmro()
1492 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001493 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001494 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001495 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001496 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00001497 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001498 inherits()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499
1500all()
1501
1502if verbose: print "All OK"