blob: 4ed6853e19f0a34aa0f9ef03394b174e471e95ad [file] [log] [blame]
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001# Test enhancements related to descriptors and new-style classes
Tim Peters6d6c1a32001-08-02 04:15:00 +00002
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
Guido van Rossum4bb1e362001-09-28 23:49:48 +00006def vereq(a, b):
7 if a != b:
8 raise TestFailed, "%r != %r" % (a, b)
9
Tim Peters6d6c1a32001-08-02 04:15:00 +000010def testunop(a, res, expr="len(a)", meth="__len__"):
11 if verbose: print "checking", expr
12 dict = {'a': a}
13 verify(eval(expr, dict) == res)
14 t = type(a)
15 m = getattr(t, meth)
16 verify(m == t.__dict__[meth])
17 verify(m(a) == res)
18 bm = getattr(a, meth)
19 verify(bm() == res)
20
21def testbinop(a, b, res, expr="a+b", meth="__add__"):
22 if verbose: print "checking", expr
23 dict = {'a': a, 'b': b}
24 verify(eval(expr, dict) == res)
25 t = type(a)
26 m = getattr(t, meth)
27 verify(m == t.__dict__[meth])
28 verify(m(a, b) == res)
29 bm = getattr(a, meth)
30 verify(bm(b) == res)
31
32def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
33 if verbose: print "checking", expr
34 dict = {'a': a, 'b': b, 'c': c}
35 verify(eval(expr, dict) == res)
36 t = type(a)
37 m = getattr(t, meth)
38 verify(m == t.__dict__[meth])
39 verify(m(a, b, c) == res)
40 bm = getattr(a, meth)
41 verify(bm(b, c) == res)
42
43def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
44 if verbose: print "checking", stmt
45 dict = {'a': deepcopy(a), 'b': b}
46 exec stmt in dict
47 verify(dict['a'] == res)
48 t = type(a)
49 m = getattr(t, meth)
50 verify(m == t.__dict__[meth])
51 dict['a'] = deepcopy(a)
52 m(dict['a'], b)
53 verify(dict['a'] == res)
54 dict['a'] = deepcopy(a)
55 bm = getattr(dict['a'], meth)
56 bm(b)
57 verify(dict['a'] == res)
58
59def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
60 if verbose: print "checking", stmt
61 dict = {'a': deepcopy(a), 'b': b, 'c': c}
62 exec stmt in dict
63 verify(dict['a'] == res)
64 t = type(a)
65 m = getattr(t, meth)
66 verify(m == t.__dict__[meth])
67 dict['a'] = deepcopy(a)
68 m(dict['a'], b, c)
69 verify(dict['a'] == res)
70 dict['a'] = deepcopy(a)
71 bm = getattr(dict['a'], meth)
72 bm(b, c)
73 verify(dict['a'] == res)
74
75def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
76 if verbose: print "checking", stmt
77 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
78 exec stmt in dict
79 verify(dict['a'] == res)
80 t = type(a)
81 m = getattr(t, meth)
82 verify(m == t.__dict__[meth])
83 dict['a'] = deepcopy(a)
84 m(dict['a'], b, c, d)
85 verify(dict['a'] == res)
86 dict['a'] = deepcopy(a)
87 bm = getattr(dict['a'], meth)
88 bm(b, c, d)
89 verify(dict['a'] == res)
90
91def lists():
92 if verbose: print "Testing list operations..."
93 testbinop([1], [2], [1,2], "a+b", "__add__")
94 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
95 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
96 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
97 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
98 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
99 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
100 testunop([1,2,3], 3, "len(a)", "__len__")
101 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
102 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
103 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
104 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
105
106def dicts():
107 if verbose: print "Testing dict operations..."
108 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
109 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
110 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
111 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
112 d = {1:2,3:4}
113 l1 = []
114 for i in d.keys(): l1.append(i)
115 l = []
116 for i in iter(d): l.append(i)
117 verify(l == l1)
118 l = []
119 for i in d.__iter__(): l.append(i)
120 verify(l == l1)
121 l = []
122 for i in dictionary.__iter__(d): l.append(i)
123 verify(l == l1)
124 d = {1:2, 3:4}
125 testunop(d, 2, "len(a)", "__len__")
126 verify(eval(repr(d), {}) == d)
127 verify(eval(d.__repr__(), {}) == d)
128 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
129
Tim Peters25786c02001-09-02 08:22:48 +0000130def dict_constructor():
131 if verbose:
132 print "Testing dictionary constructor ..."
133 d = dictionary()
134 verify(d == {})
135 d = dictionary({})
136 verify(d == {})
137 d = dictionary(mapping={})
138 verify(d == {})
139 d = dictionary({1: 2, 'a': 'b'})
140 verify(d == {1: 2, 'a': 'b'})
141 for badarg in 0, 0L, 0j, "0", [0], (0,):
142 try:
143 dictionary(badarg)
144 except TypeError:
145 pass
146 else:
147 raise TestFailed("no TypeError from dictionary(%r)" % badarg)
148 try:
149 dictionary(senseless={})
150 except TypeError:
151 pass
152 else:
153 raise TestFailed("no TypeError from dictionary(senseless={}")
154
155 try:
156 dictionary({}, {})
157 except TypeError:
158 pass
159 else:
160 raise TestFailed("no TypeError from dictionary({}, {})")
161
162 class Mapping:
163 dict = {1:2, 3:4, 'a':1j}
164
165 def __getitem__(self, i):
166 return self.dict[i]
167
168 try:
169 dictionary(Mapping())
170 except TypeError:
171 pass
172 else:
173 raise TestFailed("no TypeError from dictionary(incomplete mapping)")
174
175 Mapping.keys = lambda self: self.dict.keys()
176 d = dictionary(mapping=Mapping())
177 verify(d == Mapping.dict)
178
Tim Peters5d2b77c2001-09-03 05:47:38 +0000179def test_dir():
180 if verbose:
181 print "Testing dir() ..."
182 junk = 12
183 verify(dir() == ['junk'])
184 del junk
185
186 # Just make sure these don't blow up!
187 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
188 dir(arg)
189
Tim Peters37a309d2001-09-04 01:20:04 +0000190 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000191 class C:
192 Cdata = 1
193 def Cmethod(self): pass
194
195 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
196 verify(dir(C) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000197 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000198
199 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
200 verify(dir(c) == cstuff)
201
202 c.cdata = 2
203 c.cmethod = lambda self: 0
204 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000205 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000206
207 class A(C):
208 Adata = 1
209 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000210
Tim Peters37a309d2001-09-04 01:20:04 +0000211 astuff = ['Adata', 'Amethod'] + cstuff
212 verify(dir(A) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000213 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000214 a = A()
215 verify(dir(a) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000216 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000217 a.adata = 42
218 a.amethod = lambda self: 3
219 verify(dir(a) == astuff + ['adata', 'amethod'])
220
221 # The same, but with new-style classes. Since these have object as a
222 # base class, a lot more gets sucked in.
223 def interesting(strings):
224 return [s for s in strings if not s.startswith('_')]
225
Tim Peters5d2b77c2001-09-03 05:47:38 +0000226 class C(object):
227 Cdata = 1
228 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000229
230 cstuff = ['Cdata', 'Cmethod']
231 verify(interesting(dir(C)) == cstuff)
232
233 c = C()
234 verify(interesting(dir(c)) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000235 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000236
237 c.cdata = 2
238 c.cmethod = lambda self: 0
239 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000240 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000241
Tim Peters5d2b77c2001-09-03 05:47:38 +0000242 class A(C):
243 Adata = 1
244 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000245
246 astuff = ['Adata', 'Amethod'] + cstuff
247 verify(interesting(dir(A)) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000248 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000249 a = A()
250 verify(interesting(dir(a)) == astuff)
251 a.adata = 42
252 a.amethod = lambda self: 3
253 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000254 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000255
Tim Peterscaaff8d2001-09-10 23:12:14 +0000256 # Try a module subclass.
257 import sys
258 class M(type(sys)):
259 pass
260 minstance = M()
261 minstance.b = 2
262 minstance.a = 1
263 verify(dir(minstance) == ['a', 'b'])
264
265 class M2(M):
266 def getdict(self):
267 return "Not a dict!"
268 __dict__ = property(getdict)
269
270 m2instance = M2()
271 m2instance.b = 2
272 m2instance.a = 1
273 verify(m2instance.__dict__ == "Not a dict!")
274 try:
275 dir(m2instance)
276 except TypeError:
277 pass
278
Tim Peters6d6c1a32001-08-02 04:15:00 +0000279binops = {
280 'add': '+',
281 'sub': '-',
282 'mul': '*',
283 'div': '/',
284 'mod': '%',
285 'divmod': 'divmod',
286 'pow': '**',
287 'lshift': '<<',
288 'rshift': '>>',
289 'and': '&',
290 'xor': '^',
291 'or': '|',
292 'cmp': 'cmp',
293 'lt': '<',
294 'le': '<=',
295 'eq': '==',
296 'ne': '!=',
297 'gt': '>',
298 'ge': '>=',
299 }
300
301for name, expr in binops.items():
302 if expr.islower():
303 expr = expr + "(a, b)"
304 else:
305 expr = 'a %s b' % expr
306 binops[name] = expr
307
308unops = {
309 'pos': '+',
310 'neg': '-',
311 'abs': 'abs',
312 'invert': '~',
313 'int': 'int',
314 'long': 'long',
315 'float': 'float',
316 'oct': 'oct',
317 'hex': 'hex',
318 }
319
320for name, expr in unops.items():
321 if expr.islower():
322 expr = expr + "(a)"
323 else:
324 expr = '%s a' % expr
325 unops[name] = expr
326
327def numops(a, b, skip=[]):
328 dict = {'a': a, 'b': b}
329 for name, expr in binops.items():
330 if name not in skip:
331 name = "__%s__" % name
332 if hasattr(a, name):
333 res = eval(expr, dict)
334 testbinop(a, b, res, expr, name)
335 for name, expr in unops.items():
336 name = "__%s__" % name
337 if hasattr(a, name):
338 res = eval(expr, dict)
339 testunop(a, res, expr, name)
340
341def ints():
342 if verbose: print "Testing int operations..."
343 numops(100, 3)
344
345def longs():
346 if verbose: print "Testing long operations..."
347 numops(100L, 3L)
348
349def floats():
350 if verbose: print "Testing float operations..."
351 numops(100.0, 3.0)
352
353def complexes():
354 if verbose: print "Testing complex operations..."
355 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
356 class Number(complex):
357 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000358 def __new__(cls, *args, **kwds):
359 result = complex.__new__(cls, *args)
360 result.prec = kwds.get('prec', 12)
361 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000362 def __repr__(self):
363 prec = self.prec
364 if self.imag == 0.0:
365 return "%.*g" % (prec, self.real)
366 if self.real == 0.0:
367 return "%.*gj" % (prec, self.imag)
368 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
369 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000370
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371 a = Number(3.14, prec=6)
372 verify(`a` == "3.14")
373 verify(a.prec == 6)
374
Tim Peters3f996e72001-09-13 19:18:27 +0000375 a = Number(a, prec=2)
376 verify(`a` == "3.1")
377 verify(a.prec == 2)
378
379 a = Number(234.5)
380 verify(`a` == "234.5")
381 verify(a.prec == 12)
382
Tim Peters6d6c1a32001-08-02 04:15:00 +0000383def spamlists():
384 if verbose: print "Testing spamlist operations..."
385 import copy, xxsubtype as spam
386 def spamlist(l, memo=None):
387 import xxsubtype as spam
388 return spam.spamlist(l)
389 # This is an ugly hack:
390 copy._deepcopy_dispatch[spam.spamlist] = spamlist
391
392 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
393 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
394 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
395 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
396 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
397 "a[b:c]", "__getslice__")
398 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
399 "a+=b", "__iadd__")
400 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
401 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
402 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
403 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
404 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
405 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
406 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
407 # Test subclassing
408 class C(spam.spamlist):
409 def foo(self): return 1
410 a = C()
411 verify(a == [])
412 verify(a.foo() == 1)
413 a.append(100)
414 verify(a == [100])
415 verify(a.getstate() == 0)
416 a.setstate(42)
417 verify(a.getstate() == 42)
418
419def spamdicts():
420 if verbose: print "Testing spamdict operations..."
421 import copy, xxsubtype as spam
422 def spamdict(d, memo=None):
423 import xxsubtype as spam
424 sd = spam.spamdict()
425 for k, v in d.items(): sd[k] = v
426 return sd
427 # This is an ugly hack:
428 copy._deepcopy_dispatch[spam.spamdict] = spamdict
429
430 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
431 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
432 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
433 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
434 d = spamdict({1:2,3:4})
435 l1 = []
436 for i in d.keys(): l1.append(i)
437 l = []
438 for i in iter(d): l.append(i)
439 verify(l == l1)
440 l = []
441 for i in d.__iter__(): l.append(i)
442 verify(l == l1)
443 l = []
444 for i in type(spamdict({})).__iter__(d): l.append(i)
445 verify(l == l1)
446 straightd = {1:2, 3:4}
447 spamd = spamdict(straightd)
448 testunop(spamd, 2, "len(a)", "__len__")
449 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
450 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
451 "a[b]=c", "__setitem__")
452 # Test subclassing
453 class C(spam.spamdict):
454 def foo(self): return 1
455 a = C()
456 verify(a.items() == [])
457 verify(a.foo() == 1)
458 a['foo'] = 'bar'
459 verify(a.items() == [('foo', 'bar')])
460 verify(a.getstate() == 0)
461 a.setstate(100)
462 verify(a.getstate() == 100)
463
464def pydicts():
465 if verbose: print "Testing Python subclass of dict..."
466 verify(issubclass(dictionary, dictionary))
467 verify(isinstance({}, dictionary))
468 d = dictionary()
469 verify(d == {})
470 verify(d.__class__ is dictionary)
471 verify(isinstance(d, dictionary))
472 class C(dictionary):
473 state = -1
474 def __init__(self, *a, **kw):
475 if a:
476 assert len(a) == 1
477 self.state = a[0]
478 if kw:
479 for k, v in kw.items(): self[v] = k
480 def __getitem__(self, key):
481 return self.get(key, 0)
482 def __setitem__(self, key, value):
483 assert isinstance(key, type(0))
484 dictionary.__setitem__(self, key, value)
485 def setstate(self, state):
486 self.state = state
487 def getstate(self):
488 return self.state
489 verify(issubclass(C, dictionary))
490 a1 = C(12)
491 verify(a1.state == 12)
492 a2 = C(foo=1, bar=2)
493 verify(a2[1] == 'foo' and a2[2] == 'bar')
494 a = C()
495 verify(a.state == -1)
496 verify(a.getstate() == -1)
497 a.setstate(0)
498 verify(a.state == 0)
499 verify(a.getstate() == 0)
500 a.setstate(10)
501 verify(a.state == 10)
502 verify(a.getstate() == 10)
503 verify(a[42] == 0)
504 a[42] = 24
505 verify(a[42] == 24)
506 if verbose: print "pydict stress test ..."
507 N = 50
508 for i in range(N):
509 a[i] = C()
510 for j in range(N):
511 a[i][j] = i*j
512 for i in range(N):
513 for j in range(N):
514 verify(a[i][j] == i*j)
515
516def pylists():
517 if verbose: print "Testing Python subclass of list..."
518 class C(list):
519 def __getitem__(self, i):
520 return list.__getitem__(self, i) + 100
521 def __getslice__(self, i, j):
522 return (i, j)
523 a = C()
524 a.extend([0,1,2])
525 verify(a[0] == 100)
526 verify(a[1] == 101)
527 verify(a[2] == 102)
528 verify(a[100:200] == (100,200))
529
530def metaclass():
531 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000532 class C:
533 __metaclass__ = type
534 def __init__(self):
535 self.__state = 0
536 def getstate(self):
537 return self.__state
538 def setstate(self, state):
539 self.__state = state
540 a = C()
541 verify(a.getstate() == 0)
542 a.setstate(10)
543 verify(a.getstate() == 10)
544 class D:
545 class __metaclass__(type):
546 def myself(cls): return cls
547 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000548 d = D()
549 verify(d.__class__ is D)
550 class M1(type):
551 def __new__(cls, name, bases, dict):
552 dict['__spam__'] = 1
553 return type.__new__(cls, name, bases, dict)
554 class C:
555 __metaclass__ = M1
556 verify(C.__spam__ == 1)
557 c = C()
558 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000559
Guido van Rossum309b5662001-08-17 11:43:17 +0000560 class _instance(object):
561 pass
562 class M2(object):
563 def __new__(cls, name, bases, dict):
564 self = object.__new__(cls)
565 self.name = name
566 self.bases = bases
567 self.dict = dict
568 return self
569 __new__ = staticmethod(__new__)
570 def __call__(self):
571 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000572 # Early binding of methods
573 for key in self.dict:
574 if key.startswith("__"):
575 continue
576 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000577 return it
578 class C:
579 __metaclass__ = M2
580 def spam(self):
581 return 42
582 verify(C.name == 'C')
583 verify(C.bases == ())
584 verify('spam' in C.dict)
585 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000586 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum91ee7982001-08-30 20:52:40 +0000588 # More metaclass examples
589
590 class autosuper(type):
591 # Automatically add __super to the class
592 # This trick only works for dynamic classes
593 # so we force __dynamic__ = 1
594 def __new__(metaclass, name, bases, dict):
595 # XXX Should check that name isn't already a base class name
596 dict["__dynamic__"] = 1
597 cls = super(autosuper, metaclass).__new__(metaclass,
598 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000599 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000600 while name[:1] == "_":
601 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000602 if name:
603 name = "_%s__super" % name
604 else:
605 name = "__super"
606 setattr(cls, name, super(cls))
607 return cls
608 class A:
609 __metaclass__ = autosuper
610 def meth(self):
611 return "A"
612 class B(A):
613 def meth(self):
614 return "B" + self.__super.meth()
615 class C(A):
616 def meth(self):
617 return "C" + self.__super.meth()
618 class D(C, B):
619 def meth(self):
620 return "D" + self.__super.meth()
621 verify(D().meth() == "DCBA")
622 class E(B, C):
623 def meth(self):
624 return "E" + self.__super.meth()
625 verify(E().meth() == "EBCA")
626
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000627 class autoproperty(type):
628 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000629 # named _get_x and/or _set_x are found
630 def __new__(metaclass, name, bases, dict):
631 hits = {}
632 for key, val in dict.iteritems():
633 if key.startswith("_get_"):
634 key = key[5:]
635 get, set = hits.get(key, (None, None))
636 get = val
637 hits[key] = get, set
638 elif key.startswith("_set_"):
639 key = key[5:]
640 get, set = hits.get(key, (None, None))
641 set = val
642 hits[key] = get, set
643 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000644 dict[key] = property(get, set)
645 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000646 name, bases, dict)
647 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000648 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000649 def _get_x(self):
650 return -self.__x
651 def _set_x(self, x):
652 self.__x = -x
653 a = A()
654 verify(not hasattr(a, "x"))
655 a.x = 12
656 verify(a.x == 12)
657 verify(a._A__x == -12)
658
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000659 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000660 # Merge of multiple cooperating metaclasses
661 pass
662 class A:
663 __metaclass__ = multimetaclass
664 def _get_x(self):
665 return "A"
666 class B(A):
667 def _get_x(self):
668 return "B" + self.__super._get_x()
669 class C(A):
670 def _get_x(self):
671 return "C" + self.__super._get_x()
672 class D(C, B):
673 def _get_x(self):
674 return "D" + self.__super._get_x()
675 verify(D().x == "DCBA")
676
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677def pymods():
678 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000680 import sys
681 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 class MM(MT):
683 def __init__(self):
684 MT.__init__(self)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000685 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000687 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 def __setattr__(self, name, value):
689 log.append(("setattr", name, value))
690 MT.__setattr__(self, name, value)
691 def __delattr__(self, name):
692 log.append(("delattr", name))
693 MT.__delattr__(self, name)
694 a = MM()
695 a.foo = 12
696 x = a.foo
697 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000698 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 ("delattr", "foo")], log)
701
702def multi():
703 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704 class C(object):
705 def __init__(self):
706 self.__state = 0
707 def getstate(self):
708 return self.__state
709 def setstate(self, state):
710 self.__state = state
711 a = C()
712 verify(a.getstate() == 0)
713 a.setstate(10)
714 verify(a.getstate() == 10)
715 class D(dictionary, C):
716 def __init__(self):
717 type({}).__init__(self)
718 C.__init__(self)
719 d = D()
720 verify(d.keys() == [])
721 d["hello"] = "world"
722 verify(d.items() == [("hello", "world")])
723 verify(d["hello"] == "world")
724 verify(d.getstate() == 0)
725 d.setstate(10)
726 verify(d.getstate() == 10)
727 verify(D.__mro__ == (D, dictionary, C, object))
728
Guido van Rossume45763a2001-08-10 21:28:46 +0000729 # SF bug #442833
730 class Node(object):
731 def __int__(self):
732 return int(self.foo())
733 def foo(self):
734 return "23"
735 class Frag(Node, list):
736 def foo(self):
737 return "42"
738 verify(Node().__int__() == 23)
739 verify(int(Node()) == 23)
740 verify(Frag().__int__() == 42)
741 verify(int(Frag()) == 42)
742
Tim Peters6d6c1a32001-08-02 04:15:00 +0000743def diamond():
744 if verbose: print "Testing multiple inheritance special cases..."
745 class A(object):
746 def spam(self): return "A"
747 verify(A().spam() == "A")
748 class B(A):
749 def boo(self): return "B"
750 def spam(self): return "B"
751 verify(B().spam() == "B")
752 verify(B().boo() == "B")
753 class C(A):
754 def boo(self): return "C"
755 verify(C().spam() == "A")
756 verify(C().boo() == "C")
757 class D(B, C): pass
758 verify(D().spam() == "B")
759 verify(D().boo() == "B")
760 verify(D.__mro__ == (D, B, C, A, object))
761 class E(C, B): pass
762 verify(E().spam() == "B")
763 verify(E().boo() == "C")
764 verify(E.__mro__ == (E, C, B, A, object))
765 class F(D, E): pass
766 verify(F().spam() == "B")
767 verify(F().boo() == "B")
768 verify(F.__mro__ == (F, D, E, B, C, A, object))
769 class G(E, D): pass
770 verify(G().spam() == "B")
771 verify(G().boo() == "C")
772 verify(G.__mro__ == (G, E, D, C, B, A, object))
773
Guido van Rossum37202612001-08-09 19:45:21 +0000774def objects():
775 if verbose: print "Testing object class..."
776 a = object()
777 verify(a.__class__ == object == type(a))
778 b = object()
779 verify(a is not b)
780 verify(not hasattr(a, "foo"))
781 try:
782 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000783 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000784 pass
785 else:
786 verify(0, "object() should not allow setting a foo attribute")
787 verify(not hasattr(object(), "__dict__"))
788
789 class Cdict(object):
790 pass
791 x = Cdict()
Guido van Rossum3926a632001-09-25 16:25:58 +0000792 verify(x.__dict__ == {})
Guido van Rossum37202612001-08-09 19:45:21 +0000793 x.foo = 1
794 verify(x.foo == 1)
795 verify(x.__dict__ == {'foo': 1})
796
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797def slots():
798 if verbose: print "Testing __slots__..."
799 class C0(object):
800 __slots__ = []
801 x = C0()
802 verify(not hasattr(x, "__dict__"))
803 verify(not hasattr(x, "foo"))
804
805 class C1(object):
806 __slots__ = ['a']
807 x = C1()
808 verify(not hasattr(x, "__dict__"))
809 verify(x.a == None)
810 x.a = 1
811 verify(x.a == 1)
812 del x.a
813 verify(x.a == None)
814
815 class C3(object):
816 __slots__ = ['a', 'b', 'c']
817 x = C3()
818 verify(not hasattr(x, "__dict__"))
819 verify(x.a is None)
820 verify(x.b is None)
821 verify(x.c is None)
822 x.a = 1
823 x.b = 2
824 x.c = 3
825 verify(x.a == 1)
826 verify(x.b == 2)
827 verify(x.c == 3)
828
829def dynamics():
830 if verbose: print "Testing __dynamic__..."
831 verify(object.__dynamic__ == 0)
832 verify(list.__dynamic__ == 0)
833 class S1:
834 __metaclass__ = type
Guido van Rossum751c4c82001-09-29 00:40:25 +0000835 __dynamic__ = 0
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 verify(S1.__dynamic__ == 0)
837 class S(object):
Guido van Rossum751c4c82001-09-29 00:40:25 +0000838 __dynamic__ = 0
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000839 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840 class D(object):
841 __dynamic__ = 1
842 verify(D.__dynamic__ == 1)
843 class E(D, S):
844 pass
845 verify(E.__dynamic__ == 1)
846 class F(S, D):
847 pass
848 verify(F.__dynamic__ == 1)
849 try:
850 S.foo = 1
851 except (AttributeError, TypeError):
852 pass
853 else:
854 verify(0, "assignment to a static class attribute should be illegal")
855 D.foo = 1
856 verify(D.foo == 1)
857 # Test that dynamic attributes are inherited
858 verify(E.foo == 1)
859 verify(F.foo == 1)
860 class SS(D):
861 __dynamic__ = 0
862 verify(SS.__dynamic__ == 0)
863 verify(SS.foo == 1)
864 try:
865 SS.foo = 1
866 except (AttributeError, TypeError):
867 pass
868 else:
869 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000870 # Test dynamic instances
871 class C(object):
872 __dynamic__ = 1
Guido van Rossum4a5a2bc2001-10-03 13:59:54 +0000873 # XXX Ideally the following def shouldn't be necessary,
874 # but it's too much of a performance burden.
875 # See XXX comment in slot_tp_getattr_hook.
876 def __getattr__(self, name):
877 raise AttributeError, name
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000878 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000879 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000880 C.foobar = 2
881 verify(a.foobar == 2)
882 C.method = lambda self: 42
883 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000884 C.__repr__ = lambda self: "C()"
885 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000886 C.__int__ = lambda self: 100
887 verify(int(a) == 100)
888 verify(a.foobar == 2)
889 verify(not hasattr(a, "spam"))
890 def mygetattr(self, name):
891 if name == "spam":
892 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +0000893 raise AttributeError
894 C.__getattr__ = mygetattr
Guido van Rossumd3077402001-08-12 05:24:18 +0000895 verify(a.spam == "spam")
896 a.new = 12
897 verify(a.new == 12)
898 def mysetattr(self, name, value):
899 if name == "spam":
900 raise AttributeError
901 return object.__setattr__(self, name, value)
902 C.__setattr__ = mysetattr
903 try:
904 a.spam = "not spam"
905 except AttributeError:
906 pass
907 else:
908 verify(0, "expected AttributeError")
909 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000910 class D(C):
911 pass
912 d = D()
913 d.foo = 1
914 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000915
Guido van Rossum7e35d572001-09-15 03:14:32 +0000916 # Test handling of int*seq and seq*int
917 class I(int):
918 __dynamic__ = 1
919 verify("a"*I(2) == "aa")
920 verify(I(2)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000921 verify(2*I(3) == 6)
922 verify(I(3)*2 == 6)
923 verify(I(3)*I(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000924
925 # Test handling of long*seq and seq*long
926 class L(long):
927 __dynamic__ = 1
928 verify("a"*L(2L) == "aa")
929 verify(L(2L)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000930 verify(2*L(3) == 6)
931 verify(L(3)*2 == 6)
932 verify(L(3)*L(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000933
Guido van Rossum3d45d8f2001-09-24 18:47:40 +0000934 # Test comparison of classes with dynamic metaclasses
935 class dynamicmetaclass(type):
936 __dynamic__ = 1
937 class someclass:
938 __metaclass__ = dynamicmetaclass
939 verify(someclass != object)
940
Tim Peters6d6c1a32001-08-02 04:15:00 +0000941def errors():
942 if verbose: print "Testing errors..."
943
944 try:
945 class C(list, dictionary):
946 pass
947 except TypeError:
948 pass
949 else:
950 verify(0, "inheritance from both list and dict should be illegal")
951
952 try:
953 class C(object, None):
954 pass
955 except TypeError:
956 pass
957 else:
958 verify(0, "inheritance from non-type should be illegal")
959 class Classic:
960 pass
961
962 try:
963 class C(object, Classic):
964 pass
965 except TypeError:
966 pass
967 else:
968 verify(0, "inheritance from object and Classic should be illegal")
969
970 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000971 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972 pass
973 except TypeError:
974 pass
975 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000976 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977
978 try:
979 class C(object):
980 __slots__ = 1
981 except TypeError:
982 pass
983 else:
984 verify(0, "__slots__ = 1 should be illegal")
985
986 try:
987 class C(object):
988 __slots__ = [1]
989 except TypeError:
990 pass
991 else:
992 verify(0, "__slots__ = [1] should be illegal")
993
994def classmethods():
995 if verbose: print "Testing class methods..."
996 class C(object):
997 def foo(*a): return a
998 goo = classmethod(foo)
999 c = C()
1000 verify(C.goo(1) == (C, 1))
1001 verify(c.goo(1) == (C, 1))
1002 verify(c.foo(1) == (c, 1))
1003 class D(C):
1004 pass
1005 d = D()
1006 verify(D.goo(1) == (D, 1))
1007 verify(d.goo(1) == (D, 1))
1008 verify(d.foo(1) == (d, 1))
1009 verify(D.foo(d, 1) == (d, 1))
1010
1011def staticmethods():
1012 if verbose: print "Testing static methods..."
1013 class C(object):
1014 def foo(*a): return a
1015 goo = staticmethod(foo)
1016 c = C()
1017 verify(C.goo(1) == (1,))
1018 verify(c.goo(1) == (1,))
1019 verify(c.foo(1) == (c, 1,))
1020 class D(C):
1021 pass
1022 d = D()
1023 verify(D.goo(1) == (1,))
1024 verify(d.goo(1) == (1,))
1025 verify(d.foo(1) == (d, 1))
1026 verify(D.foo(d, 1) == (d, 1))
1027
1028def classic():
1029 if verbose: print "Testing classic classes..."
1030 class C:
1031 def foo(*a): return a
1032 goo = classmethod(foo)
1033 c = C()
1034 verify(C.goo(1) == (C, 1))
1035 verify(c.goo(1) == (C, 1))
1036 verify(c.foo(1) == (c, 1))
1037 class D(C):
1038 pass
1039 d = D()
1040 verify(D.goo(1) == (D, 1))
1041 verify(d.goo(1) == (D, 1))
1042 verify(d.foo(1) == (d, 1))
1043 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001044 class E: # *not* subclassing from C
1045 foo = C.foo
1046 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001047 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001048
1049def compattr():
1050 if verbose: print "Testing computed attributes..."
1051 class C(object):
1052 class computed_attribute(object):
1053 def __init__(self, get, set=None):
1054 self.__get = get
1055 self.__set = set
1056 def __get__(self, obj, type=None):
1057 return self.__get(obj)
1058 def __set__(self, obj, value):
1059 return self.__set(obj, value)
1060 def __init__(self):
1061 self.__x = 0
1062 def __get_x(self):
1063 x = self.__x
1064 self.__x = x+1
1065 return x
1066 def __set_x(self, x):
1067 self.__x = x
1068 x = computed_attribute(__get_x, __set_x)
1069 a = C()
1070 verify(a.x == 0)
1071 verify(a.x == 1)
1072 a.x = 10
1073 verify(a.x == 10)
1074 verify(a.x == 11)
1075
1076def newslot():
1077 if verbose: print "Testing __new__ slot override..."
1078 class C(list):
1079 def __new__(cls):
1080 self = list.__new__(cls)
1081 self.foo = 1
1082 return self
1083 def __init__(self):
1084 self.foo = self.foo + 2
1085 a = C()
1086 verify(a.foo == 3)
1087 verify(a.__class__ is C)
1088 class D(C):
1089 pass
1090 b = D()
1091 verify(b.foo == 3)
1092 verify(b.__class__ is D)
1093
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094def altmro():
1095 if verbose: print "Testing mro() and overriding it..."
1096 class A(object):
1097 def f(self): return "A"
1098 class B(A):
1099 pass
1100 class C(A):
1101 def f(self): return "C"
1102 class D(B, C):
1103 pass
1104 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1105 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001106 class PerverseMetaType(type):
1107 def mro(cls):
1108 L = type.mro(cls)
1109 L.reverse()
1110 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111 class X(A,B,C,D):
1112 __metaclass__ = PerverseMetaType
1113 verify(X.__mro__ == (object, A, C, B, D, X))
1114 verify(X().f() == "A")
1115
1116def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001117 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118
1119 class B(object):
1120 "Intermediate class because object doesn't have a __setattr__"
1121
1122 class C(B):
1123
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001124 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 if name == "foo":
1126 return ("getattr", name)
1127 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001128 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 def __setattr__(self, name, value):
1130 if name == "foo":
1131 self.setattr = (name, value)
1132 else:
1133 return B.__setattr__(self, name, value)
1134 def __delattr__(self, name):
1135 if name == "foo":
1136 self.delattr = name
1137 else:
1138 return B.__delattr__(self, name)
1139
1140 def __getitem__(self, key):
1141 return ("getitem", key)
1142 def __setitem__(self, key, value):
1143 self.setitem = (key, value)
1144 def __delitem__(self, key):
1145 self.delitem = key
1146
1147 def __getslice__(self, i, j):
1148 return ("getslice", i, j)
1149 def __setslice__(self, i, j, value):
1150 self.setslice = (i, j, value)
1151 def __delslice__(self, i, j):
1152 self.delslice = (i, j)
1153
1154 a = C()
1155 verify(a.foo == ("getattr", "foo"))
1156 a.foo = 12
1157 verify(a.setattr == ("foo", 12))
1158 del a.foo
1159 verify(a.delattr == "foo")
1160
1161 verify(a[12] == ("getitem", 12))
1162 a[12] = 21
1163 verify(a.setitem == (12, 21))
1164 del a[12]
1165 verify(a.delitem == 12)
1166
1167 verify(a[0:10] == ("getslice", 0, 10))
1168 a[0:10] = "foo"
1169 verify(a.setslice == (0, 10, "foo"))
1170 del a[0:10]
1171 verify(a.delslice == (0, 10))
1172
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001173def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001174 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001175 class C(object):
1176 def __init__(self, x):
1177 self.x = x
1178 def foo(self):
1179 return self.x
1180 c1 = C(1)
1181 verify(c1.foo() == 1)
1182 class D(C):
1183 boo = C.foo
1184 goo = c1.foo
1185 d2 = D(2)
1186 verify(d2.foo() == 2)
1187 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001188 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001189 class E(object):
1190 foo = C.foo
1191 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001192 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001193
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001194def specials():
1195 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001196 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001197 # Test the default behavior for static classes
1198 class C(object):
1199 def __getitem__(self, i):
1200 if 0 <= i < 10: return i
1201 raise IndexError
1202 c1 = C()
1203 c2 = C()
1204 verify(not not c1)
1205 verify(hash(c1) == id(c1))
1206 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1207 verify(c1 == c1)
1208 verify(c1 != c2)
1209 verify(not c1 != c1)
1210 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001211 # Note that the module name appears in str/repr, and that varies
1212 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001213 verify(str(c1).find('C object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001214 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001215 verify(-1 not in c1)
1216 for i in range(10):
1217 verify(i in c1)
1218 verify(10 not in c1)
1219 # Test the default behavior for dynamic classes
1220 class D(object):
1221 __dynamic__ = 1
1222 def __getitem__(self, i):
1223 if 0 <= i < 10: return i
1224 raise IndexError
1225 d1 = D()
1226 d2 = D()
1227 verify(not not d1)
1228 verify(hash(d1) == id(d1))
1229 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1230 verify(d1 == d1)
1231 verify(d1 != d2)
1232 verify(not d1 != d1)
1233 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001234 # Note that the module name appears in str/repr, and that varies
1235 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001236 verify(str(d1).find('D object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001237 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001238 verify(-1 not in d1)
1239 for i in range(10):
1240 verify(i in d1)
1241 verify(10 not in d1)
1242 # Test overridden behavior for static classes
1243 class Proxy(object):
1244 def __init__(self, x):
1245 self.x = x
1246 def __nonzero__(self):
1247 return not not self.x
1248 def __hash__(self):
1249 return hash(self.x)
1250 def __eq__(self, other):
1251 return self.x == other
1252 def __ne__(self, other):
1253 return self.x != other
1254 def __cmp__(self, other):
1255 return cmp(self.x, other.x)
1256 def __str__(self):
1257 return "Proxy:%s" % self.x
1258 def __repr__(self):
1259 return "Proxy(%r)" % self.x
1260 def __contains__(self, value):
1261 return value in self.x
1262 p0 = Proxy(0)
1263 p1 = Proxy(1)
1264 p_1 = Proxy(-1)
1265 verify(not p0)
1266 verify(not not p1)
1267 verify(hash(p0) == hash(0))
1268 verify(p0 == p0)
1269 verify(p0 != p1)
1270 verify(not p0 != p0)
1271 verify(not p0 == p1)
1272 verify(cmp(p0, p1) == -1)
1273 verify(cmp(p0, p0) == 0)
1274 verify(cmp(p0, p_1) == 1)
1275 verify(str(p0) == "Proxy:0")
1276 verify(repr(p0) == "Proxy(0)")
1277 p10 = Proxy(range(10))
1278 verify(-1 not in p10)
1279 for i in range(10):
1280 verify(i in p10)
1281 verify(10 not in p10)
1282 # Test overridden behavior for dynamic classes
1283 class DProxy(object):
1284 __dynamic__ = 1
1285 def __init__(self, x):
1286 self.x = x
1287 def __nonzero__(self):
1288 return not not self.x
1289 def __hash__(self):
1290 return hash(self.x)
1291 def __eq__(self, other):
1292 return self.x == other
1293 def __ne__(self, other):
1294 return self.x != other
1295 def __cmp__(self, other):
1296 return cmp(self.x, other.x)
1297 def __str__(self):
1298 return "DProxy:%s" % self.x
1299 def __repr__(self):
1300 return "DProxy(%r)" % self.x
1301 def __contains__(self, value):
1302 return value in self.x
1303 p0 = DProxy(0)
1304 p1 = DProxy(1)
1305 p_1 = DProxy(-1)
1306 verify(not p0)
1307 verify(not not p1)
1308 verify(hash(p0) == hash(0))
1309 verify(p0 == p0)
1310 verify(p0 != p1)
1311 verify(not p0 != p0)
1312 verify(not p0 == p1)
1313 verify(cmp(p0, p1) == -1)
1314 verify(cmp(p0, p0) == 0)
1315 verify(cmp(p0, p_1) == 1)
1316 verify(str(p0) == "DProxy:0")
1317 verify(repr(p0) == "DProxy(0)")
1318 p10 = DProxy(range(10))
1319 verify(-1 not in p10)
1320 for i in range(10):
1321 verify(i in p10)
1322 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001323 # Safety test for __cmp__
1324 def unsafecmp(a, b):
1325 try:
1326 a.__class__.__cmp__(a, b)
1327 except TypeError:
1328 pass
1329 else:
1330 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1331 a.__class__, a, b)
1332 unsafecmp(u"123", "123")
1333 unsafecmp("123", u"123")
1334 unsafecmp(1, 1.0)
1335 unsafecmp(1.0, 1)
1336 unsafecmp(1, 1L)
1337 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001338
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001339def weakrefs():
1340 if verbose: print "Testing weak references..."
1341 import weakref
1342 class C(object):
1343 pass
1344 c = C()
1345 r = weakref.ref(c)
1346 verify(r() is c)
1347 del c
1348 verify(r() is None)
1349 del r
1350 class NoWeak(object):
1351 __slots__ = ['foo']
1352 no = NoWeak()
1353 try:
1354 weakref.ref(no)
1355 except TypeError, msg:
1356 verify(str(msg).find("weakly") >= 0)
1357 else:
1358 verify(0, "weakref.ref(no) should be illegal")
1359 class Weak(object):
1360 __slots__ = ['foo', '__weakref__']
1361 yes = Weak()
1362 r = weakref.ref(yes)
1363 verify(r() is yes)
1364 del yes
1365 verify(r() is None)
1366 del r
1367
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001368def properties():
1369 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001370 class C(object):
1371 def getx(self):
1372 return self.__x
1373 def setx(self, value):
1374 self.__x = value
1375 def delx(self):
1376 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001377 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001378 a = C()
1379 verify(not hasattr(a, "x"))
1380 a.x = 42
1381 verify(a._C__x == 42)
1382 verify(a.x == 42)
1383 del a.x
1384 verify(not hasattr(a, "x"))
1385 verify(not hasattr(a, "_C__x"))
1386 C.x.__set__(a, 100)
1387 verify(C.x.__get__(a) == 100)
1388## C.x.__set__(a)
1389## verify(not hasattr(a, "x"))
1390
Tim Peters66c1a522001-09-24 21:17:50 +00001391 raw = C.__dict__['x']
1392 verify(isinstance(raw, property))
1393
1394 attrs = dir(raw)
1395 verify("__doc__" in attrs)
1396 verify("fget" in attrs)
1397 verify("fset" in attrs)
1398 verify("fdel" in attrs)
1399
1400 verify(raw.__doc__ == "I'm the x property.")
1401 verify(raw.fget is C.__dict__['getx'])
1402 verify(raw.fset is C.__dict__['setx'])
1403 verify(raw.fdel is C.__dict__['delx'])
1404
1405 for attr in "__doc__", "fget", "fset", "fdel":
1406 try:
1407 setattr(raw, attr, 42)
1408 except TypeError, msg:
1409 if str(msg).find('readonly') < 0:
1410 raise TestFailed("when setting readonly attr %r on a "
1411 "property, got unexpected TypeError "
1412 "msg %r" % (attr, str(msg)))
1413 else:
1414 raise TestFailed("expected TypeError from trying to set "
1415 "readonly %r attr on a property" % attr)
1416
Guido van Rossumc4a18802001-08-24 16:55:27 +00001417def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001418 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001419
1420 class A(object):
1421 def meth(self, a):
1422 return "A(%r)" % a
1423
1424 verify(A().meth(1) == "A(1)")
1425
1426 class B(A):
1427 def __init__(self):
1428 self.__super = super(B, self)
1429 def meth(self, a):
1430 return "B(%r)" % a + self.__super.meth(a)
1431
1432 verify(B().meth(2) == "B(2)A(2)")
1433
1434 class C(A):
1435 __dynamic__ = 1
1436 def meth(self, a):
1437 return "C(%r)" % a + self.__super.meth(a)
1438 C._C__super = super(C)
1439
1440 verify(C().meth(3) == "C(3)A(3)")
1441
1442 class D(C, B):
1443 def meth(self, a):
1444 return "D(%r)" % a + super(D, self).meth(a)
1445
1446 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1447
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001448def inherits():
1449 if verbose: print "Testing inheritance from basic types..."
1450
1451 class hexint(int):
1452 def __repr__(self):
1453 return hex(self)
1454 def __add__(self, other):
1455 return hexint(int.__add__(self, other))
1456 # (Note that overriding __radd__ doesn't work,
1457 # because the int type gets first dibs.)
1458 verify(repr(hexint(7) + 9) == "0x10")
1459 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001460 a = hexint(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001461 verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001462 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001463 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001464 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001465 verify((+a).__class__ is int)
1466 verify((a >> 0).__class__ is int)
1467 verify((a << 0).__class__ is int)
1468 verify((hexint(0) << 12).__class__ is int)
1469 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001470
1471 class octlong(long):
1472 __slots__ = []
1473 def __str__(self):
1474 s = oct(self)
1475 if s[-1] == 'L':
1476 s = s[:-1]
1477 return s
1478 def __add__(self, other):
1479 return self.__class__(super(octlong, self).__add__(other))
1480 __radd__ = __add__
1481 verify(str(octlong(3) + 5) == "010")
1482 # (Note that overriding __radd__ here only seems to work
1483 # because the example uses a short int left argument.)
1484 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001485 a = octlong(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001486 verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001487 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001488 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001489 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001490 verify((+a).__class__ is long)
1491 verify((-a).__class__ is long)
1492 verify((-octlong(0)).__class__ is long)
1493 verify((a >> 0).__class__ is long)
1494 verify((a << 0).__class__ is long)
1495 verify((a - 0).__class__ is long)
1496 verify((a * 1).__class__ is long)
1497 verify((a ** 1).__class__ is long)
1498 verify((a // 1).__class__ is long)
1499 verify((1 * a).__class__ is long)
1500 verify((a | 0).__class__ is long)
1501 verify((a ^ 0).__class__ is long)
1502 verify((a & -1L).__class__ is long)
1503 verify((octlong(0) << 12).__class__ is long)
1504 verify((octlong(0) >> 12).__class__ is long)
1505 verify(abs(octlong(0)).__class__ is long)
1506
1507 # Because octlong overrides __add__, we can't check the absence of +0
1508 # optimizations using octlong.
1509 class longclone(long):
1510 pass
1511 a = longclone(1)
1512 verify((a + 0).__class__ is long)
1513 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001514
1515 class precfloat(float):
1516 __slots__ = ['prec']
1517 def __init__(self, value=0.0, prec=12):
1518 self.prec = int(prec)
1519 float.__init__(value)
1520 def __repr__(self):
1521 return "%.*g" % (self.prec, self)
1522 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001523 a = precfloat(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001524 verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001525 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001526 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001527 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001528 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001529
Tim Peters2400fa42001-09-12 19:12:49 +00001530 class madcomplex(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001531 __dynamic__ = 0
Tim Peters2400fa42001-09-12 19:12:49 +00001532 def __repr__(self):
1533 return "%.17gj%+.17g" % (self.imag, self.real)
1534 a = madcomplex(-3, 4)
1535 verify(repr(a) == "4j-3")
1536 base = complex(-3, 4)
1537 verify(base.__class__ is complex)
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001538 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001539 verify(complex(a) == base)
1540 verify(complex(a).__class__ is complex)
1541 a = madcomplex(a) # just trying another form of the constructor
1542 verify(repr(a) == "4j-3")
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001543 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001544 verify(complex(a) == base)
1545 verify(complex(a).__class__ is complex)
1546 verify(hash(a) == hash(base))
1547 verify((+a).__class__ is complex)
1548 verify((a + 0).__class__ is complex)
1549 verify(a + 0 == base)
1550 verify((a - 0).__class__ is complex)
1551 verify(a - 0 == base)
1552 verify((a * 1).__class__ is complex)
1553 verify(a * 1 == base)
1554 verify((a / 1).__class__ is complex)
1555 verify(a / 1 == base)
1556
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001557 class madtuple(tuple):
1558 _rev = None
1559 def rev(self):
1560 if self._rev is not None:
1561 return self._rev
1562 L = list(self)
1563 L.reverse()
1564 self._rev = self.__class__(L)
1565 return self._rev
1566 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001567 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001568 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1569 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1570 for i in range(512):
1571 t = madtuple(range(i))
1572 u = t.rev()
1573 v = u.rev()
1574 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001575 a = madtuple((1,2,3,4,5))
1576 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001577 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001578 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001579 verify(a[:].__class__ is tuple)
1580 verify((a * 1).__class__ is tuple)
1581 verify((a * 0).__class__ is tuple)
1582 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001583 a = madtuple(())
1584 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001585 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001586 verify((a + a).__class__ is tuple)
1587 verify((a * 0).__class__ is tuple)
1588 verify((a * 1).__class__ is tuple)
1589 verify((a * 2).__class__ is tuple)
1590 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001591
1592 class madstring(str):
1593 _rev = None
1594 def rev(self):
1595 if self._rev is not None:
1596 return self._rev
1597 L = list(self)
1598 L.reverse()
1599 self._rev = self.__class__("".join(L))
1600 return self._rev
1601 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001602 verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001603 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1604 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1605 for i in range(256):
1606 s = madstring("".join(map(chr, range(i))))
1607 t = s.rev()
1608 u = t.rev()
1609 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001610 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001611 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001612 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001613
Tim Peters8fa5dd02001-09-12 02:18:30 +00001614 base = "\x00" * 5
1615 s = madstring(base)
Guido van Rossumbb77e682001-09-24 16:51:54 +00001616 verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001617 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001618 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001619 verify(hash(s) == hash(base))
Guido van Rossumbb77e682001-09-24 16:51:54 +00001620 verify({s: 1}[base] == 1)
1621 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001622 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001623 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001624 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001625 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001626 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001627 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001628 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001629 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001630 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001631 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001632 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001633 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001634 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001635 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001636 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001637 verify(s.strip() == base)
1638 verify(s.lstrip().__class__ is str)
1639 verify(s.lstrip() == base)
1640 verify(s.rstrip().__class__ is str)
1641 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001642 identitytab = ''.join([chr(i) for i in range(256)])
1643 verify(s.translate(identitytab).__class__ is str)
1644 verify(s.translate(identitytab) == base)
1645 verify(s.translate(identitytab, "x").__class__ is str)
1646 verify(s.translate(identitytab, "x") == base)
1647 verify(s.translate(identitytab, "\x00") == "")
1648 verify(s.replace("x", "x").__class__ is str)
1649 verify(s.replace("x", "x") == base)
1650 verify(s.ljust(len(s)).__class__ is str)
1651 verify(s.ljust(len(s)) == base)
1652 verify(s.rjust(len(s)).__class__ is str)
1653 verify(s.rjust(len(s)) == base)
1654 verify(s.center(len(s)).__class__ is str)
1655 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001656 verify(s.lower().__class__ is str)
1657 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001658
Tim Peters111f6092001-09-12 07:54:51 +00001659 s = madstring("x y")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001660 verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001661 verify(intern(s).__class__ is str)
1662 verify(intern(s) is intern("x y"))
1663 verify(intern(s) == "x y")
1664
1665 i = intern("y x")
1666 s = madstring("y x")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001667 verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001668 verify(intern(s).__class__ is str)
1669 verify(intern(s) is i)
1670
1671 s = madstring(i)
1672 verify(intern(s).__class__ is str)
1673 verify(intern(s) is i)
1674
Guido van Rossum91ee7982001-08-30 20:52:40 +00001675 class madunicode(unicode):
1676 _rev = None
1677 def rev(self):
1678 if self._rev is not None:
1679 return self._rev
1680 L = list(self)
1681 L.reverse()
1682 self._rev = self.__class__(u"".join(L))
1683 return self._rev
1684 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001685 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001686 verify(u.rev() == madunicode(u"FEDCBA"))
1687 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001688 base = u"12345"
1689 u = madunicode(base)
1690 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001691 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001692 verify(hash(u) == hash(base))
1693 verify({u: 1}[base] == 1)
1694 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001695 verify(u.strip().__class__ is unicode)
1696 verify(u.strip() == base)
1697 verify(u.lstrip().__class__ is unicode)
1698 verify(u.lstrip() == base)
1699 verify(u.rstrip().__class__ is unicode)
1700 verify(u.rstrip() == base)
1701 verify(u.replace(u"x", u"x").__class__ is unicode)
1702 verify(u.replace(u"x", u"x") == base)
1703 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1704 verify(u.replace(u"xy", u"xy") == base)
1705 verify(u.center(len(u)).__class__ is unicode)
1706 verify(u.center(len(u)) == base)
1707 verify(u.ljust(len(u)).__class__ is unicode)
1708 verify(u.ljust(len(u)) == base)
1709 verify(u.rjust(len(u)).__class__ is unicode)
1710 verify(u.rjust(len(u)) == base)
1711 verify(u.lower().__class__ is unicode)
1712 verify(u.lower() == base)
1713 verify(u.upper().__class__ is unicode)
1714 verify(u.upper() == base)
1715 verify(u.capitalize().__class__ is unicode)
1716 verify(u.capitalize() == base)
1717 verify(u.title().__class__ is unicode)
1718 verify(u.title() == base)
1719 verify((u + u"").__class__ is unicode)
1720 verify(u + u"" == base)
1721 verify((u"" + u).__class__ is unicode)
1722 verify(u"" + u == base)
1723 verify((u * 0).__class__ is unicode)
1724 verify(u * 0 == u"")
1725 verify((u * 1).__class__ is unicode)
1726 verify(u * 1 == base)
1727 verify((u * 2).__class__ is unicode)
1728 verify(u * 2 == base + base)
1729 verify(u[:].__class__ is unicode)
1730 verify(u[:] == base)
1731 verify(u[0:0].__class__ is unicode)
1732 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001733
Tim Peters59c9a642001-09-13 05:38:56 +00001734 class CountedInput(file):
1735 """Counts lines read by self.readline().
1736
1737 self.lineno is the 0-based ordinal of the last line read, up to
1738 a maximum of one greater than the number of lines in the file.
1739
1740 self.ateof is true if and only if the final "" line has been read,
1741 at which point self.lineno stops incrementing, and further calls
1742 to readline() continue to return "".
1743 """
1744
1745 lineno = 0
1746 ateof = 0
1747 def readline(self):
1748 if self.ateof:
1749 return ""
1750 s = file.readline(self)
1751 # Next line works too.
1752 # s = super(CountedInput, self).readline()
1753 self.lineno += 1
1754 if s == "":
1755 self.ateof = 1
1756 return s
1757
Tim Peters561f8992001-09-13 19:36:36 +00001758 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00001759 lines = ['a\n', 'b\n', 'c\n']
1760 try:
1761 f.writelines(lines)
1762 f.close()
1763 f = CountedInput(TESTFN)
1764 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1765 got = f.readline()
1766 verify(expected == got)
1767 verify(f.lineno == i)
1768 verify(f.ateof == (i > len(lines)))
1769 f.close()
1770 finally:
1771 try:
1772 f.close()
1773 except:
1774 pass
1775 try:
1776 import os
1777 os.unlink(TESTFN)
1778 except:
1779 pass
1780
Tim Peters808b94e2001-09-13 19:33:07 +00001781def keywords():
1782 if verbose:
1783 print "Testing keyword args to basic type constructors ..."
1784 verify(int(x=1) == 1)
1785 verify(float(x=2) == 2.0)
1786 verify(long(x=3) == 3L)
1787 verify(complex(imag=42, real=666) == complex(666, 42))
1788 verify(str(object=500) == '500')
1789 verify(unicode(string='abc', errors='strict') == u'abc')
1790 verify(tuple(sequence=range(3)) == (0, 1, 2))
1791 verify(list(sequence=(0, 1, 2)) == range(3))
1792 verify(dictionary(mapping={1: 2}) == {1: 2})
1793
1794 for constructor in (int, float, long, complex, str, unicode,
1795 tuple, list, dictionary, file):
1796 try:
1797 constructor(bogus_keyword_arg=1)
1798 except TypeError:
1799 pass
1800 else:
1801 raise TestFailed("expected TypeError from bogus keyword "
1802 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00001803
Tim Peters8fa45672001-09-13 21:01:29 +00001804def restricted():
1805 import rexec
1806 if verbose:
1807 print "Testing interaction with restricted execution ..."
1808
1809 sandbox = rexec.RExec()
1810
1811 code1 = """f = open(%r, 'w')""" % TESTFN
1812 code2 = """f = file(%r, 'w')""" % TESTFN
1813 code3 = """\
1814f = open(%r)
1815t = type(f) # a sneaky way to get the file() constructor
1816f.close()
1817f = t(%r, 'w') # rexec can't catch this by itself
1818""" % (TESTFN, TESTFN)
1819
1820 f = open(TESTFN, 'w') # Create the file so code3 can find it.
1821 f.close()
1822
1823 try:
1824 for code in code1, code2, code3:
1825 try:
1826 sandbox.r_exec(code)
1827 except IOError, msg:
1828 if str(msg).find("restricted") >= 0:
1829 outcome = "OK"
1830 else:
1831 outcome = "got an exception, but not an expected one"
1832 else:
1833 outcome = "expected a restricted-execution exception"
1834
1835 if outcome != "OK":
1836 raise TestFailed("%s, in %r" % (outcome, code))
1837
1838 finally:
1839 try:
1840 import os
1841 os.unlink(TESTFN)
1842 except:
1843 pass
1844
Tim Peters0ab085c2001-09-14 00:25:33 +00001845def str_subclass_as_dict_key():
1846 if verbose:
1847 print "Testing a str subclass used as dict key .."
1848
1849 class cistr(str):
1850 """Sublcass of str that computes __eq__ case-insensitively.
1851
1852 Also computes a hash code of the string in canonical form.
1853 """
1854
1855 def __init__(self, value):
1856 self.canonical = value.lower()
1857 self.hashcode = hash(self.canonical)
1858
1859 def __eq__(self, other):
1860 if not isinstance(other, cistr):
1861 other = cistr(other)
1862 return self.canonical == other.canonical
1863
1864 def __hash__(self):
1865 return self.hashcode
1866
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001867 verify(cistr('ABC') == 'abc')
1868 verify('aBc' == cistr('ABC'))
Tim Peters0ab085c2001-09-14 00:25:33 +00001869 verify(str(cistr('ABC')) == 'ABC')
1870
1871 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
1872 verify(d[cistr('one')] == 1)
1873 verify(d[cistr('tWo')] == 2)
1874 verify(d[cistr('THrEE')] == 3)
1875 verify(cistr('ONe') in d)
1876 verify(d.get(cistr('thrEE')) == 3)
1877
Guido van Rossumab3b0342001-09-18 20:38:53 +00001878def classic_comparisons():
1879 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00001880 class classic:
1881 pass
1882 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00001883 if verbose: print " (base = %s)" % base
1884 class C(base):
1885 def __init__(self, value):
1886 self.value = int(value)
1887 def __cmp__(self, other):
1888 if isinstance(other, C):
1889 return cmp(self.value, other.value)
1890 if isinstance(other, int) or isinstance(other, long):
1891 return cmp(self.value, other)
1892 return NotImplemented
1893 c1 = C(1)
1894 c2 = C(2)
1895 c3 = C(3)
1896 verify(c1 == 1)
1897 c = {1: c1, 2: c2, 3: c3}
1898 for x in 1, 2, 3:
1899 for y in 1, 2, 3:
1900 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1901 for op in "<", "<=", "==", "!=", ">", ">=":
1902 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1903 "x=%d, y=%d" % (x, y))
1904 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
1905 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1906
Guido van Rossum0639f592001-09-18 21:06:04 +00001907def rich_comparisons():
1908 if verbose:
1909 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00001910 class Z(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001911 __dynamic__ = 0
Guido van Rossum22056422001-09-24 17:52:04 +00001912 z = Z(1)
1913 verify(z == 1+0j)
1914 verify(1+0j == z)
1915 class ZZ(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001916 __dynamic__ = 0
Guido van Rossum22056422001-09-24 17:52:04 +00001917 def __eq__(self, other):
1918 try:
1919 return abs(self - other) <= 1e-6
1920 except:
1921 return NotImplemented
1922 zz = ZZ(1.0000003)
1923 verify(zz == 1+0j)
1924 verify(1+0j == zz)
Tim Peters66c1a522001-09-24 21:17:50 +00001925
Guido van Rossum0639f592001-09-18 21:06:04 +00001926 class classic:
1927 pass
1928 for base in (classic, int, object, list):
1929 if verbose: print " (base = %s)" % base
1930 class C(base):
1931 def __init__(self, value):
1932 self.value = int(value)
1933 def __cmp__(self, other):
1934 raise TestFailed, "shouldn't call __cmp__"
1935 def __eq__(self, other):
1936 if isinstance(other, C):
1937 return self.value == other.value
1938 if isinstance(other, int) or isinstance(other, long):
1939 return self.value == other
1940 return NotImplemented
1941 def __ne__(self, other):
1942 if isinstance(other, C):
1943 return self.value != other.value
1944 if isinstance(other, int) or isinstance(other, long):
1945 return self.value != other
1946 return NotImplemented
1947 def __lt__(self, other):
1948 if isinstance(other, C):
1949 return self.value < other.value
1950 if isinstance(other, int) or isinstance(other, long):
1951 return self.value < other
1952 return NotImplemented
1953 def __le__(self, other):
1954 if isinstance(other, C):
1955 return self.value <= other.value
1956 if isinstance(other, int) or isinstance(other, long):
1957 return self.value <= other
1958 return NotImplemented
1959 def __gt__(self, other):
1960 if isinstance(other, C):
1961 return self.value > other.value
1962 if isinstance(other, int) or isinstance(other, long):
1963 return self.value > other
1964 return NotImplemented
1965 def __ge__(self, other):
1966 if isinstance(other, C):
1967 return self.value >= other.value
1968 if isinstance(other, int) or isinstance(other, long):
1969 return self.value >= other
1970 return NotImplemented
1971 c1 = C(1)
1972 c2 = C(2)
1973 c3 = C(3)
1974 verify(c1 == 1)
1975 c = {1: c1, 2: c2, 3: c3}
1976 for x in 1, 2, 3:
1977 for y in 1, 2, 3:
1978 for op in "<", "<=", "==", "!=", ">", ">=":
1979 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1980 "x=%d, y=%d" % (x, y))
1981 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
1982 "x=%d, y=%d" % (x, y))
1983 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
1984 "x=%d, y=%d" % (x, y))
1985
Guido van Rossum1952e382001-09-19 01:25:16 +00001986def coercions():
1987 if verbose: print "Testing coercions..."
1988 class I(int): pass
1989 coerce(I(0), 0)
1990 coerce(0, I(0))
1991 class L(long): pass
1992 coerce(L(0), 0)
1993 coerce(L(0), 0L)
1994 coerce(0, L(0))
1995 coerce(0L, L(0))
1996 class F(float): pass
1997 coerce(F(0), 0)
1998 coerce(F(0), 0L)
1999 coerce(F(0), 0.)
2000 coerce(0, F(0))
2001 coerce(0L, F(0))
2002 coerce(0., F(0))
Guido van Rossum751c4c82001-09-29 00:40:25 +00002003 class C(complex):
2004 __dynamic__ = 0
Guido van Rossum1952e382001-09-19 01:25:16 +00002005 coerce(C(0), 0)
2006 coerce(C(0), 0L)
2007 coerce(C(0), 0.)
2008 coerce(C(0), 0j)
2009 coerce(0, C(0))
2010 coerce(0L, C(0))
2011 coerce(0., C(0))
2012 coerce(0j, C(0))
2013
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002014def descrdoc():
2015 if verbose: print "Testing descriptor doc strings..."
2016 def check(descr, what):
2017 verify(descr.__doc__ == what, repr(descr.__doc__))
2018 check(file.closed, "flag set if the file is closed") # getset descriptor
2019 check(file.name, "file name") # member descriptor
2020
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002021def setclass():
2022 if verbose: print "Testing __class__ assignment..."
2023 class C(object): pass
2024 class D(object): pass
2025 class E(object): pass
2026 class F(D, E): pass
2027 for cls in C, D, E, F:
2028 for cls2 in C, D, E, F:
2029 x = cls()
2030 x.__class__ = cls2
2031 verify(x.__class__ is cls2)
2032 x.__class__ = cls
2033 verify(x.__class__ is cls)
2034 def cant(x, C):
2035 try:
2036 x.__class__ = C
2037 except TypeError:
2038 pass
2039 else:
2040 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2041 cant(C(), list)
2042 cant(list(), C)
2043 cant(C(), 1)
2044 cant(C(), object)
2045 cant(object(), list)
2046 cant(list(), object)
2047
Guido van Rossum3926a632001-09-25 16:25:58 +00002048def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002049 if verbose:
2050 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002051 import pickle, cPickle
2052
2053 def sorteditems(d):
2054 L = d.items()
2055 L.sort()
2056 return L
2057
2058 global C
2059 class C(object):
2060 def __init__(self, a, b):
2061 super(C, self).__init__()
2062 self.a = a
2063 self.b = b
2064 def __repr__(self):
2065 return "C(%r, %r)" % (self.a, self.b)
2066
2067 global C1
2068 class C1(list):
2069 def __new__(cls, a, b):
2070 return super(C1, cls).__new__(cls)
2071 def __init__(self, a, b):
2072 self.a = a
2073 self.b = b
2074 def __repr__(self):
2075 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2076
2077 global C2
2078 class C2(int):
2079 def __new__(cls, a, b, val=0):
2080 return super(C2, cls).__new__(cls, val)
2081 def __init__(self, a, b, val=0):
2082 self.a = a
2083 self.b = b
2084 def __repr__(self):
2085 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2086
2087 for p in pickle, cPickle:
2088 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002089 if verbose:
2090 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002091
2092 for cls in C, C1, C2:
2093 s = p.dumps(cls, bin)
2094 cls2 = p.loads(s)
2095 verify(cls2 is cls)
2096
2097 a = C1(1, 2); a.append(42); a.append(24)
2098 b = C2("hello", "world", 42)
2099 s = p.dumps((a, b), bin)
2100 x, y = p.loads(s)
2101 assert x.__class__ == a.__class__
2102 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2103 assert y.__class__ == b.__class__
2104 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2105 assert `x` == `a`
2106 assert `y` == `b`
2107 if verbose:
2108 print "a = x =", a
2109 print "b = y =", b
2110
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002111 # Testing copy.deepcopy()
2112 if verbose:
2113 print "deepcopy"
2114 import copy
2115 for cls in C, C1, C2:
2116 cls2 = copy.deepcopy(cls)
2117 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002118
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002119 a = C1(1, 2); a.append(42); a.append(24)
2120 b = C2("hello", "world", 42)
2121 x, y = copy.deepcopy((a, b))
2122 assert x.__class__ == a.__class__
2123 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2124 assert y.__class__ == b.__class__
2125 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2126 assert `x` == `a`
2127 assert `y` == `b`
2128 if verbose:
2129 print "a = x =", a
2130 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002131
2132def copies():
2133 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2134 import copy
2135 class C(object):
2136 pass
2137
2138 a = C()
2139 a.foo = 12
2140 b = copy.copy(a)
2141 verify(b.__dict__ == a.__dict__)
2142
2143 a.bar = [1,2,3]
2144 c = copy.copy(a)
2145 verify(c.bar == a.bar)
2146 verify(c.bar is a.bar)
2147
2148 d = copy.deepcopy(a)
2149 verify(d.__dict__ == a.__dict__)
2150 a.bar.append(4)
2151 verify(d.bar == [1,2,3])
2152
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002153def binopoverride():
2154 if verbose: print "Testing overrides of binary operations..."
2155 class I(int):
2156 def __repr__(self):
2157 return "I(%r)" % int(self)
2158 def __add__(self, other):
2159 return I(int(self) + int(other))
2160 __radd__ = __add__
2161 def __pow__(self, other, mod=None):
2162 if mod is None:
2163 return I(pow(int(self), int(other)))
2164 else:
2165 return I(pow(int(self), int(other), int(mod)))
2166 def __rpow__(self, other, mod=None):
2167 if mod is None:
2168 return I(pow(int(other), int(self), mod))
2169 else:
2170 return I(pow(int(other), int(self), int(mod)))
2171
2172 vereq(`I(1) + I(2)`, "I(3)")
2173 vereq(`I(1) + 2`, "I(3)")
2174 vereq(`1 + I(2)`, "I(3)")
2175 vereq(`I(2) ** I(3)`, "I(8)")
2176 vereq(`2 ** I(3)`, "I(8)")
2177 vereq(`I(2) ** 3`, "I(8)")
2178 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2179 class S(str):
2180 def __eq__(self, other):
2181 return self.lower() == other.lower()
2182
Tim Peters0ab085c2001-09-14 00:25:33 +00002183
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002184def test_main():
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185 lists()
2186 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00002187 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00002188 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189 ints()
2190 longs()
2191 floats()
2192 complexes()
2193 spamlists()
2194 spamdicts()
2195 pydicts()
2196 pylists()
2197 metaclass()
2198 pymods()
2199 multi()
2200 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00002201 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 slots()
2203 dynamics()
2204 errors()
2205 classmethods()
2206 staticmethods()
2207 classic()
2208 compattr()
2209 newslot()
2210 altmro()
2211 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00002212 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00002213 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002214 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002215 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00002216 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002217 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00002218 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00002219 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00002220 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00002221 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00002222 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00002223 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002224 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002225 setclass()
Guido van Rossum3926a632001-09-25 16:25:58 +00002226 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002227 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002228 binopoverride()
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002229 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002231if __name__ == "__main__":
2232 test_main()