blob: 401489d6edf9deb225ff75c8375a087a7538e6b8 [file] [log] [blame]
Tim Peters6d6c1a32001-08-02 04:15:00 +00001# Test descriptor-related enhancements
2
Tim Peters59c9a642001-09-13 05:38:56 +00003from test_support import verify, verbose, TestFailed, TESTFN
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
5
6def testunop(a, res, expr="len(a)", meth="__len__"):
7 if verbose: print "checking", expr
8 dict = {'a': a}
9 verify(eval(expr, dict) == res)
10 t = type(a)
11 m = getattr(t, meth)
12 verify(m == t.__dict__[meth])
13 verify(m(a) == res)
14 bm = getattr(a, meth)
15 verify(bm() == res)
16
17def testbinop(a, b, res, expr="a+b", meth="__add__"):
18 if verbose: print "checking", expr
19 dict = {'a': a, 'b': b}
20 verify(eval(expr, dict) == res)
21 t = type(a)
22 m = getattr(t, meth)
23 verify(m == t.__dict__[meth])
24 verify(m(a, b) == res)
25 bm = getattr(a, meth)
26 verify(bm(b) == res)
27
28def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b, 'c': c}
31 verify(eval(expr, dict) == res)
32 t = type(a)
33 m = getattr(t, meth)
34 verify(m == t.__dict__[meth])
35 verify(m(a, b, c) == res)
36 bm = getattr(a, meth)
37 verify(bm(b, c) == res)
38
39def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
40 if verbose: print "checking", stmt
41 dict = {'a': deepcopy(a), 'b': b}
42 exec stmt in dict
43 verify(dict['a'] == res)
44 t = type(a)
45 m = getattr(t, meth)
46 verify(m == t.__dict__[meth])
47 dict['a'] = deepcopy(a)
48 m(dict['a'], b)
49 verify(dict['a'] == res)
50 dict['a'] = deepcopy(a)
51 bm = getattr(dict['a'], meth)
52 bm(b)
53 verify(dict['a'] == res)
54
55def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
56 if verbose: print "checking", stmt
57 dict = {'a': deepcopy(a), 'b': b, 'c': c}
58 exec stmt in dict
59 verify(dict['a'] == res)
60 t = type(a)
61 m = getattr(t, meth)
62 verify(m == t.__dict__[meth])
63 dict['a'] = deepcopy(a)
64 m(dict['a'], b, c)
65 verify(dict['a'] == res)
66 dict['a'] = deepcopy(a)
67 bm = getattr(dict['a'], meth)
68 bm(b, c)
69 verify(dict['a'] == res)
70
71def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
72 if verbose: print "checking", stmt
73 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
74 exec stmt in dict
75 verify(dict['a'] == res)
76 t = type(a)
77 m = getattr(t, meth)
78 verify(m == t.__dict__[meth])
79 dict['a'] = deepcopy(a)
80 m(dict['a'], b, c, d)
81 verify(dict['a'] == res)
82 dict['a'] = deepcopy(a)
83 bm = getattr(dict['a'], meth)
84 bm(b, c, d)
85 verify(dict['a'] == res)
86
87def lists():
88 if verbose: print "Testing list operations..."
89 testbinop([1], [2], [1,2], "a+b", "__add__")
90 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
91 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
92 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
93 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
94 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
95 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
96 testunop([1,2,3], 3, "len(a)", "__len__")
97 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
98 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
99 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
100 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
101
102def dicts():
103 if verbose: print "Testing dict operations..."
104 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
105 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
106 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
107 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
108 d = {1:2,3:4}
109 l1 = []
110 for i in d.keys(): l1.append(i)
111 l = []
112 for i in iter(d): l.append(i)
113 verify(l == l1)
114 l = []
115 for i in d.__iter__(): l.append(i)
116 verify(l == l1)
117 l = []
118 for i in dictionary.__iter__(d): l.append(i)
119 verify(l == l1)
120 d = {1:2, 3:4}
121 testunop(d, 2, "len(a)", "__len__")
122 verify(eval(repr(d), {}) == d)
123 verify(eval(d.__repr__(), {}) == d)
124 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
125
Tim Peters25786c02001-09-02 08:22:48 +0000126def dict_constructor():
127 if verbose:
128 print "Testing dictionary constructor ..."
129 d = dictionary()
130 verify(d == {})
131 d = dictionary({})
132 verify(d == {})
133 d = dictionary(mapping={})
134 verify(d == {})
135 d = dictionary({1: 2, 'a': 'b'})
136 verify(d == {1: 2, 'a': 'b'})
137 for badarg in 0, 0L, 0j, "0", [0], (0,):
138 try:
139 dictionary(badarg)
140 except TypeError:
141 pass
142 else:
143 raise TestFailed("no TypeError from dictionary(%r)" % badarg)
144 try:
145 dictionary(senseless={})
146 except TypeError:
147 pass
148 else:
149 raise TestFailed("no TypeError from dictionary(senseless={}")
150
151 try:
152 dictionary({}, {})
153 except TypeError:
154 pass
155 else:
156 raise TestFailed("no TypeError from dictionary({}, {})")
157
158 class Mapping:
159 dict = {1:2, 3:4, 'a':1j}
160
161 def __getitem__(self, i):
162 return self.dict[i]
163
164 try:
165 dictionary(Mapping())
166 except TypeError:
167 pass
168 else:
169 raise TestFailed("no TypeError from dictionary(incomplete mapping)")
170
171 Mapping.keys = lambda self: self.dict.keys()
172 d = dictionary(mapping=Mapping())
173 verify(d == Mapping.dict)
174
Tim Peters5d2b77c2001-09-03 05:47:38 +0000175def test_dir():
176 if verbose:
177 print "Testing dir() ..."
178 junk = 12
179 verify(dir() == ['junk'])
180 del junk
181
182 # Just make sure these don't blow up!
183 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
184 dir(arg)
185
Tim Peters37a309d2001-09-04 01:20:04 +0000186 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000187 class C:
188 Cdata = 1
189 def Cmethod(self): pass
190
191 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
192 verify(dir(C) == cstuff)
193
194 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
195 verify(dir(c) == cstuff)
196
197 c.cdata = 2
198 c.cmethod = lambda self: 0
199 verify(dir(c) == cstuff + ['cdata', 'cmethod'])
200
201 class A(C):
202 Adata = 1
203 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000204
Tim Peters37a309d2001-09-04 01:20:04 +0000205 astuff = ['Adata', 'Amethod'] + cstuff
206 verify(dir(A) == astuff)
207 a = A()
208 verify(dir(a) == astuff)
209 a.adata = 42
210 a.amethod = lambda self: 3
211 verify(dir(a) == astuff + ['adata', 'amethod'])
212
213 # The same, but with new-style classes. Since these have object as a
214 # base class, a lot more gets sucked in.
215 def interesting(strings):
216 return [s for s in strings if not s.startswith('_')]
217
Tim Peters5d2b77c2001-09-03 05:47:38 +0000218 class C(object):
219 Cdata = 1
220 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000221
222 cstuff = ['Cdata', 'Cmethod']
223 verify(interesting(dir(C)) == cstuff)
224
225 c = C()
226 verify(interesting(dir(c)) == cstuff)
227
228 c.cdata = 2
229 c.cmethod = lambda self: 0
230 verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod'])
231
Tim Peters5d2b77c2001-09-03 05:47:38 +0000232 class A(C):
233 Adata = 1
234 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000235
236 astuff = ['Adata', 'Amethod'] + cstuff
237 verify(interesting(dir(A)) == astuff)
238 a = A()
239 verify(interesting(dir(a)) == astuff)
240 a.adata = 42
241 a.amethod = lambda self: 3
242 verify(interesting(dir(a)) == astuff + ['adata', 'amethod'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000243
Tim Peterscaaff8d2001-09-10 23:12:14 +0000244 # Try a module subclass.
245 import sys
246 class M(type(sys)):
247 pass
248 minstance = M()
249 minstance.b = 2
250 minstance.a = 1
251 verify(dir(minstance) == ['a', 'b'])
252
253 class M2(M):
254 def getdict(self):
255 return "Not a dict!"
256 __dict__ = property(getdict)
257
258 m2instance = M2()
259 m2instance.b = 2
260 m2instance.a = 1
261 verify(m2instance.__dict__ == "Not a dict!")
262 try:
263 dir(m2instance)
264 except TypeError:
265 pass
266
Tim Peters6d6c1a32001-08-02 04:15:00 +0000267binops = {
268 'add': '+',
269 'sub': '-',
270 'mul': '*',
271 'div': '/',
272 'mod': '%',
273 'divmod': 'divmod',
274 'pow': '**',
275 'lshift': '<<',
276 'rshift': '>>',
277 'and': '&',
278 'xor': '^',
279 'or': '|',
280 'cmp': 'cmp',
281 'lt': '<',
282 'le': '<=',
283 'eq': '==',
284 'ne': '!=',
285 'gt': '>',
286 'ge': '>=',
287 }
288
289for name, expr in binops.items():
290 if expr.islower():
291 expr = expr + "(a, b)"
292 else:
293 expr = 'a %s b' % expr
294 binops[name] = expr
295
296unops = {
297 'pos': '+',
298 'neg': '-',
299 'abs': 'abs',
300 'invert': '~',
301 'int': 'int',
302 'long': 'long',
303 'float': 'float',
304 'oct': 'oct',
305 'hex': 'hex',
306 }
307
308for name, expr in unops.items():
309 if expr.islower():
310 expr = expr + "(a)"
311 else:
312 expr = '%s a' % expr
313 unops[name] = expr
314
315def numops(a, b, skip=[]):
316 dict = {'a': a, 'b': b}
317 for name, expr in binops.items():
318 if name not in skip:
319 name = "__%s__" % name
320 if hasattr(a, name):
321 res = eval(expr, dict)
322 testbinop(a, b, res, expr, name)
323 for name, expr in unops.items():
324 name = "__%s__" % name
325 if hasattr(a, name):
326 res = eval(expr, dict)
327 testunop(a, res, expr, name)
328
329def ints():
330 if verbose: print "Testing int operations..."
331 numops(100, 3)
332
333def longs():
334 if verbose: print "Testing long operations..."
335 numops(100L, 3L)
336
337def floats():
338 if verbose: print "Testing float operations..."
339 numops(100.0, 3.0)
340
341def complexes():
342 if verbose: print "Testing complex operations..."
343 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge'])
344 class Number(complex):
345 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000346 def __new__(cls, *args, **kwds):
347 result = complex.__new__(cls, *args)
348 result.prec = kwds.get('prec', 12)
349 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350 def __repr__(self):
351 prec = self.prec
352 if self.imag == 0.0:
353 return "%.*g" % (prec, self.real)
354 if self.real == 0.0:
355 return "%.*gj" % (prec, self.imag)
356 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
357 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000358
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359 a = Number(3.14, prec=6)
360 verify(`a` == "3.14")
361 verify(a.prec == 6)
362
Tim Peters3f996e72001-09-13 19:18:27 +0000363 a = Number(a, prec=2)
364 verify(`a` == "3.1")
365 verify(a.prec == 2)
366
367 a = Number(234.5)
368 verify(`a` == "234.5")
369 verify(a.prec == 12)
370
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371def spamlists():
372 if verbose: print "Testing spamlist operations..."
373 import copy, xxsubtype as spam
374 def spamlist(l, memo=None):
375 import xxsubtype as spam
376 return spam.spamlist(l)
377 # This is an ugly hack:
378 copy._deepcopy_dispatch[spam.spamlist] = spamlist
379
380 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
381 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
382 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
383 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
384 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
385 "a[b:c]", "__getslice__")
386 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
387 "a+=b", "__iadd__")
388 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
389 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
390 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
391 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
392 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
393 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
394 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
395 # Test subclassing
396 class C(spam.spamlist):
397 def foo(self): return 1
398 a = C()
399 verify(a == [])
400 verify(a.foo() == 1)
401 a.append(100)
402 verify(a == [100])
403 verify(a.getstate() == 0)
404 a.setstate(42)
405 verify(a.getstate() == 42)
406
407def spamdicts():
408 if verbose: print "Testing spamdict operations..."
409 import copy, xxsubtype as spam
410 def spamdict(d, memo=None):
411 import xxsubtype as spam
412 sd = spam.spamdict()
413 for k, v in d.items(): sd[k] = v
414 return sd
415 # This is an ugly hack:
416 copy._deepcopy_dispatch[spam.spamdict] = spamdict
417
418 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
419 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
420 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
421 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
422 d = spamdict({1:2,3:4})
423 l1 = []
424 for i in d.keys(): l1.append(i)
425 l = []
426 for i in iter(d): l.append(i)
427 verify(l == l1)
428 l = []
429 for i in d.__iter__(): l.append(i)
430 verify(l == l1)
431 l = []
432 for i in type(spamdict({})).__iter__(d): l.append(i)
433 verify(l == l1)
434 straightd = {1:2, 3:4}
435 spamd = spamdict(straightd)
436 testunop(spamd, 2, "len(a)", "__len__")
437 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
438 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
439 "a[b]=c", "__setitem__")
440 # Test subclassing
441 class C(spam.spamdict):
442 def foo(self): return 1
443 a = C()
444 verify(a.items() == [])
445 verify(a.foo() == 1)
446 a['foo'] = 'bar'
447 verify(a.items() == [('foo', 'bar')])
448 verify(a.getstate() == 0)
449 a.setstate(100)
450 verify(a.getstate() == 100)
451
452def pydicts():
453 if verbose: print "Testing Python subclass of dict..."
454 verify(issubclass(dictionary, dictionary))
455 verify(isinstance({}, dictionary))
456 d = dictionary()
457 verify(d == {})
458 verify(d.__class__ is dictionary)
459 verify(isinstance(d, dictionary))
460 class C(dictionary):
461 state = -1
462 def __init__(self, *a, **kw):
463 if a:
464 assert len(a) == 1
465 self.state = a[0]
466 if kw:
467 for k, v in kw.items(): self[v] = k
468 def __getitem__(self, key):
469 return self.get(key, 0)
470 def __setitem__(self, key, value):
471 assert isinstance(key, type(0))
472 dictionary.__setitem__(self, key, value)
473 def setstate(self, state):
474 self.state = state
475 def getstate(self):
476 return self.state
477 verify(issubclass(C, dictionary))
478 a1 = C(12)
479 verify(a1.state == 12)
480 a2 = C(foo=1, bar=2)
481 verify(a2[1] == 'foo' and a2[2] == 'bar')
482 a = C()
483 verify(a.state == -1)
484 verify(a.getstate() == -1)
485 a.setstate(0)
486 verify(a.state == 0)
487 verify(a.getstate() == 0)
488 a.setstate(10)
489 verify(a.state == 10)
490 verify(a.getstate() == 10)
491 verify(a[42] == 0)
492 a[42] = 24
493 verify(a[42] == 24)
494 if verbose: print "pydict stress test ..."
495 N = 50
496 for i in range(N):
497 a[i] = C()
498 for j in range(N):
499 a[i][j] = i*j
500 for i in range(N):
501 for j in range(N):
502 verify(a[i][j] == i*j)
503
504def pylists():
505 if verbose: print "Testing Python subclass of list..."
506 class C(list):
507 def __getitem__(self, i):
508 return list.__getitem__(self, i) + 100
509 def __getslice__(self, i, j):
510 return (i, j)
511 a = C()
512 a.extend([0,1,2])
513 verify(a[0] == 100)
514 verify(a[1] == 101)
515 verify(a[2] == 102)
516 verify(a[100:200] == (100,200))
517
518def metaclass():
519 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000520 class C:
521 __metaclass__ = type
522 def __init__(self):
523 self.__state = 0
524 def getstate(self):
525 return self.__state
526 def setstate(self, state):
527 self.__state = state
528 a = C()
529 verify(a.getstate() == 0)
530 a.setstate(10)
531 verify(a.getstate() == 10)
532 class D:
533 class __metaclass__(type):
534 def myself(cls): return cls
535 verify(D.myself() == D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000536 d = D()
537 verify(d.__class__ is D)
538 class M1(type):
539 def __new__(cls, name, bases, dict):
540 dict['__spam__'] = 1
541 return type.__new__(cls, name, bases, dict)
542 class C:
543 __metaclass__ = M1
544 verify(C.__spam__ == 1)
545 c = C()
546 verify(c.__spam__ == 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000547
Guido van Rossum309b5662001-08-17 11:43:17 +0000548 class _instance(object):
549 pass
550 class M2(object):
551 def __new__(cls, name, bases, dict):
552 self = object.__new__(cls)
553 self.name = name
554 self.bases = bases
555 self.dict = dict
556 return self
557 __new__ = staticmethod(__new__)
558 def __call__(self):
559 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000560 # Early binding of methods
561 for key in self.dict:
562 if key.startswith("__"):
563 continue
564 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000565 return it
566 class C:
567 __metaclass__ = M2
568 def spam(self):
569 return 42
570 verify(C.name == 'C')
571 verify(C.bases == ())
572 verify('spam' in C.dict)
573 c = C()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000574 verify(c.spam() == 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000575
Guido van Rossum91ee7982001-08-30 20:52:40 +0000576 # More metaclass examples
577
578 class autosuper(type):
579 # Automatically add __super to the class
580 # This trick only works for dynamic classes
581 # so we force __dynamic__ = 1
582 def __new__(metaclass, name, bases, dict):
583 # XXX Should check that name isn't already a base class name
584 dict["__dynamic__"] = 1
585 cls = super(autosuper, metaclass).__new__(metaclass,
586 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000587 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000588 while name[:1] == "_":
589 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000590 if name:
591 name = "_%s__super" % name
592 else:
593 name = "__super"
594 setattr(cls, name, super(cls))
595 return cls
596 class A:
597 __metaclass__ = autosuper
598 def meth(self):
599 return "A"
600 class B(A):
601 def meth(self):
602 return "B" + self.__super.meth()
603 class C(A):
604 def meth(self):
605 return "C" + self.__super.meth()
606 class D(C, B):
607 def meth(self):
608 return "D" + self.__super.meth()
609 verify(D().meth() == "DCBA")
610 class E(B, C):
611 def meth(self):
612 return "E" + self.__super.meth()
613 verify(E().meth() == "EBCA")
614
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000615 class autoproperty(type):
616 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000617 # named _get_x and/or _set_x are found
618 def __new__(metaclass, name, bases, dict):
619 hits = {}
620 for key, val in dict.iteritems():
621 if key.startswith("_get_"):
622 key = key[5:]
623 get, set = hits.get(key, (None, None))
624 get = val
625 hits[key] = get, set
626 elif key.startswith("_set_"):
627 key = key[5:]
628 get, set = hits.get(key, (None, None))
629 set = val
630 hits[key] = get, set
631 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000632 dict[key] = property(get, set)
633 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000634 name, bases, dict)
635 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000636 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000637 def _get_x(self):
638 return -self.__x
639 def _set_x(self, x):
640 self.__x = -x
641 a = A()
642 verify(not hasattr(a, "x"))
643 a.x = 12
644 verify(a.x == 12)
645 verify(a._A__x == -12)
646
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000647 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000648 # Merge of multiple cooperating metaclasses
649 pass
650 class A:
651 __metaclass__ = multimetaclass
652 def _get_x(self):
653 return "A"
654 class B(A):
655 def _get_x(self):
656 return "B" + self.__super._get_x()
657 class C(A):
658 def _get_x(self):
659 return "C" + self.__super._get_x()
660 class D(C, B):
661 def _get_x(self):
662 return "D" + self.__super._get_x()
663 verify(D().x == "DCBA")
664
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665def pymods():
666 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000668 import sys
669 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670 class MM(MT):
671 def __init__(self):
672 MT.__init__(self)
673 def __getattr__(self, name):
674 log.append(("getattr", name))
675 return MT.__getattr__(self, name)
676 def __setattr__(self, name, value):
677 log.append(("setattr", name, value))
678 MT.__setattr__(self, name, value)
679 def __delattr__(self, name):
680 log.append(("delattr", name))
681 MT.__delattr__(self, name)
682 a = MM()
683 a.foo = 12
684 x = a.foo
685 del a.foo
Guido van Rossumce129a52001-08-28 18:23:24 +0000686 verify(log == [("setattr", "foo", 12),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687 ("getattr", "foo"),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 ("delattr", "foo")], log)
689
690def multi():
691 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692 class C(object):
693 def __init__(self):
694 self.__state = 0
695 def getstate(self):
696 return self.__state
697 def setstate(self, state):
698 self.__state = state
699 a = C()
700 verify(a.getstate() == 0)
701 a.setstate(10)
702 verify(a.getstate() == 10)
703 class D(dictionary, C):
704 def __init__(self):
705 type({}).__init__(self)
706 C.__init__(self)
707 d = D()
708 verify(d.keys() == [])
709 d["hello"] = "world"
710 verify(d.items() == [("hello", "world")])
711 verify(d["hello"] == "world")
712 verify(d.getstate() == 0)
713 d.setstate(10)
714 verify(d.getstate() == 10)
715 verify(D.__mro__ == (D, dictionary, C, object))
716
Guido van Rossume45763a2001-08-10 21:28:46 +0000717 # SF bug #442833
718 class Node(object):
719 def __int__(self):
720 return int(self.foo())
721 def foo(self):
722 return "23"
723 class Frag(Node, list):
724 def foo(self):
725 return "42"
726 verify(Node().__int__() == 23)
727 verify(int(Node()) == 23)
728 verify(Frag().__int__() == 42)
729 verify(int(Frag()) == 42)
730
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731def diamond():
732 if verbose: print "Testing multiple inheritance special cases..."
733 class A(object):
734 def spam(self): return "A"
735 verify(A().spam() == "A")
736 class B(A):
737 def boo(self): return "B"
738 def spam(self): return "B"
739 verify(B().spam() == "B")
740 verify(B().boo() == "B")
741 class C(A):
742 def boo(self): return "C"
743 verify(C().spam() == "A")
744 verify(C().boo() == "C")
745 class D(B, C): pass
746 verify(D().spam() == "B")
747 verify(D().boo() == "B")
748 verify(D.__mro__ == (D, B, C, A, object))
749 class E(C, B): pass
750 verify(E().spam() == "B")
751 verify(E().boo() == "C")
752 verify(E.__mro__ == (E, C, B, A, object))
753 class F(D, E): pass
754 verify(F().spam() == "B")
755 verify(F().boo() == "B")
756 verify(F.__mro__ == (F, D, E, B, C, A, object))
757 class G(E, D): pass
758 verify(G().spam() == "B")
759 verify(G().boo() == "C")
760 verify(G.__mro__ == (G, E, D, C, B, A, object))
761
Guido van Rossum37202612001-08-09 19:45:21 +0000762def objects():
763 if verbose: print "Testing object class..."
764 a = object()
765 verify(a.__class__ == object == type(a))
766 b = object()
767 verify(a is not b)
768 verify(not hasattr(a, "foo"))
769 try:
770 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000771 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000772 pass
773 else:
774 verify(0, "object() should not allow setting a foo attribute")
775 verify(not hasattr(object(), "__dict__"))
776
777 class Cdict(object):
778 pass
779 x = Cdict()
780 verify(x.__dict__ is None)
781 x.foo = 1
782 verify(x.foo == 1)
783 verify(x.__dict__ == {'foo': 1})
784
Tim Peters6d6c1a32001-08-02 04:15:00 +0000785def slots():
786 if verbose: print "Testing __slots__..."
787 class C0(object):
788 __slots__ = []
789 x = C0()
790 verify(not hasattr(x, "__dict__"))
791 verify(not hasattr(x, "foo"))
792
793 class C1(object):
794 __slots__ = ['a']
795 x = C1()
796 verify(not hasattr(x, "__dict__"))
797 verify(x.a == None)
798 x.a = 1
799 verify(x.a == 1)
800 del x.a
801 verify(x.a == None)
802
803 class C3(object):
804 __slots__ = ['a', 'b', 'c']
805 x = C3()
806 verify(not hasattr(x, "__dict__"))
807 verify(x.a is None)
808 verify(x.b is None)
809 verify(x.c is None)
810 x.a = 1
811 x.b = 2
812 x.c = 3
813 verify(x.a == 1)
814 verify(x.b == 2)
815 verify(x.c == 3)
816
817def dynamics():
818 if verbose: print "Testing __dynamic__..."
819 verify(object.__dynamic__ == 0)
820 verify(list.__dynamic__ == 0)
821 class S1:
822 __metaclass__ = type
823 verify(S1.__dynamic__ == 0)
824 class S(object):
825 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000826 verify(S.__dynamic__ == 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 class D(object):
828 __dynamic__ = 1
829 verify(D.__dynamic__ == 1)
830 class E(D, S):
831 pass
832 verify(E.__dynamic__ == 1)
833 class F(S, D):
834 pass
835 verify(F.__dynamic__ == 1)
836 try:
837 S.foo = 1
838 except (AttributeError, TypeError):
839 pass
840 else:
841 verify(0, "assignment to a static class attribute should be illegal")
842 D.foo = 1
843 verify(D.foo == 1)
844 # Test that dynamic attributes are inherited
845 verify(E.foo == 1)
846 verify(F.foo == 1)
847 class SS(D):
848 __dynamic__ = 0
849 verify(SS.__dynamic__ == 0)
850 verify(SS.foo == 1)
851 try:
852 SS.foo = 1
853 except (AttributeError, TypeError):
854 pass
855 else:
856 verify(0, "assignment to SS.foo should be illegal")
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000857 # Test dynamic instances
858 class C(object):
859 __dynamic__ = 1
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000860 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +0000861 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000862 C.foobar = 2
863 verify(a.foobar == 2)
864 C.method = lambda self: 42
865 verify(a.method() == 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +0000866 C.__repr__ = lambda self: "C()"
867 verify(repr(a) == "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +0000868 C.__int__ = lambda self: 100
869 verify(int(a) == 100)
870 verify(a.foobar == 2)
871 verify(not hasattr(a, "spam"))
872 def mygetattr(self, name):
873 if name == "spam":
874 return "spam"
875 else:
876 return object.__getattr__(self, name)
877 C.__getattr__ = mygetattr
878 verify(a.spam == "spam")
879 a.new = 12
880 verify(a.new == 12)
881 def mysetattr(self, name, value):
882 if name == "spam":
883 raise AttributeError
884 return object.__setattr__(self, name, value)
885 C.__setattr__ = mysetattr
886 try:
887 a.spam = "not spam"
888 except AttributeError:
889 pass
890 else:
891 verify(0, "expected AttributeError")
892 verify(a.spam == "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +0000893 class D(C):
894 pass
895 d = D()
896 d.foo = 1
897 verify(d.foo == 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898
Guido van Rossum7e35d572001-09-15 03:14:32 +0000899 # Test handling of int*seq and seq*int
900 class I(int):
901 __dynamic__ = 1
902 verify("a"*I(2) == "aa")
903 verify(I(2)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000904 verify(2*I(3) == 6)
905 verify(I(3)*2 == 6)
906 verify(I(3)*I(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000907
908 # Test handling of long*seq and seq*long
909 class L(long):
910 __dynamic__ = 1
911 verify("a"*L(2L) == "aa")
912 verify(L(2L)*"a" == "aa")
Tim Peterse0007822001-09-15 06:35:55 +0000913 verify(2*L(3) == 6)
914 verify(L(3)*2 == 6)
915 verify(L(3)*L(2) == 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +0000916
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917def errors():
918 if verbose: print "Testing errors..."
919
920 try:
921 class C(list, dictionary):
922 pass
923 except TypeError:
924 pass
925 else:
926 verify(0, "inheritance from both list and dict should be illegal")
927
928 try:
929 class C(object, None):
930 pass
931 except TypeError:
932 pass
933 else:
934 verify(0, "inheritance from non-type should be illegal")
935 class Classic:
936 pass
937
938 try:
939 class C(object, Classic):
940 pass
941 except TypeError:
942 pass
943 else:
944 verify(0, "inheritance from object and Classic should be illegal")
945
946 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000947 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000948 pass
949 except TypeError:
950 pass
951 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +0000952 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953
954 try:
955 class C(object):
956 __slots__ = 1
957 except TypeError:
958 pass
959 else:
960 verify(0, "__slots__ = 1 should be illegal")
961
962 try:
963 class C(object):
964 __slots__ = [1]
965 except TypeError:
966 pass
967 else:
968 verify(0, "__slots__ = [1] should be illegal")
969
970def classmethods():
971 if verbose: print "Testing class methods..."
972 class C(object):
973 def foo(*a): return a
974 goo = classmethod(foo)
975 c = C()
976 verify(C.goo(1) == (C, 1))
977 verify(c.goo(1) == (C, 1))
978 verify(c.foo(1) == (c, 1))
979 class D(C):
980 pass
981 d = D()
982 verify(D.goo(1) == (D, 1))
983 verify(d.goo(1) == (D, 1))
984 verify(d.foo(1) == (d, 1))
985 verify(D.foo(d, 1) == (d, 1))
986
987def staticmethods():
988 if verbose: print "Testing static methods..."
989 class C(object):
990 def foo(*a): return a
991 goo = staticmethod(foo)
992 c = C()
993 verify(C.goo(1) == (1,))
994 verify(c.goo(1) == (1,))
995 verify(c.foo(1) == (c, 1,))
996 class D(C):
997 pass
998 d = D()
999 verify(D.goo(1) == (1,))
1000 verify(d.goo(1) == (1,))
1001 verify(d.foo(1) == (d, 1))
1002 verify(D.foo(d, 1) == (d, 1))
1003
1004def classic():
1005 if verbose: print "Testing classic classes..."
1006 class C:
1007 def foo(*a): return a
1008 goo = classmethod(foo)
1009 c = C()
1010 verify(C.goo(1) == (C, 1))
1011 verify(c.goo(1) == (C, 1))
1012 verify(c.foo(1) == (c, 1))
1013 class D(C):
1014 pass
1015 d = D()
1016 verify(D.goo(1) == (D, 1))
1017 verify(d.goo(1) == (D, 1))
1018 verify(d.foo(1) == (d, 1))
1019 verify(D.foo(d, 1) == (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001020 class E: # *not* subclassing from C
1021 foo = C.foo
1022 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001023 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024
1025def compattr():
1026 if verbose: print "Testing computed attributes..."
1027 class C(object):
1028 class computed_attribute(object):
1029 def __init__(self, get, set=None):
1030 self.__get = get
1031 self.__set = set
1032 def __get__(self, obj, type=None):
1033 return self.__get(obj)
1034 def __set__(self, obj, value):
1035 return self.__set(obj, value)
1036 def __init__(self):
1037 self.__x = 0
1038 def __get_x(self):
1039 x = self.__x
1040 self.__x = x+1
1041 return x
1042 def __set_x(self, x):
1043 self.__x = x
1044 x = computed_attribute(__get_x, __set_x)
1045 a = C()
1046 verify(a.x == 0)
1047 verify(a.x == 1)
1048 a.x = 10
1049 verify(a.x == 10)
1050 verify(a.x == 11)
1051
1052def newslot():
1053 if verbose: print "Testing __new__ slot override..."
1054 class C(list):
1055 def __new__(cls):
1056 self = list.__new__(cls)
1057 self.foo = 1
1058 return self
1059 def __init__(self):
1060 self.foo = self.foo + 2
1061 a = C()
1062 verify(a.foo == 3)
1063 verify(a.__class__ is C)
1064 class D(C):
1065 pass
1066 b = D()
1067 verify(b.foo == 3)
1068 verify(b.__class__ is D)
1069
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070def altmro():
1071 if verbose: print "Testing mro() and overriding it..."
1072 class A(object):
1073 def f(self): return "A"
1074 class B(A):
1075 pass
1076 class C(A):
1077 def f(self): return "C"
1078 class D(B, C):
1079 pass
1080 verify(D.mro() == [D, B, C, A, object] == list(D.__mro__))
1081 verify(D().f() == "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001082 class PerverseMetaType(type):
1083 def mro(cls):
1084 L = type.mro(cls)
1085 L.reverse()
1086 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 class X(A,B,C,D):
1088 __metaclass__ = PerverseMetaType
1089 verify(X.__mro__ == (object, A, C, B, D, X))
1090 verify(X().f() == "A")
1091
1092def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001093 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094
1095 class B(object):
1096 "Intermediate class because object doesn't have a __setattr__"
1097
1098 class C(B):
1099
1100 def __getattr__(self, name):
1101 if name == "foo":
1102 return ("getattr", name)
1103 else:
1104 return B.__getattr__(self, name)
1105 def __setattr__(self, name, value):
1106 if name == "foo":
1107 self.setattr = (name, value)
1108 else:
1109 return B.__setattr__(self, name, value)
1110 def __delattr__(self, name):
1111 if name == "foo":
1112 self.delattr = name
1113 else:
1114 return B.__delattr__(self, name)
1115
1116 def __getitem__(self, key):
1117 return ("getitem", key)
1118 def __setitem__(self, key, value):
1119 self.setitem = (key, value)
1120 def __delitem__(self, key):
1121 self.delitem = key
1122
1123 def __getslice__(self, i, j):
1124 return ("getslice", i, j)
1125 def __setslice__(self, i, j, value):
1126 self.setslice = (i, j, value)
1127 def __delslice__(self, i, j):
1128 self.delslice = (i, j)
1129
1130 a = C()
1131 verify(a.foo == ("getattr", "foo"))
1132 a.foo = 12
1133 verify(a.setattr == ("foo", 12))
1134 del a.foo
1135 verify(a.delattr == "foo")
1136
1137 verify(a[12] == ("getitem", 12))
1138 a[12] = 21
1139 verify(a.setitem == (12, 21))
1140 del a[12]
1141 verify(a.delitem == 12)
1142
1143 verify(a[0:10] == ("getslice", 0, 10))
1144 a[0:10] = "foo"
1145 verify(a.setslice == (0, 10, "foo"))
1146 del a[0:10]
1147 verify(a.delslice == (0, 10))
1148
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001149def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001150 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001151 class C(object):
1152 def __init__(self, x):
1153 self.x = x
1154 def foo(self):
1155 return self.x
1156 c1 = C(1)
1157 verify(c1.foo() == 1)
1158 class D(C):
1159 boo = C.foo
1160 goo = c1.foo
1161 d2 = D(2)
1162 verify(d2.foo() == 2)
1163 verify(d2.boo() == 2)
Guido van Rossum501c7c72001-08-16 20:41:56 +00001164 verify(d2.goo() == 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001165 class E(object):
1166 foo = C.foo
1167 verify(E().foo == C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001168 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001169
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001170def specials():
1171 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001172 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001173 # Test the default behavior for static classes
1174 class C(object):
1175 def __getitem__(self, i):
1176 if 0 <= i < 10: return i
1177 raise IndexError
1178 c1 = C()
1179 c2 = C()
1180 verify(not not c1)
1181 verify(hash(c1) == id(c1))
1182 verify(cmp(c1, c2) == cmp(id(c1), id(c2)))
1183 verify(c1 == c1)
1184 verify(c1 != c2)
1185 verify(not c1 != c1)
1186 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001187 # Note that the module name appears in str/repr, and that varies
1188 # depending on whether this test is run standalone or from a framework.
1189 verify(str(c1).find('C instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001190 verify(str(c1) == repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001191 verify(-1 not in c1)
1192 for i in range(10):
1193 verify(i in c1)
1194 verify(10 not in c1)
1195 # Test the default behavior for dynamic classes
1196 class D(object):
1197 __dynamic__ = 1
1198 def __getitem__(self, i):
1199 if 0 <= i < 10: return i
1200 raise IndexError
1201 d1 = D()
1202 d2 = D()
1203 verify(not not d1)
1204 verify(hash(d1) == id(d1))
1205 verify(cmp(d1, d2) == cmp(id(d1), id(d2)))
1206 verify(d1 == d1)
1207 verify(d1 != d2)
1208 verify(not d1 != d1)
1209 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001210 # Note that the module name appears in str/repr, and that varies
1211 # depending on whether this test is run standalone or from a framework.
1212 verify(str(d1).find('D instance at ') >= 0)
Tim Peters63a8d692001-08-16 16:56:16 +00001213 verify(str(d1) == repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001214 verify(-1 not in d1)
1215 for i in range(10):
1216 verify(i in d1)
1217 verify(10 not in d1)
1218 # Test overridden behavior for static classes
1219 class Proxy(object):
1220 def __init__(self, x):
1221 self.x = x
1222 def __nonzero__(self):
1223 return not not self.x
1224 def __hash__(self):
1225 return hash(self.x)
1226 def __eq__(self, other):
1227 return self.x == other
1228 def __ne__(self, other):
1229 return self.x != other
1230 def __cmp__(self, other):
1231 return cmp(self.x, other.x)
1232 def __str__(self):
1233 return "Proxy:%s" % self.x
1234 def __repr__(self):
1235 return "Proxy(%r)" % self.x
1236 def __contains__(self, value):
1237 return value in self.x
1238 p0 = Proxy(0)
1239 p1 = Proxy(1)
1240 p_1 = Proxy(-1)
1241 verify(not p0)
1242 verify(not not p1)
1243 verify(hash(p0) == hash(0))
1244 verify(p0 == p0)
1245 verify(p0 != p1)
1246 verify(not p0 != p0)
1247 verify(not p0 == p1)
1248 verify(cmp(p0, p1) == -1)
1249 verify(cmp(p0, p0) == 0)
1250 verify(cmp(p0, p_1) == 1)
1251 verify(str(p0) == "Proxy:0")
1252 verify(repr(p0) == "Proxy(0)")
1253 p10 = Proxy(range(10))
1254 verify(-1 not in p10)
1255 for i in range(10):
1256 verify(i in p10)
1257 verify(10 not in p10)
1258 # Test overridden behavior for dynamic classes
1259 class DProxy(object):
1260 __dynamic__ = 1
1261 def __init__(self, x):
1262 self.x = x
1263 def __nonzero__(self):
1264 return not not self.x
1265 def __hash__(self):
1266 return hash(self.x)
1267 def __eq__(self, other):
1268 return self.x == other
1269 def __ne__(self, other):
1270 return self.x != other
1271 def __cmp__(self, other):
1272 return cmp(self.x, other.x)
1273 def __str__(self):
1274 return "DProxy:%s" % self.x
1275 def __repr__(self):
1276 return "DProxy(%r)" % self.x
1277 def __contains__(self, value):
1278 return value in self.x
1279 p0 = DProxy(0)
1280 p1 = DProxy(1)
1281 p_1 = DProxy(-1)
1282 verify(not p0)
1283 verify(not not p1)
1284 verify(hash(p0) == hash(0))
1285 verify(p0 == p0)
1286 verify(p0 != p1)
1287 verify(not p0 != p0)
1288 verify(not p0 == p1)
1289 verify(cmp(p0, p1) == -1)
1290 verify(cmp(p0, p0) == 0)
1291 verify(cmp(p0, p_1) == 1)
1292 verify(str(p0) == "DProxy:0")
1293 verify(repr(p0) == "DProxy(0)")
1294 p10 = DProxy(range(10))
1295 verify(-1 not in p10)
1296 for i in range(10):
1297 verify(i in p10)
1298 verify(10 not in p10)
1299
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001300def weakrefs():
1301 if verbose: print "Testing weak references..."
1302 import weakref
1303 class C(object):
1304 pass
1305 c = C()
1306 r = weakref.ref(c)
1307 verify(r() is c)
1308 del c
1309 verify(r() is None)
1310 del r
1311 class NoWeak(object):
1312 __slots__ = ['foo']
1313 no = NoWeak()
1314 try:
1315 weakref.ref(no)
1316 except TypeError, msg:
1317 verify(str(msg).find("weakly") >= 0)
1318 else:
1319 verify(0, "weakref.ref(no) should be illegal")
1320 class Weak(object):
1321 __slots__ = ['foo', '__weakref__']
1322 yes = Weak()
1323 r = weakref.ref(yes)
1324 verify(r() is yes)
1325 del yes
1326 verify(r() is None)
1327 del r
1328
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001329def properties():
1330 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001331 class C(object):
1332 def getx(self):
1333 return self.__x
1334 def setx(self, value):
1335 self.__x = value
1336 def delx(self):
1337 del self.__x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001338 x = property(getx, setx, delx)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001339 a = C()
1340 verify(not hasattr(a, "x"))
1341 a.x = 42
1342 verify(a._C__x == 42)
1343 verify(a.x == 42)
1344 del a.x
1345 verify(not hasattr(a, "x"))
1346 verify(not hasattr(a, "_C__x"))
1347 C.x.__set__(a, 100)
1348 verify(C.x.__get__(a) == 100)
1349## C.x.__set__(a)
1350## verify(not hasattr(a, "x"))
1351
Guido van Rossumc4a18802001-08-24 16:55:27 +00001352def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001353 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001354
1355 class A(object):
1356 def meth(self, a):
1357 return "A(%r)" % a
1358
1359 verify(A().meth(1) == "A(1)")
1360
1361 class B(A):
1362 def __init__(self):
1363 self.__super = super(B, self)
1364 def meth(self, a):
1365 return "B(%r)" % a + self.__super.meth(a)
1366
1367 verify(B().meth(2) == "B(2)A(2)")
1368
1369 class C(A):
1370 __dynamic__ = 1
1371 def meth(self, a):
1372 return "C(%r)" % a + self.__super.meth(a)
1373 C._C__super = super(C)
1374
1375 verify(C().meth(3) == "C(3)A(3)")
1376
1377 class D(C, B):
1378 def meth(self, a):
1379 return "D(%r)" % a + super(D, self).meth(a)
1380
1381 verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
1382
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001383def inherits():
1384 if verbose: print "Testing inheritance from basic types..."
1385
1386 class hexint(int):
1387 def __repr__(self):
1388 return hex(self)
1389 def __add__(self, other):
1390 return hexint(int.__add__(self, other))
1391 # (Note that overriding __radd__ doesn't work,
1392 # because the int type gets first dibs.)
1393 verify(repr(hexint(7) + 9) == "0x10")
1394 verify(repr(hexint(1000) + 7) == "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001395 a = hexint(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001396 #XXX verify(a == 12345)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001397 verify(int(a) == 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001398 verify(int(a).__class__ is int)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001399 verify(hash(a) == hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001400 verify((+a).__class__ is int)
1401 verify((a >> 0).__class__ is int)
1402 verify((a << 0).__class__ is int)
1403 verify((hexint(0) << 12).__class__ is int)
1404 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001405
1406 class octlong(long):
1407 __slots__ = []
1408 def __str__(self):
1409 s = oct(self)
1410 if s[-1] == 'L':
1411 s = s[:-1]
1412 return s
1413 def __add__(self, other):
1414 return self.__class__(super(octlong, self).__add__(other))
1415 __radd__ = __add__
1416 verify(str(octlong(3) + 5) == "010")
1417 # (Note that overriding __radd__ here only seems to work
1418 # because the example uses a short int left argument.)
1419 verify(str(5 + octlong(3000)) == "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001420 a = octlong(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001421 #XXX verify(a == 12345L)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001422 verify(long(a) == 12345L)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001423 verify(hash(a) == hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001424 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001425 verify((+a).__class__ is long)
1426 verify((-a).__class__ is long)
1427 verify((-octlong(0)).__class__ is long)
1428 verify((a >> 0).__class__ is long)
1429 verify((a << 0).__class__ is long)
1430 verify((a - 0).__class__ is long)
1431 verify((a * 1).__class__ is long)
1432 verify((a ** 1).__class__ is long)
1433 verify((a // 1).__class__ is long)
1434 verify((1 * a).__class__ is long)
1435 verify((a | 0).__class__ is long)
1436 verify((a ^ 0).__class__ is long)
1437 verify((a & -1L).__class__ is long)
1438 verify((octlong(0) << 12).__class__ is long)
1439 verify((octlong(0) >> 12).__class__ is long)
1440 verify(abs(octlong(0)).__class__ is long)
1441
1442 # Because octlong overrides __add__, we can't check the absence of +0
1443 # optimizations using octlong.
1444 class longclone(long):
1445 pass
1446 a = longclone(1)
1447 verify((a + 0).__class__ is long)
1448 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001449
1450 class precfloat(float):
1451 __slots__ = ['prec']
1452 def __init__(self, value=0.0, prec=12):
1453 self.prec = int(prec)
1454 float.__init__(value)
1455 def __repr__(self):
1456 return "%.*g" % (self.prec, self)
1457 verify(repr(precfloat(1.1)) == "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001458 a = precfloat(12345)
Tim Peters4f467e82001-09-12 19:53:15 +00001459 #XXX verify(a == 12345.0)
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001460 verify(float(a) == 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001461 verify(float(a).__class__ is float)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001462 verify(hash(a) == hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001463 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001464
Tim Peters2400fa42001-09-12 19:12:49 +00001465 class madcomplex(complex):
1466 def __repr__(self):
1467 return "%.17gj%+.17g" % (self.imag, self.real)
1468 a = madcomplex(-3, 4)
1469 verify(repr(a) == "4j-3")
1470 base = complex(-3, 4)
1471 verify(base.__class__ is complex)
Tim Peters4f467e82001-09-12 19:53:15 +00001472 #XXX verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001473 verify(complex(a) == base)
1474 verify(complex(a).__class__ is complex)
1475 a = madcomplex(a) # just trying another form of the constructor
1476 verify(repr(a) == "4j-3")
Tim Peters4f467e82001-09-12 19:53:15 +00001477 #XXX verify(a == base)
Tim Peters2400fa42001-09-12 19:12:49 +00001478 verify(complex(a) == base)
1479 verify(complex(a).__class__ is complex)
1480 verify(hash(a) == hash(base))
1481 verify((+a).__class__ is complex)
1482 verify((a + 0).__class__ is complex)
1483 verify(a + 0 == base)
1484 verify((a - 0).__class__ is complex)
1485 verify(a - 0 == base)
1486 verify((a * 1).__class__ is complex)
1487 verify(a * 1 == base)
1488 verify((a / 1).__class__ is complex)
1489 verify(a / 1 == base)
1490
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001491 class madtuple(tuple):
1492 _rev = None
1493 def rev(self):
1494 if self._rev is not None:
1495 return self._rev
1496 L = list(self)
1497 L.reverse()
1498 self._rev = self.__class__(L)
1499 return self._rev
1500 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Tim Peters4f467e82001-09-12 19:53:15 +00001501 verify(a == (1,2,3,4,5,6,7,8,9,0))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001502 verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1)))
1503 verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0)))
1504 for i in range(512):
1505 t = madtuple(range(i))
1506 u = t.rev()
1507 v = u.rev()
1508 verify(v == t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001509 a = madtuple((1,2,3,4,5))
1510 verify(tuple(a) == (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001511 verify(tuple(a).__class__ is tuple)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001512 verify(hash(a) == hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001513 verify(a[:].__class__ is tuple)
1514 verify((a * 1).__class__ is tuple)
1515 verify((a * 0).__class__ is tuple)
1516 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001517 a = madtuple(())
1518 verify(tuple(a) == ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001519 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001520 verify((a + a).__class__ is tuple)
1521 verify((a * 0).__class__ is tuple)
1522 verify((a * 1).__class__ is tuple)
1523 verify((a * 2).__class__ is tuple)
1524 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001525
1526 class madstring(str):
1527 _rev = None
1528 def rev(self):
1529 if self._rev is not None:
1530 return self._rev
1531 L = list(self)
1532 L.reverse()
1533 self._rev = self.__class__("".join(L))
1534 return self._rev
1535 s = madstring("abcdefghijklmnopqrstuvwxyz")
Tim Peters4f467e82001-09-12 19:53:15 +00001536 #XXX verify(s == "abcdefghijklmnopqrstuvwxyz")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001537 verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba"))
1538 verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz"))
1539 for i in range(256):
1540 s = madstring("".join(map(chr, range(i))))
1541 t = s.rev()
1542 u = t.rev()
1543 verify(u == s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001544 s = madstring("12345")
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001545 verify(str(s) == "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001546 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001547
Tim Peters8fa5dd02001-09-12 02:18:30 +00001548 base = "\x00" * 5
1549 s = madstring(base)
Tim Peters4f467e82001-09-12 19:53:15 +00001550 #XXX verify(s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001551 verify(str(s) == base)
Tim Petersc636f562001-09-11 01:52:02 +00001552 verify(str(s).__class__ is str)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001553 verify(hash(s) == hash(base))
Tim Peters0ab085c2001-09-14 00:25:33 +00001554 #XXX verify({s: 1}[base] == 1)
1555 #XXX verify({base: 1}[s] == 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001556 verify((s + "").__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001557 verify(s + "" == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001558 verify(("" + s).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001559 verify("" + s == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001560 verify((s * 0).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001561 verify(s * 0 == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001562 verify((s * 1).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001563 verify(s * 1 == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001564 verify((s * 2).__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001565 verify(s * 2 == base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001566 verify(s[:].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001567 verify(s[:] == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001568 verify(s[0:0].__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001569 verify(s[0:0] == "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001570 verify(s.strip().__class__ is str)
Tim Peters7a29bd52001-09-12 03:03:31 +00001571 verify(s.strip() == base)
1572 verify(s.lstrip().__class__ is str)
1573 verify(s.lstrip() == base)
1574 verify(s.rstrip().__class__ is str)
1575 verify(s.rstrip() == base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001576 identitytab = ''.join([chr(i) for i in range(256)])
1577 verify(s.translate(identitytab).__class__ is str)
1578 verify(s.translate(identitytab) == base)
1579 verify(s.translate(identitytab, "x").__class__ is str)
1580 verify(s.translate(identitytab, "x") == base)
1581 verify(s.translate(identitytab, "\x00") == "")
1582 verify(s.replace("x", "x").__class__ is str)
1583 verify(s.replace("x", "x") == base)
1584 verify(s.ljust(len(s)).__class__ is str)
1585 verify(s.ljust(len(s)) == base)
1586 verify(s.rjust(len(s)).__class__ is str)
1587 verify(s.rjust(len(s)) == base)
1588 verify(s.center(len(s)).__class__ is str)
1589 verify(s.center(len(s)) == base)
Tim Peters7a29bd52001-09-12 03:03:31 +00001590 verify(s.lower().__class__ is str)
1591 verify(s.lower() == base)
Tim Petersc636f562001-09-11 01:52:02 +00001592
Tim Peters111f6092001-09-12 07:54:51 +00001593 s = madstring("x y")
Tim Peters4f467e82001-09-12 19:53:15 +00001594 #XXX verify(s == "x y")
Tim Peters111f6092001-09-12 07:54:51 +00001595 verify(intern(s).__class__ is str)
1596 verify(intern(s) is intern("x y"))
1597 verify(intern(s) == "x y")
1598
1599 i = intern("y x")
1600 s = madstring("y x")
Tim Peters4f467e82001-09-12 19:53:15 +00001601 #XXX verify(s == i)
Tim Peters111f6092001-09-12 07:54:51 +00001602 verify(intern(s).__class__ is str)
1603 verify(intern(s) is i)
1604
1605 s = madstring(i)
1606 verify(intern(s).__class__ is str)
1607 verify(intern(s) is i)
1608
Guido van Rossum91ee7982001-08-30 20:52:40 +00001609 class madunicode(unicode):
1610 _rev = None
1611 def rev(self):
1612 if self._rev is not None:
1613 return self._rev
1614 L = list(self)
1615 L.reverse()
1616 self._rev = self.__class__(u"".join(L))
1617 return self._rev
1618 u = madunicode("ABCDEF")
Tim Peters4f467e82001-09-12 19:53:15 +00001619 verify(u == u"ABCDEF")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001620 verify(u.rev() == madunicode(u"FEDCBA"))
1621 verify(u.rev().rev() == madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00001622 base = u"12345"
1623 u = madunicode(base)
1624 verify(unicode(u) == base)
Tim Peters78e0fc72001-09-11 03:07:38 +00001625 verify(unicode(u).__class__ is unicode)
Tim Petersaf90b3e2001-09-12 05:18:58 +00001626 verify(hash(u) == hash(base))
1627 verify({u: 1}[base] == 1)
1628 verify({base: 1}[u] == 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00001629 verify(u.strip().__class__ is unicode)
1630 verify(u.strip() == base)
1631 verify(u.lstrip().__class__ is unicode)
1632 verify(u.lstrip() == base)
1633 verify(u.rstrip().__class__ is unicode)
1634 verify(u.rstrip() == base)
1635 verify(u.replace(u"x", u"x").__class__ is unicode)
1636 verify(u.replace(u"x", u"x") == base)
1637 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1638 verify(u.replace(u"xy", u"xy") == base)
1639 verify(u.center(len(u)).__class__ is unicode)
1640 verify(u.center(len(u)) == base)
1641 verify(u.ljust(len(u)).__class__ is unicode)
1642 verify(u.ljust(len(u)) == base)
1643 verify(u.rjust(len(u)).__class__ is unicode)
1644 verify(u.rjust(len(u)) == base)
1645 verify(u.lower().__class__ is unicode)
1646 verify(u.lower() == base)
1647 verify(u.upper().__class__ is unicode)
1648 verify(u.upper() == base)
1649 verify(u.capitalize().__class__ is unicode)
1650 verify(u.capitalize() == base)
1651 verify(u.title().__class__ is unicode)
1652 verify(u.title() == base)
1653 verify((u + u"").__class__ is unicode)
1654 verify(u + u"" == base)
1655 verify((u"" + u).__class__ is unicode)
1656 verify(u"" + u == base)
1657 verify((u * 0).__class__ is unicode)
1658 verify(u * 0 == u"")
1659 verify((u * 1).__class__ is unicode)
1660 verify(u * 1 == base)
1661 verify((u * 2).__class__ is unicode)
1662 verify(u * 2 == base + base)
1663 verify(u[:].__class__ is unicode)
1664 verify(u[:] == base)
1665 verify(u[0:0].__class__ is unicode)
1666 verify(u[0:0] == u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00001667
Tim Peters59c9a642001-09-13 05:38:56 +00001668 class CountedInput(file):
1669 """Counts lines read by self.readline().
1670
1671 self.lineno is the 0-based ordinal of the last line read, up to
1672 a maximum of one greater than the number of lines in the file.
1673
1674 self.ateof is true if and only if the final "" line has been read,
1675 at which point self.lineno stops incrementing, and further calls
1676 to readline() continue to return "".
1677 """
1678
1679 lineno = 0
1680 ateof = 0
1681 def readline(self):
1682 if self.ateof:
1683 return ""
1684 s = file.readline(self)
1685 # Next line works too.
1686 # s = super(CountedInput, self).readline()
1687 self.lineno += 1
1688 if s == "":
1689 self.ateof = 1
1690 return s
1691
Tim Peters561f8992001-09-13 19:36:36 +00001692 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00001693 lines = ['a\n', 'b\n', 'c\n']
1694 try:
1695 f.writelines(lines)
1696 f.close()
1697 f = CountedInput(TESTFN)
1698 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
1699 got = f.readline()
1700 verify(expected == got)
1701 verify(f.lineno == i)
1702 verify(f.ateof == (i > len(lines)))
1703 f.close()
1704 finally:
1705 try:
1706 f.close()
1707 except:
1708 pass
1709 try:
1710 import os
1711 os.unlink(TESTFN)
1712 except:
1713 pass
1714
Tim Peters808b94e2001-09-13 19:33:07 +00001715def keywords():
1716 if verbose:
1717 print "Testing keyword args to basic type constructors ..."
1718 verify(int(x=1) == 1)
1719 verify(float(x=2) == 2.0)
1720 verify(long(x=3) == 3L)
1721 verify(complex(imag=42, real=666) == complex(666, 42))
1722 verify(str(object=500) == '500')
1723 verify(unicode(string='abc', errors='strict') == u'abc')
1724 verify(tuple(sequence=range(3)) == (0, 1, 2))
1725 verify(list(sequence=(0, 1, 2)) == range(3))
1726 verify(dictionary(mapping={1: 2}) == {1: 2})
1727
1728 for constructor in (int, float, long, complex, str, unicode,
1729 tuple, list, dictionary, file):
1730 try:
1731 constructor(bogus_keyword_arg=1)
1732 except TypeError:
1733 pass
1734 else:
1735 raise TestFailed("expected TypeError from bogus keyword "
1736 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00001737
Tim Peters8fa45672001-09-13 21:01:29 +00001738def restricted():
1739 import rexec
1740 if verbose:
1741 print "Testing interaction with restricted execution ..."
1742
1743 sandbox = rexec.RExec()
1744
1745 code1 = """f = open(%r, 'w')""" % TESTFN
1746 code2 = """f = file(%r, 'w')""" % TESTFN
1747 code3 = """\
1748f = open(%r)
1749t = type(f) # a sneaky way to get the file() constructor
1750f.close()
1751f = t(%r, 'w') # rexec can't catch this by itself
1752""" % (TESTFN, TESTFN)
1753
1754 f = open(TESTFN, 'w') # Create the file so code3 can find it.
1755 f.close()
1756
1757 try:
1758 for code in code1, code2, code3:
1759 try:
1760 sandbox.r_exec(code)
1761 except IOError, msg:
1762 if str(msg).find("restricted") >= 0:
1763 outcome = "OK"
1764 else:
1765 outcome = "got an exception, but not an expected one"
1766 else:
1767 outcome = "expected a restricted-execution exception"
1768
1769 if outcome != "OK":
1770 raise TestFailed("%s, in %r" % (outcome, code))
1771
1772 finally:
1773 try:
1774 import os
1775 os.unlink(TESTFN)
1776 except:
1777 pass
1778
Tim Peters0ab085c2001-09-14 00:25:33 +00001779def str_subclass_as_dict_key():
1780 if verbose:
1781 print "Testing a str subclass used as dict key .."
1782
1783 class cistr(str):
1784 """Sublcass of str that computes __eq__ case-insensitively.
1785
1786 Also computes a hash code of the string in canonical form.
1787 """
1788
1789 def __init__(self, value):
1790 self.canonical = value.lower()
1791 self.hashcode = hash(self.canonical)
1792
1793 def __eq__(self, other):
1794 if not isinstance(other, cistr):
1795 other = cistr(other)
1796 return self.canonical == other.canonical
1797
1798 def __hash__(self):
1799 return self.hashcode
1800
1801 verify('aBc' == cistr('ABC') == 'abc')
1802 verify(str(cistr('ABC')) == 'ABC')
1803
1804 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
1805 verify(d[cistr('one')] == 1)
1806 verify(d[cistr('tWo')] == 2)
1807 verify(d[cistr('THrEE')] == 3)
1808 verify(cistr('ONe') in d)
1809 verify(d.get(cistr('thrEE')) == 3)
1810
1811
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812def all():
1813 lists()
1814 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00001815 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00001816 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817 ints()
1818 longs()
1819 floats()
1820 complexes()
1821 spamlists()
1822 spamdicts()
1823 pydicts()
1824 pylists()
1825 metaclass()
1826 pymods()
1827 multi()
1828 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00001829 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 slots()
1831 dynamics()
1832 errors()
1833 classmethods()
1834 staticmethods()
1835 classic()
1836 compattr()
1837 newslot()
1838 altmro()
1839 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001840 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001841 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001842 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001843 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00001844 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001845 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00001846 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00001847 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00001848 str_subclass_as_dict_key()
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849
1850all()
1851
1852if verbose: print "All OK"