blob: f524dbaa5fdcfa85af1e7d141acdc0192a0ae9de [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")
Guido van Rossum80e36752001-08-14 20:00:33 +0000616 class D(C):
617 pass
618 d = D()
619 d.foo = 1
620 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621
622def errors():
623 if verbose: print "Testing errors..."
624
625 try:
626 class C(list, dictionary):
627 pass
628 except TypeError:
629 pass
630 else:
631 verify(0, "inheritance from both list and dict should be illegal")
632
633 try:
634 class C(object, None):
635 pass
636 except TypeError:
637 pass
638 else:
639 verify(0, "inheritance from non-type should be illegal")
640 class Classic:
641 pass
642
643 try:
644 class C(object, Classic):
645 pass
646 except TypeError:
647 pass
648 else:
649 verify(0, "inheritance from object and Classic should be illegal")
650
651 try:
652 class C(int):
653 pass
654 except TypeError:
655 pass
656 else:
657 verify(0, "inheritance from int should be illegal")
658
659 try:
660 class C(object):
661 __slots__ = 1
662 except TypeError:
663 pass
664 else:
665 verify(0, "__slots__ = 1 should be illegal")
666
667 try:
668 class C(object):
669 __slots__ = [1]
670 except TypeError:
671 pass
672 else:
673 verify(0, "__slots__ = [1] should be illegal")
674
675def classmethods():
676 if verbose: print "Testing class methods..."
677 class C(object):
678 def foo(*a): return a
679 goo = classmethod(foo)
680 c = C()
681 verify(C.goo(1) == (C, 1))
682 verify(c.goo(1) == (C, 1))
683 verify(c.foo(1) == (c, 1))
684 class D(C):
685 pass
686 d = D()
687 verify(D.goo(1) == (D, 1))
688 verify(d.goo(1) == (D, 1))
689 verify(d.foo(1) == (d, 1))
690 verify(D.foo(d, 1) == (d, 1))
691
692def staticmethods():
693 if verbose: print "Testing static methods..."
694 class C(object):
695 def foo(*a): return a
696 goo = staticmethod(foo)
697 c = C()
698 verify(C.goo(1) == (1,))
699 verify(c.goo(1) == (1,))
700 verify(c.foo(1) == (c, 1,))
701 class D(C):
702 pass
703 d = D()
704 verify(D.goo(1) == (1,))
705 verify(d.goo(1) == (1,))
706 verify(d.foo(1) == (d, 1))
707 verify(D.foo(d, 1) == (d, 1))
708
709def classic():
710 if verbose: print "Testing classic classes..."
711 class C:
712 def foo(*a): return a
713 goo = classmethod(foo)
714 c = C()
715 verify(C.goo(1) == (C, 1))
716 verify(c.goo(1) == (C, 1))
717 verify(c.foo(1) == (c, 1))
718 class D(C):
719 pass
720 d = D()
721 verify(D.goo(1) == (D, 1))
722 verify(d.goo(1) == (D, 1))
723 verify(d.foo(1) == (d, 1))
724 verify(D.foo(d, 1) == (d, 1))
725
726def compattr():
727 if verbose: print "Testing computed attributes..."
728 class C(object):
729 class computed_attribute(object):
730 def __init__(self, get, set=None):
731 self.__get = get
732 self.__set = set
733 def __get__(self, obj, type=None):
734 return self.__get(obj)
735 def __set__(self, obj, value):
736 return self.__set(obj, value)
737 def __init__(self):
738 self.__x = 0
739 def __get_x(self):
740 x = self.__x
741 self.__x = x+1
742 return x
743 def __set_x(self, x):
744 self.__x = x
745 x = computed_attribute(__get_x, __set_x)
746 a = C()
747 verify(a.x == 0)
748 verify(a.x == 1)
749 a.x = 10
750 verify(a.x == 10)
751 verify(a.x == 11)
752
753def newslot():
754 if verbose: print "Testing __new__ slot override..."
755 class C(list):
756 def __new__(cls):
757 self = list.__new__(cls)
758 self.foo = 1
759 return self
760 def __init__(self):
761 self.foo = self.foo + 2
762 a = C()
763 verify(a.foo == 3)
764 verify(a.__class__ is C)
765 class D(C):
766 pass
767 b = D()
768 verify(b.foo == 3)
769 verify(b.__class__ is D)
770
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771def altmro():
772 if verbose: print "Testing mro() and overriding it..."
773 class A(object):
774 def f(self): return "A"
775 class B(A):
776 pass
777 class C(A):
778 def f(self): return "C"
779 class D(B, C):
780 pass
781 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
782 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +0000783 class PerverseMetaType(type):
784 def mro(cls):
785 L = type.mro(cls)
786 L.reverse()
787 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788 class X(A,B,C,D):
789 __metaclass__ = PerverseMetaType
790 verify(X.__mro__ == (object, A, C, B, D, X))
791 verify(X().f() == "A")
792
793def overloading():
794 if verbose: print "testing operator overloading..."
795
796 class B(object):
797 "Intermediate class because object doesn't have a __setattr__"
798
799 class C(B):
800
801 def __getattr__(self, name):
802 if name == "foo":
803 return ("getattr", name)
804 else:
805 return B.__getattr__(self, name)
806 def __setattr__(self, name, value):
807 if name == "foo":
808 self.setattr = (name, value)
809 else:
810 return B.__setattr__(self, name, value)
811 def __delattr__(self, name):
812 if name == "foo":
813 self.delattr = name
814 else:
815 return B.__delattr__(self, name)
816
817 def __getitem__(self, key):
818 return ("getitem", key)
819 def __setitem__(self, key, value):
820 self.setitem = (key, value)
821 def __delitem__(self, key):
822 self.delitem = key
823
824 def __getslice__(self, i, j):
825 return ("getslice", i, j)
826 def __setslice__(self, i, j, value):
827 self.setslice = (i, j, value)
828 def __delslice__(self, i, j):
829 self.delslice = (i, j)
830
831 a = C()
832 verify(a.foo == ("getattr", "foo"))
833 a.foo = 12
834 verify(a.setattr == ("foo", 12))
835 del a.foo
836 verify(a.delattr == "foo")
837
838 verify(a[12] == ("getitem", 12))
839 a[12] = 21
840 verify(a.setitem == (12, 21))
841 del a[12]
842 verify(a.delitem == 12)
843
844 verify(a[0:10] == ("getslice", 0, 10))
845 a[0:10] = "foo"
846 verify(a.setslice == (0, 10, "foo"))
847 del a[0:10]
848 verify(a.delslice == (0, 10))
849
Guido van Rossumb5a136b2001-08-15 17:51:17 +0000850def methods():
851 if verbose: print "testing methods..."
852 class C(object):
853 def __init__(self, x):
854 self.x = x
855 def foo(self):
856 return self.x
857 c1 = C(1)
858 verify(c1.foo() == 1)
859 class D(C):
860 boo = C.foo
861 goo = c1.foo
862 d2 = D(2)
863 verify(d2.foo() == 2)
864 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +0000865 verify(d2.goo() == 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +0000866
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000867def specials():
868 # Test operators like __hash__ for which a built-in default exists
869 if verbose: print "testing special operators..."
870 # Test the default behavior for static classes
871 class C(object):
872 def __getitem__(self, i):
873 if 0 <= i < 10: return i
874 raise IndexError
875 c1 = C()
876 c2 = C()
877 verify(not not c1)
878 verify(hash(c1) == id(c1))
879 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
880 verify(c1 == c1)
881 verify(c1 != c2)
882 verify(not c1 != c1)
883 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +0000884 # Note that the module name appears in str/repr, and that varies
885 # depending on whether this test is run standalone or from a framework.
886 verify(str(c1).find('C instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +0000887 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000888 verify(-1 not in c1)
889 for i in range(10):
890 verify(i in c1)
891 verify(10 not in c1)
892 # Test the default behavior for dynamic classes
893 class D(object):
894 __dynamic__ = 1
895 def __getitem__(self, i):
896 if 0 <= i < 10: return i
897 raise IndexError
898 d1 = D()
899 d2 = D()
900 verify(not not d1)
901 verify(hash(d1) == id(d1))
902 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
903 verify(d1 == d1)
904 verify(d1 != d2)
905 verify(not d1 != d1)
906 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +0000907 # Note that the module name appears in str/repr, and that varies
908 # depending on whether this test is run standalone or from a framework.
909 verify(str(d1).find('D instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +0000910 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000911 verify(-1 not in d1)
912 for i in range(10):
913 verify(i in d1)
914 verify(10 not in d1)
915 # Test overridden behavior for static classes
916 class Proxy(object):
917 def __init__(self, x):
918 self.x = x
919 def __nonzero__(self):
920 return not not self.x
921 def __hash__(self):
922 return hash(self.x)
923 def __eq__(self, other):
924 return self.x == other
925 def __ne__(self, other):
926 return self.x != other
927 def __cmp__(self, other):
928 return cmp(self.x, other.x)
929 def __str__(self):
930 return "Proxy:%s" % self.x
931 def __repr__(self):
932 return "Proxy(%r)" % self.x
933 def __contains__(self, value):
934 return value in self.x
935 p0 = Proxy(0)
936 p1 = Proxy(1)
937 p_1 = Proxy(-1)
938 verify(not p0)
939 verify(not not p1)
940 verify(hash(p0) == hash(0))
941 verify(p0 == p0)
942 verify(p0 != p1)
943 verify(not p0 != p0)
944 verify(not p0 == p1)
945 verify(cmp(p0, p1) == -1)
946 verify(cmp(p0, p0) == 0)
947 verify(cmp(p0, p_1) == 1)
948 verify(str(p0) == "Proxy:0")
949 verify(repr(p0) == "Proxy(0)")
950 p10 = Proxy(range(10))
951 verify(-1 not in p10)
952 for i in range(10):
953 verify(i in p10)
954 verify(10 not in p10)
955 # Test overridden behavior for dynamic classes
956 class DProxy(object):
957 __dynamic__ = 1
958 def __init__(self, x):
959 self.x = x
960 def __nonzero__(self):
961 return not not self.x
962 def __hash__(self):
963 return hash(self.x)
964 def __eq__(self, other):
965 return self.x == other
966 def __ne__(self, other):
967 return self.x != other
968 def __cmp__(self, other):
969 return cmp(self.x, other.x)
970 def __str__(self):
971 return "DProxy:%s" % self.x
972 def __repr__(self):
973 return "DProxy(%r)" % self.x
974 def __contains__(self, value):
975 return value in self.x
976 p0 = DProxy(0)
977 p1 = DProxy(1)
978 p_1 = DProxy(-1)
979 verify(not p0)
980 verify(not not p1)
981 verify(hash(p0) == hash(0))
982 verify(p0 == p0)
983 verify(p0 != p1)
984 verify(not p0 != p0)
985 verify(not p0 == p1)
986 verify(cmp(p0, p1) == -1)
987 verify(cmp(p0, p0) == 0)
988 verify(cmp(p0, p_1) == 1)
989 verify(str(p0) == "DProxy:0")
990 verify(repr(p0) == "DProxy(0)")
991 p10 = DProxy(range(10))
992 verify(-1 not in p10)
993 for i in range(10):
994 verify(i in p10)
995 verify(10 not in p10)
996
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997def all():
998 lists()
999 dicts()
1000 ints()
1001 longs()
1002 floats()
1003 complexes()
1004 spamlists()
1005 spamdicts()
1006 pydicts()
1007 pylists()
1008 metaclass()
1009 pymods()
1010 multi()
1011 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001012 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013 slots()
1014 dynamics()
1015 errors()
1016 classmethods()
1017 staticmethods()
1018 classic()
1019 compattr()
1020 newslot()
1021 altmro()
1022 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001023 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001024 specials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025
1026all()
1027
1028if verbose: print "All OK"