blob: ed37ae82ef1f8cc6f3bb3caa8ac6dceb6eb3ecc0 [file] [log] [blame]
Tim Peters6d6c1a32001-08-02 04:15:00 +00001# Test descriptor-related enhancements
2
Tim Peters59c9a642001-09-13 05:38:56 +00003from test_support import verify, verbose, TestFailed, TESTFN
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
5
6def testunop(a, res, expr="len(a)", meth="__len__"):
7 if verbose: print "checking", expr
8 dict = {'a': a}
9 verify(eval(expr, dict) == res)
10 t = type(a)
11 m = getattr(t, meth)
12 verify(m == t.__dict__[meth])
13 verify(m(a) == res)
14 bm = getattr(a, meth)
15 verify(bm() == res)
16
17def testbinop(a, b, res, expr="a+b", meth="__add__"):
18 if verbose: print "checking", expr
19 dict = {'a': a, 'b': b}
20 verify(eval(expr, dict) == res)
21 t = type(a)
22 m = getattr(t, meth)
23 verify(m == t.__dict__[meth])
24 verify(m(a, b) == res)
25 bm = getattr(a, meth)
26 verify(bm(b) == res)
27
28def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b, 'c': c}
31 verify(eval(expr, dict) == res)
32 t = type(a)
33 m = getattr(t, meth)
34 verify(m == t.__dict__[meth])
35 verify(m(a, b, c) == res)
36 bm = getattr(a, meth)
37 verify(bm(b, c) == res)
38
39def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
40 if verbose: print "checking", stmt
41 dict = {'a': deepcopy(a), 'b': b}
42 exec stmt in dict
43 verify(dict['a'] == res)
44 t = type(a)
45 m = getattr(t, meth)
46 verify(m == t.__dict__[meth])
47 dict['a'] = deepcopy(a)
48 m(dict['a'], b)
49 verify(dict['a'] == res)
50 dict['a'] = deepcopy(a)
51 bm = getattr(dict['a'], meth)
52 bm(b)
53 verify(dict['a'] == res)
54
55def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
56 if verbose: print "checking", stmt
57 dict = {'a': deepcopy(a), 'b': b, 'c': c}
58 exec stmt in dict
59 verify(dict['a'] == res)
60 t = type(a)
61 m = getattr(t, meth)
62 verify(m == t.__dict__[meth])
63 dict['a'] = deepcopy(a)
64 m(dict['a'], b, c)
65 verify(dict['a'] == res)
66 dict['a'] = deepcopy(a)
67 bm = getattr(dict['a'], meth)
68 bm(b, c)
69 verify(dict['a'] == res)
70
71def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
72 if verbose: print "checking", stmt
73 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
74 exec stmt in dict
75 verify(dict['a'] == res)
76 t = type(a)
77 m = getattr(t, meth)
78 verify(m == t.__dict__[meth])
79 dict['a'] = deepcopy(a)
80 m(dict['a'], b, c, d)
81 verify(dict['a'] == res)
82 dict['a'] = deepcopy(a)
83 bm = getattr(dict['a'], meth)
84 bm(b, c, d)
85 verify(dict['a'] == res)
86
87def lists():
88 if verbose: print "Testing list operations..."
89 testbinop([1], [2], [1,2], "a+b", "__add__")
90 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
91 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
92 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
93 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
94 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
95 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
96 testunop([1,2,3], 3, "len(a)", "__len__")
97 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
98 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
99 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
100 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
101
102def dicts():
103 if verbose: print "Testing dict operations..."
104 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
105 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
106 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
107 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
108 d = {1:2,3:4}
109 l1 = []
110 for i in d.keys(): l1.append(i)
111 l = []
112 for i in iter(d): l.append(i)
113 verify(l == l1)
114 l = []
115 for i in d.__iter__(): l.append(i)
116 verify(l == l1)
117 l = []
118 for i in dictionary.__iter__(d): l.append(i)
119 verify(l == l1)
120 d = {1:2, 3:4}
121 testunop(d, 2, "len(a)", "__len__")
122 verify(eval(repr(d), {}) == d)
123 verify(eval(d.__repr__(), {}) == d)
124 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
125
Tim Peters25786c02001-09-02 08:22:48 +0000126def dict_constructor():
127 if verbose:
128 print "Testing dictionary constructor ..."
129 d = dictionary()
130 verify(d == {})
131 d = dictionary({})
132 verify(d == {})
133 d = dictionary(mapping={})
134 verify(d == {})
135 d = dictionary({1: 2, 'a': 'b'})
136 verify(d == {1: 2, 'a': 'b'})
137 for badarg in 0, 0L, 0j, "0", [0], (0,):
138 try:
139 dictionary(badarg)
140 except TypeError:
141 pass
142 else:
143 raise TestFailed("no TypeError from dictionary(%r)" % badarg)
144 try:
145 dictionary(senseless={})
146 except TypeError:
147 pass
148 else:
149 raise TestFailed("no TypeError from dictionary(senseless={}")
150
151 try:
152 dictionary({}, {})
153 except TypeError:
154 pass
155 else:
156 raise TestFailed("no TypeError from dictionary({}, {})")
157
158 class Mapping:
159 dict = {1:2, 3:4, 'a':1j}
160
161 def __getitem__(self, i):
162 return self.dict[i]
163
164 try:
165 dictionary(Mapping())
166 except TypeError:
167 pass
168 else:
169 raise TestFailed("no TypeError from dictionary(incomplete mapping)")
170
171 Mapping.keys = lambda self: self.dict.keys()
172 d = dictionary(mapping=Mapping())
173 verify(d == Mapping.dict)
174
Tim Peters5d2b77c2001-09-03 05:47:38 +0000175def test_dir():
176 if verbose:
177 print "Testing dir() ..."
178 junk = 12
179 verify(dir() == ['junk'])
180 del junk
181
182 # Just make sure these don't blow up!
183 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
184 dir(arg)
185
Tim Peters37a309d2001-09-04 01:20:04 +0000186 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000187 class C:
188 Cdata = 1
189 def Cmethod(self): pass
190
191 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
192 verify(dir(C) == cstuff)
193
194 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
195 verify(dir(c) == cstuff)
196
197 c.cdata = 2
198 c.cmethod = lambda self: 0
199 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
200
201 class A(C):
202 Adata = 1
203 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000204
Tim Peters37a309d2001-09-04 01:20:04 +0000205 astuff = ['Adata', 'Amethod'] + cstuff
206 verify(dir(A) == astuff)
207 a = A()
208 verify(dir(a) == astuff)
209 a.adata = 42
210 a.amethod = lambda self: 3
211 verify(dir(a) == astuff + ['adata', 'amethod'])
212
213 # The same, but with new-style classes. Since these have object as a
214 # base class, a lot more gets sucked in.
215 def interesting(strings):
216 return [s for s in strings if not s.startswith('_')]
217
Tim Peters5d2b77c2001-09-03 05:47:38 +0000218 class C(object):
219 Cdata = 1
220 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000221
222 cstuff = ['Cdata', 'Cmethod']
223 verify(interesting(dir(C)) == cstuff)
224
225 c = C()
226 verify(interesting(dir(c)) == cstuff)
227
228 c.cdata = 2
229 c.cmethod = lambda self: 0
230 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
231
Tim Peters5d2b77c2001-09-03 05:47:38 +0000232 class A(C):
233 Adata = 1
234 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000235
236 astuff = ['Adata', 'Amethod'] + cstuff
237 verify(interesting(dir(A)) == astuff)
238 a = A()
239 verify(interesting(dir(a)) == astuff)
240 a.adata = 42
241 a.amethod = lambda self: 3
242 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000243
Tim Peterscaaff8d2001-09-10 23:12:14 +0000244 # Try a module subclass.
245 import sys
246 class M(type(sys)):
247 pass
248 minstance = M()
249 minstance.b = 2
250 minstance.a = 1
251 verify(dir(minstance) == ['a', 'b'])
252
253 class M2(M):
254 def getdict(self):
255 return "Not a dict!"
256 __dict__ = property(getdict)
257
258 m2instance = M2()
259 m2instance.b = 2
260 m2instance.a = 1
261 verify(m2instance.__dict__ == "Not a dict!")
262 try:
263 dir(m2instance)
264 except TypeError:
265 pass
266
Tim Peters6d6c1a32001-08-02 04:15:00 +0000267binops = {
268 'add': '+',
269 'sub': '-',
270 'mul': '*',
271 'div': '/',
272 'mod': '%',
273 'divmod': 'divmod',
274 'pow': '**',
275 'lshift': '<<',
276 'rshift': '>>',
277 'and': '&',
278 'xor': '^',
279 'or': '|',
280 'cmp': 'cmp',
281 'lt': '<',
282 'le': '<=',
283 'eq': '==',
284 'ne': '!=',
285 'gt': '>',
286 'ge': '>=',
287 }
288
289for name, expr in binops.items():
290 if expr.islower():
291 expr = expr + "(a, b)"
292 else:
293 expr = 'a %s b' % expr
294 binops[name] = expr
295
296unops = {
297 'pos': '+',
298 'neg': '-',
299 'abs': 'abs',
300 'invert': '~',
301 'int': 'int',
302 'long': 'long',
303 'float': 'float',
304 'oct': 'oct',
305 'hex': 'hex',
306 }
307
308for name, expr in unops.items():
309 if expr.islower():
310 expr = expr + "(a)"
311 else:
312 expr = '%s a' % expr
313 unops[name] = expr
314
315def numops(a, b, skip=[]):
316 dict = {'a': a, 'b': b}
317 for name, expr in binops.items():
318 if name not in skip:
319 name = "__%s__" % name
320 if hasattr(a, name):
321 res = eval(expr, dict)
322 testbinop(a, b, res, expr, name)
323 for name, expr in unops.items():
324 name = "__%s__" % name
325 if hasattr(a, name):
326 res = eval(expr, dict)
327 testunop(a, res, expr, name)
328
329def ints():
330 if verbose: print "Testing int operations..."
331 numops(100, 3)
332
333def longs():
334 if verbose: print "Testing long operations..."
335 numops(100L, 3L)
336
337def floats():
338 if verbose: print "Testing float operations..."
339 numops(100.0, 3.0)
340
341def complexes():
342 if verbose: print "Testing complex operations..."
343 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
344 class Number(complex):
345 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000346 def __new__(cls, *args, **kwds):
347 result = complex.__new__(cls, *args)
348 result.prec = kwds.get('prec', 12)
349 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350 def __repr__(self):
351 prec = self.prec
352 if self.imag == 0.0:
353 return "%.*g" % (prec, self.real)
354 if self.real == 0.0:
355 return "%.*gj" % (prec, self.imag)
356 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
357 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000358
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359 a = Number(3.14, prec=6)
360 verify(`a` == "3.14")
361 verify(a.prec == 6)
362
Tim Peters3f996e72001-09-13 19:18:27 +0000363 a = Number(a, prec=2)
364 verify(`a` == "3.1")
365 verify(a.prec == 2)
366
367 a = Number(234.5)
368 verify(`a` == "234.5")
369 verify(a.prec == 12)
370
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371def spamlists():
372 if verbose: print "Testing spamlist operations..."
373 import copy, xxsubtype as spam
374 def spamlist(l, memo=None):
375 import xxsubtype as spam
376 return spam.spamlist(l)
377 # This is an ugly hack:
378 copy._deepcopy_dispatch[spam.spamlist] = spamlist
379
380 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
381 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
382 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
383 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
384 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
385 "a[b:c]", "__getslice__")
386 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
387 "a+=b", "__iadd__")
388 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
389 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
390 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
391 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
392 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
393 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
394 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
395 # Test subclassing
396 class C(spam.spamlist):
397 def foo(self): return 1
398 a = C()
399 verify(a == [])
400 verify(a.foo() == 1)
401 a.append(100)
402 verify(a == [100])
403 verify(a.getstate() == 0)
404 a.setstate(42)
405 verify(a.getstate() == 42)
406
407def spamdicts():
408 if verbose: print "Testing spamdict operations..."
409 import copy, xxsubtype as spam
410 def spamdict(d, memo=None):
411 import xxsubtype as spam
412 sd = spam.spamdict()
413 for k, v in d.items(): sd[k] = v
414 return sd
415 # This is an ugly hack:
416 copy._deepcopy_dispatch[spam.spamdict] = spamdict
417
418 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
419 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
420 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
421 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
422 d = spamdict({1:2,3:4})
423 l1 = []
424 for i in d.keys(): l1.append(i)
425 l = []
426 for i in iter(d): l.append(i)
427 verify(l == l1)
428 l = []
429 for i in d.__iter__(): l.append(i)
430 verify(l == l1)
431 l = []
432 for i in type(spamdict({})).__iter__(d): l.append(i)
433 verify(l == l1)
434 straightd = {1:2, 3:4}
435 spamd = spamdict(straightd)
436 testunop(spamd, 2, "len(a)", "__len__")
437 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
438 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
439 "a[b]=c", "__setitem__")
440 # Test subclassing
441 class C(spam.spamdict):
442 def foo(self): return 1
443 a = C()
444 verify(a.items() == [])
445 verify(a.foo() == 1)
446 a['foo'] = 'bar'
447 verify(a.items() == [('foo', 'bar')])
448 verify(a.getstate() == 0)
449 a.setstate(100)
450 verify(a.getstate() == 100)
451
452def pydicts():
453 if verbose: print "Testing Python subclass of dict..."
454 verify(issubclass(dictionary, dictionary))
455 verify(isinstance({}, dictionary))
456 d = dictionary()
457 verify(d == {})
458 verify(d.__class__ is dictionary)
459 verify(isinstance(d, dictionary))
460 class C(dictionary):
461 state = -1
462 def __init__(self, *a, **kw):
463 if a:
464 assert len(a) == 1
465 self.state = a[0]
466 if kw:
467 for k, v in kw.items(): self[v] = k
468 def __getitem__(self, key):
469 return self.get(key, 0)
470 def __setitem__(self, key, value):
471 assert isinstance(key, type(0))
472 dictionary.__setitem__(self, key, value)
473 def setstate(self, state):
474 self.state = state
475 def getstate(self):
476 return self.state
477 verify(issubclass(C, dictionary))
478 a1 = C(12)
479 verify(a1.state == 12)
480 a2 = C(foo=1, bar=2)
481 verify(a2[1] == 'foo' and a2[2] == 'bar')
482 a = C()
483 verify(a.state == -1)
484 verify(a.getstate() == -1)
485 a.setstate(0)
486 verify(a.state == 0)
487 verify(a.getstate() == 0)
488 a.setstate(10)
489 verify(a.state == 10)
490 verify(a.getstate() == 10)
491 verify(a[42] == 0)
492 a[42] = 24
493 verify(a[42] == 24)
494 if verbose: print "pydict stress test ..."
495 N = 50
496 for i in range(N):
497 a[i] = C()
498 for j in range(N):
499 a[i][j] = i*j
500 for i in range(N):
501 for j in range(N):
502 verify(a[i][j] == i*j)
503
504def pylists():
505 if verbose: print "Testing Python subclass of list..."
506 class C(list):
507 def __getitem__(self, i):
508 return list.__getitem__(self, i) + 100
509 def __getslice__(self, i, j):
510 return (i, j)
511 a = C()
512 a.extend([0,1,2])
513 verify(a[0] == 100)
514 verify(a[1] == 101)
515 verify(a[2] == 102)
516 verify(a[100:200] == (100,200))
517
518def metaclass():
519 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000520 class C:
521 __metaclass__ = type
522 def __init__(self):
523 self.__state = 0
524 def getstate(self):
525 return self.__state
526 def setstate(self, state):
527 self.__state = state
528 a = C()
529 verify(a.getstate() == 0)
530 a.setstate(10)
531 verify(a.getstate() == 10)
532 class D:
533 class __metaclass__(type):
534 def myself(cls): return cls
535 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000536 d = D()
537 verify(d.__class__ is D)
538 class M1(type):
539 def __new__(cls, name, bases, dict):
540 dict['__spam__'] = 1
541 return type.__new__(cls, name, bases, dict)
542 class C:
543 __metaclass__ = M1
544 verify(C.__spam__ == 1)
545 c = C()
546 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000547
Guido van Rossum309b5662001-08-17 11:43:17 +0000548 class _instance(object):
549 pass
550 class M2(object):
551 def __new__(cls, name, bases, dict):
552 self = object.__new__(cls)
553 self.name = name
554 self.bases = bases
555 self.dict = dict
556 return self
557 __new__ = staticmethod(__new__)
558 def __call__(self):
559 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000560 # Early binding of methods
561 for key in self.dict:
562 if key.startswith("__"):
563 continue
564 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000565 return it
566 class C:
567 __metaclass__ = M2
568 def spam(self):
569 return 42
570 verify(C.name == 'C')
571 verify(C.bases == ())
572 verify('spam' in C.dict)
573 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000574 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000575
Guido van Rossum91ee7982001-08-30 20:52:40 +0000576 # More metaclass examples
577
578 class autosuper(type):
579 # Automatically add __super to the class
580 # This trick only works for dynamic classes
581 # so we force __dynamic__ = 1
582 def __new__(metaclass, name, bases, dict):
583 # XXX Should check that name isn't already a base class name
584 dict["__dynamic__"] = 1
585 cls = super(autosuper, metaclass).__new__(metaclass,
586 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000587 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000588 while name[:1] == "_":
589 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000590 if name:
591 name = "_%s__super" % name
592 else:
593 name = "__super"
594 setattr(cls, name, super(cls))
595 return cls
596 class A:
597 __metaclass__ = autosuper
598 def meth(self):
599 return "A"
600 class B(A):
601 def meth(self):
602 return "B" + self.__super.meth()
603 class C(A):
604 def meth(self):
605 return "C" + self.__super.meth()
606 class D(C, B):
607 def meth(self):
608 return "D" + self.__super.meth()
609 verify(D().meth() == "DCBA")
610 class E(B, C):
611 def meth(self):
612 return "E" + self.__super.meth()
613 verify(E().meth() == "EBCA")
614
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000615 class autoproperty(type):
616 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000617 # named _get_x and/or _set_x are found
618 def __new__(metaclass, name, bases, dict):
619 hits = {}
620 for key, val in dict.iteritems():
621 if key.startswith("_get_"):
622 key = key[5:]
623 get, set = hits.get(key, (None, None))
624 get = val
625 hits[key] = get, set
626 elif key.startswith("_set_"):
627 key = key[5:]
628 get, set = hits.get(key, (None, None))
629 set = val
630 hits[key] = get, set
631 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000632 dict[key] = property(get, set)
633 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000634 name, bases, dict)
635 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000636 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000637 def _get_x(self):
638 return -self.__x
639 def _set_x(self, x):
640 self.__x = -x
641 a = A()
642 verify(not hasattr(a, "x"))
643 a.x = 12
644 verify(a.x == 12)
645 verify(a._A__x == -12)
646
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000647 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000648 # Merge of multiple cooperating metaclasses
649 pass
650 class A:
651 __metaclass__ = multimetaclass
652 def _get_x(self):
653 return "A"
654 class B(A):
655 def _get_x(self):
656 return "B" + self.__super._get_x()
657 class C(A):
658 def _get_x(self):
659 return "C" + self.__super._get_x()
660 class D(C, B):
661 def _get_x(self):
662 return "D" + self.__super._get_x()
663 verify(D().x == "DCBA")
664
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665def pymods():
666 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000668 import sys
669 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670 class MM(MT):
671 def __init__(self):
672 MT.__init__(self)
673 def __getattr__(self, name):
674 log.append(("getattr", name))
675 return MT.__getattr__(self, name)
676 def __setattr__(self, name, value):
677 log.append(("setattr", name, value))
678 MT.__setattr__(self, name, value)
679 def __delattr__(self, name):
680 log.append(("delattr", name))
681 MT.__delattr__(self, name)
682 a = MM()
683 a.foo = 12
684 x = a.foo
685 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000686 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 ("delattr", "foo")], log)
689
690def multi():
691 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692 class C(object):
693 def __init__(self):
694 self.__state = 0
695 def getstate(self):
696 return self.__state
697 def setstate(self, state):
698 self.__state = state
699 a = C()
700 verify(a.getstate() == 0)
701 a.setstate(10)
702 verify(a.getstate() == 10)
703 class D(dictionary, C):
704 def __init__(self):
705 type({}).__init__(self)
706 C.__init__(self)
707 d = D()
708 verify(d.keys() == [])
709 d["hello"] = "world"
710 verify(d.items() == [("hello", "world")])
711 verify(d["hello"] == "world")
712 verify(d.getstate() == 0)
713 d.setstate(10)
714 verify(d.getstate() == 10)
715 verify(D.__mro__ == (D, dictionary, C, object))
716
Guido van Rossume45763a2001-08-10 21:28:46 +0000717 # SF bug #442833
718 class Node(object):
719 def __int__(self):
720 return int(self.foo())
721 def foo(self):
722 return "23"
723 class Frag(Node, list):
724 def foo(self):
725 return "42"
726 verify(Node().__int__() == 23)
727 verify(int(Node()) == 23)
728 verify(Frag().__int__() == 42)
729 verify(int(Frag()) == 42)
730
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731def diamond():
732 if verbose: print "Testing multiple inheritance special cases..."
733 class A(object):
734 def spam(self): return "A"
735 verify(A().spam() == "A")
736 class B(A):
737 def boo(self): return "B"
738 def spam(self): return "B"
739 verify(B().spam() == "B")
740 verify(B().boo() == "B")
741 class C(A):
742 def boo(self): return "C"
743 verify(C().spam() == "A")
744 verify(C().boo() == "C")
745 class D(B, C): pass
746 verify(D().spam() == "B")
747 verify(D().boo() == "B")
748 verify(D.__mro__ == (D, B, C, A, object))
749 class E(C, B): pass
750 verify(E().spam() == "B")
751 verify(E().boo() == "C")
752 verify(E.__mro__ == (E, C, B, A, object))
753 class F(D, E): pass
754 verify(F().spam() == "B")
755 verify(F().boo() == "B")
756 verify(F.__mro__ == (F, D, E, B, C, A, object))
757 class G(E, D): pass
758 verify(G().spam() == "B")
759 verify(G().boo() == "C")
760 verify(G.__mro__ == (G, E, D, C, B, A, object))
761
Guido van Rossum37202612001-08-09 19:45:21 +0000762def objects():
763 if verbose: print "Testing object class..."
764 a = object()
765 verify(a.__class__ == object == type(a))
766 b = object()
767 verify(a is not b)
768 verify(not hasattr(a, "foo"))
769 try:
770 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000771 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000772 pass
773 else:
774 verify(0, "object() should not allow setting a foo attribute")
775 verify(not hasattr(object(), "__dict__"))
776
777 class Cdict(object):
778 pass
779 x = Cdict()
780 verify(x.__dict__ is None)
781 x.foo = 1
782 verify(x.foo == 1)
783 verify(x.__dict__ == {'foo': 1})
784
Tim Peters6d6c1a32001-08-02 04:15:00 +0000785def slots():
786 if verbose: print "Testing __slots__..."
787 class C0(object):
788 __slots__ = []
789 x = C0()
790 verify(not hasattr(x, "__dict__"))
791 verify(not hasattr(x, "foo"))
792
793 class C1(object):
794 __slots__ = ['a']
795 x = C1()
796 verify(not hasattr(x, "__dict__"))
797 verify(x.a == None)
798 x.a = 1
799 verify(x.a == 1)
800 del x.a
801 verify(x.a == None)
802
803 class C3(object):
804 __slots__ = ['a', 'b', 'c']
805 x = C3()
806 verify(not hasattr(x, "__dict__"))
807 verify(x.a is None)
808 verify(x.b is None)
809 verify(x.c is None)
810 x.a = 1
811 x.b = 2
812 x.c = 3
813 verify(x.a == 1)
814 verify(x.b == 2)
815 verify(x.c == 3)
816
817def dynamics():
818 if verbose: print "Testing __dynamic__..."
819 verify(object.__dynamic__ == 0)
820 verify(list.__dynamic__ == 0)
821 class S1:
822 __metaclass__ = type
823 verify(S1.__dynamic__ == 0)
824 class S(object):
825 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000826 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 class D(object):
828 __dynamic__ = 1
829 verify(D.__dynamic__ == 1)
830 class E(D, S):
831 pass
832 verify(E.__dynamic__ == 1)
833 class F(S, D):
834 pass
835 verify(F.__dynamic__ == 1)
836 try:
837 S.foo = 1
838 except (AttributeError, TypeError):
839 pass
840 else:
841 verify(0, "assignment to a static class attribute should be illegal")
842 D.foo = 1
843 verify(D.foo == 1)
844 # Test that dynamic attributes are inherited
845 verify(E.foo == 1)
846 verify(F.foo == 1)
847 class SS(D):
848 __dynamic__ = 0
849 verify(SS.__dynamic__ == 0)
850 verify(SS.foo == 1)
851 try:
852 SS.foo = 1
853 except (AttributeError, TypeError):
854 pass
855 else:
856 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000857 # Test dynamic instances
858 class C(object):
859 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000860 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000861 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000862 C.foobar = 2
863 verify(a.foobar == 2)
864 C.method = lambda self: 42
865 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000866 C.__repr__ = lambda self: "C()"
867 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000868 C.__int__ = lambda self: 100
869 verify(int(a) == 100)
870 verify(a.foobar == 2)
871 verify(not hasattr(a, "spam"))
872 def mygetattr(self, name):
873 if name == "spam":
874 return "spam"
875 else:
876 return object.__getattr__(self, name)
877 C.__getattr__ = mygetattr
878 verify(a.spam == "spam")
879 a.new = 12
880 verify(a.new == 12)
881 def mysetattr(self, name, value):
882 if name == "spam":
883 raise AttributeError
884 return object.__setattr__(self, name, value)
885 C.__setattr__ = mysetattr
886 try:
887 a.spam = "not spam"
888 except AttributeError:
889 pass
890 else:
891 verify(0, "expected AttributeError")
892 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000893 class D(C):
894 pass
895 d = D()
896 d.foo = 1
897 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898
899def errors():
900 if verbose: print "Testing errors..."
901
902 try:
903 class C(list, dictionary):
904 pass
905 except TypeError:
906 pass
907 else:
908 verify(0, "inheritance from both list and dict should be illegal")
909
910 try:
911 class C(object, None):
912 pass
913 except TypeError:
914 pass
915 else:
916 verify(0, "inheritance from non-type should be illegal")
917 class Classic:
918 pass
919
920 try:
921 class C(object, Classic):
922 pass
923 except TypeError:
924 pass
925 else:
926 verify(0, "inheritance from object and Classic should be illegal")
927
928 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000929 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000930 pass
931 except TypeError:
932 pass
933 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000934 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935
936 try:
937 class C(object):
938 __slots__ = 1
939 except TypeError:
940 pass
941 else:
942 verify(0, "__slots__ = 1 should be illegal")
943
944 try:
945 class C(object):
946 __slots__ = [1]
947 except TypeError:
948 pass
949 else:
950 verify(0, "__slots__ = [1] should be illegal")
951
952def classmethods():
953 if verbose: print "Testing class methods..."
954 class C(object):
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))
968
969def staticmethods():
970 if verbose: print "Testing static methods..."
971 class C(object):
972 def foo(*a): return a
973 goo = staticmethod(foo)
974 c = C()
975 verify(C.goo(1) == (1,))
976 verify(c.goo(1) == (1,))
977 verify(c.foo(1) == (c, 1,))
978 class D(C):
979 pass
980 d = D()
981 verify(D.goo(1) == (1,))
982 verify(d.goo(1) == (1,))
983 verify(d.foo(1) == (d, 1))
984 verify(D.foo(d, 1) == (d, 1))
985
986def classic():
987 if verbose: print "Testing classic classes..."
988 class C:
989 def foo(*a): return a
990 goo = classmethod(foo)
991 c = C()
992 verify(C.goo(1) == (C, 1))
993 verify(c.goo(1) == (C, 1))
994 verify(c.foo(1) == (c, 1))
995 class D(C):
996 pass
997 d = D()
998 verify(D.goo(1) == (D, 1))
999 verify(d.goo(1) == (D, 1))
1000 verify(d.foo(1) == (d, 1))
1001 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001002 class E: # *not* subclassing from C
1003 foo = C.foo
1004 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001005 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006
1007def compattr():
1008 if verbose: print "Testing computed attributes..."
1009 class C(object):
1010 class computed_attribute(object):
1011 def __init__(self, get, set=None):
1012 self.__get = get
1013 self.__set = set
1014 def __get__(self, obj, type=None):
1015 return self.__get(obj)
1016 def __set__(self, obj, value):
1017 return self.__set(obj, value)
1018 def __init__(self):
1019 self.__x = 0
1020 def __get_x(self):
1021 x = self.__x
1022 self.__x = x+1
1023 return x
1024 def __set_x(self, x):
1025 self.__x = x
1026 x = computed_attribute(__get_x, __set_x)
1027 a = C()
1028 verify(a.x == 0)
1029 verify(a.x == 1)
1030 a.x = 10
1031 verify(a.x == 10)
1032 verify(a.x == 11)
1033
1034def newslot():
1035 if verbose: print "Testing __new__ slot override..."
1036 class C(list):
1037 def __new__(cls):
1038 self = list.__new__(cls)
1039 self.foo = 1
1040 return self
1041 def __init__(self):
1042 self.foo = self.foo + 2
1043 a = C()
1044 verify(a.foo == 3)
1045 verify(a.__class__ is C)
1046 class D(C):
1047 pass
1048 b = D()
1049 verify(b.foo == 3)
1050 verify(b.__class__ is D)
1051
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052def altmro():
1053 if verbose: print "Testing mro() and overriding it..."
1054 class A(object):
1055 def f(self): return "A"
1056 class B(A):
1057 pass
1058 class C(A):
1059 def f(self): return "C"
1060 class D(B, C):
1061 pass
1062 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1063 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001064 class PerverseMetaType(type):
1065 def mro(cls):
1066 L = type.mro(cls)
1067 L.reverse()
1068 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069 class X(A,B,C,D):
1070 __metaclass__ = PerverseMetaType
1071 verify(X.__mro__ == (object, A, C, B, D, X))
1072 verify(X().f() == "A")
1073
1074def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001075 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076
1077 class B(object):
1078 "Intermediate class because object doesn't have a __setattr__"
1079
1080 class C(B):
1081
1082 def __getattr__(self, name):
1083 if name == "foo":
1084 return ("getattr", name)
1085 else:
1086 return B.__getattr__(self, name)
1087 def __setattr__(self, name, value):
1088 if name == "foo":
1089 self.setattr = (name, value)
1090 else:
1091 return B.__setattr__(self, name, value)
1092 def __delattr__(self, name):
1093 if name == "foo":
1094 self.delattr = name
1095 else:
1096 return B.__delattr__(self, name)
1097
1098 def __getitem__(self, key):
1099 return ("getitem", key)
1100 def __setitem__(self, key, value):
1101 self.setitem = (key, value)
1102 def __delitem__(self, key):
1103 self.delitem = key
1104
1105 def __getslice__(self, i, j):
1106 return ("getslice", i, j)
1107 def __setslice__(self, i, j, value):
1108 self.setslice = (i, j, value)
1109 def __delslice__(self, i, j):
1110 self.delslice = (i, j)
1111
1112 a = C()
1113 verify(a.foo == ("getattr", "foo"))
1114 a.foo = 12
1115 verify(a.setattr == ("foo", 12))
1116 del a.foo
1117 verify(a.delattr == "foo")
1118
1119 verify(a[12] == ("getitem", 12))
1120 a[12] = 21
1121 verify(a.setitem == (12, 21))
1122 del a[12]
1123 verify(a.delitem == 12)
1124
1125 verify(a[0:10] == ("getslice", 0, 10))
1126 a[0:10] = "foo"
1127 verify(a.setslice == (0, 10, "foo"))
1128 del a[0:10]
1129 verify(a.delslice == (0, 10))
1130
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001131def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001132 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001133 class C(object):
1134 def __init__(self, x):
1135 self.x = x
1136 def foo(self):
1137 return self.x
1138 c1 = C(1)
1139 verify(c1.foo() == 1)
1140 class D(C):
1141 boo = C.foo
1142 goo = c1.foo
1143 d2 = D(2)
1144 verify(d2.foo() == 2)
1145 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001146 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001147 class E(object):
1148 foo = C.foo
1149 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001150 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001151
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001152def specials():
1153 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001154 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001155 # Test the default behavior for static classes
1156 class C(object):
1157 def __getitem__(self, i):
1158 if 0 <= i < 10: return i
1159 raise IndexError
1160 c1 = C()
1161 c2 = C()
1162 verify(not not c1)
1163 verify(hash(c1) == id(c1))
1164 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1165 verify(c1 == c1)
1166 verify(c1 != c2)
1167 verify(not c1 != c1)
1168 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001169 # Note that the module name appears in str/repr, and that varies
1170 # depending on whether this test is run standalone or from a framework.
1171 verify(str(c1).find('C instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001172 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001173 verify(-1 not in c1)
1174 for i in range(10):
1175 verify(i in c1)
1176 verify(10 not in c1)
1177 # Test the default behavior for dynamic classes
1178 class D(object):
1179 __dynamic__ = 1
1180 def __getitem__(self, i):
1181 if 0 <= i < 10: return i
1182 raise IndexError
1183 d1 = D()
1184 d2 = D()
1185 verify(not not d1)
1186 verify(hash(d1) == id(d1))
1187 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1188 verify(d1 == d1)
1189 verify(d1 != d2)
1190 verify(not d1 != d1)
1191 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001192 # Note that the module name appears in str/repr, and that varies
1193 # depending on whether this test is run standalone or from a framework.
1194 verify(str(d1).find('D instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001195 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001196 verify(-1 not in d1)
1197 for i in range(10):
1198 verify(i in d1)
1199 verify(10 not in d1)
1200 # Test overridden behavior for static classes
1201 class Proxy(object):
1202 def __init__(self, x):
1203 self.x = x
1204 def __nonzero__(self):
1205 return not not self.x
1206 def __hash__(self):
1207 return hash(self.x)
1208 def __eq__(self, other):
1209 return self.x == other
1210 def __ne__(self, other):
1211 return self.x != other
1212 def __cmp__(self, other):
1213 return cmp(self.x, other.x)
1214 def __str__(self):
1215 return "Proxy:%s" % self.x
1216 def __repr__(self):
1217 return "Proxy(%r)" % self.x
1218 def __contains__(self, value):
1219 return value in self.x
1220 p0 = Proxy(0)
1221 p1 = Proxy(1)
1222 p_1 = Proxy(-1)
1223 verify(not p0)
1224 verify(not not p1)
1225 verify(hash(p0) == hash(0))
1226 verify(p0 == p0)
1227 verify(p0 != p1)
1228 verify(not p0 != p0)
1229 verify(not p0 == p1)
1230 verify(cmp(p0, p1) == -1)
1231 verify(cmp(p0, p0) == 0)
1232 verify(cmp(p0, p_1) == 1)
1233 verify(str(p0) == "Proxy:0")
1234 verify(repr(p0) == "Proxy(0)")
1235 p10 = Proxy(range(10))
1236 verify(-1 not in p10)
1237 for i in range(10):
1238 verify(i in p10)
1239 verify(10 not in p10)
1240 # Test overridden behavior for dynamic classes
1241 class DProxy(object):
1242 __dynamic__ = 1
1243 def __init__(self, x):
1244 self.x = x
1245 def __nonzero__(self):
1246 return not not self.x
1247 def __hash__(self):
1248 return hash(self.x)
1249 def __eq__(self, other):
1250 return self.x == other
1251 def __ne__(self, other):
1252 return self.x != other
1253 def __cmp__(self, other):
1254 return cmp(self.x, other.x)
1255 def __str__(self):
1256 return "DProxy:%s" % self.x
1257 def __repr__(self):
1258 return "DProxy(%r)" % self.x
1259 def __contains__(self, value):
1260 return value in self.x
1261 p0 = DProxy(0)
1262 p1 = DProxy(1)
1263 p_1 = DProxy(-1)
1264 verify(not p0)
1265 verify(not not p1)
1266 verify(hash(p0) == hash(0))
1267 verify(p0 == p0)
1268 verify(p0 != p1)
1269 verify(not p0 != p0)
1270 verify(not p0 == p1)
1271 verify(cmp(p0, p1) == -1)
1272 verify(cmp(p0, p0) == 0)
1273 verify(cmp(p0, p_1) == 1)
1274 verify(str(p0) == "DProxy:0")
1275 verify(repr(p0) == "DProxy(0)")
1276 p10 = DProxy(range(10))
1277 verify(-1 not in p10)
1278 for i in range(10):
1279 verify(i in p10)
1280 verify(10 not in p10)
1281
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001282def weakrefs():
1283 if verbose: print "Testing weak references..."
1284 import weakref
1285 class C(object):
1286 pass
1287 c = C()
1288 r = weakref.ref(c)
1289 verify(r() is c)
1290 del c
1291 verify(r() is None)
1292 del r
1293 class NoWeak(object):
1294 __slots__ = ['foo']
1295 no = NoWeak()
1296 try:
1297 weakref.ref(no)
1298 except TypeError, msg:
1299 verify(str(msg).find("weakly") >= 0)
1300 else:
1301 verify(0, "weakref.ref(no) should be illegal")
1302 class Weak(object):
1303 __slots__ = ['foo', '__weakref__']
1304 yes = Weak()
1305 r = weakref.ref(yes)
1306 verify(r() is yes)
1307 del yes
1308 verify(r() is None)
1309 del r
1310
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001311def properties():
1312 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001313 class C(object):
1314 def getx(self):
1315 return self.__x
1316 def setx(self, value):
1317 self.__x = value
1318 def delx(self):
1319 del self.__x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001320 x = property(getx, setx, delx)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001321 a = C()
1322 verify(not hasattr(a, "x"))
1323 a.x = 42
1324 verify(a._C__x == 42)
1325 verify(a.x == 42)
1326 del a.x
1327 verify(not hasattr(a, "x"))
1328 verify(not hasattr(a, "_C__x"))
1329 C.x.__set__(a, 100)
1330 verify(C.x.__get__(a) == 100)
1331## C.x.__set__(a)
1332## verify(not hasattr(a, "x"))
1333
Guido van Rossumc4a18802001-08-24 16:55:27 +00001334def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001335 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001336
1337 class A(object):
1338 def meth(self, a):
1339 return "A(%r)" % a
1340
1341 verify(A().meth(1) == "A(1)")
1342
1343 class B(A):
1344 def __init__(self):
1345 self.__super = super(B, self)
1346 def meth(self, a):
1347 return "B(%r)" % a + self.__super.meth(a)
1348
1349 verify(B().meth(2) == "B(2)A(2)")
1350
1351 class C(A):
1352 __dynamic__ = 1
1353 def meth(self, a):
1354 return "C(%r)" % a + self.__super.meth(a)
1355 C._C__super = super(C)
1356
1357 verify(C().meth(3) == "C(3)A(3)")
1358
1359 class D(C, B):
1360 def meth(self, a):
1361 return "D(%r)" % a + super(D, self).meth(a)
1362
1363 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1364
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001365def inherits():
1366 if verbose: print "Testing inheritance from basic types..."
1367
1368 class hexint(int):
1369 def __repr__(self):
1370 return hex(self)
1371 def __add__(self, other):
1372 return hexint(int.__add__(self, other))
1373 # (Note that overriding __radd__ doesn't work,
1374 # because the int type gets first dibs.)
1375 verify(repr(hexint(7) + 9) == "0x10")
1376 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001377 a = hexint(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001378 #XXX verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001379 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001380 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001381 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001382 verify((+a).__class__ is int)
1383 verify((a >> 0).__class__ is int)
1384 verify((a << 0).__class__ is int)
1385 verify((hexint(0) << 12).__class__ is int)
1386 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001387
1388 class octlong(long):
1389 __slots__ = []
1390 def __str__(self):
1391 s = oct(self)
1392 if s[-1] == 'L':
1393 s = s[:-1]
1394 return s
1395 def __add__(self, other):
1396 return self.__class__(super(octlong, self).__add__(other))
1397 __radd__ = __add__
1398 verify(str(octlong(3) + 5) == "010")
1399 # (Note that overriding __radd__ here only seems to work
1400 # because the example uses a short int left argument.)
1401 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001402 a = octlong(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001403 #XXX verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001404 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001405 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001406 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001407 verify((+a).__class__ is long)
1408 verify((-a).__class__ is long)
1409 verify((-octlong(0)).__class__ is long)
1410 verify((a >> 0).__class__ is long)
1411 verify((a << 0).__class__ is long)
1412 verify((a - 0).__class__ is long)
1413 verify((a * 1).__class__ is long)
1414 verify((a ** 1).__class__ is long)
1415 verify((a // 1).__class__ is long)
1416 verify((1 * a).__class__ is long)
1417 verify((a | 0).__class__ is long)
1418 verify((a ^ 0).__class__ is long)
1419 verify((a & -1L).__class__ is long)
1420 verify((octlong(0) << 12).__class__ is long)
1421 verify((octlong(0) >> 12).__class__ is long)
1422 verify(abs(octlong(0)).__class__ is long)
1423
1424 # Because octlong overrides __add__, we can't check the absence of +0
1425 # optimizations using octlong.
1426 class longclone(long):
1427 pass
1428 a = longclone(1)
1429 verify((a + 0).__class__ is long)
1430 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001431
1432 class precfloat(float):
1433 __slots__ = ['prec']
1434 def __init__(self, value=0.0, prec=12):
1435 self.prec = int(prec)
1436 float.__init__(value)
1437 def __repr__(self):
1438 return "%.*g" % (self.prec, self)
1439 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001440 a = precfloat(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001441 #XXX verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001442 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001443 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001444 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001445 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001446
Tim Peters2400fa42001-09-12 19:12:49 +00001447 class madcomplex(complex):
1448 def __repr__(self):
1449 return "%.17gj%+.17g" % (self.imag, self.real)
1450 a = madcomplex(-3, 4)
1451 verify(repr(a) == "4j-3")
1452 base = complex(-3, 4)
1453 verify(base.__class__ is complex)
Tim Peters4f467e82001-09-12 19:53:15 +00001454 #XXX verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001455 verify(complex(a) == base)
1456 verify(complex(a).__class__ is complex)
1457 a = madcomplex(a) # just trying another form of the constructor
1458 verify(repr(a) == "4j-3")
Tim Peters4f467e82001-09-12 19:53:15 +00001459 #XXX verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001460 verify(complex(a) == base)
1461 verify(complex(a).__class__ is complex)
1462 verify(hash(a) == hash(base))
1463 verify((+a).__class__ is complex)
1464 verify((a + 0).__class__ is complex)
1465 verify(a + 0 == base)
1466 verify((a - 0).__class__ is complex)
1467 verify(a - 0 == base)
1468 verify((a * 1).__class__ is complex)
1469 verify(a * 1 == base)
1470 verify((a / 1).__class__ is complex)
1471 verify(a / 1 == base)
1472
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001473 class madtuple(tuple):
1474 _rev = None
1475 def rev(self):
1476 if self._rev is not None:
1477 return self._rev
1478 L = list(self)
1479 L.reverse()
1480 self._rev = self.__class__(L)
1481 return self._rev
1482 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001483 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001484 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1485 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1486 for i in range(512):
1487 t = madtuple(range(i))
1488 u = t.rev()
1489 v = u.rev()
1490 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001491 a = madtuple((1,2,3,4,5))
1492 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001493 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001494 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001495 verify(a[:].__class__ is tuple)
1496 verify((a * 1).__class__ is tuple)
1497 verify((a * 0).__class__ is tuple)
1498 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001499 a = madtuple(())
1500 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001501 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001502 verify((a + a).__class__ is tuple)
1503 verify((a * 0).__class__ is tuple)
1504 verify((a * 1).__class__ is tuple)
1505 verify((a * 2).__class__ is tuple)
1506 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001507
1508 class madstring(str):
1509 _rev = None
1510 def rev(self):
1511 if self._rev is not None:
1512 return self._rev
1513 L = list(self)
1514 L.reverse()
1515 self._rev = self.__class__("".join(L))
1516 return self._rev
1517 s = madstring("abcdefghijklmnopqrstuvwxyz")
Tim Peters4f467e82001-09-12 19:53:15 +00001518 #XXX verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001519 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1520 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1521 for i in range(256):
1522 s = madstring("".join(map(chr, range(i))))
1523 t = s.rev()
1524 u = t.rev()
1525 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001526 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001527 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001528 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001529
Tim Peters8fa5dd02001-09-12 02:18:30 +00001530 base = "\x00" * 5
1531 s = madstring(base)
Tim Peters4f467e82001-09-12 19:53:15 +00001532 #XXX verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001533 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001534 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001535 verify(hash(s) == hash(base))
1536 verify({s: 1}[base] == 1)
1537 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001538 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001539 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001540 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001541 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001542 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001543 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001544 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001545 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001546 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001547 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001548 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001549 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001550 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001551 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001552 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001553 verify(s.strip() == base)
1554 verify(s.lstrip().__class__ is str)
1555 verify(s.lstrip() == base)
1556 verify(s.rstrip().__class__ is str)
1557 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001558 identitytab = ''.join([chr(i) for i in range(256)])
1559 verify(s.translate(identitytab).__class__ is str)
1560 verify(s.translate(identitytab) == base)
1561 verify(s.translate(identitytab, "x").__class__ is str)
1562 verify(s.translate(identitytab, "x") == base)
1563 verify(s.translate(identitytab, "\x00") == "")
1564 verify(s.replace("x", "x").__class__ is str)
1565 verify(s.replace("x", "x") == base)
1566 verify(s.ljust(len(s)).__class__ is str)
1567 verify(s.ljust(len(s)) == base)
1568 verify(s.rjust(len(s)).__class__ is str)
1569 verify(s.rjust(len(s)) == base)
1570 verify(s.center(len(s)).__class__ is str)
1571 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001572 verify(s.lower().__class__ is str)
1573 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001574
Tim Peters111f6092001-09-12 07:54:51 +00001575 s = madstring("x y")
Tim Peters4f467e82001-09-12 19:53:15 +00001576 #XXX verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001577 verify(intern(s).__class__ is str)
1578 verify(intern(s) is intern("x y"))
1579 verify(intern(s) == "x y")
1580
1581 i = intern("y x")
1582 s = madstring("y x")
Tim Peters4f467e82001-09-12 19:53:15 +00001583 #XXX verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001584 verify(intern(s).__class__ is str)
1585 verify(intern(s) is i)
1586
1587 s = madstring(i)
1588 verify(intern(s).__class__ is str)
1589 verify(intern(s) is i)
1590
Guido van Rossum91ee7982001-08-30 20:52:40 +00001591 class madunicode(unicode):
1592 _rev = None
1593 def rev(self):
1594 if self._rev is not None:
1595 return self._rev
1596 L = list(self)
1597 L.reverse()
1598 self._rev = self.__class__(u"".join(L))
1599 return self._rev
1600 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001601 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001602 verify(u.rev() == madunicode(u"FEDCBA"))
1603 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001604 base = u"12345"
1605 u = madunicode(base)
1606 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001607 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001608 verify(hash(u) == hash(base))
1609 verify({u: 1}[base] == 1)
1610 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001611 verify(u.strip().__class__ is unicode)
1612 verify(u.strip() == base)
1613 verify(u.lstrip().__class__ is unicode)
1614 verify(u.lstrip() == base)
1615 verify(u.rstrip().__class__ is unicode)
1616 verify(u.rstrip() == base)
1617 verify(u.replace(u"x", u"x").__class__ is unicode)
1618 verify(u.replace(u"x", u"x") == base)
1619 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1620 verify(u.replace(u"xy", u"xy") == base)
1621 verify(u.center(len(u)).__class__ is unicode)
1622 verify(u.center(len(u)) == base)
1623 verify(u.ljust(len(u)).__class__ is unicode)
1624 verify(u.ljust(len(u)) == base)
1625 verify(u.rjust(len(u)).__class__ is unicode)
1626 verify(u.rjust(len(u)) == base)
1627 verify(u.lower().__class__ is unicode)
1628 verify(u.lower() == base)
1629 verify(u.upper().__class__ is unicode)
1630 verify(u.upper() == base)
1631 verify(u.capitalize().__class__ is unicode)
1632 verify(u.capitalize() == base)
1633 verify(u.title().__class__ is unicode)
1634 verify(u.title() == base)
1635 verify((u + u"").__class__ is unicode)
1636 verify(u + u"" == base)
1637 verify((u"" + u).__class__ is unicode)
1638 verify(u"" + u == base)
1639 verify((u * 0).__class__ is unicode)
1640 verify(u * 0 == u"")
1641 verify((u * 1).__class__ is unicode)
1642 verify(u * 1 == base)
1643 verify((u * 2).__class__ is unicode)
1644 verify(u * 2 == base + base)
1645 verify(u[:].__class__ is unicode)
1646 verify(u[:] == base)
1647 verify(u[0:0].__class__ is unicode)
1648 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001649
Tim Peters59c9a642001-09-13 05:38:56 +00001650 class CountedInput(file):
1651 """Counts lines read by self.readline().
1652
1653 self.lineno is the 0-based ordinal of the last line read, up to
1654 a maximum of one greater than the number of lines in the file.
1655
1656 self.ateof is true if and only if the final "" line has been read,
1657 at which point self.lineno stops incrementing, and further calls
1658 to readline() continue to return "".
1659 """
1660
1661 lineno = 0
1662 ateof = 0
1663 def readline(self):
1664 if self.ateof:
1665 return ""
1666 s = file.readline(self)
1667 # Next line works too.
1668 # s = super(CountedInput, self).readline()
1669 self.lineno += 1
1670 if s == "":
1671 self.ateof = 1
1672 return s
1673
1674 f = open(TESTFN, 'w')
1675 lines = ['a\n', 'b\n', 'c\n']
1676 try:
1677 f.writelines(lines)
1678 f.close()
1679 f = CountedInput(TESTFN)
1680 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1681 got = f.readline()
1682 verify(expected == got)
1683 verify(f.lineno == i)
1684 verify(f.ateof == (i > len(lines)))
1685 f.close()
1686 finally:
1687 try:
1688 f.close()
1689 except:
1690 pass
1691 try:
1692 import os
1693 os.unlink(TESTFN)
1694 except:
1695 pass
1696
Tim Peters808b94e2001-09-13 19:33:07 +00001697def keywords():
1698 if verbose:
1699 print "Testing keyword args to basic type constructors ..."
1700 verify(int(x=1) == 1)
1701 verify(float(x=2) == 2.0)
1702 verify(long(x=3) == 3L)
1703 verify(complex(imag=42, real=666) == complex(666, 42))
1704 verify(str(object=500) == '500')
1705 verify(unicode(string='abc', errors='strict') == u'abc')
1706 verify(tuple(sequence=range(3)) == (0, 1, 2))
1707 verify(list(sequence=(0, 1, 2)) == range(3))
1708 verify(dictionary(mapping={1: 2}) == {1: 2})
1709
1710 for constructor in (int, float, long, complex, str, unicode,
1711 tuple, list, dictionary, file):
1712 try:
1713 constructor(bogus_keyword_arg=1)
1714 except TypeError:
1715 pass
1716 else:
1717 raise TestFailed("expected TypeError from bogus keyword "
1718 "argument to %r" % constructor)
1719
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720def all():
1721 lists()
1722 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00001723 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00001724 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001725 ints()
1726 longs()
1727 floats()
1728 complexes()
1729 spamlists()
1730 spamdicts()
1731 pydicts()
1732 pylists()
1733 metaclass()
1734 pymods()
1735 multi()
1736 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001737 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738 slots()
1739 dynamics()
1740 errors()
1741 classmethods()
1742 staticmethods()
1743 classic()
1744 compattr()
1745 newslot()
1746 altmro()
1747 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001748 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001749 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001750 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001751 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00001752 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001753 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00001754 keywords()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755
1756all()
1757
1758if verbose: print "All OK"