blob: b26f1653f92fe2f52e43cc1871f5a9337fc62dfb [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)
Guido van Rossum309b5662001-08-17 11:43:17 +0000384 d = D()
385 verify(d.__class__ is D)
386 class M1(type):
387 def __new__(cls, name, bases, dict):
388 dict['__spam__'] = 1
389 return type.__new__(cls, name, bases, dict)
390 class C:
391 __metaclass__ = M1
392 verify(C.__spam__ == 1)
393 c = C()
394 verify(c.__spam__ == 1)
395 class _instance(object):
396 pass
397 class M2(object):
398 def __new__(cls, name, bases, dict):
399 self = object.__new__(cls)
400 self.name = name
401 self.bases = bases
402 self.dict = dict
403 return self
404 __new__ = staticmethod(__new__)
405 def __call__(self):
406 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000407 # Early binding of methods
408 for key in self.dict:
409 if key.startswith("__"):
410 continue
411 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000412 return it
413 class C:
414 __metaclass__ = M2
415 def spam(self):
416 return 42
417 verify(C.name == 'C')
418 verify(C.bases == ())
419 verify('spam' in C.dict)
420 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000421 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423def pymods():
424 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000426 import sys
427 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 class MM(MT):
429 def __init__(self):
430 MT.__init__(self)
431 def __getattr__(self, name):
432 log.append(("getattr", name))
433 return MT.__getattr__(self, name)
434 def __setattr__(self, name, value):
435 log.append(("setattr", name, value))
436 MT.__setattr__(self, name, value)
437 def __delattr__(self, name):
438 log.append(("delattr", name))
439 MT.__delattr__(self, name)
440 a = MM()
441 a.foo = 12
442 x = a.foo
443 del a.foo
444 verify(log == [('getattr', '__init__'),
445 ('getattr', '__setattr__'),
446 ("setattr", "foo", 12),
447 ("getattr", "foo"),
448 ('getattr', '__delattr__'),
449 ("delattr", "foo")], log)
450
451def multi():
452 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453 class C(object):
454 def __init__(self):
455 self.__state = 0
456 def getstate(self):
457 return self.__state
458 def setstate(self, state):
459 self.__state = state
460 a = C()
461 verify(a.getstate() == 0)
462 a.setstate(10)
463 verify(a.getstate() == 10)
464 class D(dictionary, C):
465 def __init__(self):
466 type({}).__init__(self)
467 C.__init__(self)
468 d = D()
469 verify(d.keys() == [])
470 d["hello"] = "world"
471 verify(d.items() == [("hello", "world")])
472 verify(d["hello"] == "world")
473 verify(d.getstate() == 0)
474 d.setstate(10)
475 verify(d.getstate() == 10)
476 verify(D.__mro__ == (D, dictionary, C, object))
477
Guido van Rossume45763a2001-08-10 21:28:46 +0000478 # SF bug #442833
479 class Node(object):
480 def __int__(self):
481 return int(self.foo())
482 def foo(self):
483 return "23"
484 class Frag(Node, list):
485 def foo(self):
486 return "42"
487 verify(Node().__int__() == 23)
488 verify(int(Node()) == 23)
489 verify(Frag().__int__() == 42)
490 verify(int(Frag()) == 42)
491
Tim Peters6d6c1a32001-08-02 04:15:00 +0000492def diamond():
493 if verbose: print "Testing multiple inheritance special cases..."
494 class A(object):
495 def spam(self): return "A"
496 verify(A().spam() == "A")
497 class B(A):
498 def boo(self): return "B"
499 def spam(self): return "B"
500 verify(B().spam() == "B")
501 verify(B().boo() == "B")
502 class C(A):
503 def boo(self): return "C"
504 verify(C().spam() == "A")
505 verify(C().boo() == "C")
506 class D(B, C): pass
507 verify(D().spam() == "B")
508 verify(D().boo() == "B")
509 verify(D.__mro__ == (D, B, C, A, object))
510 class E(C, B): pass
511 verify(E().spam() == "B")
512 verify(E().boo() == "C")
513 verify(E.__mro__ == (E, C, B, A, object))
514 class F(D, E): pass
515 verify(F().spam() == "B")
516 verify(F().boo() == "B")
517 verify(F.__mro__ == (F, D, E, B, C, A, object))
518 class G(E, D): pass
519 verify(G().spam() == "B")
520 verify(G().boo() == "C")
521 verify(G.__mro__ == (G, E, D, C, B, A, object))
522
Guido van Rossum37202612001-08-09 19:45:21 +0000523def objects():
524 if verbose: print "Testing object class..."
525 a = object()
526 verify(a.__class__ == object == type(a))
527 b = object()
528 verify(a is not b)
529 verify(not hasattr(a, "foo"))
530 try:
531 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000532 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000533 pass
534 else:
535 verify(0, "object() should not allow setting a foo attribute")
536 verify(not hasattr(object(), "__dict__"))
537
538 class Cdict(object):
539 pass
540 x = Cdict()
541 verify(x.__dict__ is None)
542 x.foo = 1
543 verify(x.foo == 1)
544 verify(x.__dict__ == {'foo': 1})
545
Tim Peters6d6c1a32001-08-02 04:15:00 +0000546def slots():
547 if verbose: print "Testing __slots__..."
548 class C0(object):
549 __slots__ = []
550 x = C0()
551 verify(not hasattr(x, "__dict__"))
552 verify(not hasattr(x, "foo"))
553
554 class C1(object):
555 __slots__ = ['a']
556 x = C1()
557 verify(not hasattr(x, "__dict__"))
558 verify(x.a == None)
559 x.a = 1
560 verify(x.a == 1)
561 del x.a
562 verify(x.a == None)
563
564 class C3(object):
565 __slots__ = ['a', 'b', 'c']
566 x = C3()
567 verify(not hasattr(x, "__dict__"))
568 verify(x.a is None)
569 verify(x.b is None)
570 verify(x.c is None)
571 x.a = 1
572 x.b = 2
573 x.c = 3
574 verify(x.a == 1)
575 verify(x.b == 2)
576 verify(x.c == 3)
577
578def dynamics():
579 if verbose: print "Testing __dynamic__..."
580 verify(object.__dynamic__ == 0)
581 verify(list.__dynamic__ == 0)
582 class S1:
583 __metaclass__ = type
584 verify(S1.__dynamic__ == 0)
585 class S(object):
586 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000587 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588 class D(object):
589 __dynamic__ = 1
590 verify(D.__dynamic__ == 1)
591 class E(D, S):
592 pass
593 verify(E.__dynamic__ == 1)
594 class F(S, D):
595 pass
596 verify(F.__dynamic__ == 1)
597 try:
598 S.foo = 1
599 except (AttributeError, TypeError):
600 pass
601 else:
602 verify(0, "assignment to a static class attribute should be illegal")
603 D.foo = 1
604 verify(D.foo == 1)
605 # Test that dynamic attributes are inherited
606 verify(E.foo == 1)
607 verify(F.foo == 1)
608 class SS(D):
609 __dynamic__ = 0
610 verify(SS.__dynamic__ == 0)
611 verify(SS.foo == 1)
612 try:
613 SS.foo = 1
614 except (AttributeError, TypeError):
615 pass
616 else:
617 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000618 # Test dynamic instances
619 class C(object):
620 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000621 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000622 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000623 C.foobar = 2
624 verify(a.foobar == 2)
625 C.method = lambda self: 42
626 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000627 C.__repr__ = lambda self: "C()"
628 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000629 C.__int__ = lambda self: 100
630 verify(int(a) == 100)
631 verify(a.foobar == 2)
632 verify(not hasattr(a, "spam"))
633 def mygetattr(self, name):
634 if name == "spam":
635 return "spam"
636 else:
637 return object.__getattr__(self, name)
638 C.__getattr__ = mygetattr
639 verify(a.spam == "spam")
640 a.new = 12
641 verify(a.new == 12)
642 def mysetattr(self, name, value):
643 if name == "spam":
644 raise AttributeError
645 return object.__setattr__(self, name, value)
646 C.__setattr__ = mysetattr
647 try:
648 a.spam = "not spam"
649 except AttributeError:
650 pass
651 else:
652 verify(0, "expected AttributeError")
653 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000654 class D(C):
655 pass
656 d = D()
657 d.foo = 1
658 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659
660def errors():
661 if verbose: print "Testing errors..."
662
663 try:
664 class C(list, dictionary):
665 pass
666 except TypeError:
667 pass
668 else:
669 verify(0, "inheritance from both list and dict should be illegal")
670
671 try:
672 class C(object, None):
673 pass
674 except TypeError:
675 pass
676 else:
677 verify(0, "inheritance from non-type should be illegal")
678 class Classic:
679 pass
680
681 try:
682 class C(object, Classic):
683 pass
684 except TypeError:
685 pass
686 else:
687 verify(0, "inheritance from object and Classic should be illegal")
688
689 try:
690 class C(int):
691 pass
692 except TypeError:
693 pass
694 else:
695 verify(0, "inheritance from int should be illegal")
696
697 try:
698 class C(object):
699 __slots__ = 1
700 except TypeError:
701 pass
702 else:
703 verify(0, "__slots__ = 1 should be illegal")
704
705 try:
706 class C(object):
707 __slots__ = [1]
708 except TypeError:
709 pass
710 else:
711 verify(0, "__slots__ = [1] should be illegal")
712
713def classmethods():
714 if verbose: print "Testing class methods..."
715 class C(object):
716 def foo(*a): return a
717 goo = classmethod(foo)
718 c = C()
719 verify(C.goo(1) == (C, 1))
720 verify(c.goo(1) == (C, 1))
721 verify(c.foo(1) == (c, 1))
722 class D(C):
723 pass
724 d = D()
725 verify(D.goo(1) == (D, 1))
726 verify(d.goo(1) == (D, 1))
727 verify(d.foo(1) == (d, 1))
728 verify(D.foo(d, 1) == (d, 1))
729
730def staticmethods():
731 if verbose: print "Testing static methods..."
732 class C(object):
733 def foo(*a): return a
734 goo = staticmethod(foo)
735 c = C()
736 verify(C.goo(1) == (1,))
737 verify(c.goo(1) == (1,))
738 verify(c.foo(1) == (c, 1,))
739 class D(C):
740 pass
741 d = D()
742 verify(D.goo(1) == (1,))
743 verify(d.goo(1) == (1,))
744 verify(d.foo(1) == (d, 1))
745 verify(D.foo(d, 1) == (d, 1))
746
747def classic():
748 if verbose: print "Testing classic classes..."
749 class C:
750 def foo(*a): return a
751 goo = classmethod(foo)
752 c = C()
753 verify(C.goo(1) == (C, 1))
754 verify(c.goo(1) == (C, 1))
755 verify(c.foo(1) == (c, 1))
756 class D(C):
757 pass
758 d = D()
759 verify(D.goo(1) == (D, 1))
760 verify(d.goo(1) == (D, 1))
761 verify(d.foo(1) == (d, 1))
762 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +0000763 class E: # *not* subclassing from C
764 foo = C.foo
765 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +0000766 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000767
768def compattr():
769 if verbose: print "Testing computed attributes..."
770 class C(object):
771 class computed_attribute(object):
772 def __init__(self, get, set=None):
773 self.__get = get
774 self.__set = set
775 def __get__(self, obj, type=None):
776 return self.__get(obj)
777 def __set__(self, obj, value):
778 return self.__set(obj, value)
779 def __init__(self):
780 self.__x = 0
781 def __get_x(self):
782 x = self.__x
783 self.__x = x+1
784 return x
785 def __set_x(self, x):
786 self.__x = x
787 x = computed_attribute(__get_x, __set_x)
788 a = C()
789 verify(a.x == 0)
790 verify(a.x == 1)
791 a.x = 10
792 verify(a.x == 10)
793 verify(a.x == 11)
794
795def newslot():
796 if verbose: print "Testing __new__ slot override..."
797 class C(list):
798 def __new__(cls):
799 self = list.__new__(cls)
800 self.foo = 1
801 return self
802 def __init__(self):
803 self.foo = self.foo + 2
804 a = C()
805 verify(a.foo == 3)
806 verify(a.__class__ is C)
807 class D(C):
808 pass
809 b = D()
810 verify(b.foo == 3)
811 verify(b.__class__ is D)
812
Tim Peters6d6c1a32001-08-02 04:15:00 +0000813def altmro():
814 if verbose: print "Testing mro() and overriding it..."
815 class A(object):
816 def f(self): return "A"
817 class B(A):
818 pass
819 class C(A):
820 def f(self): return "C"
821 class D(B, C):
822 pass
823 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
824 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +0000825 class PerverseMetaType(type):
826 def mro(cls):
827 L = type.mro(cls)
828 L.reverse()
829 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 class X(A,B,C,D):
831 __metaclass__ = PerverseMetaType
832 verify(X.__mro__ == (object, A, C, B, D, X))
833 verify(X().f() == "A")
834
835def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +0000836 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000837
838 class B(object):
839 "Intermediate class because object doesn't have a __setattr__"
840
841 class C(B):
842
843 def __getattr__(self, name):
844 if name == "foo":
845 return ("getattr", name)
846 else:
847 return B.__getattr__(self, name)
848 def __setattr__(self, name, value):
849 if name == "foo":
850 self.setattr = (name, value)
851 else:
852 return B.__setattr__(self, name, value)
853 def __delattr__(self, name):
854 if name == "foo":
855 self.delattr = name
856 else:
857 return B.__delattr__(self, name)
858
859 def __getitem__(self, key):
860 return ("getitem", key)
861 def __setitem__(self, key, value):
862 self.setitem = (key, value)
863 def __delitem__(self, key):
864 self.delitem = key
865
866 def __getslice__(self, i, j):
867 return ("getslice", i, j)
868 def __setslice__(self, i, j, value):
869 self.setslice = (i, j, value)
870 def __delslice__(self, i, j):
871 self.delslice = (i, j)
872
873 a = C()
874 verify(a.foo == ("getattr", "foo"))
875 a.foo = 12
876 verify(a.setattr == ("foo", 12))
877 del a.foo
878 verify(a.delattr == "foo")
879
880 verify(a[12] == ("getitem", 12))
881 a[12] = 21
882 verify(a.setitem == (12, 21))
883 del a[12]
884 verify(a.delitem == 12)
885
886 verify(a[0:10] == ("getslice", 0, 10))
887 a[0:10] = "foo"
888 verify(a.setslice == (0, 10, "foo"))
889 del a[0:10]
890 verify(a.delslice == (0, 10))
891
Guido van Rossumb5a136b2001-08-15 17:51:17 +0000892def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +0000893 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +0000894 class C(object):
895 def __init__(self, x):
896 self.x = x
897 def foo(self):
898 return self.x
899 c1 = C(1)
900 verify(c1.foo() == 1)
901 class D(C):
902 boo = C.foo
903 goo = c1.foo
904 d2 = D(2)
905 verify(d2.foo() == 2)
906 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +0000907 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +0000908 class E(object):
909 foo = C.foo
910 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +0000911 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +0000912
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000913def specials():
914 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +0000915 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000916 # Test the default behavior for static classes
917 class C(object):
918 def __getitem__(self, i):
919 if 0 <= i < 10: return i
920 raise IndexError
921 c1 = C()
922 c2 = C()
923 verify(not not c1)
924 verify(hash(c1) == id(c1))
925 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
926 verify(c1 == c1)
927 verify(c1 != c2)
928 verify(not c1 != c1)
929 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +0000930 # Note that the module name appears in str/repr, and that varies
931 # depending on whether this test is run standalone or from a framework.
932 verify(str(c1).find('C instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +0000933 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000934 verify(-1 not in c1)
935 for i in range(10):
936 verify(i in c1)
937 verify(10 not in c1)
938 # Test the default behavior for dynamic classes
939 class D(object):
940 __dynamic__ = 1
941 def __getitem__(self, i):
942 if 0 <= i < 10: return i
943 raise IndexError
944 d1 = D()
945 d2 = D()
946 verify(not not d1)
947 verify(hash(d1) == id(d1))
948 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
949 verify(d1 == d1)
950 verify(d1 != d2)
951 verify(not d1 != d1)
952 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +0000953 # Note that the module name appears in str/repr, and that varies
954 # depending on whether this test is run standalone or from a framework.
955 verify(str(d1).find('D instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +0000956 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +0000957 verify(-1 not in d1)
958 for i in range(10):
959 verify(i in d1)
960 verify(10 not in d1)
961 # Test overridden behavior for static classes
962 class Proxy(object):
963 def __init__(self, x):
964 self.x = x
965 def __nonzero__(self):
966 return not not self.x
967 def __hash__(self):
968 return hash(self.x)
969 def __eq__(self, other):
970 return self.x == other
971 def __ne__(self, other):
972 return self.x != other
973 def __cmp__(self, other):
974 return cmp(self.x, other.x)
975 def __str__(self):
976 return "Proxy:%s" % self.x
977 def __repr__(self):
978 return "Proxy(%r)" % self.x
979 def __contains__(self, value):
980 return value in self.x
981 p0 = Proxy(0)
982 p1 = Proxy(1)
983 p_1 = Proxy(-1)
984 verify(not p0)
985 verify(not not p1)
986 verify(hash(p0) == hash(0))
987 verify(p0 == p0)
988 verify(p0 != p1)
989 verify(not p0 != p0)
990 verify(not p0 == p1)
991 verify(cmp(p0, p1) == -1)
992 verify(cmp(p0, p0) == 0)
993 verify(cmp(p0, p_1) == 1)
994 verify(str(p0) == "Proxy:0")
995 verify(repr(p0) == "Proxy(0)")
996 p10 = Proxy(range(10))
997 verify(-1 not in p10)
998 for i in range(10):
999 verify(i in p10)
1000 verify(10 not in p10)
1001 # Test overridden behavior for dynamic classes
1002 class DProxy(object):
1003 __dynamic__ = 1
1004 def __init__(self, x):
1005 self.x = x
1006 def __nonzero__(self):
1007 return not not self.x
1008 def __hash__(self):
1009 return hash(self.x)
1010 def __eq__(self, other):
1011 return self.x == other
1012 def __ne__(self, other):
1013 return self.x != other
1014 def __cmp__(self, other):
1015 return cmp(self.x, other.x)
1016 def __str__(self):
1017 return "DProxy:%s" % self.x
1018 def __repr__(self):
1019 return "DProxy(%r)" % self.x
1020 def __contains__(self, value):
1021 return value in self.x
1022 p0 = DProxy(0)
1023 p1 = DProxy(1)
1024 p_1 = DProxy(-1)
1025 verify(not p0)
1026 verify(not not p1)
1027 verify(hash(p0) == hash(0))
1028 verify(p0 == p0)
1029 verify(p0 != p1)
1030 verify(not p0 != p0)
1031 verify(not p0 == p1)
1032 verify(cmp(p0, p1) == -1)
1033 verify(cmp(p0, p0) == 0)
1034 verify(cmp(p0, p_1) == 1)
1035 verify(str(p0) == "DProxy:0")
1036 verify(repr(p0) == "DProxy(0)")
1037 p10 = DProxy(range(10))
1038 verify(-1 not in p10)
1039 for i in range(10):
1040 verify(i in p10)
1041 verify(10 not in p10)
1042
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001043def weakrefs():
1044 if verbose: print "Testing weak references..."
1045 import weakref
1046 class C(object):
1047 pass
1048 c = C()
1049 r = weakref.ref(c)
1050 verify(r() is c)
1051 del c
1052 verify(r() is None)
1053 del r
1054 class NoWeak(object):
1055 __slots__ = ['foo']
1056 no = NoWeak()
1057 try:
1058 weakref.ref(no)
1059 except TypeError, msg:
1060 verify(str(msg).find("weakly") >= 0)
1061 else:
1062 verify(0, "weakref.ref(no) should be illegal")
1063 class Weak(object):
1064 __slots__ = ['foo', '__weakref__']
1065 yes = Weak()
1066 r = weakref.ref(yes)
1067 verify(r() is yes)
1068 del yes
1069 verify(r() is None)
1070 del r
1071
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072def all():
1073 lists()
1074 dicts()
1075 ints()
1076 longs()
1077 floats()
1078 complexes()
1079 spamlists()
1080 spamdicts()
1081 pydicts()
1082 pylists()
1083 metaclass()
1084 pymods()
1085 multi()
1086 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001087 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 slots()
1089 dynamics()
1090 errors()
1091 classmethods()
1092 staticmethods()
1093 classic()
1094 compattr()
1095 newslot()
1096 altmro()
1097 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001098 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001099 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001100 weakrefs()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101
1102all()
1103
1104if verbose: print "All OK"