blob: 36703f52a464d0878bf4b57320b72e30e3cc182e [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 Rossum9d4fe422001-08-12 03:38:18 +0000873 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000874 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000875 C.foobar = 2
876 verify(a.foobar == 2)
877 C.method = lambda self: 42
878 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000879 C.__repr__ = lambda self: "C()"
880 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000881 C.__int__ = lambda self: 100
882 verify(int(a) == 100)
883 verify(a.foobar == 2)
884 verify(not hasattr(a, "spam"))
885 def mygetattr(self, name):
886 if name == "spam":
887 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +0000888 raise AttributeError
889 C.__getattr__ = mygetattr
Guido van Rossumd3077402001-08-12 05:24:18 +0000890 verify(a.spam == "spam")
891 a.new = 12
892 verify(a.new == 12)
893 def mysetattr(self, name, value):
894 if name == "spam":
895 raise AttributeError
896 return object.__setattr__(self, name, value)
897 C.__setattr__ = mysetattr
898 try:
899 a.spam = "not spam"
900 except AttributeError:
901 pass
902 else:
903 verify(0, "expected AttributeError")
904 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000905 class D(C):
906 pass
907 d = D()
908 d.foo = 1
909 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
Guido van Rossum7e35d572001-09-15 03:14:32 +0000911 # Test handling of int*seq and seq*int
912 class I(int):
913 __dynamic__ = 1
914 verify("a"*I(2) == "aa")
915 verify(I(2)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000916 verify(2*I(3) == 6)
917 verify(I(3)*2 == 6)
918 verify(I(3)*I(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000919
920 # Test handling of long*seq and seq*long
921 class L(long):
922 __dynamic__ = 1
923 verify("a"*L(2L) == "aa")
924 verify(L(2L)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000925 verify(2*L(3) == 6)
926 verify(L(3)*2 == 6)
927 verify(L(3)*L(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000928
Guido van Rossum3d45d8f2001-09-24 18:47:40 +0000929 # Test comparison of classes with dynamic metaclasses
930 class dynamicmetaclass(type):
931 __dynamic__ = 1
932 class someclass:
933 __metaclass__ = dynamicmetaclass
934 verify(someclass != object)
935
Tim Peters6d6c1a32001-08-02 04:15:00 +0000936def errors():
937 if verbose: print "Testing errors..."
938
939 try:
940 class C(list, dictionary):
941 pass
942 except TypeError:
943 pass
944 else:
945 verify(0, "inheritance from both list and dict should be illegal")
946
947 try:
948 class C(object, None):
949 pass
950 except TypeError:
951 pass
952 else:
953 verify(0, "inheritance from non-type should be illegal")
954 class Classic:
955 pass
956
957 try:
958 class C(object, Classic):
959 pass
960 except TypeError:
961 pass
962 else:
963 verify(0, "inheritance from object and Classic should be illegal")
964
965 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000966 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000967 pass
968 except TypeError:
969 pass
970 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000971 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972
973 try:
974 class C(object):
975 __slots__ = 1
976 except TypeError:
977 pass
978 else:
979 verify(0, "__slots__ = 1 should be illegal")
980
981 try:
982 class C(object):
983 __slots__ = [1]
984 except TypeError:
985 pass
986 else:
987 verify(0, "__slots__ = [1] should be illegal")
988
989def classmethods():
990 if verbose: print "Testing class methods..."
991 class C(object):
992 def foo(*a): return a
993 goo = classmethod(foo)
994 c = C()
995 verify(C.goo(1) == (C, 1))
996 verify(c.goo(1) == (C, 1))
997 verify(c.foo(1) == (c, 1))
998 class D(C):
999 pass
1000 d = D()
1001 verify(D.goo(1) == (D, 1))
1002 verify(d.goo(1) == (D, 1))
1003 verify(d.foo(1) == (d, 1))
1004 verify(D.foo(d, 1) == (d, 1))
1005
1006def staticmethods():
1007 if verbose: print "Testing static methods..."
1008 class C(object):
1009 def foo(*a): return a
1010 goo = staticmethod(foo)
1011 c = C()
1012 verify(C.goo(1) == (1,))
1013 verify(c.goo(1) == (1,))
1014 verify(c.foo(1) == (c, 1,))
1015 class D(C):
1016 pass
1017 d = D()
1018 verify(D.goo(1) == (1,))
1019 verify(d.goo(1) == (1,))
1020 verify(d.foo(1) == (d, 1))
1021 verify(D.foo(d, 1) == (d, 1))
1022
1023def classic():
1024 if verbose: print "Testing classic classes..."
1025 class C:
1026 def foo(*a): return a
1027 goo = classmethod(foo)
1028 c = C()
1029 verify(C.goo(1) == (C, 1))
1030 verify(c.goo(1) == (C, 1))
1031 verify(c.foo(1) == (c, 1))
1032 class D(C):
1033 pass
1034 d = D()
1035 verify(D.goo(1) == (D, 1))
1036 verify(d.goo(1) == (D, 1))
1037 verify(d.foo(1) == (d, 1))
1038 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001039 class E: # *not* subclassing from C
1040 foo = C.foo
1041 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001042 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043
1044def compattr():
1045 if verbose: print "Testing computed attributes..."
1046 class C(object):
1047 class computed_attribute(object):
1048 def __init__(self, get, set=None):
1049 self.__get = get
1050 self.__set = set
1051 def __get__(self, obj, type=None):
1052 return self.__get(obj)
1053 def __set__(self, obj, value):
1054 return self.__set(obj, value)
1055 def __init__(self):
1056 self.__x = 0
1057 def __get_x(self):
1058 x = self.__x
1059 self.__x = x+1
1060 return x
1061 def __set_x(self, x):
1062 self.__x = x
1063 x = computed_attribute(__get_x, __set_x)
1064 a = C()
1065 verify(a.x == 0)
1066 verify(a.x == 1)
1067 a.x = 10
1068 verify(a.x == 10)
1069 verify(a.x == 11)
1070
1071def newslot():
1072 if verbose: print "Testing __new__ slot override..."
1073 class C(list):
1074 def __new__(cls):
1075 self = list.__new__(cls)
1076 self.foo = 1
1077 return self
1078 def __init__(self):
1079 self.foo = self.foo + 2
1080 a = C()
1081 verify(a.foo == 3)
1082 verify(a.__class__ is C)
1083 class D(C):
1084 pass
1085 b = D()
1086 verify(b.foo == 3)
1087 verify(b.__class__ is D)
1088
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089def altmro():
1090 if verbose: print "Testing mro() and overriding it..."
1091 class A(object):
1092 def f(self): return "A"
1093 class B(A):
1094 pass
1095 class C(A):
1096 def f(self): return "C"
1097 class D(B, C):
1098 pass
1099 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1100 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001101 class PerverseMetaType(type):
1102 def mro(cls):
1103 L = type.mro(cls)
1104 L.reverse()
1105 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106 class X(A,B,C,D):
1107 __metaclass__ = PerverseMetaType
1108 verify(X.__mro__ == (object, A, C, B, D, X))
1109 verify(X().f() == "A")
1110
1111def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001112 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113
1114 class B(object):
1115 "Intermediate class because object doesn't have a __setattr__"
1116
1117 class C(B):
1118
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001119 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120 if name == "foo":
1121 return ("getattr", name)
1122 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001123 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124 def __setattr__(self, name, value):
1125 if name == "foo":
1126 self.setattr = (name, value)
1127 else:
1128 return B.__setattr__(self, name, value)
1129 def __delattr__(self, name):
1130 if name == "foo":
1131 self.delattr = name
1132 else:
1133 return B.__delattr__(self, name)
1134
1135 def __getitem__(self, key):
1136 return ("getitem", key)
1137 def __setitem__(self, key, value):
1138 self.setitem = (key, value)
1139 def __delitem__(self, key):
1140 self.delitem = key
1141
1142 def __getslice__(self, i, j):
1143 return ("getslice", i, j)
1144 def __setslice__(self, i, j, value):
1145 self.setslice = (i, j, value)
1146 def __delslice__(self, i, j):
1147 self.delslice = (i, j)
1148
1149 a = C()
1150 verify(a.foo == ("getattr", "foo"))
1151 a.foo = 12
1152 verify(a.setattr == ("foo", 12))
1153 del a.foo
1154 verify(a.delattr == "foo")
1155
1156 verify(a[12] == ("getitem", 12))
1157 a[12] = 21
1158 verify(a.setitem == (12, 21))
1159 del a[12]
1160 verify(a.delitem == 12)
1161
1162 verify(a[0:10] == ("getslice", 0, 10))
1163 a[0:10] = "foo"
1164 verify(a.setslice == (0, 10, "foo"))
1165 del a[0:10]
1166 verify(a.delslice == (0, 10))
1167
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001168def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001169 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001170 class C(object):
1171 def __init__(self, x):
1172 self.x = x
1173 def foo(self):
1174 return self.x
1175 c1 = C(1)
1176 verify(c1.foo() == 1)
1177 class D(C):
1178 boo = C.foo
1179 goo = c1.foo
1180 d2 = D(2)
1181 verify(d2.foo() == 2)
1182 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001183 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001184 class E(object):
1185 foo = C.foo
1186 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001187 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001188
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001189def specials():
1190 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001191 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001192 # Test the default behavior for static classes
1193 class C(object):
1194 def __getitem__(self, i):
1195 if 0 <= i < 10: return i
1196 raise IndexError
1197 c1 = C()
1198 c2 = C()
1199 verify(not not c1)
1200 verify(hash(c1) == id(c1))
1201 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1202 verify(c1 == c1)
1203 verify(c1 != c2)
1204 verify(not c1 != c1)
1205 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001206 # Note that the module name appears in str/repr, and that varies
1207 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001208 verify(str(c1).find('C object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001209 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001210 verify(-1 not in c1)
1211 for i in range(10):
1212 verify(i in c1)
1213 verify(10 not in c1)
1214 # Test the default behavior for dynamic classes
1215 class D(object):
1216 __dynamic__ = 1
1217 def __getitem__(self, i):
1218 if 0 <= i < 10: return i
1219 raise IndexError
1220 d1 = D()
1221 d2 = D()
1222 verify(not not d1)
1223 verify(hash(d1) == id(d1))
1224 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1225 verify(d1 == d1)
1226 verify(d1 != d2)
1227 verify(not d1 != d1)
1228 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001229 # Note that the module name appears in str/repr, and that varies
1230 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001231 verify(str(d1).find('D object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001232 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001233 verify(-1 not in d1)
1234 for i in range(10):
1235 verify(i in d1)
1236 verify(10 not in d1)
1237 # Test overridden behavior for static classes
1238 class Proxy(object):
1239 def __init__(self, x):
1240 self.x = x
1241 def __nonzero__(self):
1242 return not not self.x
1243 def __hash__(self):
1244 return hash(self.x)
1245 def __eq__(self, other):
1246 return self.x == other
1247 def __ne__(self, other):
1248 return self.x != other
1249 def __cmp__(self, other):
1250 return cmp(self.x, other.x)
1251 def __str__(self):
1252 return "Proxy:%s" % self.x
1253 def __repr__(self):
1254 return "Proxy(%r)" % self.x
1255 def __contains__(self, value):
1256 return value in self.x
1257 p0 = Proxy(0)
1258 p1 = Proxy(1)
1259 p_1 = Proxy(-1)
1260 verify(not p0)
1261 verify(not not p1)
1262 verify(hash(p0) == hash(0))
1263 verify(p0 == p0)
1264 verify(p0 != p1)
1265 verify(not p0 != p0)
1266 verify(not p0 == p1)
1267 verify(cmp(p0, p1) == -1)
1268 verify(cmp(p0, p0) == 0)
1269 verify(cmp(p0, p_1) == 1)
1270 verify(str(p0) == "Proxy:0")
1271 verify(repr(p0) == "Proxy(0)")
1272 p10 = Proxy(range(10))
1273 verify(-1 not in p10)
1274 for i in range(10):
1275 verify(i in p10)
1276 verify(10 not in p10)
1277 # Test overridden behavior for dynamic classes
1278 class DProxy(object):
1279 __dynamic__ = 1
1280 def __init__(self, x):
1281 self.x = x
1282 def __nonzero__(self):
1283 return not not self.x
1284 def __hash__(self):
1285 return hash(self.x)
1286 def __eq__(self, other):
1287 return self.x == other
1288 def __ne__(self, other):
1289 return self.x != other
1290 def __cmp__(self, other):
1291 return cmp(self.x, other.x)
1292 def __str__(self):
1293 return "DProxy:%s" % self.x
1294 def __repr__(self):
1295 return "DProxy(%r)" % self.x
1296 def __contains__(self, value):
1297 return value in self.x
1298 p0 = DProxy(0)
1299 p1 = DProxy(1)
1300 p_1 = DProxy(-1)
1301 verify(not p0)
1302 verify(not not p1)
1303 verify(hash(p0) == hash(0))
1304 verify(p0 == p0)
1305 verify(p0 != p1)
1306 verify(not p0 != p0)
1307 verify(not p0 == p1)
1308 verify(cmp(p0, p1) == -1)
1309 verify(cmp(p0, p0) == 0)
1310 verify(cmp(p0, p_1) == 1)
1311 verify(str(p0) == "DProxy:0")
1312 verify(repr(p0) == "DProxy(0)")
1313 p10 = DProxy(range(10))
1314 verify(-1 not in p10)
1315 for i in range(10):
1316 verify(i in p10)
1317 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001318 # Safety test for __cmp__
1319 def unsafecmp(a, b):
1320 try:
1321 a.__class__.__cmp__(a, b)
1322 except TypeError:
1323 pass
1324 else:
1325 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1326 a.__class__, a, b)
1327 unsafecmp(u"123", "123")
1328 unsafecmp("123", u"123")
1329 unsafecmp(1, 1.0)
1330 unsafecmp(1.0, 1)
1331 unsafecmp(1, 1L)
1332 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001333
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001334def weakrefs():
1335 if verbose: print "Testing weak references..."
1336 import weakref
1337 class C(object):
1338 pass
1339 c = C()
1340 r = weakref.ref(c)
1341 verify(r() is c)
1342 del c
1343 verify(r() is None)
1344 del r
1345 class NoWeak(object):
1346 __slots__ = ['foo']
1347 no = NoWeak()
1348 try:
1349 weakref.ref(no)
1350 except TypeError, msg:
1351 verify(str(msg).find("weakly") >= 0)
1352 else:
1353 verify(0, "weakref.ref(no) should be illegal")
1354 class Weak(object):
1355 __slots__ = ['foo', '__weakref__']
1356 yes = Weak()
1357 r = weakref.ref(yes)
1358 verify(r() is yes)
1359 del yes
1360 verify(r() is None)
1361 del r
1362
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001363def properties():
1364 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001365 class C(object):
1366 def getx(self):
1367 return self.__x
1368 def setx(self, value):
1369 self.__x = value
1370 def delx(self):
1371 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001372 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001373 a = C()
1374 verify(not hasattr(a, "x"))
1375 a.x = 42
1376 verify(a._C__x == 42)
1377 verify(a.x == 42)
1378 del a.x
1379 verify(not hasattr(a, "x"))
1380 verify(not hasattr(a, "_C__x"))
1381 C.x.__set__(a, 100)
1382 verify(C.x.__get__(a) == 100)
1383## C.x.__set__(a)
1384## verify(not hasattr(a, "x"))
1385
Tim Peters66c1a522001-09-24 21:17:50 +00001386 raw = C.__dict__['x']
1387 verify(isinstance(raw, property))
1388
1389 attrs = dir(raw)
1390 verify("__doc__" in attrs)
1391 verify("fget" in attrs)
1392 verify("fset" in attrs)
1393 verify("fdel" in attrs)
1394
1395 verify(raw.__doc__ == "I'm the x property.")
1396 verify(raw.fget is C.__dict__['getx'])
1397 verify(raw.fset is C.__dict__['setx'])
1398 verify(raw.fdel is C.__dict__['delx'])
1399
1400 for attr in "__doc__", "fget", "fset", "fdel":
1401 try:
1402 setattr(raw, attr, 42)
1403 except TypeError, msg:
1404 if str(msg).find('readonly') < 0:
1405 raise TestFailed("when setting readonly attr %r on a "
1406 "property, got unexpected TypeError "
1407 "msg %r" % (attr, str(msg)))
1408 else:
1409 raise TestFailed("expected TypeError from trying to set "
1410 "readonly %r attr on a property" % attr)
1411
Guido van Rossumc4a18802001-08-24 16:55:27 +00001412def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001413 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001414
1415 class A(object):
1416 def meth(self, a):
1417 return "A(%r)" % a
1418
1419 verify(A().meth(1) == "A(1)")
1420
1421 class B(A):
1422 def __init__(self):
1423 self.__super = super(B, self)
1424 def meth(self, a):
1425 return "B(%r)" % a + self.__super.meth(a)
1426
1427 verify(B().meth(2) == "B(2)A(2)")
1428
1429 class C(A):
1430 __dynamic__ = 1
1431 def meth(self, a):
1432 return "C(%r)" % a + self.__super.meth(a)
1433 C._C__super = super(C)
1434
1435 verify(C().meth(3) == "C(3)A(3)")
1436
1437 class D(C, B):
1438 def meth(self, a):
1439 return "D(%r)" % a + super(D, self).meth(a)
1440
1441 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1442
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001443def inherits():
1444 if verbose: print "Testing inheritance from basic types..."
1445
1446 class hexint(int):
1447 def __repr__(self):
1448 return hex(self)
1449 def __add__(self, other):
1450 return hexint(int.__add__(self, other))
1451 # (Note that overriding __radd__ doesn't work,
1452 # because the int type gets first dibs.)
1453 verify(repr(hexint(7) + 9) == "0x10")
1454 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001455 a = hexint(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001456 verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001457 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001458 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001459 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001460 verify((+a).__class__ is int)
1461 verify((a >> 0).__class__ is int)
1462 verify((a << 0).__class__ is int)
1463 verify((hexint(0) << 12).__class__ is int)
1464 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001465
1466 class octlong(long):
1467 __slots__ = []
1468 def __str__(self):
1469 s = oct(self)
1470 if s[-1] == 'L':
1471 s = s[:-1]
1472 return s
1473 def __add__(self, other):
1474 return self.__class__(super(octlong, self).__add__(other))
1475 __radd__ = __add__
1476 verify(str(octlong(3) + 5) == "010")
1477 # (Note that overriding __radd__ here only seems to work
1478 # because the example uses a short int left argument.)
1479 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001480 a = octlong(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001481 verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001482 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001483 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001484 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001485 verify((+a).__class__ is long)
1486 verify((-a).__class__ is long)
1487 verify((-octlong(0)).__class__ is long)
1488 verify((a >> 0).__class__ is long)
1489 verify((a << 0).__class__ is long)
1490 verify((a - 0).__class__ is long)
1491 verify((a * 1).__class__ is long)
1492 verify((a ** 1).__class__ is long)
1493 verify((a // 1).__class__ is long)
1494 verify((1 * a).__class__ is long)
1495 verify((a | 0).__class__ is long)
1496 verify((a ^ 0).__class__ is long)
1497 verify((a & -1L).__class__ is long)
1498 verify((octlong(0) << 12).__class__ is long)
1499 verify((octlong(0) >> 12).__class__ is long)
1500 verify(abs(octlong(0)).__class__ is long)
1501
1502 # Because octlong overrides __add__, we can't check the absence of +0
1503 # optimizations using octlong.
1504 class longclone(long):
1505 pass
1506 a = longclone(1)
1507 verify((a + 0).__class__ is long)
1508 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001509
1510 class precfloat(float):
1511 __slots__ = ['prec']
1512 def __init__(self, value=0.0, prec=12):
1513 self.prec = int(prec)
1514 float.__init__(value)
1515 def __repr__(self):
1516 return "%.*g" % (self.prec, self)
1517 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001518 a = precfloat(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001519 verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001520 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001521 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001522 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001523 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001524
Tim Peters2400fa42001-09-12 19:12:49 +00001525 class madcomplex(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001526 __dynamic__ = 0
Tim Peters2400fa42001-09-12 19:12:49 +00001527 def __repr__(self):
1528 return "%.17gj%+.17g" % (self.imag, self.real)
1529 a = madcomplex(-3, 4)
1530 verify(repr(a) == "4j-3")
1531 base = complex(-3, 4)
1532 verify(base.__class__ is complex)
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001533 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001534 verify(complex(a) == base)
1535 verify(complex(a).__class__ is complex)
1536 a = madcomplex(a) # just trying another form of the constructor
1537 verify(repr(a) == "4j-3")
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 verify(hash(a) == hash(base))
1542 verify((+a).__class__ is complex)
1543 verify((a + 0).__class__ is complex)
1544 verify(a + 0 == base)
1545 verify((a - 0).__class__ is complex)
1546 verify(a - 0 == base)
1547 verify((a * 1).__class__ is complex)
1548 verify(a * 1 == base)
1549 verify((a / 1).__class__ is complex)
1550 verify(a / 1 == base)
1551
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001552 class madtuple(tuple):
1553 _rev = None
1554 def rev(self):
1555 if self._rev is not None:
1556 return self._rev
1557 L = list(self)
1558 L.reverse()
1559 self._rev = self.__class__(L)
1560 return self._rev
1561 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001562 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001563 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1564 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1565 for i in range(512):
1566 t = madtuple(range(i))
1567 u = t.rev()
1568 v = u.rev()
1569 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001570 a = madtuple((1,2,3,4,5))
1571 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001572 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001573 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001574 verify(a[:].__class__ is tuple)
1575 verify((a * 1).__class__ is tuple)
1576 verify((a * 0).__class__ is tuple)
1577 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001578 a = madtuple(())
1579 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001580 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001581 verify((a + a).__class__ is tuple)
1582 verify((a * 0).__class__ is tuple)
1583 verify((a * 1).__class__ is tuple)
1584 verify((a * 2).__class__ is tuple)
1585 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001586
1587 class madstring(str):
1588 _rev = None
1589 def rev(self):
1590 if self._rev is not None:
1591 return self._rev
1592 L = list(self)
1593 L.reverse()
1594 self._rev = self.__class__("".join(L))
1595 return self._rev
1596 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001597 verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001598 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1599 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1600 for i in range(256):
1601 s = madstring("".join(map(chr, range(i))))
1602 t = s.rev()
1603 u = t.rev()
1604 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001605 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001606 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001607 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001608
Tim Peters8fa5dd02001-09-12 02:18:30 +00001609 base = "\x00" * 5
1610 s = madstring(base)
Guido van Rossumbb77e682001-09-24 16:51:54 +00001611 verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001612 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001613 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001614 verify(hash(s) == hash(base))
Guido van Rossumbb77e682001-09-24 16:51:54 +00001615 verify({s: 1}[base] == 1)
1616 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001617 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001618 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001619 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001620 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001621 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001622 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001623 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001624 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001625 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001626 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001627 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001628 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001629 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001630 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001631 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001632 verify(s.strip() == base)
1633 verify(s.lstrip().__class__ is str)
1634 verify(s.lstrip() == base)
1635 verify(s.rstrip().__class__ is str)
1636 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001637 identitytab = ''.join([chr(i) for i in range(256)])
1638 verify(s.translate(identitytab).__class__ is str)
1639 verify(s.translate(identitytab) == base)
1640 verify(s.translate(identitytab, "x").__class__ is str)
1641 verify(s.translate(identitytab, "x") == base)
1642 verify(s.translate(identitytab, "\x00") == "")
1643 verify(s.replace("x", "x").__class__ is str)
1644 verify(s.replace("x", "x") == base)
1645 verify(s.ljust(len(s)).__class__ is str)
1646 verify(s.ljust(len(s)) == base)
1647 verify(s.rjust(len(s)).__class__ is str)
1648 verify(s.rjust(len(s)) == base)
1649 verify(s.center(len(s)).__class__ is str)
1650 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001651 verify(s.lower().__class__ is str)
1652 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001653
Tim Peters111f6092001-09-12 07:54:51 +00001654 s = madstring("x y")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001655 verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001656 verify(intern(s).__class__ is str)
1657 verify(intern(s) is intern("x y"))
1658 verify(intern(s) == "x y")
1659
1660 i = intern("y x")
1661 s = madstring("y x")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001662 verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001663 verify(intern(s).__class__ is str)
1664 verify(intern(s) is i)
1665
1666 s = madstring(i)
1667 verify(intern(s).__class__ is str)
1668 verify(intern(s) is i)
1669
Guido van Rossum91ee7982001-08-30 20:52:40 +00001670 class madunicode(unicode):
1671 _rev = None
1672 def rev(self):
1673 if self._rev is not None:
1674 return self._rev
1675 L = list(self)
1676 L.reverse()
1677 self._rev = self.__class__(u"".join(L))
1678 return self._rev
1679 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001680 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001681 verify(u.rev() == madunicode(u"FEDCBA"))
1682 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001683 base = u"12345"
1684 u = madunicode(base)
1685 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001686 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001687 verify(hash(u) == hash(base))
1688 verify({u: 1}[base] == 1)
1689 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001690 verify(u.strip().__class__ is unicode)
1691 verify(u.strip() == base)
1692 verify(u.lstrip().__class__ is unicode)
1693 verify(u.lstrip() == base)
1694 verify(u.rstrip().__class__ is unicode)
1695 verify(u.rstrip() == base)
1696 verify(u.replace(u"x", u"x").__class__ is unicode)
1697 verify(u.replace(u"x", u"x") == base)
1698 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1699 verify(u.replace(u"xy", u"xy") == base)
1700 verify(u.center(len(u)).__class__ is unicode)
1701 verify(u.center(len(u)) == base)
1702 verify(u.ljust(len(u)).__class__ is unicode)
1703 verify(u.ljust(len(u)) == base)
1704 verify(u.rjust(len(u)).__class__ is unicode)
1705 verify(u.rjust(len(u)) == base)
1706 verify(u.lower().__class__ is unicode)
1707 verify(u.lower() == base)
1708 verify(u.upper().__class__ is unicode)
1709 verify(u.upper() == base)
1710 verify(u.capitalize().__class__ is unicode)
1711 verify(u.capitalize() == base)
1712 verify(u.title().__class__ is unicode)
1713 verify(u.title() == base)
1714 verify((u + u"").__class__ is unicode)
1715 verify(u + u"" == base)
1716 verify((u"" + u).__class__ is unicode)
1717 verify(u"" + u == base)
1718 verify((u * 0).__class__ is unicode)
1719 verify(u * 0 == u"")
1720 verify((u * 1).__class__ is unicode)
1721 verify(u * 1 == base)
1722 verify((u * 2).__class__ is unicode)
1723 verify(u * 2 == base + base)
1724 verify(u[:].__class__ is unicode)
1725 verify(u[:] == base)
1726 verify(u[0:0].__class__ is unicode)
1727 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001728
Tim Peters59c9a642001-09-13 05:38:56 +00001729 class CountedInput(file):
1730 """Counts lines read by self.readline().
1731
1732 self.lineno is the 0-based ordinal of the last line read, up to
1733 a maximum of one greater than the number of lines in the file.
1734
1735 self.ateof is true if and only if the final "" line has been read,
1736 at which point self.lineno stops incrementing, and further calls
1737 to readline() continue to return "".
1738 """
1739
1740 lineno = 0
1741 ateof = 0
1742 def readline(self):
1743 if self.ateof:
1744 return ""
1745 s = file.readline(self)
1746 # Next line works too.
1747 # s = super(CountedInput, self).readline()
1748 self.lineno += 1
1749 if s == "":
1750 self.ateof = 1
1751 return s
1752
Tim Peters561f8992001-09-13 19:36:36 +00001753 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00001754 lines = ['a\n', 'b\n', 'c\n']
1755 try:
1756 f.writelines(lines)
1757 f.close()
1758 f = CountedInput(TESTFN)
1759 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1760 got = f.readline()
1761 verify(expected == got)
1762 verify(f.lineno == i)
1763 verify(f.ateof == (i > len(lines)))
1764 f.close()
1765 finally:
1766 try:
1767 f.close()
1768 except:
1769 pass
1770 try:
1771 import os
1772 os.unlink(TESTFN)
1773 except:
1774 pass
1775
Tim Peters808b94e2001-09-13 19:33:07 +00001776def keywords():
1777 if verbose:
1778 print "Testing keyword args to basic type constructors ..."
1779 verify(int(x=1) == 1)
1780 verify(float(x=2) == 2.0)
1781 verify(long(x=3) == 3L)
1782 verify(complex(imag=42, real=666) == complex(666, 42))
1783 verify(str(object=500) == '500')
1784 verify(unicode(string='abc', errors='strict') == u'abc')
1785 verify(tuple(sequence=range(3)) == (0, 1, 2))
1786 verify(list(sequence=(0, 1, 2)) == range(3))
1787 verify(dictionary(mapping={1: 2}) == {1: 2})
1788
1789 for constructor in (int, float, long, complex, str, unicode,
1790 tuple, list, dictionary, file):
1791 try:
1792 constructor(bogus_keyword_arg=1)
1793 except TypeError:
1794 pass
1795 else:
1796 raise TestFailed("expected TypeError from bogus keyword "
1797 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00001798
Tim Peters8fa45672001-09-13 21:01:29 +00001799def restricted():
1800 import rexec
1801 if verbose:
1802 print "Testing interaction with restricted execution ..."
1803
1804 sandbox = rexec.RExec()
1805
1806 code1 = """f = open(%r, 'w')""" % TESTFN
1807 code2 = """f = file(%r, 'w')""" % TESTFN
1808 code3 = """\
1809f = open(%r)
1810t = type(f) # a sneaky way to get the file() constructor
1811f.close()
1812f = t(%r, 'w') # rexec can't catch this by itself
1813""" % (TESTFN, TESTFN)
1814
1815 f = open(TESTFN, 'w') # Create the file so code3 can find it.
1816 f.close()
1817
1818 try:
1819 for code in code1, code2, code3:
1820 try:
1821 sandbox.r_exec(code)
1822 except IOError, msg:
1823 if str(msg).find("restricted") >= 0:
1824 outcome = "OK"
1825 else:
1826 outcome = "got an exception, but not an expected one"
1827 else:
1828 outcome = "expected a restricted-execution exception"
1829
1830 if outcome != "OK":
1831 raise TestFailed("%s, in %r" % (outcome, code))
1832
1833 finally:
1834 try:
1835 import os
1836 os.unlink(TESTFN)
1837 except:
1838 pass
1839
Tim Peters0ab085c2001-09-14 00:25:33 +00001840def str_subclass_as_dict_key():
1841 if verbose:
1842 print "Testing a str subclass used as dict key .."
1843
1844 class cistr(str):
1845 """Sublcass of str that computes __eq__ case-insensitively.
1846
1847 Also computes a hash code of the string in canonical form.
1848 """
1849
1850 def __init__(self, value):
1851 self.canonical = value.lower()
1852 self.hashcode = hash(self.canonical)
1853
1854 def __eq__(self, other):
1855 if not isinstance(other, cistr):
1856 other = cistr(other)
1857 return self.canonical == other.canonical
1858
1859 def __hash__(self):
1860 return self.hashcode
1861
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001862 verify(cistr('ABC') == 'abc')
1863 verify('aBc' == cistr('ABC'))
Tim Peters0ab085c2001-09-14 00:25:33 +00001864 verify(str(cistr('ABC')) == 'ABC')
1865
1866 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
1867 verify(d[cistr('one')] == 1)
1868 verify(d[cistr('tWo')] == 2)
1869 verify(d[cistr('THrEE')] == 3)
1870 verify(cistr('ONe') in d)
1871 verify(d.get(cistr('thrEE')) == 3)
1872
Guido van Rossumab3b0342001-09-18 20:38:53 +00001873def classic_comparisons():
1874 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00001875 class classic:
1876 pass
1877 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00001878 if verbose: print " (base = %s)" % base
1879 class C(base):
1880 def __init__(self, value):
1881 self.value = int(value)
1882 def __cmp__(self, other):
1883 if isinstance(other, C):
1884 return cmp(self.value, other.value)
1885 if isinstance(other, int) or isinstance(other, long):
1886 return cmp(self.value, other)
1887 return NotImplemented
1888 c1 = C(1)
1889 c2 = C(2)
1890 c3 = C(3)
1891 verify(c1 == 1)
1892 c = {1: c1, 2: c2, 3: c3}
1893 for x in 1, 2, 3:
1894 for y in 1, 2, 3:
1895 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1896 for op in "<", "<=", "==", "!=", ">", ">=":
1897 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1898 "x=%d, y=%d" % (x, y))
1899 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
1900 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1901
Guido van Rossum0639f592001-09-18 21:06:04 +00001902def rich_comparisons():
1903 if verbose:
1904 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00001905 class Z(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001906 __dynamic__ = 0
Guido van Rossum22056422001-09-24 17:52:04 +00001907 z = Z(1)
1908 verify(z == 1+0j)
1909 verify(1+0j == z)
1910 class ZZ(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001911 __dynamic__ = 0
Guido van Rossum22056422001-09-24 17:52:04 +00001912 def __eq__(self, other):
1913 try:
1914 return abs(self - other) <= 1e-6
1915 except:
1916 return NotImplemented
1917 zz = ZZ(1.0000003)
1918 verify(zz == 1+0j)
1919 verify(1+0j == zz)
Tim Peters66c1a522001-09-24 21:17:50 +00001920
Guido van Rossum0639f592001-09-18 21:06:04 +00001921 class classic:
1922 pass
1923 for base in (classic, int, object, list):
1924 if verbose: print " (base = %s)" % base
1925 class C(base):
1926 def __init__(self, value):
1927 self.value = int(value)
1928 def __cmp__(self, other):
1929 raise TestFailed, "shouldn't call __cmp__"
1930 def __eq__(self, other):
1931 if isinstance(other, C):
1932 return self.value == other.value
1933 if isinstance(other, int) or isinstance(other, long):
1934 return self.value == other
1935 return NotImplemented
1936 def __ne__(self, other):
1937 if isinstance(other, C):
1938 return self.value != other.value
1939 if isinstance(other, int) or isinstance(other, long):
1940 return self.value != other
1941 return NotImplemented
1942 def __lt__(self, other):
1943 if isinstance(other, C):
1944 return self.value < other.value
1945 if isinstance(other, int) or isinstance(other, long):
1946 return self.value < other
1947 return NotImplemented
1948 def __le__(self, other):
1949 if isinstance(other, C):
1950 return self.value <= other.value
1951 if isinstance(other, int) or isinstance(other, long):
1952 return self.value <= other
1953 return NotImplemented
1954 def __gt__(self, other):
1955 if isinstance(other, C):
1956 return self.value > other.value
1957 if isinstance(other, int) or isinstance(other, long):
1958 return self.value > other
1959 return NotImplemented
1960 def __ge__(self, other):
1961 if isinstance(other, C):
1962 return self.value >= other.value
1963 if isinstance(other, int) or isinstance(other, long):
1964 return self.value >= other
1965 return NotImplemented
1966 c1 = C(1)
1967 c2 = C(2)
1968 c3 = C(3)
1969 verify(c1 == 1)
1970 c = {1: c1, 2: c2, 3: c3}
1971 for x in 1, 2, 3:
1972 for y in 1, 2, 3:
1973 for op in "<", "<=", "==", "!=", ">", ">=":
1974 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1975 "x=%d, y=%d" % (x, y))
1976 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
1977 "x=%d, y=%d" % (x, y))
1978 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
1979 "x=%d, y=%d" % (x, y))
1980
Guido van Rossum1952e382001-09-19 01:25:16 +00001981def coercions():
1982 if verbose: print "Testing coercions..."
1983 class I(int): pass
1984 coerce(I(0), 0)
1985 coerce(0, I(0))
1986 class L(long): pass
1987 coerce(L(0), 0)
1988 coerce(L(0), 0L)
1989 coerce(0, L(0))
1990 coerce(0L, L(0))
1991 class F(float): pass
1992 coerce(F(0), 0)
1993 coerce(F(0), 0L)
1994 coerce(F(0), 0.)
1995 coerce(0, F(0))
1996 coerce(0L, F(0))
1997 coerce(0., F(0))
Guido van Rossum751c4c82001-09-29 00:40:25 +00001998 class C(complex):
1999 __dynamic__ = 0
Guido van Rossum1952e382001-09-19 01:25:16 +00002000 coerce(C(0), 0)
2001 coerce(C(0), 0L)
2002 coerce(C(0), 0.)
2003 coerce(C(0), 0j)
2004 coerce(0, C(0))
2005 coerce(0L, C(0))
2006 coerce(0., C(0))
2007 coerce(0j, C(0))
2008
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002009def descrdoc():
2010 if verbose: print "Testing descriptor doc strings..."
2011 def check(descr, what):
2012 verify(descr.__doc__ == what, repr(descr.__doc__))
2013 check(file.closed, "flag set if the file is closed") # getset descriptor
2014 check(file.name, "file name") # member descriptor
2015
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002016def setclass():
2017 if verbose: print "Testing __class__ assignment..."
2018 class C(object): pass
2019 class D(object): pass
2020 class E(object): pass
2021 class F(D, E): pass
2022 for cls in C, D, E, F:
2023 for cls2 in C, D, E, F:
2024 x = cls()
2025 x.__class__ = cls2
2026 verify(x.__class__ is cls2)
2027 x.__class__ = cls
2028 verify(x.__class__ is cls)
2029 def cant(x, C):
2030 try:
2031 x.__class__ = C
2032 except TypeError:
2033 pass
2034 else:
2035 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2036 cant(C(), list)
2037 cant(list(), C)
2038 cant(C(), 1)
2039 cant(C(), object)
2040 cant(object(), list)
2041 cant(list(), object)
2042
Guido van Rossum3926a632001-09-25 16:25:58 +00002043def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002044 if verbose:
2045 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002046 import pickle, cPickle
2047
2048 def sorteditems(d):
2049 L = d.items()
2050 L.sort()
2051 return L
2052
2053 global C
2054 class C(object):
2055 def __init__(self, a, b):
2056 super(C, self).__init__()
2057 self.a = a
2058 self.b = b
2059 def __repr__(self):
2060 return "C(%r, %r)" % (self.a, self.b)
2061
2062 global C1
2063 class C1(list):
2064 def __new__(cls, a, b):
2065 return super(C1, cls).__new__(cls)
2066 def __init__(self, a, b):
2067 self.a = a
2068 self.b = b
2069 def __repr__(self):
2070 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2071
2072 global C2
2073 class C2(int):
2074 def __new__(cls, a, b, val=0):
2075 return super(C2, cls).__new__(cls, val)
2076 def __init__(self, a, b, val=0):
2077 self.a = a
2078 self.b = b
2079 def __repr__(self):
2080 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2081
2082 for p in pickle, cPickle:
2083 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002084 if verbose:
2085 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002086
2087 for cls in C, C1, C2:
2088 s = p.dumps(cls, bin)
2089 cls2 = p.loads(s)
2090 verify(cls2 is cls)
2091
2092 a = C1(1, 2); a.append(42); a.append(24)
2093 b = C2("hello", "world", 42)
2094 s = p.dumps((a, b), bin)
2095 x, y = p.loads(s)
2096 assert x.__class__ == a.__class__
2097 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2098 assert y.__class__ == b.__class__
2099 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2100 assert `x` == `a`
2101 assert `y` == `b`
2102 if verbose:
2103 print "a = x =", a
2104 print "b = y =", b
2105
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002106 # Testing copy.deepcopy()
2107 if verbose:
2108 print "deepcopy"
2109 import copy
2110 for cls in C, C1, C2:
2111 cls2 = copy.deepcopy(cls)
2112 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002113
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002114 a = C1(1, 2); a.append(42); a.append(24)
2115 b = C2("hello", "world", 42)
2116 x, y = copy.deepcopy((a, b))
2117 assert x.__class__ == a.__class__
2118 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2119 assert y.__class__ == b.__class__
2120 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2121 assert `x` == `a`
2122 assert `y` == `b`
2123 if verbose:
2124 print "a = x =", a
2125 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002126
2127def copies():
2128 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2129 import copy
2130 class C(object):
2131 pass
2132
2133 a = C()
2134 a.foo = 12
2135 b = copy.copy(a)
2136 verify(b.__dict__ == a.__dict__)
2137
2138 a.bar = [1,2,3]
2139 c = copy.copy(a)
2140 verify(c.bar == a.bar)
2141 verify(c.bar is a.bar)
2142
2143 d = copy.deepcopy(a)
2144 verify(d.__dict__ == a.__dict__)
2145 a.bar.append(4)
2146 verify(d.bar == [1,2,3])
2147
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002148def binopoverride():
2149 if verbose: print "Testing overrides of binary operations..."
2150 class I(int):
2151 def __repr__(self):
2152 return "I(%r)" % int(self)
2153 def __add__(self, other):
2154 return I(int(self) + int(other))
2155 __radd__ = __add__
2156 def __pow__(self, other, mod=None):
2157 if mod is None:
2158 return I(pow(int(self), int(other)))
2159 else:
2160 return I(pow(int(self), int(other), int(mod)))
2161 def __rpow__(self, other, mod=None):
2162 if mod is None:
2163 return I(pow(int(other), int(self), mod))
2164 else:
2165 return I(pow(int(other), int(self), int(mod)))
2166
2167 vereq(`I(1) + I(2)`, "I(3)")
2168 vereq(`I(1) + 2`, "I(3)")
2169 vereq(`1 + I(2)`, "I(3)")
2170 vereq(`I(2) ** I(3)`, "I(8)")
2171 vereq(`2 ** I(3)`, "I(8)")
2172 vereq(`I(2) ** 3`, "I(8)")
2173 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2174 class S(str):
2175 def __eq__(self, other):
2176 return self.lower() == other.lower()
2177
Tim Peters0ab085c2001-09-14 00:25:33 +00002178
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002179def test_main():
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180 lists()
2181 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00002182 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00002183 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184 ints()
2185 longs()
2186 floats()
2187 complexes()
2188 spamlists()
2189 spamdicts()
2190 pydicts()
2191 pylists()
2192 metaclass()
2193 pymods()
2194 multi()
2195 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00002196 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 slots()
2198 dynamics()
2199 errors()
2200 classmethods()
2201 staticmethods()
2202 classic()
2203 compattr()
2204 newslot()
2205 altmro()
2206 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00002207 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00002208 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002209 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002210 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00002211 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002212 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00002213 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00002214 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00002215 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00002216 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00002217 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00002218 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002219 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002220 setclass()
Guido van Rossum3926a632001-09-25 16:25:58 +00002221 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002222 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002223 binopoverride()
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002224 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002226if __name__ == "__main__":
2227 test_main()