blob: bdde4519695fb216766d3f50c3b882068378c002 [file] [log] [blame]
Tim Peters6d6c1a32001-08-02 04:15:00 +00001# Test descriptor-related enhancements
2
3from test_support import verify, verbose
4from 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
126binops = {
127 'add': '+',
128 'sub': '-',
129 'mul': '*',
130 'div': '/',
131 'mod': '%',
132 'divmod': 'divmod',
133 'pow': '**',
134 'lshift': '<<',
135 'rshift': '>>',
136 'and': '&',
137 'xor': '^',
138 'or': '|',
139 'cmp': 'cmp',
140 'lt': '<',
141 'le': '<=',
142 'eq': '==',
143 'ne': '!=',
144 'gt': '>',
145 'ge': '>=',
146 }
147
148for name, expr in binops.items():
149 if expr.islower():
150 expr = expr + "(a, b)"
151 else:
152 expr = 'a %s b' % expr
153 binops[name] = expr
154
155unops = {
156 'pos': '+',
157 'neg': '-',
158 'abs': 'abs',
159 'invert': '~',
160 'int': 'int',
161 'long': 'long',
162 'float': 'float',
163 'oct': 'oct',
164 'hex': 'hex',
165 }
166
167for name, expr in unops.items():
168 if expr.islower():
169 expr = expr + "(a)"
170 else:
171 expr = '%s a' % expr
172 unops[name] = expr
173
174def numops(a, b, skip=[]):
175 dict = {'a': a, 'b': b}
176 for name, expr in binops.items():
177 if name not in skip:
178 name = "__%s__" % name
179 if hasattr(a, name):
180 res = eval(expr, dict)
181 testbinop(a, b, res, expr, name)
182 for name, expr in unops.items():
183 name = "__%s__" % name
184 if hasattr(a, name):
185 res = eval(expr, dict)
186 testunop(a, res, expr, name)
187
188def ints():
189 if verbose: print "Testing int operations..."
190 numops(100, 3)
191
192def longs():
193 if verbose: print "Testing long operations..."
194 numops(100L, 3L)
195
196def floats():
197 if verbose: print "Testing float operations..."
198 numops(100.0, 3.0)
199
200def complexes():
201 if verbose: print "Testing complex operations..."
202 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
203 class Number(complex):
204 __slots__ = ['prec']
205 def __init__(self, *args, **kwds):
206 self.prec = kwds.get('prec', 12)
207 def __repr__(self):
208 prec = self.prec
209 if self.imag == 0.0:
210 return "%.*g" % (prec, self.real)
211 if self.real == 0.0:
212 return "%.*gj" % (prec, self.imag)
213 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
214 __str__ = __repr__
215 a = Number(3.14, prec=6)
216 verify(`a` == "3.14")
217 verify(a.prec == 6)
218
219def spamlists():
220 if verbose: print "Testing spamlist operations..."
221 import copy, xxsubtype as spam
222 def spamlist(l, memo=None):
223 import xxsubtype as spam
224 return spam.spamlist(l)
225 # This is an ugly hack:
226 copy._deepcopy_dispatch[spam.spamlist] = spamlist
227
228 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
229 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
230 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
231 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
232 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
233 "a[b:c]", "__getslice__")
234 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
235 "a+=b", "__iadd__")
236 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
237 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
238 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
239 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
240 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
241 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
242 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
243 # Test subclassing
244 class C(spam.spamlist):
245 def foo(self): return 1
246 a = C()
247 verify(a == [])
248 verify(a.foo() == 1)
249 a.append(100)
250 verify(a == [100])
251 verify(a.getstate() == 0)
252 a.setstate(42)
253 verify(a.getstate() == 42)
254
255def spamdicts():
256 if verbose: print "Testing spamdict operations..."
257 import copy, xxsubtype as spam
258 def spamdict(d, memo=None):
259 import xxsubtype as spam
260 sd = spam.spamdict()
261 for k, v in d.items(): sd[k] = v
262 return sd
263 # This is an ugly hack:
264 copy._deepcopy_dispatch[spam.spamdict] = spamdict
265
266 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
267 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
268 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
269 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
270 d = spamdict({1:2,3:4})
271 l1 = []
272 for i in d.keys(): l1.append(i)
273 l = []
274 for i in iter(d): l.append(i)
275 verify(l == l1)
276 l = []
277 for i in d.__iter__(): l.append(i)
278 verify(l == l1)
279 l = []
280 for i in type(spamdict({})).__iter__(d): l.append(i)
281 verify(l == l1)
282 straightd = {1:2, 3:4}
283 spamd = spamdict(straightd)
284 testunop(spamd, 2, "len(a)", "__len__")
285 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
286 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
287 "a[b]=c", "__setitem__")
288 # Test subclassing
289 class C(spam.spamdict):
290 def foo(self): return 1
291 a = C()
292 verify(a.items() == [])
293 verify(a.foo() == 1)
294 a['foo'] = 'bar'
295 verify(a.items() == [('foo', 'bar')])
296 verify(a.getstate() == 0)
297 a.setstate(100)
298 verify(a.getstate() == 100)
299
300def pydicts():
301 if verbose: print "Testing Python subclass of dict..."
302 verify(issubclass(dictionary, dictionary))
303 verify(isinstance({}, dictionary))
304 d = dictionary()
305 verify(d == {})
306 verify(d.__class__ is dictionary)
307 verify(isinstance(d, dictionary))
308 class C(dictionary):
309 state = -1
310 def __init__(self, *a, **kw):
311 if a:
312 assert len(a) == 1
313 self.state = a[0]
314 if kw:
315 for k, v in kw.items(): self[v] = k
316 def __getitem__(self, key):
317 return self.get(key, 0)
318 def __setitem__(self, key, value):
319 assert isinstance(key, type(0))
320 dictionary.__setitem__(self, key, value)
321 def setstate(self, state):
322 self.state = state
323 def getstate(self):
324 return self.state
325 verify(issubclass(C, dictionary))
326 a1 = C(12)
327 verify(a1.state == 12)
328 a2 = C(foo=1, bar=2)
329 verify(a2[1] == 'foo' and a2[2] == 'bar')
330 a = C()
331 verify(a.state == -1)
332 verify(a.getstate() == -1)
333 a.setstate(0)
334 verify(a.state == 0)
335 verify(a.getstate() == 0)
336 a.setstate(10)
337 verify(a.state == 10)
338 verify(a.getstate() == 10)
339 verify(a[42] == 0)
340 a[42] = 24
341 verify(a[42] == 24)
342 if verbose: print "pydict stress test ..."
343 N = 50
344 for i in range(N):
345 a[i] = C()
346 for j in range(N):
347 a[i][j] = i*j
348 for i in range(N):
349 for j in range(N):
350 verify(a[i][j] == i*j)
351
352def pylists():
353 if verbose: print "Testing Python subclass of list..."
354 class C(list):
355 def __getitem__(self, i):
356 return list.__getitem__(self, i) + 100
357 def __getslice__(self, i, j):
358 return (i, j)
359 a = C()
360 a.extend([0,1,2])
361 verify(a[0] == 100)
362 verify(a[1] == 101)
363 verify(a[2] == 102)
364 verify(a[100:200] == (100,200))
365
366def metaclass():
367 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368 class C:
369 __metaclass__ = type
370 def __init__(self):
371 self.__state = 0
372 def getstate(self):
373 return self.__state
374 def setstate(self, state):
375 self.__state = state
376 a = C()
377 verify(a.getstate() == 0)
378 a.setstate(10)
379 verify(a.getstate() == 10)
380 class D:
381 class __metaclass__(type):
382 def myself(cls): return cls
383 verify(D.myself() == D)
384
Tim Peters6d6c1a32001-08-02 04:15:00 +0000385def pymods():
386 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000387 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000388 import sys
389 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000390 class MM(MT):
391 def __init__(self):
392 MT.__init__(self)
393 def __getattr__(self, name):
394 log.append(("getattr", name))
395 return MT.__getattr__(self, name)
396 def __setattr__(self, name, value):
397 log.append(("setattr", name, value))
398 MT.__setattr__(self, name, value)
399 def __delattr__(self, name):
400 log.append(("delattr", name))
401 MT.__delattr__(self, name)
402 a = MM()
403 a.foo = 12
404 x = a.foo
405 del a.foo
406 verify(log == [('getattr', '__init__'),
407 ('getattr', '__setattr__'),
408 ("setattr", "foo", 12),
409 ("getattr", "foo"),
410 ('getattr', '__delattr__'),
411 ("delattr", "foo")], log)
412
413def multi():
414 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415 class C(object):
416 def __init__(self):
417 self.__state = 0
418 def getstate(self):
419 return self.__state
420 def setstate(self, state):
421 self.__state = state
422 a = C()
423 verify(a.getstate() == 0)
424 a.setstate(10)
425 verify(a.getstate() == 10)
426 class D(dictionary, C):
427 def __init__(self):
428 type({}).__init__(self)
429 C.__init__(self)
430 d = D()
431 verify(d.keys() == [])
432 d["hello"] = "world"
433 verify(d.items() == [("hello", "world")])
434 verify(d["hello"] == "world")
435 verify(d.getstate() == 0)
436 d.setstate(10)
437 verify(d.getstate() == 10)
438 verify(D.__mro__ == (D, dictionary, C, object))
439
Guido van Rossume45763a2001-08-10 21:28:46 +0000440 # SF bug #442833
441 class Node(object):
442 def __int__(self):
443 return int(self.foo())
444 def foo(self):
445 return "23"
446 class Frag(Node, list):
447 def foo(self):
448 return "42"
449 verify(Node().__int__() == 23)
450 verify(int(Node()) == 23)
451 verify(Frag().__int__() == 42)
452 verify(int(Frag()) == 42)
453
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454def diamond():
455 if verbose: print "Testing multiple inheritance special cases..."
456 class A(object):
457 def spam(self): return "A"
458 verify(A().spam() == "A")
459 class B(A):
460 def boo(self): return "B"
461 def spam(self): return "B"
462 verify(B().spam() == "B")
463 verify(B().boo() == "B")
464 class C(A):
465 def boo(self): return "C"
466 verify(C().spam() == "A")
467 verify(C().boo() == "C")
468 class D(B, C): pass
469 verify(D().spam() == "B")
470 verify(D().boo() == "B")
471 verify(D.__mro__ == (D, B, C, A, object))
472 class E(C, B): pass
473 verify(E().spam() == "B")
474 verify(E().boo() == "C")
475 verify(E.__mro__ == (E, C, B, A, object))
476 class F(D, E): pass
477 verify(F().spam() == "B")
478 verify(F().boo() == "B")
479 verify(F.__mro__ == (F, D, E, B, C, A, object))
480 class G(E, D): pass
481 verify(G().spam() == "B")
482 verify(G().boo() == "C")
483 verify(G.__mro__ == (G, E, D, C, B, A, object))
484
Guido van Rossum37202612001-08-09 19:45:21 +0000485def objects():
486 if verbose: print "Testing object class..."
487 a = object()
488 verify(a.__class__ == object == type(a))
489 b = object()
490 verify(a is not b)
491 verify(not hasattr(a, "foo"))
492 try:
493 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000494 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000495 pass
496 else:
497 verify(0, "object() should not allow setting a foo attribute")
498 verify(not hasattr(object(), "__dict__"))
499
500 class Cdict(object):
501 pass
502 x = Cdict()
503 verify(x.__dict__ is None)
504 x.foo = 1
505 verify(x.foo == 1)
506 verify(x.__dict__ == {'foo': 1})
507
Tim Peters6d6c1a32001-08-02 04:15:00 +0000508def slots():
509 if verbose: print "Testing __slots__..."
510 class C0(object):
511 __slots__ = []
512 x = C0()
513 verify(not hasattr(x, "__dict__"))
514 verify(not hasattr(x, "foo"))
515
516 class C1(object):
517 __slots__ = ['a']
518 x = C1()
519 verify(not hasattr(x, "__dict__"))
520 verify(x.a == None)
521 x.a = 1
522 verify(x.a == 1)
523 del x.a
524 verify(x.a == None)
525
526 class C3(object):
527 __slots__ = ['a', 'b', 'c']
528 x = C3()
529 verify(not hasattr(x, "__dict__"))
530 verify(x.a is None)
531 verify(x.b is None)
532 verify(x.c is None)
533 x.a = 1
534 x.b = 2
535 x.c = 3
536 verify(x.a == 1)
537 verify(x.b == 2)
538 verify(x.c == 3)
539
540def dynamics():
541 if verbose: print "Testing __dynamic__..."
542 verify(object.__dynamic__ == 0)
543 verify(list.__dynamic__ == 0)
544 class S1:
545 __metaclass__ = type
546 verify(S1.__dynamic__ == 0)
547 class S(object):
548 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000549 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000550 class D(object):
551 __dynamic__ = 1
552 verify(D.__dynamic__ == 1)
553 class E(D, S):
554 pass
555 verify(E.__dynamic__ == 1)
556 class F(S, D):
557 pass
558 verify(F.__dynamic__ == 1)
559 try:
560 S.foo = 1
561 except (AttributeError, TypeError):
562 pass
563 else:
564 verify(0, "assignment to a static class attribute should be illegal")
565 D.foo = 1
566 verify(D.foo == 1)
567 # Test that dynamic attributes are inherited
568 verify(E.foo == 1)
569 verify(F.foo == 1)
570 class SS(D):
571 __dynamic__ = 0
572 verify(SS.__dynamic__ == 0)
573 verify(SS.foo == 1)
574 try:
575 SS.foo = 1
576 except (AttributeError, TypeError):
577 pass
578 else:
579 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000580 # Test dynamic instances
581 class C(object):
582 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000583 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000584 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000585 C.foobar = 2
586 verify(a.foobar == 2)
587 C.method = lambda self: 42
588 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000589 C.__repr__ = lambda self: "C()"
590 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000591 C.__int__ = lambda self: 100
592 verify(int(a) == 100)
593 verify(a.foobar == 2)
594 verify(not hasattr(a, "spam"))
595 def mygetattr(self, name):
596 if name == "spam":
597 return "spam"
598 else:
599 return object.__getattr__(self, name)
600 C.__getattr__ = mygetattr
601 verify(a.spam == "spam")
602 a.new = 12
603 verify(a.new == 12)
604 def mysetattr(self, name, value):
605 if name == "spam":
606 raise AttributeError
607 return object.__setattr__(self, name, value)
608 C.__setattr__ = mysetattr
609 try:
610 a.spam = "not spam"
611 except AttributeError:
612 pass
613 else:
614 verify(0, "expected AttributeError")
615 verify(a.spam == "spam")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616
617def errors():
618 if verbose: print "Testing errors..."
619
620 try:
621 class C(list, dictionary):
622 pass
623 except TypeError:
624 pass
625 else:
626 verify(0, "inheritance from both list and dict should be illegal")
627
628 try:
629 class C(object, None):
630 pass
631 except TypeError:
632 pass
633 else:
634 verify(0, "inheritance from non-type should be illegal")
635 class Classic:
636 pass
637
638 try:
639 class C(object, Classic):
640 pass
641 except TypeError:
642 pass
643 else:
644 verify(0, "inheritance from object and Classic should be illegal")
645
646 try:
647 class C(int):
648 pass
649 except TypeError:
650 pass
651 else:
652 verify(0, "inheritance from int should be illegal")
653
654 try:
655 class C(object):
656 __slots__ = 1
657 except TypeError:
658 pass
659 else:
660 verify(0, "__slots__ = 1 should be illegal")
661
662 try:
663 class C(object):
664 __slots__ = [1]
665 except TypeError:
666 pass
667 else:
668 verify(0, "__slots__ = [1] should be illegal")
669
670def classmethods():
671 if verbose: print "Testing class methods..."
672 class C(object):
673 def foo(*a): return a
674 goo = classmethod(foo)
675 c = C()
676 verify(C.goo(1) == (C, 1))
677 verify(c.goo(1) == (C, 1))
678 verify(c.foo(1) == (c, 1))
679 class D(C):
680 pass
681 d = D()
682 verify(D.goo(1) == (D, 1))
683 verify(d.goo(1) == (D, 1))
684 verify(d.foo(1) == (d, 1))
685 verify(D.foo(d, 1) == (d, 1))
686
687def staticmethods():
688 if verbose: print "Testing static methods..."
689 class C(object):
690 def foo(*a): return a
691 goo = staticmethod(foo)
692 c = C()
693 verify(C.goo(1) == (1,))
694 verify(c.goo(1) == (1,))
695 verify(c.foo(1) == (c, 1,))
696 class D(C):
697 pass
698 d = D()
699 verify(D.goo(1) == (1,))
700 verify(d.goo(1) == (1,))
701 verify(d.foo(1) == (d, 1))
702 verify(D.foo(d, 1) == (d, 1))
703
704def classic():
705 if verbose: print "Testing classic classes..."
706 class C:
707 def foo(*a): return a
708 goo = classmethod(foo)
709 c = C()
710 verify(C.goo(1) == (C, 1))
711 verify(c.goo(1) == (C, 1))
712 verify(c.foo(1) == (c, 1))
713 class D(C):
714 pass
715 d = D()
716 verify(D.goo(1) == (D, 1))
717 verify(d.goo(1) == (D, 1))
718 verify(d.foo(1) == (d, 1))
719 verify(D.foo(d, 1) == (d, 1))
720
721def compattr():
722 if verbose: print "Testing computed attributes..."
723 class C(object):
724 class computed_attribute(object):
725 def __init__(self, get, set=None):
726 self.__get = get
727 self.__set = set
728 def __get__(self, obj, type=None):
729 return self.__get(obj)
730 def __set__(self, obj, value):
731 return self.__set(obj, value)
732 def __init__(self):
733 self.__x = 0
734 def __get_x(self):
735 x = self.__x
736 self.__x = x+1
737 return x
738 def __set_x(self, x):
739 self.__x = x
740 x = computed_attribute(__get_x, __set_x)
741 a = C()
742 verify(a.x == 0)
743 verify(a.x == 1)
744 a.x = 10
745 verify(a.x == 10)
746 verify(a.x == 11)
747
748def newslot():
749 if verbose: print "Testing __new__ slot override..."
750 class C(list):
751 def __new__(cls):
752 self = list.__new__(cls)
753 self.foo = 1
754 return self
755 def __init__(self):
756 self.foo = self.foo + 2
757 a = C()
758 verify(a.foo == 3)
759 verify(a.__class__ is C)
760 class D(C):
761 pass
762 b = D()
763 verify(b.foo == 3)
764 verify(b.__class__ is D)
765
Tim Peters6d6c1a32001-08-02 04:15:00 +0000766def altmro():
767 if verbose: print "Testing mro() and overriding it..."
768 class A(object):
769 def f(self): return "A"
770 class B(A):
771 pass
772 class C(A):
773 def f(self): return "C"
774 class D(B, C):
775 pass
776 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
777 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +0000778 class PerverseMetaType(type):
779 def mro(cls):
780 L = type.mro(cls)
781 L.reverse()
782 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783 class X(A,B,C,D):
784 __metaclass__ = PerverseMetaType
785 verify(X.__mro__ == (object, A, C, B, D, X))
786 verify(X().f() == "A")
787
788def overloading():
789 if verbose: print "testing operator overloading..."
790
791 class B(object):
792 "Intermediate class because object doesn't have a __setattr__"
793
794 class C(B):
795
796 def __getattr__(self, name):
797 if name == "foo":
798 return ("getattr", name)
799 else:
800 return B.__getattr__(self, name)
801 def __setattr__(self, name, value):
802 if name == "foo":
803 self.setattr = (name, value)
804 else:
805 return B.__setattr__(self, name, value)
806 def __delattr__(self, name):
807 if name == "foo":
808 self.delattr = name
809 else:
810 return B.__delattr__(self, name)
811
812 def __getitem__(self, key):
813 return ("getitem", key)
814 def __setitem__(self, key, value):
815 self.setitem = (key, value)
816 def __delitem__(self, key):
817 self.delitem = key
818
819 def __getslice__(self, i, j):
820 return ("getslice", i, j)
821 def __setslice__(self, i, j, value):
822 self.setslice = (i, j, value)
823 def __delslice__(self, i, j):
824 self.delslice = (i, j)
825
826 a = C()
827 verify(a.foo == ("getattr", "foo"))
828 a.foo = 12
829 verify(a.setattr == ("foo", 12))
830 del a.foo
831 verify(a.delattr == "foo")
832
833 verify(a[12] == ("getitem", 12))
834 a[12] = 21
835 verify(a.setitem == (12, 21))
836 del a[12]
837 verify(a.delitem == 12)
838
839 verify(a[0:10] == ("getslice", 0, 10))
840 a[0:10] = "foo"
841 verify(a.setslice == (0, 10, "foo"))
842 del a[0:10]
843 verify(a.delslice == (0, 10))
844
845def all():
846 lists()
847 dicts()
848 ints()
849 longs()
850 floats()
851 complexes()
852 spamlists()
853 spamdicts()
854 pydicts()
855 pylists()
856 metaclass()
857 pymods()
858 multi()
859 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +0000860 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861 slots()
862 dynamics()
863 errors()
864 classmethods()
865 staticmethods()
866 classic()
867 compattr()
868 newslot()
869 altmro()
870 overloading()
871
872all()
873
874if verbose: print "All OK"