blob: cd65c2c963fc1a3bdaf216e3b3f2b552ce5861fd [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
Tim Peters2f93e282001-10-04 05:27:00 +000091def class_docstrings():
92 class Classic:
93 "A classic docstring."
94 verify(Classic.__doc__ == "A classic docstring.")
95 verify(Classic.__dict__['__doc__'] == "A classic docstring.")
96
97 class Classic2:
98 pass
99 verify(Classic2.__doc__ is None)
100
101 class NewStatic:
102 "Another docstring."
103 __dynamic__ = 0
104 verify(NewStatic.__doc__ == "Another docstring.")
105 verify(NewStatic.__dict__['__doc__'] == "Another docstring.")
106
107 class NewStatic2:
108 __dynamic__ = 0
109 pass
110 verify(NewStatic2.__doc__ is None)
111
112 class NewDynamic:
113 "Another docstring."
114 __dynamic__ = 1
115 verify(NewDynamic.__doc__ == "Another docstring.")
116 verify(NewDynamic.__dict__['__doc__'] == "Another docstring.")
117
118 class NewDynamic2:
119 __dynamic__ = 1
120 pass
121 verify(NewDynamic2.__doc__ is None)
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123def lists():
124 if verbose: print "Testing list operations..."
125 testbinop([1], [2], [1,2], "a+b", "__add__")
126 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
127 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
128 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
129 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
130 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
131 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
132 testunop([1,2,3], 3, "len(a)", "__len__")
133 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
134 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
135 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
136 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
137
138def dicts():
139 if verbose: print "Testing dict operations..."
140 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
141 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
142 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
143 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
144 d = {1:2,3:4}
145 l1 = []
146 for i in d.keys(): l1.append(i)
147 l = []
148 for i in iter(d): l.append(i)
149 verify(l == l1)
150 l = []
151 for i in d.__iter__(): l.append(i)
152 verify(l == l1)
153 l = []
154 for i in dictionary.__iter__(d): l.append(i)
155 verify(l == l1)
156 d = {1:2, 3:4}
157 testunop(d, 2, "len(a)", "__len__")
158 verify(eval(repr(d), {}) == d)
159 verify(eval(d.__repr__(), {}) == d)
160 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
161
Tim Peters25786c02001-09-02 08:22:48 +0000162def dict_constructor():
163 if verbose:
164 print "Testing dictionary constructor ..."
165 d = dictionary()
166 verify(d == {})
167 d = dictionary({})
168 verify(d == {})
169 d = dictionary(mapping={})
170 verify(d == {})
171 d = dictionary({1: 2, 'a': 'b'})
172 verify(d == {1: 2, 'a': 'b'})
173 for badarg in 0, 0L, 0j, "0", [0], (0,):
174 try:
175 dictionary(badarg)
176 except TypeError:
177 pass
178 else:
179 raise TestFailed("no TypeError from dictionary(%r)" % badarg)
180 try:
181 dictionary(senseless={})
182 except TypeError:
183 pass
184 else:
185 raise TestFailed("no TypeError from dictionary(senseless={}")
186
187 try:
188 dictionary({}, {})
189 except TypeError:
190 pass
191 else:
192 raise TestFailed("no TypeError from dictionary({}, {})")
193
194 class Mapping:
195 dict = {1:2, 3:4, 'a':1j}
196
197 def __getitem__(self, i):
198 return self.dict[i]
199
200 try:
201 dictionary(Mapping())
202 except TypeError:
203 pass
204 else:
205 raise TestFailed("no TypeError from dictionary(incomplete mapping)")
206
207 Mapping.keys = lambda self: self.dict.keys()
208 d = dictionary(mapping=Mapping())
209 verify(d == Mapping.dict)
210
Tim Peters5d2b77c2001-09-03 05:47:38 +0000211def test_dir():
212 if verbose:
213 print "Testing dir() ..."
214 junk = 12
215 verify(dir() == ['junk'])
216 del junk
217
218 # Just make sure these don't blow up!
219 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
220 dir(arg)
221
Tim Peters37a309d2001-09-04 01:20:04 +0000222 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000223 class C:
224 Cdata = 1
225 def Cmethod(self): pass
226
227 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
228 verify(dir(C) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000229 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000230
231 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
232 verify(dir(c) == cstuff)
233
234 c.cdata = 2
235 c.cmethod = lambda self: 0
236 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000237 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000238
239 class A(C):
240 Adata = 1
241 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000242
Tim Peters37a309d2001-09-04 01:20:04 +0000243 astuff = ['Adata', 'Amethod'] + cstuff
244 verify(dir(A) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000245 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000246 a = A()
247 verify(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.adata = 42
250 a.amethod = lambda self: 3
251 verify(dir(a) == astuff + ['adata', 'amethod'])
252
253 # The same, but with new-style classes. Since these have object as a
254 # base class, a lot more gets sucked in.
255 def interesting(strings):
256 return [s for s in strings if not s.startswith('_')]
257
Tim Peters5d2b77c2001-09-03 05:47:38 +0000258 class C(object):
259 Cdata = 1
260 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000261
262 cstuff = ['Cdata', 'Cmethod']
263 verify(interesting(dir(C)) == cstuff)
264
265 c = C()
266 verify(interesting(dir(c)) == cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000267 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000268
269 c.cdata = 2
270 c.cmethod = lambda self: 0
271 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000272 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000273
Tim Peters5d2b77c2001-09-03 05:47:38 +0000274 class A(C):
275 Adata = 1
276 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000277
278 astuff = ['Adata', 'Amethod'] + cstuff
279 verify(interesting(dir(A)) == astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000280 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000281 a = A()
282 verify(interesting(dir(a)) == astuff)
283 a.adata = 42
284 a.amethod = lambda self: 3
285 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000286 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000287
Tim Peterscaaff8d2001-09-10 23:12:14 +0000288 # Try a module subclass.
289 import sys
290 class M(type(sys)):
291 pass
292 minstance = M()
293 minstance.b = 2
294 minstance.a = 1
295 verify(dir(minstance) == ['a', 'b'])
296
297 class M2(M):
298 def getdict(self):
299 return "Not a dict!"
300 __dict__ = property(getdict)
301
302 m2instance = M2()
303 m2instance.b = 2
304 m2instance.a = 1
305 verify(m2instance.__dict__ == "Not a dict!")
306 try:
307 dir(m2instance)
308 except TypeError:
309 pass
310
Tim Peters6d6c1a32001-08-02 04:15:00 +0000311binops = {
312 'add': '+',
313 'sub': '-',
314 'mul': '*',
315 'div': '/',
316 'mod': '%',
317 'divmod': 'divmod',
318 'pow': '**',
319 'lshift': '<<',
320 'rshift': '>>',
321 'and': '&',
322 'xor': '^',
323 'or': '|',
324 'cmp': 'cmp',
325 'lt': '<',
326 'le': '<=',
327 'eq': '==',
328 'ne': '!=',
329 'gt': '>',
330 'ge': '>=',
331 }
332
333for name, expr in binops.items():
334 if expr.islower():
335 expr = expr + "(a, b)"
336 else:
337 expr = 'a %s b' % expr
338 binops[name] = expr
339
340unops = {
341 'pos': '+',
342 'neg': '-',
343 'abs': 'abs',
344 'invert': '~',
345 'int': 'int',
346 'long': 'long',
347 'float': 'float',
348 'oct': 'oct',
349 'hex': 'hex',
350 }
351
352for name, expr in unops.items():
353 if expr.islower():
354 expr = expr + "(a)"
355 else:
356 expr = '%s a' % expr
357 unops[name] = expr
358
359def numops(a, b, skip=[]):
360 dict = {'a': a, 'b': b}
361 for name, expr in binops.items():
362 if name not in skip:
363 name = "__%s__" % name
364 if hasattr(a, name):
365 res = eval(expr, dict)
366 testbinop(a, b, res, expr, name)
367 for name, expr in unops.items():
368 name = "__%s__" % name
369 if hasattr(a, name):
370 res = eval(expr, dict)
371 testunop(a, res, expr, name)
372
373def ints():
374 if verbose: print "Testing int operations..."
375 numops(100, 3)
376
377def longs():
378 if verbose: print "Testing long operations..."
379 numops(100L, 3L)
380
381def floats():
382 if verbose: print "Testing float operations..."
383 numops(100.0, 3.0)
384
385def complexes():
386 if verbose: print "Testing complex operations..."
387 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
388 class Number(complex):
389 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000390 def __new__(cls, *args, **kwds):
391 result = complex.__new__(cls, *args)
392 result.prec = kwds.get('prec', 12)
393 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000394 def __repr__(self):
395 prec = self.prec
396 if self.imag == 0.0:
397 return "%.*g" % (prec, self.real)
398 if self.real == 0.0:
399 return "%.*gj" % (prec, self.imag)
400 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
401 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000402
Tim Peters6d6c1a32001-08-02 04:15:00 +0000403 a = Number(3.14, prec=6)
404 verify(`a` == "3.14")
405 verify(a.prec == 6)
406
Tim Peters3f996e72001-09-13 19:18:27 +0000407 a = Number(a, prec=2)
408 verify(`a` == "3.1")
409 verify(a.prec == 2)
410
411 a = Number(234.5)
412 verify(`a` == "234.5")
413 verify(a.prec == 12)
414
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415def spamlists():
416 if verbose: print "Testing spamlist operations..."
417 import copy, xxsubtype as spam
418 def spamlist(l, memo=None):
419 import xxsubtype as spam
420 return spam.spamlist(l)
421 # This is an ugly hack:
422 copy._deepcopy_dispatch[spam.spamlist] = spamlist
423
424 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
425 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
426 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
427 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
428 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
429 "a[b:c]", "__getslice__")
430 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
431 "a+=b", "__iadd__")
432 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
433 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
434 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
435 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
436 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
437 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
438 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
439 # Test subclassing
440 class C(spam.spamlist):
441 def foo(self): return 1
442 a = C()
443 verify(a == [])
444 verify(a.foo() == 1)
445 a.append(100)
446 verify(a == [100])
447 verify(a.getstate() == 0)
448 a.setstate(42)
449 verify(a.getstate() == 42)
450
451def spamdicts():
452 if verbose: print "Testing spamdict operations..."
453 import copy, xxsubtype as spam
454 def spamdict(d, memo=None):
455 import xxsubtype as spam
456 sd = spam.spamdict()
457 for k, v in d.items(): sd[k] = v
458 return sd
459 # This is an ugly hack:
460 copy._deepcopy_dispatch[spam.spamdict] = spamdict
461
462 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
463 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
464 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
465 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
466 d = spamdict({1:2,3:4})
467 l1 = []
468 for i in d.keys(): l1.append(i)
469 l = []
470 for i in iter(d): l.append(i)
471 verify(l == l1)
472 l = []
473 for i in d.__iter__(): l.append(i)
474 verify(l == l1)
475 l = []
476 for i in type(spamdict({})).__iter__(d): l.append(i)
477 verify(l == l1)
478 straightd = {1:2, 3:4}
479 spamd = spamdict(straightd)
480 testunop(spamd, 2, "len(a)", "__len__")
481 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
482 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
483 "a[b]=c", "__setitem__")
484 # Test subclassing
485 class C(spam.spamdict):
486 def foo(self): return 1
487 a = C()
488 verify(a.items() == [])
489 verify(a.foo() == 1)
490 a['foo'] = 'bar'
491 verify(a.items() == [('foo', 'bar')])
492 verify(a.getstate() == 0)
493 a.setstate(100)
494 verify(a.getstate() == 100)
495
496def pydicts():
497 if verbose: print "Testing Python subclass of dict..."
498 verify(issubclass(dictionary, dictionary))
499 verify(isinstance({}, dictionary))
500 d = dictionary()
501 verify(d == {})
502 verify(d.__class__ is dictionary)
503 verify(isinstance(d, dictionary))
504 class C(dictionary):
505 state = -1
506 def __init__(self, *a, **kw):
507 if a:
508 assert len(a) == 1
509 self.state = a[0]
510 if kw:
511 for k, v in kw.items(): self[v] = k
512 def __getitem__(self, key):
513 return self.get(key, 0)
514 def __setitem__(self, key, value):
515 assert isinstance(key, type(0))
516 dictionary.__setitem__(self, key, value)
517 def setstate(self, state):
518 self.state = state
519 def getstate(self):
520 return self.state
521 verify(issubclass(C, dictionary))
522 a1 = C(12)
523 verify(a1.state == 12)
524 a2 = C(foo=1, bar=2)
525 verify(a2[1] == 'foo' and a2[2] == 'bar')
526 a = C()
527 verify(a.state == -1)
528 verify(a.getstate() == -1)
529 a.setstate(0)
530 verify(a.state == 0)
531 verify(a.getstate() == 0)
532 a.setstate(10)
533 verify(a.state == 10)
534 verify(a.getstate() == 10)
535 verify(a[42] == 0)
536 a[42] = 24
537 verify(a[42] == 24)
538 if verbose: print "pydict stress test ..."
539 N = 50
540 for i in range(N):
541 a[i] = C()
542 for j in range(N):
543 a[i][j] = i*j
544 for i in range(N):
545 for j in range(N):
546 verify(a[i][j] == i*j)
547
548def pylists():
549 if verbose: print "Testing Python subclass of list..."
550 class C(list):
551 def __getitem__(self, i):
552 return list.__getitem__(self, i) + 100
553 def __getslice__(self, i, j):
554 return (i, j)
555 a = C()
556 a.extend([0,1,2])
557 verify(a[0] == 100)
558 verify(a[1] == 101)
559 verify(a[2] == 102)
560 verify(a[100:200] == (100,200))
561
562def metaclass():
563 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564 class C:
565 __metaclass__ = type
566 def __init__(self):
567 self.__state = 0
568 def getstate(self):
569 return self.__state
570 def setstate(self, state):
571 self.__state = state
572 a = C()
573 verify(a.getstate() == 0)
574 a.setstate(10)
575 verify(a.getstate() == 10)
576 class D:
577 class __metaclass__(type):
578 def myself(cls): return cls
579 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000580 d = D()
581 verify(d.__class__ is D)
582 class M1(type):
583 def __new__(cls, name, bases, dict):
584 dict['__spam__'] = 1
585 return type.__new__(cls, name, bases, dict)
586 class C:
587 __metaclass__ = M1
588 verify(C.__spam__ == 1)
589 c = C()
590 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000591
Guido van Rossum309b5662001-08-17 11:43:17 +0000592 class _instance(object):
593 pass
594 class M2(object):
595 def __new__(cls, name, bases, dict):
596 self = object.__new__(cls)
597 self.name = name
598 self.bases = bases
599 self.dict = dict
600 return self
601 __new__ = staticmethod(__new__)
602 def __call__(self):
603 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000604 # Early binding of methods
605 for key in self.dict:
606 if key.startswith("__"):
607 continue
608 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000609 return it
610 class C:
611 __metaclass__ = M2
612 def spam(self):
613 return 42
614 verify(C.name == 'C')
615 verify(C.bases == ())
616 verify('spam' in C.dict)
617 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000618 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000619
Guido van Rossum91ee7982001-08-30 20:52:40 +0000620 # More metaclass examples
621
622 class autosuper(type):
623 # Automatically add __super to the class
624 # This trick only works for dynamic classes
625 # so we force __dynamic__ = 1
626 def __new__(metaclass, name, bases, dict):
627 # XXX Should check that name isn't already a base class name
628 dict["__dynamic__"] = 1
629 cls = super(autosuper, metaclass).__new__(metaclass,
630 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000631 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000632 while name[:1] == "_":
633 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000634 if name:
635 name = "_%s__super" % name
636 else:
637 name = "__super"
638 setattr(cls, name, super(cls))
639 return cls
640 class A:
641 __metaclass__ = autosuper
642 def meth(self):
643 return "A"
644 class B(A):
645 def meth(self):
646 return "B" + self.__super.meth()
647 class C(A):
648 def meth(self):
649 return "C" + self.__super.meth()
650 class D(C, B):
651 def meth(self):
652 return "D" + self.__super.meth()
653 verify(D().meth() == "DCBA")
654 class E(B, C):
655 def meth(self):
656 return "E" + self.__super.meth()
657 verify(E().meth() == "EBCA")
658
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000659 class autoproperty(type):
660 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000661 # named _get_x and/or _set_x are found
662 def __new__(metaclass, name, bases, dict):
663 hits = {}
664 for key, val in dict.iteritems():
665 if key.startswith("_get_"):
666 key = key[5:]
667 get, set = hits.get(key, (None, None))
668 get = val
669 hits[key] = get, set
670 elif key.startswith("_set_"):
671 key = key[5:]
672 get, set = hits.get(key, (None, None))
673 set = val
674 hits[key] = get, set
675 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000676 dict[key] = property(get, set)
677 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000678 name, bases, dict)
679 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000680 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000681 def _get_x(self):
682 return -self.__x
683 def _set_x(self, x):
684 self.__x = -x
685 a = A()
686 verify(not hasattr(a, "x"))
687 a.x = 12
688 verify(a.x == 12)
689 verify(a._A__x == -12)
690
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000691 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000692 # Merge of multiple cooperating metaclasses
693 pass
694 class A:
695 __metaclass__ = multimetaclass
696 def _get_x(self):
697 return "A"
698 class B(A):
699 def _get_x(self):
700 return "B" + self.__super._get_x()
701 class C(A):
702 def _get_x(self):
703 return "C" + self.__super._get_x()
704 class D(C, B):
705 def _get_x(self):
706 return "D" + self.__super._get_x()
707 verify(D().x == "DCBA")
708
Tim Peters6d6c1a32001-08-02 04:15:00 +0000709def pymods():
710 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000712 import sys
713 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714 class MM(MT):
715 def __init__(self):
716 MT.__init__(self)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000717 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000719 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720 def __setattr__(self, name, value):
721 log.append(("setattr", name, value))
722 MT.__setattr__(self, name, value)
723 def __delattr__(self, name):
724 log.append(("delattr", name))
725 MT.__delattr__(self, name)
726 a = MM()
727 a.foo = 12
728 x = a.foo
729 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000730 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000732 ("delattr", "foo")], log)
733
734def multi():
735 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736 class C(object):
737 def __init__(self):
738 self.__state = 0
739 def getstate(self):
740 return self.__state
741 def setstate(self, state):
742 self.__state = state
743 a = C()
744 verify(a.getstate() == 0)
745 a.setstate(10)
746 verify(a.getstate() == 10)
747 class D(dictionary, C):
748 def __init__(self):
749 type({}).__init__(self)
750 C.__init__(self)
751 d = D()
752 verify(d.keys() == [])
753 d["hello"] = "world"
754 verify(d.items() == [("hello", "world")])
755 verify(d["hello"] == "world")
756 verify(d.getstate() == 0)
757 d.setstate(10)
758 verify(d.getstate() == 10)
759 verify(D.__mro__ == (D, dictionary, C, object))
760
Guido van Rossume45763a2001-08-10 21:28:46 +0000761 # SF bug #442833
762 class Node(object):
763 def __int__(self):
764 return int(self.foo())
765 def foo(self):
766 return "23"
767 class Frag(Node, list):
768 def foo(self):
769 return "42"
770 verify(Node().__int__() == 23)
771 verify(int(Node()) == 23)
772 verify(Frag().__int__() == 42)
773 verify(int(Frag()) == 42)
774
Tim Peters6d6c1a32001-08-02 04:15:00 +0000775def diamond():
776 if verbose: print "Testing multiple inheritance special cases..."
777 class A(object):
778 def spam(self): return "A"
779 verify(A().spam() == "A")
780 class B(A):
781 def boo(self): return "B"
782 def spam(self): return "B"
783 verify(B().spam() == "B")
784 verify(B().boo() == "B")
785 class C(A):
786 def boo(self): return "C"
787 verify(C().spam() == "A")
788 verify(C().boo() == "C")
789 class D(B, C): pass
790 verify(D().spam() == "B")
791 verify(D().boo() == "B")
792 verify(D.__mro__ == (D, B, C, A, object))
793 class E(C, B): pass
794 verify(E().spam() == "B")
795 verify(E().boo() == "C")
796 verify(E.__mro__ == (E, C, B, A, object))
797 class F(D, E): pass
798 verify(F().spam() == "B")
799 verify(F().boo() == "B")
800 verify(F.__mro__ == (F, D, E, B, C, A, object))
801 class G(E, D): pass
802 verify(G().spam() == "B")
803 verify(G().boo() == "C")
804 verify(G.__mro__ == (G, E, D, C, B, A, object))
805
Guido van Rossum37202612001-08-09 19:45:21 +0000806def objects():
807 if verbose: print "Testing object class..."
808 a = object()
809 verify(a.__class__ == object == type(a))
810 b = object()
811 verify(a is not b)
812 verify(not hasattr(a, "foo"))
813 try:
814 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000815 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000816 pass
817 else:
818 verify(0, "object() should not allow setting a foo attribute")
819 verify(not hasattr(object(), "__dict__"))
820
821 class Cdict(object):
822 pass
823 x = Cdict()
Guido van Rossum3926a632001-09-25 16:25:58 +0000824 verify(x.__dict__ == {})
Guido van Rossum37202612001-08-09 19:45:21 +0000825 x.foo = 1
826 verify(x.foo == 1)
827 verify(x.__dict__ == {'foo': 1})
828
Tim Peters6d6c1a32001-08-02 04:15:00 +0000829def slots():
830 if verbose: print "Testing __slots__..."
831 class C0(object):
832 __slots__ = []
833 x = C0()
834 verify(not hasattr(x, "__dict__"))
835 verify(not hasattr(x, "foo"))
836
837 class C1(object):
838 __slots__ = ['a']
839 x = C1()
840 verify(not hasattr(x, "__dict__"))
841 verify(x.a == None)
842 x.a = 1
843 verify(x.a == 1)
844 del x.a
845 verify(x.a == None)
846
847 class C3(object):
848 __slots__ = ['a', 'b', 'c']
849 x = C3()
850 verify(not hasattr(x, "__dict__"))
851 verify(x.a is None)
852 verify(x.b is None)
853 verify(x.c is None)
854 x.a = 1
855 x.b = 2
856 x.c = 3
857 verify(x.a == 1)
858 verify(x.b == 2)
859 verify(x.c == 3)
860
861def dynamics():
862 if verbose: print "Testing __dynamic__..."
863 verify(object.__dynamic__ == 0)
864 verify(list.__dynamic__ == 0)
865 class S1:
866 __metaclass__ = type
Guido van Rossum751c4c82001-09-29 00:40:25 +0000867 __dynamic__ = 0
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 verify(S1.__dynamic__ == 0)
869 class S(object):
Guido van Rossum751c4c82001-09-29 00:40:25 +0000870 __dynamic__ = 0
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000871 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872 class D(object):
873 __dynamic__ = 1
874 verify(D.__dynamic__ == 1)
875 class E(D, S):
876 pass
877 verify(E.__dynamic__ == 1)
878 class F(S, D):
879 pass
880 verify(F.__dynamic__ == 1)
881 try:
882 S.foo = 1
883 except (AttributeError, TypeError):
884 pass
885 else:
886 verify(0, "assignment to a static class attribute should be illegal")
887 D.foo = 1
888 verify(D.foo == 1)
889 # Test that dynamic attributes are inherited
890 verify(E.foo == 1)
891 verify(F.foo == 1)
892 class SS(D):
893 __dynamic__ = 0
894 verify(SS.__dynamic__ == 0)
895 verify(SS.foo == 1)
896 try:
897 SS.foo = 1
898 except (AttributeError, TypeError):
899 pass
900 else:
901 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000902 # Test dynamic instances
903 class C(object):
904 __dynamic__ = 1
Guido van Rossum4a5a2bc2001-10-03 13:59:54 +0000905 # XXX Ideally the following def shouldn't be necessary,
906 # but it's too much of a performance burden.
907 # See XXX comment in slot_tp_getattr_hook.
908 def __getattr__(self, name):
909 raise AttributeError, name
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000910 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000911 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000912 C.foobar = 2
913 verify(a.foobar == 2)
914 C.method = lambda self: 42
915 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000916 C.__repr__ = lambda self: "C()"
917 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000918 C.__int__ = lambda self: 100
919 verify(int(a) == 100)
920 verify(a.foobar == 2)
921 verify(not hasattr(a, "spam"))
922 def mygetattr(self, name):
923 if name == "spam":
924 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +0000925 raise AttributeError
926 C.__getattr__ = mygetattr
Guido van Rossumd3077402001-08-12 05:24:18 +0000927 verify(a.spam == "spam")
928 a.new = 12
929 verify(a.new == 12)
930 def mysetattr(self, name, value):
931 if name == "spam":
932 raise AttributeError
933 return object.__setattr__(self, name, value)
934 C.__setattr__ = mysetattr
935 try:
936 a.spam = "not spam"
937 except AttributeError:
938 pass
939 else:
940 verify(0, "expected AttributeError")
941 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000942 class D(C):
943 pass
944 d = D()
945 d.foo = 1
946 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000947
Guido van Rossum7e35d572001-09-15 03:14:32 +0000948 # Test handling of int*seq and seq*int
949 class I(int):
950 __dynamic__ = 1
951 verify("a"*I(2) == "aa")
952 verify(I(2)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000953 verify(2*I(3) == 6)
954 verify(I(3)*2 == 6)
955 verify(I(3)*I(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000956
957 # Test handling of long*seq and seq*long
958 class L(long):
959 __dynamic__ = 1
960 verify("a"*L(2L) == "aa")
961 verify(L(2L)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000962 verify(2*L(3) == 6)
963 verify(L(3)*2 == 6)
964 verify(L(3)*L(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000965
Guido van Rossum3d45d8f2001-09-24 18:47:40 +0000966 # Test comparison of classes with dynamic metaclasses
967 class dynamicmetaclass(type):
968 __dynamic__ = 1
969 class someclass:
970 __metaclass__ = dynamicmetaclass
971 verify(someclass != object)
972
Tim Peters6d6c1a32001-08-02 04:15:00 +0000973def errors():
974 if verbose: print "Testing errors..."
975
976 try:
977 class C(list, dictionary):
978 pass
979 except TypeError:
980 pass
981 else:
982 verify(0, "inheritance from both list and dict should be illegal")
983
984 try:
985 class C(object, None):
986 pass
987 except TypeError:
988 pass
989 else:
990 verify(0, "inheritance from non-type should be illegal")
991 class Classic:
992 pass
993
994 try:
995 class C(object, Classic):
996 pass
997 except TypeError:
998 pass
999 else:
1000 verify(0, "inheritance from object and Classic should be illegal")
1001
1002 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001003 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004 pass
1005 except TypeError:
1006 pass
1007 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001008 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009
1010 try:
1011 class C(object):
1012 __slots__ = 1
1013 except TypeError:
1014 pass
1015 else:
1016 verify(0, "__slots__ = 1 should be illegal")
1017
1018 try:
1019 class C(object):
1020 __slots__ = [1]
1021 except TypeError:
1022 pass
1023 else:
1024 verify(0, "__slots__ = [1] should be illegal")
1025
1026def classmethods():
1027 if verbose: print "Testing class methods..."
1028 class C(object):
1029 def foo(*a): return a
1030 goo = classmethod(foo)
1031 c = C()
1032 verify(C.goo(1) == (C, 1))
1033 verify(c.goo(1) == (C, 1))
1034 verify(c.foo(1) == (c, 1))
1035 class D(C):
1036 pass
1037 d = D()
1038 verify(D.goo(1) == (D, 1))
1039 verify(d.goo(1) == (D, 1))
1040 verify(d.foo(1) == (d, 1))
1041 verify(D.foo(d, 1) == (d, 1))
1042
1043def staticmethods():
1044 if verbose: print "Testing static methods..."
1045 class C(object):
1046 def foo(*a): return a
1047 goo = staticmethod(foo)
1048 c = C()
1049 verify(C.goo(1) == (1,))
1050 verify(c.goo(1) == (1,))
1051 verify(c.foo(1) == (c, 1,))
1052 class D(C):
1053 pass
1054 d = D()
1055 verify(D.goo(1) == (1,))
1056 verify(d.goo(1) == (1,))
1057 verify(d.foo(1) == (d, 1))
1058 verify(D.foo(d, 1) == (d, 1))
1059
1060def classic():
1061 if verbose: print "Testing classic classes..."
1062 class C:
1063 def foo(*a): return a
1064 goo = classmethod(foo)
1065 c = C()
1066 verify(C.goo(1) == (C, 1))
1067 verify(c.goo(1) == (C, 1))
1068 verify(c.foo(1) == (c, 1))
1069 class D(C):
1070 pass
1071 d = D()
1072 verify(D.goo(1) == (D, 1))
1073 verify(d.goo(1) == (D, 1))
1074 verify(d.foo(1) == (d, 1))
1075 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001076 class E: # *not* subclassing from C
1077 foo = C.foo
1078 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001079 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
1081def compattr():
1082 if verbose: print "Testing computed attributes..."
1083 class C(object):
1084 class computed_attribute(object):
1085 def __init__(self, get, set=None):
1086 self.__get = get
1087 self.__set = set
1088 def __get__(self, obj, type=None):
1089 return self.__get(obj)
1090 def __set__(self, obj, value):
1091 return self.__set(obj, value)
1092 def __init__(self):
1093 self.__x = 0
1094 def __get_x(self):
1095 x = self.__x
1096 self.__x = x+1
1097 return x
1098 def __set_x(self, x):
1099 self.__x = x
1100 x = computed_attribute(__get_x, __set_x)
1101 a = C()
1102 verify(a.x == 0)
1103 verify(a.x == 1)
1104 a.x = 10
1105 verify(a.x == 10)
1106 verify(a.x == 11)
1107
1108def newslot():
1109 if verbose: print "Testing __new__ slot override..."
1110 class C(list):
1111 def __new__(cls):
1112 self = list.__new__(cls)
1113 self.foo = 1
1114 return self
1115 def __init__(self):
1116 self.foo = self.foo + 2
1117 a = C()
1118 verify(a.foo == 3)
1119 verify(a.__class__ is C)
1120 class D(C):
1121 pass
1122 b = D()
1123 verify(b.foo == 3)
1124 verify(b.__class__ is D)
1125
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126def altmro():
1127 if verbose: print "Testing mro() and overriding it..."
1128 class A(object):
1129 def f(self): return "A"
1130 class B(A):
1131 pass
1132 class C(A):
1133 def f(self): return "C"
1134 class D(B, C):
1135 pass
1136 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1137 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001138 class PerverseMetaType(type):
1139 def mro(cls):
1140 L = type.mro(cls)
1141 L.reverse()
1142 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001143 class X(A,B,C,D):
1144 __metaclass__ = PerverseMetaType
1145 verify(X.__mro__ == (object, A, C, B, D, X))
1146 verify(X().f() == "A")
1147
1148def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001149 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150
1151 class B(object):
1152 "Intermediate class because object doesn't have a __setattr__"
1153
1154 class C(B):
1155
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001156 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157 if name == "foo":
1158 return ("getattr", name)
1159 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001160 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 def __setattr__(self, name, value):
1162 if name == "foo":
1163 self.setattr = (name, value)
1164 else:
1165 return B.__setattr__(self, name, value)
1166 def __delattr__(self, name):
1167 if name == "foo":
1168 self.delattr = name
1169 else:
1170 return B.__delattr__(self, name)
1171
1172 def __getitem__(self, key):
1173 return ("getitem", key)
1174 def __setitem__(self, key, value):
1175 self.setitem = (key, value)
1176 def __delitem__(self, key):
1177 self.delitem = key
1178
1179 def __getslice__(self, i, j):
1180 return ("getslice", i, j)
1181 def __setslice__(self, i, j, value):
1182 self.setslice = (i, j, value)
1183 def __delslice__(self, i, j):
1184 self.delslice = (i, j)
1185
1186 a = C()
1187 verify(a.foo == ("getattr", "foo"))
1188 a.foo = 12
1189 verify(a.setattr == ("foo", 12))
1190 del a.foo
1191 verify(a.delattr == "foo")
1192
1193 verify(a[12] == ("getitem", 12))
1194 a[12] = 21
1195 verify(a.setitem == (12, 21))
1196 del a[12]
1197 verify(a.delitem == 12)
1198
1199 verify(a[0:10] == ("getslice", 0, 10))
1200 a[0:10] = "foo"
1201 verify(a.setslice == (0, 10, "foo"))
1202 del a[0:10]
1203 verify(a.delslice == (0, 10))
1204
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001205def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001206 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001207 class C(object):
1208 def __init__(self, x):
1209 self.x = x
1210 def foo(self):
1211 return self.x
1212 c1 = C(1)
1213 verify(c1.foo() == 1)
1214 class D(C):
1215 boo = C.foo
1216 goo = c1.foo
1217 d2 = D(2)
1218 verify(d2.foo() == 2)
1219 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001220 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001221 class E(object):
1222 foo = C.foo
1223 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001224 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001225
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001226def specials():
1227 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001228 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001229 # Test the default behavior for static classes
1230 class C(object):
1231 def __getitem__(self, i):
1232 if 0 <= i < 10: return i
1233 raise IndexError
1234 c1 = C()
1235 c2 = C()
1236 verify(not not c1)
1237 verify(hash(c1) == id(c1))
1238 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1239 verify(c1 == c1)
1240 verify(c1 != c2)
1241 verify(not c1 != c1)
1242 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001243 # Note that the module name appears in str/repr, and that varies
1244 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001245 verify(str(c1).find('C object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001246 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001247 verify(-1 not in c1)
1248 for i in range(10):
1249 verify(i in c1)
1250 verify(10 not in c1)
1251 # Test the default behavior for dynamic classes
1252 class D(object):
1253 __dynamic__ = 1
1254 def __getitem__(self, i):
1255 if 0 <= i < 10: return i
1256 raise IndexError
1257 d1 = D()
1258 d2 = D()
1259 verify(not not d1)
1260 verify(hash(d1) == id(d1))
1261 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1262 verify(d1 == d1)
1263 verify(d1 != d2)
1264 verify(not d1 != d1)
1265 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001266 # Note that the module name appears in str/repr, and that varies
1267 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001268 verify(str(d1).find('D object at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001269 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001270 verify(-1 not in d1)
1271 for i in range(10):
1272 verify(i in d1)
1273 verify(10 not in d1)
1274 # Test overridden behavior for static classes
1275 class Proxy(object):
1276 def __init__(self, x):
1277 self.x = x
1278 def __nonzero__(self):
1279 return not not self.x
1280 def __hash__(self):
1281 return hash(self.x)
1282 def __eq__(self, other):
1283 return self.x == other
1284 def __ne__(self, other):
1285 return self.x != other
1286 def __cmp__(self, other):
1287 return cmp(self.x, other.x)
1288 def __str__(self):
1289 return "Proxy:%s" % self.x
1290 def __repr__(self):
1291 return "Proxy(%r)" % self.x
1292 def __contains__(self, value):
1293 return value in self.x
1294 p0 = Proxy(0)
1295 p1 = Proxy(1)
1296 p_1 = Proxy(-1)
1297 verify(not p0)
1298 verify(not not p1)
1299 verify(hash(p0) == hash(0))
1300 verify(p0 == p0)
1301 verify(p0 != p1)
1302 verify(not p0 != p0)
1303 verify(not p0 == p1)
1304 verify(cmp(p0, p1) == -1)
1305 verify(cmp(p0, p0) == 0)
1306 verify(cmp(p0, p_1) == 1)
1307 verify(str(p0) == "Proxy:0")
1308 verify(repr(p0) == "Proxy(0)")
1309 p10 = Proxy(range(10))
1310 verify(-1 not in p10)
1311 for i in range(10):
1312 verify(i in p10)
1313 verify(10 not in p10)
1314 # Test overridden behavior for dynamic classes
1315 class DProxy(object):
1316 __dynamic__ = 1
1317 def __init__(self, x):
1318 self.x = x
1319 def __nonzero__(self):
1320 return not not self.x
1321 def __hash__(self):
1322 return hash(self.x)
1323 def __eq__(self, other):
1324 return self.x == other
1325 def __ne__(self, other):
1326 return self.x != other
1327 def __cmp__(self, other):
1328 return cmp(self.x, other.x)
1329 def __str__(self):
1330 return "DProxy:%s" % self.x
1331 def __repr__(self):
1332 return "DProxy(%r)" % self.x
1333 def __contains__(self, value):
1334 return value in self.x
1335 p0 = DProxy(0)
1336 p1 = DProxy(1)
1337 p_1 = DProxy(-1)
1338 verify(not p0)
1339 verify(not not p1)
1340 verify(hash(p0) == hash(0))
1341 verify(p0 == p0)
1342 verify(p0 != p1)
1343 verify(not p0 != p0)
1344 verify(not p0 == p1)
1345 verify(cmp(p0, p1) == -1)
1346 verify(cmp(p0, p0) == 0)
1347 verify(cmp(p0, p_1) == 1)
1348 verify(str(p0) == "DProxy:0")
1349 verify(repr(p0) == "DProxy(0)")
1350 p10 = DProxy(range(10))
1351 verify(-1 not in p10)
1352 for i in range(10):
1353 verify(i in p10)
1354 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001355 # Safety test for __cmp__
1356 def unsafecmp(a, b):
1357 try:
1358 a.__class__.__cmp__(a, b)
1359 except TypeError:
1360 pass
1361 else:
1362 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1363 a.__class__, a, b)
1364 unsafecmp(u"123", "123")
1365 unsafecmp("123", u"123")
1366 unsafecmp(1, 1.0)
1367 unsafecmp(1.0, 1)
1368 unsafecmp(1, 1L)
1369 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001370
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001371def weakrefs():
1372 if verbose: print "Testing weak references..."
1373 import weakref
1374 class C(object):
1375 pass
1376 c = C()
1377 r = weakref.ref(c)
1378 verify(r() is c)
1379 del c
1380 verify(r() is None)
1381 del r
1382 class NoWeak(object):
1383 __slots__ = ['foo']
1384 no = NoWeak()
1385 try:
1386 weakref.ref(no)
1387 except TypeError, msg:
1388 verify(str(msg).find("weakly") >= 0)
1389 else:
1390 verify(0, "weakref.ref(no) should be illegal")
1391 class Weak(object):
1392 __slots__ = ['foo', '__weakref__']
1393 yes = Weak()
1394 r = weakref.ref(yes)
1395 verify(r() is yes)
1396 del yes
1397 verify(r() is None)
1398 del r
1399
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001400def properties():
1401 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001402 class C(object):
1403 def getx(self):
1404 return self.__x
1405 def setx(self, value):
1406 self.__x = value
1407 def delx(self):
1408 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001409 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001410 a = C()
1411 verify(not hasattr(a, "x"))
1412 a.x = 42
1413 verify(a._C__x == 42)
1414 verify(a.x == 42)
1415 del a.x
1416 verify(not hasattr(a, "x"))
1417 verify(not hasattr(a, "_C__x"))
1418 C.x.__set__(a, 100)
1419 verify(C.x.__get__(a) == 100)
1420## C.x.__set__(a)
1421## verify(not hasattr(a, "x"))
1422
Tim Peters66c1a522001-09-24 21:17:50 +00001423 raw = C.__dict__['x']
1424 verify(isinstance(raw, property))
1425
1426 attrs = dir(raw)
1427 verify("__doc__" in attrs)
1428 verify("fget" in attrs)
1429 verify("fset" in attrs)
1430 verify("fdel" in attrs)
1431
1432 verify(raw.__doc__ == "I'm the x property.")
1433 verify(raw.fget is C.__dict__['getx'])
1434 verify(raw.fset is C.__dict__['setx'])
1435 verify(raw.fdel is C.__dict__['delx'])
1436
1437 for attr in "__doc__", "fget", "fset", "fdel":
1438 try:
1439 setattr(raw, attr, 42)
1440 except TypeError, msg:
1441 if str(msg).find('readonly') < 0:
1442 raise TestFailed("when setting readonly attr %r on a "
1443 "property, got unexpected TypeError "
1444 "msg %r" % (attr, str(msg)))
1445 else:
1446 raise TestFailed("expected TypeError from trying to set "
1447 "readonly %r attr on a property" % attr)
1448
Guido van Rossumc4a18802001-08-24 16:55:27 +00001449def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001450 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001451
1452 class A(object):
1453 def meth(self, a):
1454 return "A(%r)" % a
1455
1456 verify(A().meth(1) == "A(1)")
1457
1458 class B(A):
1459 def __init__(self):
1460 self.__super = super(B, self)
1461 def meth(self, a):
1462 return "B(%r)" % a + self.__super.meth(a)
1463
1464 verify(B().meth(2) == "B(2)A(2)")
1465
1466 class C(A):
1467 __dynamic__ = 1
1468 def meth(self, a):
1469 return "C(%r)" % a + self.__super.meth(a)
1470 C._C__super = super(C)
1471
1472 verify(C().meth(3) == "C(3)A(3)")
1473
1474 class D(C, B):
1475 def meth(self, a):
1476 return "D(%r)" % a + super(D, self).meth(a)
1477
1478 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1479
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001480def inherits():
1481 if verbose: print "Testing inheritance from basic types..."
1482
1483 class hexint(int):
1484 def __repr__(self):
1485 return hex(self)
1486 def __add__(self, other):
1487 return hexint(int.__add__(self, other))
1488 # (Note that overriding __radd__ doesn't work,
1489 # because the int type gets first dibs.)
1490 verify(repr(hexint(7) + 9) == "0x10")
1491 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001492 a = hexint(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001493 verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001494 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001495 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001496 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001497 verify((+a).__class__ is int)
1498 verify((a >> 0).__class__ is int)
1499 verify((a << 0).__class__ is int)
1500 verify((hexint(0) << 12).__class__ is int)
1501 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001502
1503 class octlong(long):
1504 __slots__ = []
1505 def __str__(self):
1506 s = oct(self)
1507 if s[-1] == 'L':
1508 s = s[:-1]
1509 return s
1510 def __add__(self, other):
1511 return self.__class__(super(octlong, self).__add__(other))
1512 __radd__ = __add__
1513 verify(str(octlong(3) + 5) == "010")
1514 # (Note that overriding __radd__ here only seems to work
1515 # because the example uses a short int left argument.)
1516 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001517 a = octlong(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001518 verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001519 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001520 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001521 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001522 verify((+a).__class__ is long)
1523 verify((-a).__class__ is long)
1524 verify((-octlong(0)).__class__ is long)
1525 verify((a >> 0).__class__ is long)
1526 verify((a << 0).__class__ is long)
1527 verify((a - 0).__class__ is long)
1528 verify((a * 1).__class__ is long)
1529 verify((a ** 1).__class__ is long)
1530 verify((a // 1).__class__ is long)
1531 verify((1 * a).__class__ is long)
1532 verify((a | 0).__class__ is long)
1533 verify((a ^ 0).__class__ is long)
1534 verify((a & -1L).__class__ is long)
1535 verify((octlong(0) << 12).__class__ is long)
1536 verify((octlong(0) >> 12).__class__ is long)
1537 verify(abs(octlong(0)).__class__ is long)
1538
1539 # Because octlong overrides __add__, we can't check the absence of +0
1540 # optimizations using octlong.
1541 class longclone(long):
1542 pass
1543 a = longclone(1)
1544 verify((a + 0).__class__ is long)
1545 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001546
1547 class precfloat(float):
1548 __slots__ = ['prec']
1549 def __init__(self, value=0.0, prec=12):
1550 self.prec = int(prec)
1551 float.__init__(value)
1552 def __repr__(self):
1553 return "%.*g" % (self.prec, self)
1554 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001555 a = precfloat(12345)
Tim Peters50fda6c2001-09-18 21:24:18 +00001556 verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001557 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001558 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001559 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001560 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001561
Tim Peters2400fa42001-09-12 19:12:49 +00001562 class madcomplex(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001563 __dynamic__ = 0
Tim Peters2400fa42001-09-12 19:12:49 +00001564 def __repr__(self):
1565 return "%.17gj%+.17g" % (self.imag, self.real)
1566 a = madcomplex(-3, 4)
1567 verify(repr(a) == "4j-3")
1568 base = complex(-3, 4)
1569 verify(base.__class__ is complex)
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001570 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001571 verify(complex(a) == base)
1572 verify(complex(a).__class__ is complex)
1573 a = madcomplex(a) # just trying another form of the constructor
1574 verify(repr(a) == "4j-3")
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001575 verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001576 verify(complex(a) == base)
1577 verify(complex(a).__class__ is complex)
1578 verify(hash(a) == hash(base))
1579 verify((+a).__class__ is complex)
1580 verify((a + 0).__class__ is complex)
1581 verify(a + 0 == base)
1582 verify((a - 0).__class__ is complex)
1583 verify(a - 0 == base)
1584 verify((a * 1).__class__ is complex)
1585 verify(a * 1 == base)
1586 verify((a / 1).__class__ is complex)
1587 verify(a / 1 == base)
1588
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001589 class madtuple(tuple):
1590 _rev = None
1591 def rev(self):
1592 if self._rev is not None:
1593 return self._rev
1594 L = list(self)
1595 L.reverse()
1596 self._rev = self.__class__(L)
1597 return self._rev
1598 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001599 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001600 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1601 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1602 for i in range(512):
1603 t = madtuple(range(i))
1604 u = t.rev()
1605 v = u.rev()
1606 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001607 a = madtuple((1,2,3,4,5))
1608 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001609 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001610 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001611 verify(a[:].__class__ is tuple)
1612 verify((a * 1).__class__ is tuple)
1613 verify((a * 0).__class__ is tuple)
1614 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001615 a = madtuple(())
1616 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001617 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001618 verify((a + a).__class__ is tuple)
1619 verify((a * 0).__class__ is tuple)
1620 verify((a * 1).__class__ is tuple)
1621 verify((a * 2).__class__ is tuple)
1622 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001623
1624 class madstring(str):
1625 _rev = None
1626 def rev(self):
1627 if self._rev is not None:
1628 return self._rev
1629 L = list(self)
1630 L.reverse()
1631 self._rev = self.__class__("".join(L))
1632 return self._rev
1633 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001634 verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001635 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1636 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1637 for i in range(256):
1638 s = madstring("".join(map(chr, range(i))))
1639 t = s.rev()
1640 u = t.rev()
1641 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001642 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001643 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001644 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001645
Tim Peters8fa5dd02001-09-12 02:18:30 +00001646 base = "\x00" * 5
1647 s = madstring(base)
Guido van Rossumbb77e682001-09-24 16:51:54 +00001648 verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001649 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001650 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001651 verify(hash(s) == hash(base))
Guido van Rossumbb77e682001-09-24 16:51:54 +00001652 verify({s: 1}[base] == 1)
1653 verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001654 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001655 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001656 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001657 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001658 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001659 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001660 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001661 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001662 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001663 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001664 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001665 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001666 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001667 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001668 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001669 verify(s.strip() == base)
1670 verify(s.lstrip().__class__ is str)
1671 verify(s.lstrip() == base)
1672 verify(s.rstrip().__class__ is str)
1673 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001674 identitytab = ''.join([chr(i) for i in range(256)])
1675 verify(s.translate(identitytab).__class__ is str)
1676 verify(s.translate(identitytab) == base)
1677 verify(s.translate(identitytab, "x").__class__ is str)
1678 verify(s.translate(identitytab, "x") == base)
1679 verify(s.translate(identitytab, "\x00") == "")
1680 verify(s.replace("x", "x").__class__ is str)
1681 verify(s.replace("x", "x") == base)
1682 verify(s.ljust(len(s)).__class__ is str)
1683 verify(s.ljust(len(s)) == base)
1684 verify(s.rjust(len(s)).__class__ is str)
1685 verify(s.rjust(len(s)) == base)
1686 verify(s.center(len(s)).__class__ is str)
1687 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001688 verify(s.lower().__class__ is str)
1689 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001690
Tim Peters111f6092001-09-12 07:54:51 +00001691 s = madstring("x y")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001692 verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001693 verify(intern(s).__class__ is str)
1694 verify(intern(s) is intern("x y"))
1695 verify(intern(s) == "x y")
1696
1697 i = intern("y x")
1698 s = madstring("y x")
Guido van Rossumbb77e682001-09-24 16:51:54 +00001699 verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001700 verify(intern(s).__class__ is str)
1701 verify(intern(s) is i)
1702
1703 s = madstring(i)
1704 verify(intern(s).__class__ is str)
1705 verify(intern(s) is i)
1706
Guido van Rossum91ee7982001-08-30 20:52:40 +00001707 class madunicode(unicode):
1708 _rev = None
1709 def rev(self):
1710 if self._rev is not None:
1711 return self._rev
1712 L = list(self)
1713 L.reverse()
1714 self._rev = self.__class__(u"".join(L))
1715 return self._rev
1716 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001717 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001718 verify(u.rev() == madunicode(u"FEDCBA"))
1719 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001720 base = u"12345"
1721 u = madunicode(base)
1722 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001723 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001724 verify(hash(u) == hash(base))
1725 verify({u: 1}[base] == 1)
1726 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001727 verify(u.strip().__class__ is unicode)
1728 verify(u.strip() == base)
1729 verify(u.lstrip().__class__ is unicode)
1730 verify(u.lstrip() == base)
1731 verify(u.rstrip().__class__ is unicode)
1732 verify(u.rstrip() == base)
1733 verify(u.replace(u"x", u"x").__class__ is unicode)
1734 verify(u.replace(u"x", u"x") == base)
1735 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1736 verify(u.replace(u"xy", u"xy") == base)
1737 verify(u.center(len(u)).__class__ is unicode)
1738 verify(u.center(len(u)) == base)
1739 verify(u.ljust(len(u)).__class__ is unicode)
1740 verify(u.ljust(len(u)) == base)
1741 verify(u.rjust(len(u)).__class__ is unicode)
1742 verify(u.rjust(len(u)) == base)
1743 verify(u.lower().__class__ is unicode)
1744 verify(u.lower() == base)
1745 verify(u.upper().__class__ is unicode)
1746 verify(u.upper() == base)
1747 verify(u.capitalize().__class__ is unicode)
1748 verify(u.capitalize() == base)
1749 verify(u.title().__class__ is unicode)
1750 verify(u.title() == base)
1751 verify((u + u"").__class__ is unicode)
1752 verify(u + u"" == base)
1753 verify((u"" + u).__class__ is unicode)
1754 verify(u"" + u == base)
1755 verify((u * 0).__class__ is unicode)
1756 verify(u * 0 == u"")
1757 verify((u * 1).__class__ is unicode)
1758 verify(u * 1 == base)
1759 verify((u * 2).__class__ is unicode)
1760 verify(u * 2 == base + base)
1761 verify(u[:].__class__ is unicode)
1762 verify(u[:] == base)
1763 verify(u[0:0].__class__ is unicode)
1764 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001765
Tim Peters59c9a642001-09-13 05:38:56 +00001766 class CountedInput(file):
1767 """Counts lines read by self.readline().
1768
1769 self.lineno is the 0-based ordinal of the last line read, up to
1770 a maximum of one greater than the number of lines in the file.
1771
1772 self.ateof is true if and only if the final "" line has been read,
1773 at which point self.lineno stops incrementing, and further calls
1774 to readline() continue to return "".
1775 """
1776
1777 lineno = 0
1778 ateof = 0
1779 def readline(self):
1780 if self.ateof:
1781 return ""
1782 s = file.readline(self)
1783 # Next line works too.
1784 # s = super(CountedInput, self).readline()
1785 self.lineno += 1
1786 if s == "":
1787 self.ateof = 1
1788 return s
1789
Tim Peters561f8992001-09-13 19:36:36 +00001790 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00001791 lines = ['a\n', 'b\n', 'c\n']
1792 try:
1793 f.writelines(lines)
1794 f.close()
1795 f = CountedInput(TESTFN)
1796 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1797 got = f.readline()
1798 verify(expected == got)
1799 verify(f.lineno == i)
1800 verify(f.ateof == (i > len(lines)))
1801 f.close()
1802 finally:
1803 try:
1804 f.close()
1805 except:
1806 pass
1807 try:
1808 import os
1809 os.unlink(TESTFN)
1810 except:
1811 pass
1812
Tim Peters808b94e2001-09-13 19:33:07 +00001813def keywords():
1814 if verbose:
1815 print "Testing keyword args to basic type constructors ..."
1816 verify(int(x=1) == 1)
1817 verify(float(x=2) == 2.0)
1818 verify(long(x=3) == 3L)
1819 verify(complex(imag=42, real=666) == complex(666, 42))
1820 verify(str(object=500) == '500')
1821 verify(unicode(string='abc', errors='strict') == u'abc')
1822 verify(tuple(sequence=range(3)) == (0, 1, 2))
1823 verify(list(sequence=(0, 1, 2)) == range(3))
1824 verify(dictionary(mapping={1: 2}) == {1: 2})
1825
1826 for constructor in (int, float, long, complex, str, unicode,
1827 tuple, list, dictionary, file):
1828 try:
1829 constructor(bogus_keyword_arg=1)
1830 except TypeError:
1831 pass
1832 else:
1833 raise TestFailed("expected TypeError from bogus keyword "
1834 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00001835
Tim Peters8fa45672001-09-13 21:01:29 +00001836def restricted():
1837 import rexec
1838 if verbose:
1839 print "Testing interaction with restricted execution ..."
1840
1841 sandbox = rexec.RExec()
1842
1843 code1 = """f = open(%r, 'w')""" % TESTFN
1844 code2 = """f = file(%r, 'w')""" % TESTFN
1845 code3 = """\
1846f = open(%r)
1847t = type(f) # a sneaky way to get the file() constructor
1848f.close()
1849f = t(%r, 'w') # rexec can't catch this by itself
1850""" % (TESTFN, TESTFN)
1851
1852 f = open(TESTFN, 'w') # Create the file so code3 can find it.
1853 f.close()
1854
1855 try:
1856 for code in code1, code2, code3:
1857 try:
1858 sandbox.r_exec(code)
1859 except IOError, msg:
1860 if str(msg).find("restricted") >= 0:
1861 outcome = "OK"
1862 else:
1863 outcome = "got an exception, but not an expected one"
1864 else:
1865 outcome = "expected a restricted-execution exception"
1866
1867 if outcome != "OK":
1868 raise TestFailed("%s, in %r" % (outcome, code))
1869
1870 finally:
1871 try:
1872 import os
1873 os.unlink(TESTFN)
1874 except:
1875 pass
1876
Tim Peters0ab085c2001-09-14 00:25:33 +00001877def str_subclass_as_dict_key():
1878 if verbose:
1879 print "Testing a str subclass used as dict key .."
1880
1881 class cistr(str):
1882 """Sublcass of str that computes __eq__ case-insensitively.
1883
1884 Also computes a hash code of the string in canonical form.
1885 """
1886
1887 def __init__(self, value):
1888 self.canonical = value.lower()
1889 self.hashcode = hash(self.canonical)
1890
1891 def __eq__(self, other):
1892 if not isinstance(other, cistr):
1893 other = cistr(other)
1894 return self.canonical == other.canonical
1895
1896 def __hash__(self):
1897 return self.hashcode
1898
Guido van Rossumd5d8e4a2001-09-19 01:16:16 +00001899 verify(cistr('ABC') == 'abc')
1900 verify('aBc' == cistr('ABC'))
Tim Peters0ab085c2001-09-14 00:25:33 +00001901 verify(str(cistr('ABC')) == 'ABC')
1902
1903 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
1904 verify(d[cistr('one')] == 1)
1905 verify(d[cistr('tWo')] == 2)
1906 verify(d[cistr('THrEE')] == 3)
1907 verify(cistr('ONe') in d)
1908 verify(d.get(cistr('thrEE')) == 3)
1909
Guido van Rossumab3b0342001-09-18 20:38:53 +00001910def classic_comparisons():
1911 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00001912 class classic:
1913 pass
1914 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00001915 if verbose: print " (base = %s)" % base
1916 class C(base):
1917 def __init__(self, value):
1918 self.value = int(value)
1919 def __cmp__(self, other):
1920 if isinstance(other, C):
1921 return cmp(self.value, other.value)
1922 if isinstance(other, int) or isinstance(other, long):
1923 return cmp(self.value, other)
1924 return NotImplemented
1925 c1 = C(1)
1926 c2 = C(2)
1927 c3 = C(3)
1928 verify(c1 == 1)
1929 c = {1: c1, 2: c2, 3: c3}
1930 for x in 1, 2, 3:
1931 for y in 1, 2, 3:
1932 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1933 for op in "<", "<=", "==", "!=", ">", ">=":
1934 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
1935 "x=%d, y=%d" % (x, y))
1936 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
1937 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
1938
Guido van Rossum0639f592001-09-18 21:06:04 +00001939def rich_comparisons():
1940 if verbose:
1941 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00001942 class Z(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001943 __dynamic__ = 0
Guido van Rossum22056422001-09-24 17:52:04 +00001944 z = Z(1)
1945 verify(z == 1+0j)
1946 verify(1+0j == z)
1947 class ZZ(complex):
Guido van Rossum751c4c82001-09-29 00:40:25 +00001948 __dynamic__ = 0
Guido van Rossum22056422001-09-24 17:52:04 +00001949 def __eq__(self, other):
1950 try:
1951 return abs(self - other) <= 1e-6
1952 except:
1953 return NotImplemented
1954 zz = ZZ(1.0000003)
1955 verify(zz == 1+0j)
1956 verify(1+0j == zz)
Tim Peters66c1a522001-09-24 21:17:50 +00001957
Guido van Rossum0639f592001-09-18 21:06:04 +00001958 class classic:
1959 pass
1960 for base in (classic, int, object, list):
1961 if verbose: print " (base = %s)" % base
1962 class C(base):
1963 def __init__(self, value):
1964 self.value = int(value)
1965 def __cmp__(self, other):
1966 raise TestFailed, "shouldn't call __cmp__"
1967 def __eq__(self, other):
1968 if isinstance(other, C):
1969 return self.value == other.value
1970 if isinstance(other, int) or isinstance(other, long):
1971 return self.value == other
1972 return NotImplemented
1973 def __ne__(self, other):
1974 if isinstance(other, C):
1975 return self.value != other.value
1976 if isinstance(other, int) or isinstance(other, long):
1977 return self.value != other
1978 return NotImplemented
1979 def __lt__(self, other):
1980 if isinstance(other, C):
1981 return self.value < other.value
1982 if isinstance(other, int) or isinstance(other, long):
1983 return self.value < other
1984 return NotImplemented
1985 def __le__(self, other):
1986 if isinstance(other, C):
1987 return self.value <= other.value
1988 if isinstance(other, int) or isinstance(other, long):
1989 return self.value <= other
1990 return NotImplemented
1991 def __gt__(self, other):
1992 if isinstance(other, C):
1993 return self.value > other.value
1994 if isinstance(other, int) or isinstance(other, long):
1995 return self.value > other
1996 return NotImplemented
1997 def __ge__(self, other):
1998 if isinstance(other, C):
1999 return self.value >= other.value
2000 if isinstance(other, int) or isinstance(other, long):
2001 return self.value >= other
2002 return NotImplemented
2003 c1 = C(1)
2004 c2 = C(2)
2005 c3 = C(3)
2006 verify(c1 == 1)
2007 c = {1: c1, 2: c2, 3: c3}
2008 for x in 1, 2, 3:
2009 for y in 1, 2, 3:
2010 for op in "<", "<=", "==", "!=", ">", ">=":
2011 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2012 "x=%d, y=%d" % (x, y))
2013 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2014 "x=%d, y=%d" % (x, y))
2015 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2016 "x=%d, y=%d" % (x, y))
2017
Guido van Rossum1952e382001-09-19 01:25:16 +00002018def coercions():
2019 if verbose: print "Testing coercions..."
2020 class I(int): pass
2021 coerce(I(0), 0)
2022 coerce(0, I(0))
2023 class L(long): pass
2024 coerce(L(0), 0)
2025 coerce(L(0), 0L)
2026 coerce(0, L(0))
2027 coerce(0L, L(0))
2028 class F(float): pass
2029 coerce(F(0), 0)
2030 coerce(F(0), 0L)
2031 coerce(F(0), 0.)
2032 coerce(0, F(0))
2033 coerce(0L, F(0))
2034 coerce(0., F(0))
Guido van Rossum751c4c82001-09-29 00:40:25 +00002035 class C(complex):
2036 __dynamic__ = 0
Guido van Rossum1952e382001-09-19 01:25:16 +00002037 coerce(C(0), 0)
2038 coerce(C(0), 0L)
2039 coerce(C(0), 0.)
2040 coerce(C(0), 0j)
2041 coerce(0, C(0))
2042 coerce(0L, C(0))
2043 coerce(0., C(0))
2044 coerce(0j, C(0))
2045
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002046def descrdoc():
2047 if verbose: print "Testing descriptor doc strings..."
2048 def check(descr, what):
2049 verify(descr.__doc__ == what, repr(descr.__doc__))
2050 check(file.closed, "flag set if the file is closed") # getset descriptor
2051 check(file.name, "file name") # member descriptor
2052
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002053def setclass():
2054 if verbose: print "Testing __class__ assignment..."
2055 class C(object): pass
2056 class D(object): pass
2057 class E(object): pass
2058 class F(D, E): pass
2059 for cls in C, D, E, F:
2060 for cls2 in C, D, E, F:
2061 x = cls()
2062 x.__class__ = cls2
2063 verify(x.__class__ is cls2)
2064 x.__class__ = cls
2065 verify(x.__class__ is cls)
2066 def cant(x, C):
2067 try:
2068 x.__class__ = C
2069 except TypeError:
2070 pass
2071 else:
2072 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2073 cant(C(), list)
2074 cant(list(), C)
2075 cant(C(), 1)
2076 cant(C(), object)
2077 cant(object(), list)
2078 cant(list(), object)
2079
Guido van Rossum3926a632001-09-25 16:25:58 +00002080def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002081 if verbose:
2082 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002083 import pickle, cPickle
2084
2085 def sorteditems(d):
2086 L = d.items()
2087 L.sort()
2088 return L
2089
2090 global C
2091 class C(object):
2092 def __init__(self, a, b):
2093 super(C, self).__init__()
2094 self.a = a
2095 self.b = b
2096 def __repr__(self):
2097 return "C(%r, %r)" % (self.a, self.b)
2098
2099 global C1
2100 class C1(list):
2101 def __new__(cls, a, b):
2102 return super(C1, cls).__new__(cls)
2103 def __init__(self, a, b):
2104 self.a = a
2105 self.b = b
2106 def __repr__(self):
2107 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2108
2109 global C2
2110 class C2(int):
2111 def __new__(cls, a, b, val=0):
2112 return super(C2, cls).__new__(cls, val)
2113 def __init__(self, a, b, val=0):
2114 self.a = a
2115 self.b = b
2116 def __repr__(self):
2117 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2118
2119 for p in pickle, cPickle:
2120 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002121 if verbose:
2122 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002123
2124 for cls in C, C1, C2:
2125 s = p.dumps(cls, bin)
2126 cls2 = p.loads(s)
2127 verify(cls2 is cls)
2128
2129 a = C1(1, 2); a.append(42); a.append(24)
2130 b = C2("hello", "world", 42)
2131 s = p.dumps((a, b), bin)
2132 x, y = p.loads(s)
2133 assert x.__class__ == a.__class__
2134 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2135 assert y.__class__ == b.__class__
2136 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2137 assert `x` == `a`
2138 assert `y` == `b`
2139 if verbose:
2140 print "a = x =", a
2141 print "b = y =", b
2142
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002143 # Testing copy.deepcopy()
2144 if verbose:
2145 print "deepcopy"
2146 import copy
2147 for cls in C, C1, C2:
2148 cls2 = copy.deepcopy(cls)
2149 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002150
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002151 a = C1(1, 2); a.append(42); a.append(24)
2152 b = C2("hello", "world", 42)
2153 x, y = copy.deepcopy((a, b))
2154 assert x.__class__ == a.__class__
2155 assert sorteditems(x.__dict__) == sorteditems(a.__dict__)
2156 assert y.__class__ == b.__class__
2157 assert sorteditems(y.__dict__) == sorteditems(b.__dict__)
2158 assert `x` == `a`
2159 assert `y` == `b`
2160 if verbose:
2161 print "a = x =", a
2162 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002163
2164def copies():
2165 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2166 import copy
2167 class C(object):
2168 pass
2169
2170 a = C()
2171 a.foo = 12
2172 b = copy.copy(a)
2173 verify(b.__dict__ == a.__dict__)
2174
2175 a.bar = [1,2,3]
2176 c = copy.copy(a)
2177 verify(c.bar == a.bar)
2178 verify(c.bar is a.bar)
2179
2180 d = copy.deepcopy(a)
2181 verify(d.__dict__ == a.__dict__)
2182 a.bar.append(4)
2183 verify(d.bar == [1,2,3])
2184
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002185def binopoverride():
2186 if verbose: print "Testing overrides of binary operations..."
2187 class I(int):
2188 def __repr__(self):
2189 return "I(%r)" % int(self)
2190 def __add__(self, other):
2191 return I(int(self) + int(other))
2192 __radd__ = __add__
2193 def __pow__(self, other, mod=None):
2194 if mod is None:
2195 return I(pow(int(self), int(other)))
2196 else:
2197 return I(pow(int(self), int(other), int(mod)))
2198 def __rpow__(self, other, mod=None):
2199 if mod is None:
2200 return I(pow(int(other), int(self), mod))
2201 else:
2202 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00002203
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002204 vereq(`I(1) + I(2)`, "I(3)")
2205 vereq(`I(1) + 2`, "I(3)")
2206 vereq(`1 + I(2)`, "I(3)")
2207 vereq(`I(2) ** I(3)`, "I(8)")
2208 vereq(`2 ** I(3)`, "I(8)")
2209 vereq(`I(2) ** 3`, "I(8)")
2210 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2211 class S(str):
2212 def __eq__(self, other):
2213 return self.lower() == other.lower()
2214
Tim Peters0ab085c2001-09-14 00:25:33 +00002215
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002216def test_main():
Tim Peters2f93e282001-10-04 05:27:00 +00002217 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 lists()
2219 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00002220 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00002221 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222 ints()
2223 longs()
2224 floats()
2225 complexes()
2226 spamlists()
2227 spamdicts()
2228 pydicts()
2229 pylists()
2230 metaclass()
2231 pymods()
2232 multi()
2233 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00002234 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235 slots()
2236 dynamics()
2237 errors()
2238 classmethods()
2239 staticmethods()
2240 classic()
2241 compattr()
2242 newslot()
2243 altmro()
2244 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00002245 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00002246 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002247 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002248 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00002249 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002250 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00002251 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00002252 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00002253 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00002254 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00002255 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00002256 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002257 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002258 setclass()
Guido van Rossum3926a632001-09-25 16:25:58 +00002259 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002260 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002261 binopoverride()
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002262 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00002263
Guido van Rossuma56b42b2001-09-20 21:39:07 +00002264if __name__ == "__main__":
2265 test_main()