blob: f0f121b008e44620ef8c9c84b14491bfff516ca3 [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 Peters6d6c1a32001-08-02 04:15:00 +0000244binops = {
245 'add': '+',
246 'sub': '-',
247 'mul': '*',
248 'div': '/',
249 'mod': '%',
250 'divmod': 'divmod',
251 'pow': '**',
252 'lshift': '<<',
253 'rshift': '>>',
254 'and': '&',
255 'xor': '^',
256 'or': '|',
257 'cmp': 'cmp',
258 'lt': '<',
259 'le': '<=',
260 'eq': '==',
261 'ne': '!=',
262 'gt': '>',
263 'ge': '>=',
264 }
265
266for name, expr in binops.items():
267 if expr.islower():
268 expr = expr + "(a, b)"
269 else:
270 expr = 'a %s b' % expr
271 binops[name] = expr
272
273unops = {
274 'pos': '+',
275 'neg': '-',
276 'abs': 'abs',
277 'invert': '~',
278 'int': 'int',
279 'long': 'long',
280 'float': 'float',
281 'oct': 'oct',
282 'hex': 'hex',
283 }
284
285for name, expr in unops.items():
286 if expr.islower():
287 expr = expr + "(a)"
288 else:
289 expr = '%s a' % expr
290 unops[name] = expr
291
292def numops(a, b, skip=[]):
293 dict = {'a': a, 'b': b}
294 for name, expr in binops.items():
295 if name not in skip:
296 name = "__%s__" % name
297 if hasattr(a, name):
298 res = eval(expr, dict)
299 testbinop(a, b, res, expr, name)
300 for name, expr in unops.items():
301 name = "__%s__" % name
302 if hasattr(a, name):
303 res = eval(expr, dict)
304 testunop(a, res, expr, name)
305
306def ints():
307 if verbose: print "Testing int operations..."
308 numops(100, 3)
309
310def longs():
311 if verbose: print "Testing long operations..."
312 numops(100L, 3L)
313
314def floats():
315 if verbose: print "Testing float operations..."
316 numops(100.0, 3.0)
317
318def complexes():
319 if verbose: print "Testing complex operations..."
320 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
321 class Number(complex):
322 __slots__ = ['prec']
323 def __init__(self, *args, **kwds):
324 self.prec = kwds.get('prec', 12)
325 def __repr__(self):
326 prec = self.prec
327 if self.imag == 0.0:
328 return "%.*g" % (prec, self.real)
329 if self.real == 0.0:
330 return "%.*gj" % (prec, self.imag)
331 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
332 __str__ = __repr__
333 a = Number(3.14, prec=6)
334 verify(`a` == "3.14")
335 verify(a.prec == 6)
336
337def spamlists():
338 if verbose: print "Testing spamlist operations..."
339 import copy, xxsubtype as spam
340 def spamlist(l, memo=None):
341 import xxsubtype as spam
342 return spam.spamlist(l)
343 # This is an ugly hack:
344 copy._deepcopy_dispatch[spam.spamlist] = spamlist
345
346 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
347 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
348 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
349 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
350 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
351 "a[b:c]", "__getslice__")
352 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
353 "a+=b", "__iadd__")
354 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
355 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
356 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
357 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
358 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
359 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
360 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
361 # Test subclassing
362 class C(spam.spamlist):
363 def foo(self): return 1
364 a = C()
365 verify(a == [])
366 verify(a.foo() == 1)
367 a.append(100)
368 verify(a == [100])
369 verify(a.getstate() == 0)
370 a.setstate(42)
371 verify(a.getstate() == 42)
372
373def spamdicts():
374 if verbose: print "Testing spamdict operations..."
375 import copy, xxsubtype as spam
376 def spamdict(d, memo=None):
377 import xxsubtype as spam
378 sd = spam.spamdict()
379 for k, v in d.items(): sd[k] = v
380 return sd
381 # This is an ugly hack:
382 copy._deepcopy_dispatch[spam.spamdict] = spamdict
383
384 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
385 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
386 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
387 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
388 d = spamdict({1:2,3:4})
389 l1 = []
390 for i in d.keys(): l1.append(i)
391 l = []
392 for i in iter(d): l.append(i)
393 verify(l == l1)
394 l = []
395 for i in d.__iter__(): l.append(i)
396 verify(l == l1)
397 l = []
398 for i in type(spamdict({})).__iter__(d): l.append(i)
399 verify(l == l1)
400 straightd = {1:2, 3:4}
401 spamd = spamdict(straightd)
402 testunop(spamd, 2, "len(a)", "__len__")
403 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
404 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
405 "a[b]=c", "__setitem__")
406 # Test subclassing
407 class C(spam.spamdict):
408 def foo(self): return 1
409 a = C()
410 verify(a.items() == [])
411 verify(a.foo() == 1)
412 a['foo'] = 'bar'
413 verify(a.items() == [('foo', 'bar')])
414 verify(a.getstate() == 0)
415 a.setstate(100)
416 verify(a.getstate() == 100)
417
418def pydicts():
419 if verbose: print "Testing Python subclass of dict..."
420 verify(issubclass(dictionary, dictionary))
421 verify(isinstance({}, dictionary))
422 d = dictionary()
423 verify(d == {})
424 verify(d.__class__ is dictionary)
425 verify(isinstance(d, dictionary))
426 class C(dictionary):
427 state = -1
428 def __init__(self, *a, **kw):
429 if a:
430 assert len(a) == 1
431 self.state = a[0]
432 if kw:
433 for k, v in kw.items(): self[v] = k
434 def __getitem__(self, key):
435 return self.get(key, 0)
436 def __setitem__(self, key, value):
437 assert isinstance(key, type(0))
438 dictionary.__setitem__(self, key, value)
439 def setstate(self, state):
440 self.state = state
441 def getstate(self):
442 return self.state
443 verify(issubclass(C, dictionary))
444 a1 = C(12)
445 verify(a1.state == 12)
446 a2 = C(foo=1, bar=2)
447 verify(a2[1] == 'foo' and a2[2] == 'bar')
448 a = C()
449 verify(a.state == -1)
450 verify(a.getstate() == -1)
451 a.setstate(0)
452 verify(a.state == 0)
453 verify(a.getstate() == 0)
454 a.setstate(10)
455 verify(a.state == 10)
456 verify(a.getstate() == 10)
457 verify(a[42] == 0)
458 a[42] = 24
459 verify(a[42] == 24)
460 if verbose: print "pydict stress test ..."
461 N = 50
462 for i in range(N):
463 a[i] = C()
464 for j in range(N):
465 a[i][j] = i*j
466 for i in range(N):
467 for j in range(N):
468 verify(a[i][j] == i*j)
469
470def pylists():
471 if verbose: print "Testing Python subclass of list..."
472 class C(list):
473 def __getitem__(self, i):
474 return list.__getitem__(self, i) + 100
475 def __getslice__(self, i, j):
476 return (i, j)
477 a = C()
478 a.extend([0,1,2])
479 verify(a[0] == 100)
480 verify(a[1] == 101)
481 verify(a[2] == 102)
482 verify(a[100:200] == (100,200))
483
484def metaclass():
485 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000486 class C:
487 __metaclass__ = type
488 def __init__(self):
489 self.__state = 0
490 def getstate(self):
491 return self.__state
492 def setstate(self, state):
493 self.__state = state
494 a = C()
495 verify(a.getstate() == 0)
496 a.setstate(10)
497 verify(a.getstate() == 10)
498 class D:
499 class __metaclass__(type):
500 def myself(cls): return cls
501 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000502 d = D()
503 verify(d.__class__ is D)
504 class M1(type):
505 def __new__(cls, name, bases, dict):
506 dict['__spam__'] = 1
507 return type.__new__(cls, name, bases, dict)
508 class C:
509 __metaclass__ = M1
510 verify(C.__spam__ == 1)
511 c = C()
512 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000513
Guido van Rossum309b5662001-08-17 11:43:17 +0000514 class _instance(object):
515 pass
516 class M2(object):
517 def __new__(cls, name, bases, dict):
518 self = object.__new__(cls)
519 self.name = name
520 self.bases = bases
521 self.dict = dict
522 return self
523 __new__ = staticmethod(__new__)
524 def __call__(self):
525 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000526 # Early binding of methods
527 for key in self.dict:
528 if key.startswith("__"):
529 continue
530 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000531 return it
532 class C:
533 __metaclass__ = M2
534 def spam(self):
535 return 42
536 verify(C.name == 'C')
537 verify(C.bases == ())
538 verify('spam' in C.dict)
539 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000540 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000541
Guido van Rossum91ee7982001-08-30 20:52:40 +0000542 # More metaclass examples
543
544 class autosuper(type):
545 # Automatically add __super to the class
546 # This trick only works for dynamic classes
547 # so we force __dynamic__ = 1
548 def __new__(metaclass, name, bases, dict):
549 # XXX Should check that name isn't already a base class name
550 dict["__dynamic__"] = 1
551 cls = super(autosuper, metaclass).__new__(metaclass,
552 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000553 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000554 while name[:1] == "_":
555 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000556 if name:
557 name = "_%s__super" % name
558 else:
559 name = "__super"
560 setattr(cls, name, super(cls))
561 return cls
562 class A:
563 __metaclass__ = autosuper
564 def meth(self):
565 return "A"
566 class B(A):
567 def meth(self):
568 return "B" + self.__super.meth()
569 class C(A):
570 def meth(self):
571 return "C" + self.__super.meth()
572 class D(C, B):
573 def meth(self):
574 return "D" + self.__super.meth()
575 verify(D().meth() == "DCBA")
576 class E(B, C):
577 def meth(self):
578 return "E" + self.__super.meth()
579 verify(E().meth() == "EBCA")
580
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000581 class autoproperty(type):
582 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000583 # named _get_x and/or _set_x are found
584 def __new__(metaclass, name, bases, dict):
585 hits = {}
586 for key, val in dict.iteritems():
587 if key.startswith("_get_"):
588 key = key[5:]
589 get, set = hits.get(key, (None, None))
590 get = val
591 hits[key] = get, set
592 elif key.startswith("_set_"):
593 key = key[5:]
594 get, set = hits.get(key, (None, None))
595 set = val
596 hits[key] = get, set
597 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000598 dict[key] = property(get, set)
599 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000600 name, bases, dict)
601 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000602 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000603 def _get_x(self):
604 return -self.__x
605 def _set_x(self, x):
606 self.__x = -x
607 a = A()
608 verify(not hasattr(a, "x"))
609 a.x = 12
610 verify(a.x == 12)
611 verify(a._A__x == -12)
612
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000613 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000614 # Merge of multiple cooperating metaclasses
615 pass
616 class A:
617 __metaclass__ = multimetaclass
618 def _get_x(self):
619 return "A"
620 class B(A):
621 def _get_x(self):
622 return "B" + self.__super._get_x()
623 class C(A):
624 def _get_x(self):
625 return "C" + self.__super._get_x()
626 class D(C, B):
627 def _get_x(self):
628 return "D" + self.__super._get_x()
629 verify(D().x == "DCBA")
630
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631def pymods():
632 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000633 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000634 import sys
635 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000636 class MM(MT):
637 def __init__(self):
638 MT.__init__(self)
639 def __getattr__(self, name):
640 log.append(("getattr", name))
641 return MT.__getattr__(self, name)
642 def __setattr__(self, name, value):
643 log.append(("setattr", name, value))
644 MT.__setattr__(self, name, value)
645 def __delattr__(self, name):
646 log.append(("delattr", name))
647 MT.__delattr__(self, name)
648 a = MM()
649 a.foo = 12
650 x = a.foo
651 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000652 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000653 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654 ("delattr", "foo")], log)
655
656def multi():
657 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000658 class C(object):
659 def __init__(self):
660 self.__state = 0
661 def getstate(self):
662 return self.__state
663 def setstate(self, state):
664 self.__state = state
665 a = C()
666 verify(a.getstate() == 0)
667 a.setstate(10)
668 verify(a.getstate() == 10)
669 class D(dictionary, C):
670 def __init__(self):
671 type({}).__init__(self)
672 C.__init__(self)
673 d = D()
674 verify(d.keys() == [])
675 d["hello"] = "world"
676 verify(d.items() == [("hello", "world")])
677 verify(d["hello"] == "world")
678 verify(d.getstate() == 0)
679 d.setstate(10)
680 verify(d.getstate() == 10)
681 verify(D.__mro__ == (D, dictionary, C, object))
682
Guido van Rossume45763a2001-08-10 21:28:46 +0000683 # SF bug #442833
684 class Node(object):
685 def __int__(self):
686 return int(self.foo())
687 def foo(self):
688 return "23"
689 class Frag(Node, list):
690 def foo(self):
691 return "42"
692 verify(Node().__int__() == 23)
693 verify(int(Node()) == 23)
694 verify(Frag().__int__() == 42)
695 verify(int(Frag()) == 42)
696
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697def diamond():
698 if verbose: print "Testing multiple inheritance special cases..."
699 class A(object):
700 def spam(self): return "A"
701 verify(A().spam() == "A")
702 class B(A):
703 def boo(self): return "B"
704 def spam(self): return "B"
705 verify(B().spam() == "B")
706 verify(B().boo() == "B")
707 class C(A):
708 def boo(self): return "C"
709 verify(C().spam() == "A")
710 verify(C().boo() == "C")
711 class D(B, C): pass
712 verify(D().spam() == "B")
713 verify(D().boo() == "B")
714 verify(D.__mro__ == (D, B, C, A, object))
715 class E(C, B): pass
716 verify(E().spam() == "B")
717 verify(E().boo() == "C")
718 verify(E.__mro__ == (E, C, B, A, object))
719 class F(D, E): pass
720 verify(F().spam() == "B")
721 verify(F().boo() == "B")
722 verify(F.__mro__ == (F, D, E, B, C, A, object))
723 class G(E, D): pass
724 verify(G().spam() == "B")
725 verify(G().boo() == "C")
726 verify(G.__mro__ == (G, E, D, C, B, A, object))
727
Guido van Rossum37202612001-08-09 19:45:21 +0000728def objects():
729 if verbose: print "Testing object class..."
730 a = object()
731 verify(a.__class__ == object == type(a))
732 b = object()
733 verify(a is not b)
734 verify(not hasattr(a, "foo"))
735 try:
736 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000737 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000738 pass
739 else:
740 verify(0, "object() should not allow setting a foo attribute")
741 verify(not hasattr(object(), "__dict__"))
742
743 class Cdict(object):
744 pass
745 x = Cdict()
746 verify(x.__dict__ is None)
747 x.foo = 1
748 verify(x.foo == 1)
749 verify(x.__dict__ == {'foo': 1})
750
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751def slots():
752 if verbose: print "Testing __slots__..."
753 class C0(object):
754 __slots__ = []
755 x = C0()
756 verify(not hasattr(x, "__dict__"))
757 verify(not hasattr(x, "foo"))
758
759 class C1(object):
760 __slots__ = ['a']
761 x = C1()
762 verify(not hasattr(x, "__dict__"))
763 verify(x.a == None)
764 x.a = 1
765 verify(x.a == 1)
766 del x.a
767 verify(x.a == None)
768
769 class C3(object):
770 __slots__ = ['a', 'b', 'c']
771 x = C3()
772 verify(not hasattr(x, "__dict__"))
773 verify(x.a is None)
774 verify(x.b is None)
775 verify(x.c is None)
776 x.a = 1
777 x.b = 2
778 x.c = 3
779 verify(x.a == 1)
780 verify(x.b == 2)
781 verify(x.c == 3)
782
783def dynamics():
784 if verbose: print "Testing __dynamic__..."
785 verify(object.__dynamic__ == 0)
786 verify(list.__dynamic__ == 0)
787 class S1:
788 __metaclass__ = type
789 verify(S1.__dynamic__ == 0)
790 class S(object):
791 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000792 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793 class D(object):
794 __dynamic__ = 1
795 verify(D.__dynamic__ == 1)
796 class E(D, S):
797 pass
798 verify(E.__dynamic__ == 1)
799 class F(S, D):
800 pass
801 verify(F.__dynamic__ == 1)
802 try:
803 S.foo = 1
804 except (AttributeError, TypeError):
805 pass
806 else:
807 verify(0, "assignment to a static class attribute should be illegal")
808 D.foo = 1
809 verify(D.foo == 1)
810 # Test that dynamic attributes are inherited
811 verify(E.foo == 1)
812 verify(F.foo == 1)
813 class SS(D):
814 __dynamic__ = 0
815 verify(SS.__dynamic__ == 0)
816 verify(SS.foo == 1)
817 try:
818 SS.foo = 1
819 except (AttributeError, TypeError):
820 pass
821 else:
822 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000823 # Test dynamic instances
824 class C(object):
825 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000826 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000827 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000828 C.foobar = 2
829 verify(a.foobar == 2)
830 C.method = lambda self: 42
831 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000832 C.__repr__ = lambda self: "C()"
833 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000834 C.__int__ = lambda self: 100
835 verify(int(a) == 100)
836 verify(a.foobar == 2)
837 verify(not hasattr(a, "spam"))
838 def mygetattr(self, name):
839 if name == "spam":
840 return "spam"
841 else:
842 return object.__getattr__(self, name)
843 C.__getattr__ = mygetattr
844 verify(a.spam == "spam")
845 a.new = 12
846 verify(a.new == 12)
847 def mysetattr(self, name, value):
848 if name == "spam":
849 raise AttributeError
850 return object.__setattr__(self, name, value)
851 C.__setattr__ = mysetattr
852 try:
853 a.spam = "not spam"
854 except AttributeError:
855 pass
856 else:
857 verify(0, "expected AttributeError")
858 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000859 class D(C):
860 pass
861 d = D()
862 d.foo = 1
863 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864
865def errors():
866 if verbose: print "Testing errors..."
867
868 try:
869 class C(list, dictionary):
870 pass
871 except TypeError:
872 pass
873 else:
874 verify(0, "inheritance from both list and dict should be illegal")
875
876 try:
877 class C(object, None):
878 pass
879 except TypeError:
880 pass
881 else:
882 verify(0, "inheritance from non-type should be illegal")
883 class Classic:
884 pass
885
886 try:
887 class C(object, Classic):
888 pass
889 except TypeError:
890 pass
891 else:
892 verify(0, "inheritance from object and Classic should be illegal")
893
894 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000895 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000896 pass
897 except TypeError:
898 pass
899 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000900 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901
902 try:
903 class C(object):
904 __slots__ = 1
905 except TypeError:
906 pass
907 else:
908 verify(0, "__slots__ = 1 should be illegal")
909
910 try:
911 class C(object):
912 __slots__ = [1]
913 except TypeError:
914 pass
915 else:
916 verify(0, "__slots__ = [1] should be illegal")
917
918def classmethods():
919 if verbose: print "Testing class methods..."
920 class C(object):
921 def foo(*a): return a
922 goo = classmethod(foo)
923 c = C()
924 verify(C.goo(1) == (C, 1))
925 verify(c.goo(1) == (C, 1))
926 verify(c.foo(1) == (c, 1))
927 class D(C):
928 pass
929 d = D()
930 verify(D.goo(1) == (D, 1))
931 verify(d.goo(1) == (D, 1))
932 verify(d.foo(1) == (d, 1))
933 verify(D.foo(d, 1) == (d, 1))
934
935def staticmethods():
936 if verbose: print "Testing static methods..."
937 class C(object):
938 def foo(*a): return a
939 goo = staticmethod(foo)
940 c = C()
941 verify(C.goo(1) == (1,))
942 verify(c.goo(1) == (1,))
943 verify(c.foo(1) == (c, 1,))
944 class D(C):
945 pass
946 d = D()
947 verify(D.goo(1) == (1,))
948 verify(d.goo(1) == (1,))
949 verify(d.foo(1) == (d, 1))
950 verify(D.foo(d, 1) == (d, 1))
951
952def classic():
953 if verbose: print "Testing classic classes..."
954 class C:
955 def foo(*a): return a
956 goo = classmethod(foo)
957 c = C()
958 verify(C.goo(1) == (C, 1))
959 verify(c.goo(1) == (C, 1))
960 verify(c.foo(1) == (c, 1))
961 class D(C):
962 pass
963 d = D()
964 verify(D.goo(1) == (D, 1))
965 verify(d.goo(1) == (D, 1))
966 verify(d.foo(1) == (d, 1))
967 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +0000968 class E: # *not* subclassing from C
969 foo = C.foo
970 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +0000971 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972
973def compattr():
974 if verbose: print "Testing computed attributes..."
975 class C(object):
976 class computed_attribute(object):
977 def __init__(self, get, set=None):
978 self.__get = get
979 self.__set = set
980 def __get__(self, obj, type=None):
981 return self.__get(obj)
982 def __set__(self, obj, value):
983 return self.__set(obj, value)
984 def __init__(self):
985 self.__x = 0
986 def __get_x(self):
987 x = self.__x
988 self.__x = x+1
989 return x
990 def __set_x(self, x):
991 self.__x = x
992 x = computed_attribute(__get_x, __set_x)
993 a = C()
994 verify(a.x == 0)
995 verify(a.x == 1)
996 a.x = 10
997 verify(a.x == 10)
998 verify(a.x == 11)
999
1000def newslot():
1001 if verbose: print "Testing __new__ slot override..."
1002 class C(list):
1003 def __new__(cls):
1004 self = list.__new__(cls)
1005 self.foo = 1
1006 return self
1007 def __init__(self):
1008 self.foo = self.foo + 2
1009 a = C()
1010 verify(a.foo == 3)
1011 verify(a.__class__ is C)
1012 class D(C):
1013 pass
1014 b = D()
1015 verify(b.foo == 3)
1016 verify(b.__class__ is D)
1017
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018def altmro():
1019 if verbose: print "Testing mro() and overriding it..."
1020 class A(object):
1021 def f(self): return "A"
1022 class B(A):
1023 pass
1024 class C(A):
1025 def f(self): return "C"
1026 class D(B, C):
1027 pass
1028 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1029 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001030 class PerverseMetaType(type):
1031 def mro(cls):
1032 L = type.mro(cls)
1033 L.reverse()
1034 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 class X(A,B,C,D):
1036 __metaclass__ = PerverseMetaType
1037 verify(X.__mro__ == (object, A, C, B, D, X))
1038 verify(X().f() == "A")
1039
1040def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001041 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042
1043 class B(object):
1044 "Intermediate class because object doesn't have a __setattr__"
1045
1046 class C(B):
1047
1048 def __getattr__(self, name):
1049 if name == "foo":
1050 return ("getattr", name)
1051 else:
1052 return B.__getattr__(self, name)
1053 def __setattr__(self, name, value):
1054 if name == "foo":
1055 self.setattr = (name, value)
1056 else:
1057 return B.__setattr__(self, name, value)
1058 def __delattr__(self, name):
1059 if name == "foo":
1060 self.delattr = name
1061 else:
1062 return B.__delattr__(self, name)
1063
1064 def __getitem__(self, key):
1065 return ("getitem", key)
1066 def __setitem__(self, key, value):
1067 self.setitem = (key, value)
1068 def __delitem__(self, key):
1069 self.delitem = key
1070
1071 def __getslice__(self, i, j):
1072 return ("getslice", i, j)
1073 def __setslice__(self, i, j, value):
1074 self.setslice = (i, j, value)
1075 def __delslice__(self, i, j):
1076 self.delslice = (i, j)
1077
1078 a = C()
1079 verify(a.foo == ("getattr", "foo"))
1080 a.foo = 12
1081 verify(a.setattr == ("foo", 12))
1082 del a.foo
1083 verify(a.delattr == "foo")
1084
1085 verify(a[12] == ("getitem", 12))
1086 a[12] = 21
1087 verify(a.setitem == (12, 21))
1088 del a[12]
1089 verify(a.delitem == 12)
1090
1091 verify(a[0:10] == ("getslice", 0, 10))
1092 a[0:10] = "foo"
1093 verify(a.setslice == (0, 10, "foo"))
1094 del a[0:10]
1095 verify(a.delslice == (0, 10))
1096
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001097def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001098 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001099 class C(object):
1100 def __init__(self, x):
1101 self.x = x
1102 def foo(self):
1103 return self.x
1104 c1 = C(1)
1105 verify(c1.foo() == 1)
1106 class D(C):
1107 boo = C.foo
1108 goo = c1.foo
1109 d2 = D(2)
1110 verify(d2.foo() == 2)
1111 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001112 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001113 class E(object):
1114 foo = C.foo
1115 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001116 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001117
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001118def specials():
1119 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001120 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001121 # Test the default behavior for static classes
1122 class C(object):
1123 def __getitem__(self, i):
1124 if 0 <= i < 10: return i
1125 raise IndexError
1126 c1 = C()
1127 c2 = C()
1128 verify(not not c1)
1129 verify(hash(c1) == id(c1))
1130 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1131 verify(c1 == c1)
1132 verify(c1 != c2)
1133 verify(not c1 != c1)
1134 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001135 # Note that the module name appears in str/repr, and that varies
1136 # depending on whether this test is run standalone or from a framework.
1137 verify(str(c1).find('C instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001138 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001139 verify(-1 not in c1)
1140 for i in range(10):
1141 verify(i in c1)
1142 verify(10 not in c1)
1143 # Test the default behavior for dynamic classes
1144 class D(object):
1145 __dynamic__ = 1
1146 def __getitem__(self, i):
1147 if 0 <= i < 10: return i
1148 raise IndexError
1149 d1 = D()
1150 d2 = D()
1151 verify(not not d1)
1152 verify(hash(d1) == id(d1))
1153 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1154 verify(d1 == d1)
1155 verify(d1 != d2)
1156 verify(not d1 != d1)
1157 verify(not d1 == d2)
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(d1).find('D instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001161 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001162 verify(-1 not in d1)
1163 for i in range(10):
1164 verify(i in d1)
1165 verify(10 not in d1)
1166 # Test overridden behavior for static classes
1167 class Proxy(object):
1168 def __init__(self, x):
1169 self.x = x
1170 def __nonzero__(self):
1171 return not not self.x
1172 def __hash__(self):
1173 return hash(self.x)
1174 def __eq__(self, other):
1175 return self.x == other
1176 def __ne__(self, other):
1177 return self.x != other
1178 def __cmp__(self, other):
1179 return cmp(self.x, other.x)
1180 def __str__(self):
1181 return "Proxy:%s" % self.x
1182 def __repr__(self):
1183 return "Proxy(%r)" % self.x
1184 def __contains__(self, value):
1185 return value in self.x
1186 p0 = Proxy(0)
1187 p1 = Proxy(1)
1188 p_1 = Proxy(-1)
1189 verify(not p0)
1190 verify(not not p1)
1191 verify(hash(p0) == hash(0))
1192 verify(p0 == p0)
1193 verify(p0 != p1)
1194 verify(not p0 != p0)
1195 verify(not p0 == p1)
1196 verify(cmp(p0, p1) == -1)
1197 verify(cmp(p0, p0) == 0)
1198 verify(cmp(p0, p_1) == 1)
1199 verify(str(p0) == "Proxy:0")
1200 verify(repr(p0) == "Proxy(0)")
1201 p10 = Proxy(range(10))
1202 verify(-1 not in p10)
1203 for i in range(10):
1204 verify(i in p10)
1205 verify(10 not in p10)
1206 # Test overridden behavior for dynamic classes
1207 class DProxy(object):
1208 __dynamic__ = 1
1209 def __init__(self, x):
1210 self.x = x
1211 def __nonzero__(self):
1212 return not not self.x
1213 def __hash__(self):
1214 return hash(self.x)
1215 def __eq__(self, other):
1216 return self.x == other
1217 def __ne__(self, other):
1218 return self.x != other
1219 def __cmp__(self, other):
1220 return cmp(self.x, other.x)
1221 def __str__(self):
1222 return "DProxy:%s" % self.x
1223 def __repr__(self):
1224 return "DProxy(%r)" % self.x
1225 def __contains__(self, value):
1226 return value in self.x
1227 p0 = DProxy(0)
1228 p1 = DProxy(1)
1229 p_1 = DProxy(-1)
1230 verify(not p0)
1231 verify(not not p1)
1232 verify(hash(p0) == hash(0))
1233 verify(p0 == p0)
1234 verify(p0 != p1)
1235 verify(not p0 != p0)
1236 verify(not p0 == p1)
1237 verify(cmp(p0, p1) == -1)
1238 verify(cmp(p0, p0) == 0)
1239 verify(cmp(p0, p_1) == 1)
1240 verify(str(p0) == "DProxy:0")
1241 verify(repr(p0) == "DProxy(0)")
1242 p10 = DProxy(range(10))
1243 verify(-1 not in p10)
1244 for i in range(10):
1245 verify(i in p10)
1246 verify(10 not in p10)
1247
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001248def weakrefs():
1249 if verbose: print "Testing weak references..."
1250 import weakref
1251 class C(object):
1252 pass
1253 c = C()
1254 r = weakref.ref(c)
1255 verify(r() is c)
1256 del c
1257 verify(r() is None)
1258 del r
1259 class NoWeak(object):
1260 __slots__ = ['foo']
1261 no = NoWeak()
1262 try:
1263 weakref.ref(no)
1264 except TypeError, msg:
1265 verify(str(msg).find("weakly") >= 0)
1266 else:
1267 verify(0, "weakref.ref(no) should be illegal")
1268 class Weak(object):
1269 __slots__ = ['foo', '__weakref__']
1270 yes = Weak()
1271 r = weakref.ref(yes)
1272 verify(r() is yes)
1273 del yes
1274 verify(r() is None)
1275 del r
1276
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001277def properties():
1278 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001279 class C(object):
1280 def getx(self):
1281 return self.__x
1282 def setx(self, value):
1283 self.__x = value
1284 def delx(self):
1285 del self.__x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001286 x = property(getx, setx, delx)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001287 a = C()
1288 verify(not hasattr(a, "x"))
1289 a.x = 42
1290 verify(a._C__x == 42)
1291 verify(a.x == 42)
1292 del a.x
1293 verify(not hasattr(a, "x"))
1294 verify(not hasattr(a, "_C__x"))
1295 C.x.__set__(a, 100)
1296 verify(C.x.__get__(a) == 100)
1297## C.x.__set__(a)
1298## verify(not hasattr(a, "x"))
1299
Guido van Rossumc4a18802001-08-24 16:55:27 +00001300def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001301 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001302
1303 class A(object):
1304 def meth(self, a):
1305 return "A(%r)" % a
1306
1307 verify(A().meth(1) == "A(1)")
1308
1309 class B(A):
1310 def __init__(self):
1311 self.__super = super(B, self)
1312 def meth(self, a):
1313 return "B(%r)" % a + self.__super.meth(a)
1314
1315 verify(B().meth(2) == "B(2)A(2)")
1316
1317 class C(A):
1318 __dynamic__ = 1
1319 def meth(self, a):
1320 return "C(%r)" % a + self.__super.meth(a)
1321 C._C__super = super(C)
1322
1323 verify(C().meth(3) == "C(3)A(3)")
1324
1325 class D(C, B):
1326 def meth(self, a):
1327 return "D(%r)" % a + super(D, self).meth(a)
1328
1329 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1330
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001331def inherits():
1332 if verbose: print "Testing inheritance from basic types..."
1333
1334 class hexint(int):
1335 def __repr__(self):
1336 return hex(self)
1337 def __add__(self, other):
1338 return hexint(int.__add__(self, other))
1339 # (Note that overriding __radd__ doesn't work,
1340 # because the int type gets first dibs.)
1341 verify(repr(hexint(7) + 9) == "0x10")
1342 verify(repr(hexint(1000) + 7) == "0x3ef")
1343
1344 class octlong(long):
1345 __slots__ = []
1346 def __str__(self):
1347 s = oct(self)
1348 if s[-1] == 'L':
1349 s = s[:-1]
1350 return s
1351 def __add__(self, other):
1352 return self.__class__(super(octlong, self).__add__(other))
1353 __radd__ = __add__
1354 verify(str(octlong(3) + 5) == "010")
1355 # (Note that overriding __radd__ here only seems to work
1356 # because the example uses a short int left argument.)
1357 verify(str(5 + octlong(3000)) == "05675")
1358
1359 class precfloat(float):
1360 __slots__ = ['prec']
1361 def __init__(self, value=0.0, prec=12):
1362 self.prec = int(prec)
1363 float.__init__(value)
1364 def __repr__(self):
1365 return "%.*g" % (self.prec, self)
1366 verify(repr(precfloat(1.1)) == "1.1")
1367
1368 class madtuple(tuple):
1369 _rev = None
1370 def rev(self):
1371 if self._rev is not None:
1372 return self._rev
1373 L = list(self)
1374 L.reverse()
1375 self._rev = self.__class__(L)
1376 return self._rev
1377 a = madtuple((1,2,3,4,5,6,7,8,9,0))
1378 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1379 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1380 for i in range(512):
1381 t = madtuple(range(i))
1382 u = t.rev()
1383 v = u.rev()
1384 verify(v == t)
1385
1386 class madstring(str):
1387 _rev = None
1388 def rev(self):
1389 if self._rev is not None:
1390 return self._rev
1391 L = list(self)
1392 L.reverse()
1393 self._rev = self.__class__("".join(L))
1394 return self._rev
1395 s = madstring("abcdefghijklmnopqrstuvwxyz")
1396 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1397 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1398 for i in range(256):
1399 s = madstring("".join(map(chr, range(i))))
1400 t = s.rev()
1401 u = t.rev()
1402 verify(u == s)
1403
Guido van Rossum91ee7982001-08-30 20:52:40 +00001404 class madunicode(unicode):
1405 _rev = None
1406 def rev(self):
1407 if self._rev is not None:
1408 return self._rev
1409 L = list(self)
1410 L.reverse()
1411 self._rev = self.__class__(u"".join(L))
1412 return self._rev
1413 u = madunicode("ABCDEF")
1414 verify(u.rev() == madunicode(u"FEDCBA"))
1415 verify(u.rev().rev() == madunicode(u"ABCDEF"))
1416
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417def all():
1418 lists()
1419 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00001420 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00001421 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 ints()
1423 longs()
1424 floats()
1425 complexes()
1426 spamlists()
1427 spamdicts()
1428 pydicts()
1429 pylists()
1430 metaclass()
1431 pymods()
1432 multi()
1433 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001434 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435 slots()
1436 dynamics()
1437 errors()
1438 classmethods()
1439 staticmethods()
1440 classic()
1441 compattr()
1442 newslot()
1443 altmro()
1444 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001445 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001446 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001447 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001448 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00001449 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001450 inherits()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451
1452all()
1453
1454if verbose: print "All OK"