blob: 1d54c4dba4d038e1af65179fcef709881ef86e82 [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
Armin Rigoc0ba52d2007-04-19 14:44:48 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
Tim Peters4d9b4662002-04-16 01:59:17 +00005import warnings
Armin Rigo9790a272007-05-02 19:23:31 +00006import types
Tim Peters4d9b4662002-04-16 01:59:17 +00007
8warnings.filterwarnings("ignore",
9 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +000010 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Guido van Rossum875eeaa2001-10-11 18:33:53 +000012def veris(a, b):
13 if a is not b:
14 raise TestFailed, "%r is %r" % (a, b)
15
Tim Peters6d6c1a32001-08-02 04:15:00 +000016def testunop(a, res, expr="len(a)", meth="__len__"):
17 if verbose: print "checking", expr
18 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000019 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000020 t = type(a)
21 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000022 while meth not in t.__dict__:
23 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000024 vereq(m, t.__dict__[meth])
25 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000026 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000027 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000028
29def testbinop(a, b, res, expr="a+b", meth="__add__"):
30 if verbose: print "checking", expr
31 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000032
33 # XXX Hack so this passes before 2.3 when -Qnew is specified.
34 if meth == "__div__" and 1/2 == 0.5:
35 meth = "__truediv__"
36
Guido van Rossum45704552001-10-08 16:35:45 +000037 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000038 t = type(a)
39 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000040 while meth not in t.__dict__:
41 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000042 vereq(m, t.__dict__[meth])
43 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000044 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000045 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000046
47def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
48 if verbose: print "checking", expr
49 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000050 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000051 t = type(a)
52 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000053 while meth not in t.__dict__:
54 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000055 vereq(m, t.__dict__[meth])
56 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000057 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000058 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000059
60def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
61 if verbose: print "checking", stmt
62 dict = {'a': deepcopy(a), 'b': b}
63 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000064 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000065 t = type(a)
66 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000067 while meth not in t.__dict__:
68 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000069 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000070 dict['a'] = deepcopy(a)
71 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000072 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000073 dict['a'] = deepcopy(a)
74 bm = getattr(dict['a'], meth)
75 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000076 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000077
78def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
79 if verbose: print "checking", stmt
80 dict = {'a': deepcopy(a), 'b': b, 'c': c}
81 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000082 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000083 t = type(a)
84 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000085 while meth not in t.__dict__:
86 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000087 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000088 dict['a'] = deepcopy(a)
89 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000090 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000091 dict['a'] = deepcopy(a)
92 bm = getattr(dict['a'], meth)
93 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000094 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000095
96def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
97 if verbose: print "checking", stmt
98 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
99 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +0000100 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000102 while meth not in t.__dict__:
103 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000105 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000106 dict['a'] = deepcopy(a)
107 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000108 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000109 dict['a'] = deepcopy(a)
110 bm = getattr(dict['a'], meth)
111 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000112 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000113
Tim Peters2f93e282001-10-04 05:27:00 +0000114def class_docstrings():
115 class Classic:
116 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000117 vereq(Classic.__doc__, "A classic docstring.")
118 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000119
120 class Classic2:
121 pass
122 verify(Classic2.__doc__ is None)
123
Tim Peters4fb1fe82001-10-04 05:48:13 +0000124 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000125 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000126 vereq(NewStatic.__doc__, "Another docstring.")
127 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000128
Tim Peters4fb1fe82001-10-04 05:48:13 +0000129 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000130 pass
131 verify(NewStatic2.__doc__ is None)
132
Tim Peters4fb1fe82001-10-04 05:48:13 +0000133 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000134 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000135 vereq(NewDynamic.__doc__, "Another docstring.")
136 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000137
Tim Peters4fb1fe82001-10-04 05:48:13 +0000138 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000139 pass
140 verify(NewDynamic2.__doc__ is None)
141
Tim Peters6d6c1a32001-08-02 04:15:00 +0000142def lists():
143 if verbose: print "Testing list operations..."
144 testbinop([1], [2], [1,2], "a+b", "__add__")
145 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
146 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
147 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
148 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
149 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
150 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
151 testunop([1,2,3], 3, "len(a)", "__len__")
152 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
153 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
154 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
155 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
156
157def dicts():
158 if verbose: print "Testing dict operations..."
159 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
160 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
161 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
162 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
163 d = {1:2,3:4}
164 l1 = []
165 for i in d.keys(): l1.append(i)
166 l = []
167 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000168 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000169 l = []
170 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000171 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000172 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000173 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000174 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000175 d = {1:2, 3:4}
176 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000177 vereq(eval(repr(d), {}), d)
178 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
180
Tim Peters25786c02001-09-02 08:22:48 +0000181def dict_constructor():
182 if verbose:
Tim Petersa427a2b2001-10-29 22:25:45 +0000183 print "Testing dict constructor ..."
184 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000185 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000186 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000187 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000188 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000189 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000190 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000191 vereq(d, dict(d.iteritems()))
192 d = dict({'one':1, 'two':2})
193 vereq(d, dict(one=1, two=2))
194 vereq(d, dict(**d))
195 vereq(d, dict({"one": 1}, two=2))
196 vereq(d, dict([("two", 2)], one=1))
197 vereq(d, dict([("one", 100), ("two", 200)], **d))
198 verify(d is not dict(**d))
Tim Peters25786c02001-09-02 08:22:48 +0000199 for badarg in 0, 0L, 0j, "0", [0], (0,):
200 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000201 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000202 except TypeError:
203 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000204 except ValueError:
205 if badarg == "0":
206 # It's a sequence, and its elements are also sequences (gotta
207 # love strings <wink>), but they aren't of length 2, so this
208 # one seemed better as a ValueError than a TypeError.
209 pass
210 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000211 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000212 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000213 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000214
215 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000216 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000217 except TypeError:
218 pass
219 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000220 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000221
222 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000223 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000224 dict = {1:2, 3:4, 'a':1j}
225
Tim Peters25786c02001-09-02 08:22:48 +0000226 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000227 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000228 except TypeError:
229 pass
230 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000231 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000232
233 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000234 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000235 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000236 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000237
Tim Peters1fc240e2001-10-26 05:06:50 +0000238 # Init from sequence of iterable objects, each producing a 2-sequence.
239 class AddressBookEntry:
240 def __init__(self, first, last):
241 self.first = first
242 self.last = last
243 def __iter__(self):
244 return iter([self.first, self.last])
245
Tim Petersa427a2b2001-10-29 22:25:45 +0000246 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000247 AddressBookEntry('Barry', 'Peters'),
248 AddressBookEntry('Tim', 'Peters'),
249 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000250 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
251
Tim Petersa427a2b2001-10-29 22:25:45 +0000252 d = dict(zip(range(4), range(1, 5)))
253 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000254
255 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000256 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000257 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000258 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000259 except ValueError:
260 pass
261 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000262 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000263
Tim Peters5d2b77c2001-09-03 05:47:38 +0000264def test_dir():
265 if verbose:
266 print "Testing dir() ..."
267 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000268 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000269 del junk
270
271 # Just make sure these don't blow up!
272 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
273 dir(arg)
274
Tim Peters37a309d2001-09-04 01:20:04 +0000275 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000276 class C:
277 Cdata = 1
278 def Cmethod(self): pass
279
280 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
Guido van Rossum45704552001-10-08 16:35:45 +0000281 vereq(dir(C), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000282 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000283
284 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
Guido van Rossum45704552001-10-08 16:35:45 +0000285 vereq(dir(c), cstuff)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000286
287 c.cdata = 2
288 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000289 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000290 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000291
292 class A(C):
293 Adata = 1
294 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000295
Tim Peters37a309d2001-09-04 01:20:04 +0000296 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000297 vereq(dir(A), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000298 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000299 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000300 vereq(dir(a), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000301 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000302 a.adata = 42
303 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000304 vereq(dir(a), astuff + ['adata', 'amethod'])
Tim Peters37a309d2001-09-04 01:20:04 +0000305
306 # The same, but with new-style classes. Since these have object as a
307 # base class, a lot more gets sucked in.
308 def interesting(strings):
309 return [s for s in strings if not s.startswith('_')]
310
Tim Peters5d2b77c2001-09-03 05:47:38 +0000311 class C(object):
312 Cdata = 1
313 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000314
315 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000316 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000317
318 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000319 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000320 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000321
322 c.cdata = 2
323 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000324 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000325 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000326
Tim Peters5d2b77c2001-09-03 05:47:38 +0000327 class A(C):
328 Adata = 1
329 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000330
331 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000332 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000333 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000334 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000335 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000336 a.adata = 42
337 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000338 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000339 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000340
Tim Peterscaaff8d2001-09-10 23:12:14 +0000341 # Try a module subclass.
342 import sys
343 class M(type(sys)):
344 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000345 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000346 minstance.b = 2
347 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000348 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
349 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000350
351 class M2(M):
352 def getdict(self):
353 return "Not a dict!"
354 __dict__ = property(getdict)
355
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000356 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000357 m2instance.b = 2
358 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000359 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000360 try:
361 dir(m2instance)
362 except TypeError:
363 pass
364
Tim Peters9e6a3992001-10-30 05:45:26 +0000365 # Two essentially featureless objects, just inheriting stuff from
366 # object.
367 vereq(dir(None), dir(Ellipsis))
368
Guido van Rossum44022412002-05-13 18:29:46 +0000369 # Nasty test case for proxied objects
370 class Wrapper(object):
371 def __init__(self, obj):
372 self.__obj = obj
373 def __repr__(self):
374 return "Wrapper(%s)" % repr(self.__obj)
375 def __getitem__(self, key):
376 return Wrapper(self.__obj[key])
377 def __len__(self):
378 return len(self.__obj)
379 def __getattr__(self, name):
380 return Wrapper(getattr(self.__obj, name))
381
382 class C(object):
383 def __getclass(self):
384 return Wrapper(type(self))
385 __class__ = property(__getclass)
386
387 dir(C()) # This used to segfault
388
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389binops = {
390 'add': '+',
391 'sub': '-',
392 'mul': '*',
393 'div': '/',
394 'mod': '%',
395 'divmod': 'divmod',
396 'pow': '**',
397 'lshift': '<<',
398 'rshift': '>>',
399 'and': '&',
400 'xor': '^',
401 'or': '|',
402 'cmp': 'cmp',
403 'lt': '<',
404 'le': '<=',
405 'eq': '==',
406 'ne': '!=',
407 'gt': '>',
408 'ge': '>=',
409 }
410
411for name, expr in binops.items():
412 if expr.islower():
413 expr = expr + "(a, b)"
414 else:
415 expr = 'a %s b' % expr
416 binops[name] = expr
417
418unops = {
419 'pos': '+',
420 'neg': '-',
421 'abs': 'abs',
422 'invert': '~',
423 'int': 'int',
424 'long': 'long',
425 'float': 'float',
426 'oct': 'oct',
427 'hex': 'hex',
428 }
429
430for name, expr in unops.items():
431 if expr.islower():
432 expr = expr + "(a)"
433 else:
434 expr = '%s a' % expr
435 unops[name] = expr
436
437def numops(a, b, skip=[]):
438 dict = {'a': a, 'b': b}
439 for name, expr in binops.items():
440 if name not in skip:
441 name = "__%s__" % name
442 if hasattr(a, name):
443 res = eval(expr, dict)
444 testbinop(a, b, res, expr, name)
445 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000446 if name not in skip:
447 name = "__%s__" % name
448 if hasattr(a, name):
449 res = eval(expr, dict)
450 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452def ints():
453 if verbose: print "Testing int operations..."
454 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000455 # The following crashes in Python 2.2
456 vereq((1).__nonzero__(), 1)
457 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000458 # This returns 'NotImplemented' in Python 2.2
459 class C(int):
460 def __add__(self, other):
461 return NotImplemented
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000462 vereq(C(5L), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000463 try:
464 C() + ""
465 except TypeError:
466 pass
467 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000468 raise TestFailed, "NotImplemented should have caused TypeError"
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000469 import sys
470 try:
471 C(sys.maxint+1)
472 except OverflowError:
473 pass
474 else:
475 raise TestFailed, "should have raised OverflowError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000476
477def longs():
478 if verbose: print "Testing long operations..."
479 numops(100L, 3L)
480
481def floats():
482 if verbose: print "Testing float operations..."
483 numops(100.0, 3.0)
484
485def complexes():
486 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000487 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000488 class Number(complex):
489 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000490 def __new__(cls, *args, **kwds):
491 result = complex.__new__(cls, *args)
492 result.prec = kwds.get('prec', 12)
493 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000494 def __repr__(self):
495 prec = self.prec
496 if self.imag == 0.0:
497 return "%.*g" % (prec, self.real)
498 if self.real == 0.0:
499 return "%.*gj" % (prec, self.imag)
500 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
501 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000502
Tim Peters6d6c1a32001-08-02 04:15:00 +0000503 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000504 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000505 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000506
Tim Peters3f996e72001-09-13 19:18:27 +0000507 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000508 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000509 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000510
511 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000512 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000513 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000514
Tim Peters6d6c1a32001-08-02 04:15:00 +0000515def spamlists():
516 if verbose: print "Testing spamlist operations..."
517 import copy, xxsubtype as spam
518 def spamlist(l, memo=None):
519 import xxsubtype as spam
520 return spam.spamlist(l)
521 # This is an ugly hack:
522 copy._deepcopy_dispatch[spam.spamlist] = spamlist
523
524 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
525 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
526 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
527 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
528 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
529 "a[b:c]", "__getslice__")
530 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
531 "a+=b", "__iadd__")
532 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
533 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
535 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
536 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
537 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
538 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
539 # Test subclassing
540 class C(spam.spamlist):
541 def foo(self): return 1
542 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000543 vereq(a, [])
544 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000546 vereq(a, [100])
547 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000549 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000550
551def spamdicts():
552 if verbose: print "Testing spamdict operations..."
553 import copy, xxsubtype as spam
554 def spamdict(d, memo=None):
555 import xxsubtype as spam
556 sd = spam.spamdict()
557 for k, v in d.items(): sd[k] = v
558 return sd
559 # This is an ugly hack:
560 copy._deepcopy_dispatch[spam.spamdict] = spamdict
561
562 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
563 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
564 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
565 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
566 d = spamdict({1:2,3:4})
567 l1 = []
568 for i in d.keys(): l1.append(i)
569 l = []
570 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000571 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000572 l = []
573 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000574 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000575 l = []
576 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000577 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000578 straightd = {1:2, 3:4}
579 spamd = spamdict(straightd)
580 testunop(spamd, 2, "len(a)", "__len__")
581 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
582 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
583 "a[b]=c", "__setitem__")
584 # Test subclassing
585 class C(spam.spamdict):
586 def foo(self): return 1
587 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000588 vereq(a.items(), [])
589 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000590 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000591 vereq(a.items(), [('foo', 'bar')])
592 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000594 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000595
596def pydicts():
597 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000598 verify(issubclass(dict, dict))
599 verify(isinstance({}, dict))
600 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000601 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000602 verify(d.__class__ is dict)
603 verify(isinstance(d, dict))
604 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000605 state = -1
606 def __init__(self, *a, **kw):
607 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000608 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609 self.state = a[0]
610 if kw:
611 for k, v in kw.items(): self[v] = k
612 def __getitem__(self, key):
613 return self.get(key, 0)
614 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000615 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000616 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000617 def setstate(self, state):
618 self.state = state
619 def getstate(self):
620 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000621 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000623 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000625 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000626 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000627 vereq(a.state, -1)
628 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000629 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000630 vereq(a.state, 0)
631 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000633 vereq(a.state, 10)
634 vereq(a.getstate(), 10)
635 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000636 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000637 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638 if verbose: print "pydict stress test ..."
639 N = 50
640 for i in range(N):
641 a[i] = C()
642 for j in range(N):
643 a[i][j] = i*j
644 for i in range(N):
645 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000646 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647
648def pylists():
649 if verbose: print "Testing Python subclass of list..."
650 class C(list):
651 def __getitem__(self, i):
652 return list.__getitem__(self, i) + 100
653 def __getslice__(self, i, j):
654 return (i, j)
655 a = C()
656 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000657 vereq(a[0], 100)
658 vereq(a[1], 101)
659 vereq(a[2], 102)
660 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000661
662def metaclass():
663 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000664 class C:
665 __metaclass__ = type
666 def __init__(self):
667 self.__state = 0
668 def getstate(self):
669 return self.__state
670 def setstate(self, state):
671 self.__state = state
672 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000673 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000675 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676 class D:
677 class __metaclass__(type):
678 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000679 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000680 d = D()
681 verify(d.__class__ is D)
682 class M1(type):
683 def __new__(cls, name, bases, dict):
684 dict['__spam__'] = 1
685 return type.__new__(cls, name, bases, dict)
686 class C:
687 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000688 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000689 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000690 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000691
Guido van Rossum309b5662001-08-17 11:43:17 +0000692 class _instance(object):
693 pass
694 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000695 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000696 def __new__(cls, name, bases, dict):
697 self = object.__new__(cls)
698 self.name = name
699 self.bases = bases
700 self.dict = dict
701 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000702 def __call__(self):
703 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000704 # Early binding of methods
705 for key in self.dict:
706 if key.startswith("__"):
707 continue
708 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000709 return it
710 class C:
711 __metaclass__ = M2
712 def spam(self):
713 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000714 vereq(C.name, 'C')
715 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000716 verify('spam' in C.dict)
717 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000718 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719
Guido van Rossum91ee7982001-08-30 20:52:40 +0000720 # More metaclass examples
721
722 class autosuper(type):
723 # Automatically add __super to the class
724 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000725 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000726 cls = super(autosuper, metaclass).__new__(metaclass,
727 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000728 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000729 while name[:1] == "_":
730 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000731 if name:
732 name = "_%s__super" % name
733 else:
734 name = "__super"
735 setattr(cls, name, super(cls))
736 return cls
737 class A:
738 __metaclass__ = autosuper
739 def meth(self):
740 return "A"
741 class B(A):
742 def meth(self):
743 return "B" + self.__super.meth()
744 class C(A):
745 def meth(self):
746 return "C" + self.__super.meth()
747 class D(C, B):
748 def meth(self):
749 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000750 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000751 class E(B, C):
752 def meth(self):
753 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000754 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000755
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000756 class autoproperty(type):
757 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000758 # named _get_x and/or _set_x are found
759 def __new__(metaclass, name, bases, dict):
760 hits = {}
761 for key, val in dict.iteritems():
762 if key.startswith("_get_"):
763 key = key[5:]
764 get, set = hits.get(key, (None, None))
765 get = val
766 hits[key] = get, set
767 elif key.startswith("_set_"):
768 key = key[5:]
769 get, set = hits.get(key, (None, None))
770 set = val
771 hits[key] = get, set
772 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000773 dict[key] = property(get, set)
774 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000775 name, bases, dict)
776 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000777 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000778 def _get_x(self):
779 return -self.__x
780 def _set_x(self, x):
781 self.__x = -x
782 a = A()
783 verify(not hasattr(a, "x"))
784 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000785 vereq(a.x, 12)
786 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000787
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000788 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000789 # Merge of multiple cooperating metaclasses
790 pass
791 class A:
792 __metaclass__ = multimetaclass
793 def _get_x(self):
794 return "A"
795 class B(A):
796 def _get_x(self):
797 return "B" + self.__super._get_x()
798 class C(A):
799 def _get_x(self):
800 return "C" + self.__super._get_x()
801 class D(C, B):
802 def _get_x(self):
803 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000804 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000805
Guido van Rossumf76de622001-10-18 15:49:21 +0000806 # Make sure type(x) doesn't call x.__class__.__init__
807 class T(type):
808 counter = 0
809 def __init__(self, *args):
810 T.counter += 1
811 class C:
812 __metaclass__ = T
813 vereq(T.counter, 1)
814 a = C()
815 vereq(type(a), C)
816 vereq(T.counter, 1)
817
Guido van Rossum29d26062001-12-11 04:37:34 +0000818 class C(object): pass
819 c = C()
820 try: c()
821 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000822 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000823
Jeremy Hyltonfa955692007-02-27 18:29:45 +0000824 # Testing code to find most derived baseclass
825 class A(type):
826 def __new__(*args, **kwargs):
827 return type.__new__(*args, **kwargs)
828
829 class B(object):
830 pass
831
832 class C(object):
833 __metaclass__ = A
834
835 # The most derived metaclass of D is A rather than type.
836 class D(B, C):
837 pass
838
839
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840def pymods():
841 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000843 import sys
844 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000845 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000846 def __init__(self, name):
847 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000848 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000849 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000850 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851 def __setattr__(self, name, value):
852 log.append(("setattr", name, value))
853 MT.__setattr__(self, name, value)
854 def __delattr__(self, name):
855 log.append(("delattr", name))
856 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000857 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000858 a.foo = 12
859 x = a.foo
860 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000861 vereq(log, [("setattr", "foo", 12),
862 ("getattr", "foo"),
863 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864
Armin Rigo9790a272007-05-02 19:23:31 +0000865 # http://python.org/sf/1174712
866 try:
867 class Module(types.ModuleType, str):
868 pass
869 except TypeError:
870 pass
871 else:
872 raise TestFailed("inheriting from ModuleType and str at the "
873 "same time should fail")
874
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875def multi():
876 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 class C(object):
878 def __init__(self):
879 self.__state = 0
880 def getstate(self):
881 return self.__state
882 def setstate(self, state):
883 self.__state = state
884 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000885 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000887 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000888 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889 def __init__(self):
890 type({}).__init__(self)
891 C.__init__(self)
892 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000893 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000894 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000895 vereq(d.items(), [("hello", "world")])
896 vereq(d["hello"], "world")
897 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000899 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000900 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901
Guido van Rossume45763a2001-08-10 21:28:46 +0000902 # SF bug #442833
903 class Node(object):
904 def __int__(self):
905 return int(self.foo())
906 def foo(self):
907 return "23"
908 class Frag(Node, list):
909 def foo(self):
910 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000911 vereq(Node().__int__(), 23)
912 vereq(int(Node()), 23)
913 vereq(Frag().__int__(), 42)
914 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000915
Tim Petersa91e9642001-11-14 23:32:33 +0000916 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000917
918 class A:
919 x = 1
920
921 class B(A):
922 pass
923
924 class C(A):
925 x = 2
926
927 class D(B, C):
928 pass
929 vereq(D.x, 1)
930
931 # Classic MRO is preserved for a classic base class.
932 class E(D, object):
933 pass
934 vereq(E.__mro__, (E, D, B, A, C, object))
935 vereq(E.x, 1)
936
937 # But with a mix of classic bases, their MROs are combined using
938 # new-style MRO.
939 class F(B, C, object):
940 pass
941 vereq(F.__mro__, (F, B, C, A, object))
942 vereq(F.x, 2)
943
944 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000945 class C:
946 def cmethod(self):
947 return "C a"
948 def all_method(self):
949 return "C b"
950
951 class M1(C, object):
952 def m1method(self):
953 return "M1 a"
954 def all_method(self):
955 return "M1 b"
956
957 vereq(M1.__mro__, (M1, C, object))
958 m = M1()
959 vereq(m.cmethod(), "C a")
960 vereq(m.m1method(), "M1 a")
961 vereq(m.all_method(), "M1 b")
962
963 class D(C):
964 def dmethod(self):
965 return "D a"
966 def all_method(self):
967 return "D b"
968
Guido van Rossum9a818922002-11-14 19:50:14 +0000969 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000970 def m2method(self):
971 return "M2 a"
972 def all_method(self):
973 return "M2 b"
974
Guido van Rossum9a818922002-11-14 19:50:14 +0000975 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000976 m = M2()
977 vereq(m.cmethod(), "C a")
978 vereq(m.dmethod(), "D a")
979 vereq(m.m2method(), "M2 a")
980 vereq(m.all_method(), "M2 b")
981
Guido van Rossum9a818922002-11-14 19:50:14 +0000982 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000983 def m3method(self):
984 return "M3 a"
985 def all_method(self):
986 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000987 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000988 m = M3()
989 vereq(m.cmethod(), "C a")
990 vereq(m.dmethod(), "D a")
991 vereq(m.m1method(), "M1 a")
992 vereq(m.m2method(), "M2 a")
993 vereq(m.m3method(), "M3 a")
994 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000995
Guido van Rossume54616c2001-12-14 04:19:56 +0000996 class Classic:
997 pass
998 try:
999 class New(Classic):
1000 __metaclass__ = type
1001 except TypeError:
1002 pass
1003 else:
1004 raise TestFailed, "new class with only classic bases - shouldn't be"
1005
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006def diamond():
1007 if verbose: print "Testing multiple inheritance special cases..."
1008 class A(object):
1009 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +00001010 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011 class B(A):
1012 def boo(self): return "B"
1013 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +00001014 vereq(B().spam(), "B")
1015 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016 class C(A):
1017 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +00001018 vereq(C().spam(), "A")
1019 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001020 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001021 vereq(D().spam(), "B")
1022 vereq(D().boo(), "B")
1023 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001025 vereq(E().spam(), "B")
1026 vereq(E().boo(), "C")
1027 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +00001028 # MRO order disagreement
1029 try:
1030 class F(D, E): pass
1031 except TypeError:
1032 pass
1033 else:
1034 raise TestFailed, "expected MRO order disagreement (F)"
1035 try:
1036 class G(E, D): pass
1037 except TypeError:
1038 pass
1039 else:
1040 raise TestFailed, "expected MRO order disagreement (G)"
1041
1042
1043# see thread python-dev/2002-October/029035.html
1044def ex5():
1045 if verbose: print "Testing ex5 from C3 switch discussion..."
1046 class A(object): pass
1047 class B(object): pass
1048 class C(object): pass
1049 class X(A): pass
1050 class Y(A): pass
1051 class Z(X,B,Y,C): pass
1052 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1053
1054# see "A Monotonic Superclass Linearization for Dylan",
1055# by Kim Barrett et al. (OOPSLA 1996)
1056def monotonicity():
1057 if verbose: print "Testing MRO monotonicity..."
1058 class Boat(object): pass
1059 class DayBoat(Boat): pass
1060 class WheelBoat(Boat): pass
1061 class EngineLess(DayBoat): pass
1062 class SmallMultihull(DayBoat): pass
1063 class PedalWheelBoat(EngineLess,WheelBoat): pass
1064 class SmallCatamaran(SmallMultihull): pass
1065 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1066
1067 vereq(PedalWheelBoat.__mro__,
1068 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1069 object))
1070 vereq(SmallCatamaran.__mro__,
1071 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1072
1073 vereq(Pedalo.__mro__,
1074 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1075 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1076
1077# see "A Monotonic Superclass Linearization for Dylan",
1078# by Kim Barrett et al. (OOPSLA 1996)
1079def consistency_with_epg():
1080 if verbose: print "Testing consistentcy with EPG..."
1081 class Pane(object): pass
1082 class ScrollingMixin(object): pass
1083 class EditingMixin(object): pass
1084 class ScrollablePane(Pane,ScrollingMixin): pass
1085 class EditablePane(Pane,EditingMixin): pass
1086 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1087
1088 vereq(EditableScrollablePane.__mro__,
1089 (EditableScrollablePane, ScrollablePane, EditablePane,
1090 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091
Raymond Hettingerf394df42003-04-06 19:13:41 +00001092mro_err_msg = """Cannot create a consistent method resolution
1093order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +00001094
Guido van Rossumd32047f2002-11-25 21:38:52 +00001095def mro_disagreement():
1096 if verbose: print "Testing error messages for MRO disagreement..."
1097 def raises(exc, expected, callable, *args):
1098 try:
1099 callable(*args)
1100 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001101 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001102 raise TestFailed, "Message %r, expected %r" % (str(msg),
1103 expected)
1104 else:
1105 raise TestFailed, "Expected %s" % exc
1106 class A(object): pass
1107 class B(A): pass
1108 class C(object): pass
1109 # Test some very simple errors
1110 raises(TypeError, "duplicate base class A",
1111 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001112 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001113 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001114 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001115 type, "X", (A, C, B), {})
1116 # Test a slightly more complex error
1117 class GridLayout(object): pass
1118 class HorizontalGrid(GridLayout): pass
1119 class VerticalGrid(GridLayout): pass
1120 class HVGrid(HorizontalGrid, VerticalGrid): pass
1121 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +00001122 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001123 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1124
Guido van Rossum37202612001-08-09 19:45:21 +00001125def objects():
1126 if verbose: print "Testing object class..."
1127 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001128 vereq(a.__class__, object)
1129 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001130 b = object()
1131 verify(a is not b)
1132 verify(not hasattr(a, "foo"))
1133 try:
1134 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001135 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001136 pass
1137 else:
1138 verify(0, "object() should not allow setting a foo attribute")
1139 verify(not hasattr(object(), "__dict__"))
1140
1141 class Cdict(object):
1142 pass
1143 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001144 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001145 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001146 vereq(x.foo, 1)
1147 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001148
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149def slots():
1150 if verbose: print "Testing __slots__..."
1151 class C0(object):
1152 __slots__ = []
1153 x = C0()
1154 verify(not hasattr(x, "__dict__"))
1155 verify(not hasattr(x, "foo"))
1156
1157 class C1(object):
1158 __slots__ = ['a']
1159 x = C1()
1160 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001161 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001163 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001164 x.a = None
1165 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001167 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
1169 class C3(object):
1170 __slots__ = ['a', 'b', 'c']
1171 x = C3()
1172 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001173 verify(not hasattr(x, 'a'))
1174 verify(not hasattr(x, 'b'))
1175 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 x.a = 1
1177 x.b = 2
1178 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001179 vereq(x.a, 1)
1180 vereq(x.b, 2)
1181 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001183 class C4(object):
1184 """Validate name mangling"""
1185 __slots__ = ['__a']
1186 def __init__(self, value):
1187 self.__a = value
1188 def get(self):
1189 return self.__a
1190 x = C4(5)
1191 verify(not hasattr(x, '__dict__'))
1192 verify(not hasattr(x, '__a'))
1193 vereq(x.get(), 5)
1194 try:
1195 x.__a = 6
1196 except AttributeError:
1197 pass
1198 else:
1199 raise TestFailed, "Double underscored names not mangled"
1200
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001201 # Make sure slot names are proper identifiers
1202 try:
1203 class C(object):
1204 __slots__ = [None]
1205 except TypeError:
1206 pass
1207 else:
1208 raise TestFailed, "[None] slots not caught"
1209 try:
1210 class C(object):
1211 __slots__ = ["foo bar"]
1212 except TypeError:
1213 pass
1214 else:
1215 raise TestFailed, "['foo bar'] slots not caught"
1216 try:
1217 class C(object):
1218 __slots__ = ["foo\0bar"]
1219 except TypeError:
1220 pass
1221 else:
1222 raise TestFailed, "['foo\\0bar'] slots not caught"
1223 try:
1224 class C(object):
1225 __slots__ = ["1"]
1226 except TypeError:
1227 pass
1228 else:
1229 raise TestFailed, "['1'] slots not caught"
1230 try:
1231 class C(object):
1232 __slots__ = [""]
1233 except TypeError:
1234 pass
1235 else:
1236 raise TestFailed, "[''] slots not caught"
1237 class C(object):
1238 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001239 # XXX(nnorwitz): was there supposed to be something tested
1240 # from the class above?
1241
1242 # Test a single string is not expanded as a sequence.
1243 class C(object):
1244 __slots__ = "abc"
1245 c = C()
1246 c.abc = 5
1247 vereq(c.abc, 5)
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001248
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001249 # Test unicode slot names
1250 try:
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001251 unicode
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001252 except NameError:
1253 pass
1254 else:
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001255 # Test a single unicode string is not expanded as a sequence.
1256 class C(object):
1257 __slots__ = unicode("abc")
1258 c = C()
1259 c.abc = 5
1260 vereq(c.abc, 5)
1261
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001262 # _unicode_to_string used to modify slots in certain circumstances
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001263 slots = (unicode("foo"), unicode("bar"))
1264 class C(object):
1265 __slots__ = slots
1266 x = C()
1267 x.foo = 5
1268 vereq(x.foo, 5)
1269 veris(type(slots[0]), unicode)
1270 # this used to leak references
1271 try:
1272 class C(object):
1273 __slots__ = [unichr(128)]
1274 except (TypeError, UnicodeEncodeError):
1275 pass
1276 else:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001277 raise TestFailed, "[unichr(128)] slots not caught"
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001278
Guido van Rossum33bab012001-12-05 22:45:48 +00001279 # Test leaks
1280 class Counted(object):
1281 counter = 0 # counts the number of instances alive
1282 def __init__(self):
1283 Counted.counter += 1
1284 def __del__(self):
1285 Counted.counter -= 1
1286 class C(object):
1287 __slots__ = ['a', 'b', 'c']
1288 x = C()
1289 x.a = Counted()
1290 x.b = Counted()
1291 x.c = Counted()
1292 vereq(Counted.counter, 3)
1293 del x
1294 vereq(Counted.counter, 0)
1295 class D(C):
1296 pass
1297 x = D()
1298 x.a = Counted()
1299 x.z = Counted()
1300 vereq(Counted.counter, 2)
1301 del x
1302 vereq(Counted.counter, 0)
1303 class E(D):
1304 __slots__ = ['e']
1305 x = E()
1306 x.a = Counted()
1307 x.z = Counted()
1308 x.e = Counted()
1309 vereq(Counted.counter, 3)
1310 del x
1311 vereq(Counted.counter, 0)
1312
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001313 # Test cyclical leaks [SF bug 519621]
1314 class F(object):
1315 __slots__ = ['a', 'b']
1316 log = []
1317 s = F()
1318 s.a = [Counted(), s]
1319 vereq(Counted.counter, 1)
1320 s = None
1321 import gc
1322 gc.collect()
1323 vereq(Counted.counter, 0)
1324
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001325 # Test lookup leaks [SF bug 572567]
1326 import sys,gc
1327 class G(object):
1328 def __cmp__(self, other):
1329 return 0
1330 g = G()
1331 orig_objects = len(gc.get_objects())
1332 for i in xrange(10):
1333 g==g
1334 new_objects = len(gc.get_objects())
1335 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001336 class H(object):
1337 __slots__ = ['a', 'b']
1338 def __init__(self):
1339 self.a = 1
1340 self.b = 2
1341 def __del__(self):
1342 assert self.a == 1
1343 assert self.b == 2
1344
1345 save_stderr = sys.stderr
1346 sys.stderr = sys.stdout
1347 h = H()
1348 try:
1349 del h
1350 finally:
1351 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001352
Guido van Rossum8b056da2002-08-13 18:26:26 +00001353def slotspecials():
1354 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1355
1356 class D(object):
1357 __slots__ = ["__dict__"]
1358 a = D()
1359 verify(hasattr(a, "__dict__"))
1360 verify(not hasattr(a, "__weakref__"))
1361 a.foo = 42
1362 vereq(a.__dict__, {"foo": 42})
1363
1364 class W(object):
1365 __slots__ = ["__weakref__"]
1366 a = W()
1367 verify(hasattr(a, "__weakref__"))
1368 verify(not hasattr(a, "__dict__"))
1369 try:
1370 a.foo = 42
1371 except AttributeError:
1372 pass
1373 else:
1374 raise TestFailed, "shouldn't be allowed to set a.foo"
1375
1376 class C1(W, D):
1377 __slots__ = []
1378 a = C1()
1379 verify(hasattr(a, "__dict__"))
1380 verify(hasattr(a, "__weakref__"))
1381 a.foo = 42
1382 vereq(a.__dict__, {"foo": 42})
1383
1384 class C2(D, W):
1385 __slots__ = []
1386 a = C2()
1387 verify(hasattr(a, "__dict__"))
1388 verify(hasattr(a, "__weakref__"))
1389 a.foo = 42
1390 vereq(a.__dict__, {"foo": 42})
1391
Guido van Rossum9a818922002-11-14 19:50:14 +00001392# MRO order disagreement
1393#
1394# class C3(C1, C2):
1395# __slots__ = []
1396#
1397# class C4(C2, C1):
1398# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001399
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001401 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001404 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001406 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001409 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001411 vereq(E.foo, 1)
1412 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001413 # Test dynamic instances
1414 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001415 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001416 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001417 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001418 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001419 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001420 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001421 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001422 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001423 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001424 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001425 vereq(int(a), 100)
1426 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001427 verify(not hasattr(a, "spam"))
1428 def mygetattr(self, name):
1429 if name == "spam":
1430 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001431 raise AttributeError
1432 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001433 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001434 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001435 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001436 def mysetattr(self, name, value):
1437 if name == "spam":
1438 raise AttributeError
1439 return object.__setattr__(self, name, value)
1440 C.__setattr__ = mysetattr
1441 try:
1442 a.spam = "not spam"
1443 except AttributeError:
1444 pass
1445 else:
1446 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001447 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001448 class D(C):
1449 pass
1450 d = D()
1451 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001452 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453
Guido van Rossum7e35d572001-09-15 03:14:32 +00001454 # Test handling of int*seq and seq*int
1455 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001456 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001457 vereq("a"*I(2), "aa")
1458 vereq(I(2)*"a", "aa")
1459 vereq(2*I(3), 6)
1460 vereq(I(3)*2, 6)
1461 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001462
1463 # Test handling of long*seq and seq*long
1464 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001465 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001466 vereq("a"*L(2L), "aa")
1467 vereq(L(2L)*"a", "aa")
1468 vereq(2*L(3), 6)
1469 vereq(L(3)*2, 6)
1470 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001471
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001472 # Test comparison of classes with dynamic metaclasses
1473 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001474 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001475 class someclass:
1476 __metaclass__ = dynamicmetaclass
1477 verify(someclass != object)
1478
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479def errors():
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001480 if verbose: print "Testing errors..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001482 try:
1483 class C(list, dict):
1484 pass
1485 except TypeError:
1486 pass
1487 else:
1488 verify(0, "inheritance from both list and dict should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001490 try:
1491 class C(object, None):
1492 pass
1493 except TypeError:
1494 pass
1495 else:
1496 verify(0, "inheritance from non-type should be illegal")
1497 class Classic:
1498 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001500 try:
1501 class C(type(len)):
1502 pass
1503 except TypeError:
1504 pass
1505 else:
1506 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001508 try:
1509 class C(object):
1510 __slots__ = 1
1511 except TypeError:
1512 pass
1513 else:
1514 verify(0, "__slots__ = 1 should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001516 try:
1517 class C(object):
1518 __slots__ = [1]
1519 except TypeError:
1520 pass
1521 else:
1522 verify(0, "__slots__ = [1] should be illegal")
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001523
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001524 class M1(type):
1525 pass
1526 class M2(type):
1527 pass
1528 class A1(object):
1529 __metaclass__ = M1
1530 class A2(object):
1531 __metaclass__ = M2
1532 try:
1533 class B(A1, A2):
1534 pass
1535 except TypeError:
1536 pass
1537 else:
1538 verify(0, "finding the most derived metaclass should have failed")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539
1540def classmethods():
1541 if verbose: print "Testing class methods..."
1542 class C(object):
1543 def foo(*a): return a
1544 goo = classmethod(foo)
1545 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001546 vereq(C.goo(1), (C, 1))
1547 vereq(c.goo(1), (C, 1))
1548 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549 class D(C):
1550 pass
1551 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001552 vereq(D.goo(1), (D, 1))
1553 vereq(d.goo(1), (D, 1))
1554 vereq(d.foo(1), (d, 1))
1555 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001556 # Test for a specific crash (SF bug 528132)
1557 def f(cls, arg): return (cls, arg)
1558 ff = classmethod(f)
1559 vereq(ff.__get__(0, int)(42), (int, 42))
1560 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561
Guido van Rossum155db9a2002-04-02 17:53:47 +00001562 # Test super() with classmethods (SF bug 535444)
1563 veris(C.goo.im_self, C)
1564 veris(D.goo.im_self, D)
1565 veris(super(D,D).goo.im_self, D)
1566 veris(super(D,d).goo.im_self, D)
1567 vereq(super(D,D).goo(), (D,))
1568 vereq(super(D,d).goo(), (D,))
1569
Raymond Hettingerbe971532003-06-18 01:13:41 +00001570 # Verify that argument is checked for callability (SF bug 753451)
1571 try:
1572 classmethod(1).__get__(1)
1573 except TypeError:
1574 pass
1575 else:
1576 raise TestFailed, "classmethod should check for callability"
1577
Georg Brandl6a29c322006-02-21 22:17:46 +00001578 # Verify that classmethod() doesn't allow keyword args
1579 try:
1580 classmethod(f, kw=1)
1581 except TypeError:
1582 pass
1583 else:
1584 raise TestFailed, "classmethod shouldn't accept keyword args"
1585
Fred Drakef841aa62002-03-28 15:49:54 +00001586def classmethods_in_c():
1587 if verbose: print "Testing C-based class methods..."
1588 import xxsubtype as spam
1589 a = (1, 2, 3)
1590 d = {'abc': 123}
1591 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001592 veris(x, spam.spamlist)
1593 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001594 vereq(d, d1)
1595 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001596 veris(x, spam.spamlist)
1597 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001598 vereq(d, d1)
1599
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600def staticmethods():
1601 if verbose: print "Testing static methods..."
1602 class C(object):
1603 def foo(*a): return a
1604 goo = staticmethod(foo)
1605 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001606 vereq(C.goo(1), (1,))
1607 vereq(c.goo(1), (1,))
1608 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 class D(C):
1610 pass
1611 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001612 vereq(D.goo(1), (1,))
1613 vereq(d.goo(1), (1,))
1614 vereq(d.foo(1), (d, 1))
1615 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616
Fred Drakef841aa62002-03-28 15:49:54 +00001617def staticmethods_in_c():
1618 if verbose: print "Testing C-based static methods..."
1619 import xxsubtype as spam
1620 a = (1, 2, 3)
1621 d = {"abc": 123}
1622 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1623 veris(x, None)
1624 vereq(a, a1)
1625 vereq(d, d1)
1626 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1627 veris(x, None)
1628 vereq(a, a1)
1629 vereq(d, d1)
1630
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631def classic():
1632 if verbose: print "Testing classic classes..."
1633 class C:
1634 def foo(*a): return a
1635 goo = classmethod(foo)
1636 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001637 vereq(C.goo(1), (C, 1))
1638 vereq(c.goo(1), (C, 1))
1639 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 class D(C):
1641 pass
1642 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001643 vereq(D.goo(1), (D, 1))
1644 vereq(d.goo(1), (D, 1))
1645 vereq(d.foo(1), (d, 1))
1646 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001647 class E: # *not* subclassing from C
1648 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001649 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001650 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651
1652def compattr():
1653 if verbose: print "Testing computed attributes..."
1654 class C(object):
1655 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001656 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 self.__get = get
1658 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001659 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660 def __get__(self, obj, type=None):
1661 return self.__get(obj)
1662 def __set__(self, obj, value):
1663 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001664 def __delete__(self, obj):
1665 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 def __init__(self):
1667 self.__x = 0
1668 def __get_x(self):
1669 x = self.__x
1670 self.__x = x+1
1671 return x
1672 def __set_x(self, x):
1673 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001674 def __delete_x(self):
1675 del self.__x
1676 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001678 vereq(a.x, 0)
1679 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001681 vereq(a.x, 10)
1682 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001683 del a.x
1684 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685
1686def newslot():
1687 if verbose: print "Testing __new__ slot override..."
1688 class C(list):
1689 def __new__(cls):
1690 self = list.__new__(cls)
1691 self.foo = 1
1692 return self
1693 def __init__(self):
1694 self.foo = self.foo + 2
1695 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001696 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697 verify(a.__class__ is C)
1698 class D(C):
1699 pass
1700 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001701 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 verify(b.__class__ is D)
1703
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704def altmro():
1705 if verbose: print "Testing mro() and overriding it..."
1706 class A(object):
1707 def f(self): return "A"
1708 class B(A):
1709 pass
1710 class C(A):
1711 def f(self): return "C"
1712 class D(B, C):
1713 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001714 vereq(D.mro(), [D, B, C, A, object])
1715 vereq(D.__mro__, (D, B, C, A, object))
1716 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001717
Guido van Rossumd3077402001-08-12 05:24:18 +00001718 class PerverseMetaType(type):
1719 def mro(cls):
1720 L = type.mro(cls)
1721 L.reverse()
1722 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001723 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001725 vereq(X.__mro__, (object, A, C, B, D, X))
1726 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727
Armin Rigo037d1e02005-12-29 17:07:39 +00001728 try:
1729 class X(object):
1730 class __metaclass__(type):
1731 def mro(self):
1732 return [self, dict, object]
1733 except TypeError:
1734 pass
1735 else:
1736 raise TestFailed, "devious mro() return not caught"
1737
1738 try:
1739 class X(object):
1740 class __metaclass__(type):
1741 def mro(self):
1742 return [1]
1743 except TypeError:
1744 pass
1745 else:
1746 raise TestFailed, "non-class mro() return not caught"
1747
1748 try:
1749 class X(object):
1750 class __metaclass__(type):
1751 def mro(self):
1752 return 1
1753 except TypeError:
1754 pass
1755 else:
1756 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001757
Armin Rigo037d1e02005-12-29 17:07:39 +00001758
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001760 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761
1762 class B(object):
1763 "Intermediate class because object doesn't have a __setattr__"
1764
1765 class C(B):
1766
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001767 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 if name == "foo":
1769 return ("getattr", name)
1770 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001771 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 def __setattr__(self, name, value):
1773 if name == "foo":
1774 self.setattr = (name, value)
1775 else:
1776 return B.__setattr__(self, name, value)
1777 def __delattr__(self, name):
1778 if name == "foo":
1779 self.delattr = name
1780 else:
1781 return B.__delattr__(self, name)
1782
1783 def __getitem__(self, key):
1784 return ("getitem", key)
1785 def __setitem__(self, key, value):
1786 self.setitem = (key, value)
1787 def __delitem__(self, key):
1788 self.delitem = key
1789
1790 def __getslice__(self, i, j):
1791 return ("getslice", i, j)
1792 def __setslice__(self, i, j, value):
1793 self.setslice = (i, j, value)
1794 def __delslice__(self, i, j):
1795 self.delslice = (i, j)
1796
1797 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001798 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001800 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001802 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803
Guido van Rossum45704552001-10-08 16:35:45 +00001804 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001806 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001808 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809
Guido van Rossum45704552001-10-08 16:35:45 +00001810 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001812 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001813 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001814 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001816def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001817 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001818 class C(object):
1819 def __init__(self, x):
1820 self.x = x
1821 def foo(self):
1822 return self.x
1823 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001824 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001825 class D(C):
1826 boo = C.foo
1827 goo = c1.foo
1828 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001829 vereq(d2.foo(), 2)
1830 vereq(d2.boo(), 2)
1831 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001832 class E(object):
1833 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001834 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001835 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001836
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001837def specials():
1838 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001839 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001840 # Test the default behavior for static classes
1841 class C(object):
1842 def __getitem__(self, i):
1843 if 0 <= i < 10: return i
1844 raise IndexError
1845 c1 = C()
1846 c2 = C()
1847 verify(not not c1)
Tim Peters85b362f2006-04-11 01:21:00 +00001848 verify(id(c1) != id(c2))
1849 hash(c1)
1850 hash(c2)
Guido van Rossum45704552001-10-08 16:35:45 +00001851 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1852 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001853 verify(c1 != c2)
1854 verify(not c1 != c1)
1855 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001856 # Note that the module name appears in str/repr, and that varies
1857 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001858 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001859 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001860 verify(-1 not in c1)
1861 for i in range(10):
1862 verify(i in c1)
1863 verify(10 not in c1)
1864 # Test the default behavior for dynamic classes
1865 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001866 def __getitem__(self, i):
1867 if 0 <= i < 10: return i
1868 raise IndexError
1869 d1 = D()
1870 d2 = D()
1871 verify(not not d1)
Tim Peters85b362f2006-04-11 01:21:00 +00001872 verify(id(d1) != id(d2))
1873 hash(d1)
1874 hash(d2)
Guido van Rossum45704552001-10-08 16:35:45 +00001875 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1876 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001877 verify(d1 != d2)
1878 verify(not d1 != d1)
1879 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001880 # Note that the module name appears in str/repr, and that varies
1881 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001882 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001883 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001884 verify(-1 not in d1)
1885 for i in range(10):
1886 verify(i in d1)
1887 verify(10 not in d1)
1888 # Test overridden behavior for static classes
1889 class Proxy(object):
1890 def __init__(self, x):
1891 self.x = x
1892 def __nonzero__(self):
1893 return not not self.x
1894 def __hash__(self):
1895 return hash(self.x)
1896 def __eq__(self, other):
1897 return self.x == other
1898 def __ne__(self, other):
1899 return self.x != other
1900 def __cmp__(self, other):
1901 return cmp(self.x, other.x)
1902 def __str__(self):
1903 return "Proxy:%s" % self.x
1904 def __repr__(self):
1905 return "Proxy(%r)" % self.x
1906 def __contains__(self, value):
1907 return value in self.x
1908 p0 = Proxy(0)
1909 p1 = Proxy(1)
1910 p_1 = Proxy(-1)
1911 verify(not p0)
1912 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001913 vereq(hash(p0), hash(0))
1914 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001915 verify(p0 != p1)
1916 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001917 vereq(not p0, p1)
1918 vereq(cmp(p0, p1), -1)
1919 vereq(cmp(p0, p0), 0)
1920 vereq(cmp(p0, p_1), 1)
1921 vereq(str(p0), "Proxy:0")
1922 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001923 p10 = Proxy(range(10))
1924 verify(-1 not in p10)
1925 for i in range(10):
1926 verify(i in p10)
1927 verify(10 not in p10)
1928 # Test overridden behavior for dynamic classes
1929 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001930 def __init__(self, x):
1931 self.x = x
1932 def __nonzero__(self):
1933 return not not self.x
1934 def __hash__(self):
1935 return hash(self.x)
1936 def __eq__(self, other):
1937 return self.x == other
1938 def __ne__(self, other):
1939 return self.x != other
1940 def __cmp__(self, other):
1941 return cmp(self.x, other.x)
1942 def __str__(self):
1943 return "DProxy:%s" % self.x
1944 def __repr__(self):
1945 return "DProxy(%r)" % self.x
1946 def __contains__(self, value):
1947 return value in self.x
1948 p0 = DProxy(0)
1949 p1 = DProxy(1)
1950 p_1 = DProxy(-1)
1951 verify(not p0)
1952 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001953 vereq(hash(p0), hash(0))
1954 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001955 verify(p0 != p1)
1956 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001957 vereq(not p0, p1)
1958 vereq(cmp(p0, p1), -1)
1959 vereq(cmp(p0, p0), 0)
1960 vereq(cmp(p0, p_1), 1)
1961 vereq(str(p0), "DProxy:0")
1962 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001963 p10 = DProxy(range(10))
1964 verify(-1 not in p10)
1965 for i in range(10):
1966 verify(i in p10)
1967 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001968 # Safety test for __cmp__
1969 def unsafecmp(a, b):
1970 try:
1971 a.__class__.__cmp__(a, b)
1972 except TypeError:
1973 pass
1974 else:
1975 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1976 a.__class__, a, b)
1977 unsafecmp(u"123", "123")
1978 unsafecmp("123", u"123")
1979 unsafecmp(1, 1.0)
1980 unsafecmp(1.0, 1)
1981 unsafecmp(1, 1L)
1982 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001983
Brett Cannon1e534b52007-09-07 04:18:30 +00001984def recursions():
1985 if verbose:
1986 print "Testing recursion checks ..."
1987
Neal Norwitz1a997502003-01-13 20:13:12 +00001988 class Letter(str):
1989 def __new__(cls, letter):
1990 if letter == 'EPS':
1991 return str.__new__(cls)
1992 return str.__new__(cls, letter)
1993 def __str__(self):
1994 if not self:
1995 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001996 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001997 # sys.stdout needs to be the original to trigger the recursion bug
1998 import sys
1999 test_stdout = sys.stdout
2000 sys.stdout = get_original_stdout()
2001 try:
2002 # nothing should actually be printed, this should raise an exception
2003 print Letter('w')
2004 except RuntimeError:
2005 pass
2006 else:
2007 raise TestFailed, "expected a RuntimeError for print recursion"
2008 sys.stdout = test_stdout
2009
Brett Cannon1e534b52007-09-07 04:18:30 +00002010 # Bug #1202533.
2011 class A(object):
2012 pass
Christian Heimes636afc52007-11-27 23:53:14 +00002013 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
Brett Cannon1e534b52007-09-07 04:18:30 +00002014 try:
2015 A()*2
2016 except RuntimeError:
2017 pass
2018 else:
2019 raise TestFailed("expected a RuntimeError")
2020
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002021def weakrefs():
2022 if verbose: print "Testing weak references..."
2023 import weakref
2024 class C(object):
2025 pass
2026 c = C()
2027 r = weakref.ref(c)
2028 verify(r() is c)
2029 del c
2030 verify(r() is None)
2031 del r
2032 class NoWeak(object):
2033 __slots__ = ['foo']
2034 no = NoWeak()
2035 try:
2036 weakref.ref(no)
2037 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00002038 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002039 else:
2040 verify(0, "weakref.ref(no) should be illegal")
2041 class Weak(object):
2042 __slots__ = ['foo', '__weakref__']
2043 yes = Weak()
2044 r = weakref.ref(yes)
2045 verify(r() is yes)
2046 del yes
2047 verify(r() is None)
2048 del r
2049
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002050def properties():
2051 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002052 class C(object):
2053 def getx(self):
2054 return self.__x
2055 def setx(self, value):
2056 self.__x = value
2057 def delx(self):
2058 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00002059 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002060 a = C()
2061 verify(not hasattr(a, "x"))
2062 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00002063 vereq(a._C__x, 42)
2064 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002065 del a.x
2066 verify(not hasattr(a, "x"))
2067 verify(not hasattr(a, "_C__x"))
2068 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00002069 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002070 C.x.__delete__(a)
2071 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002072
Tim Peters66c1a522001-09-24 21:17:50 +00002073 raw = C.__dict__['x']
2074 verify(isinstance(raw, property))
2075
2076 attrs = dir(raw)
2077 verify("__doc__" in attrs)
2078 verify("fget" in attrs)
2079 verify("fset" in attrs)
2080 verify("fdel" in attrs)
2081
Guido van Rossum45704552001-10-08 16:35:45 +00002082 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00002083 verify(raw.fget is C.__dict__['getx'])
2084 verify(raw.fset is C.__dict__['setx'])
2085 verify(raw.fdel is C.__dict__['delx'])
2086
2087 for attr in "__doc__", "fget", "fset", "fdel":
2088 try:
2089 setattr(raw, attr, 42)
2090 except TypeError, msg:
2091 if str(msg).find('readonly') < 0:
2092 raise TestFailed("when setting readonly attr %r on a "
2093 "property, got unexpected TypeError "
2094 "msg %r" % (attr, str(msg)))
2095 else:
2096 raise TestFailed("expected TypeError from trying to set "
2097 "readonly %r attr on a property" % attr)
2098
Neal Norwitz673cd822002-10-18 16:33:13 +00002099 class D(object):
2100 __getitem__ = property(lambda s: 1/0)
2101
2102 d = D()
2103 try:
2104 for i in d:
2105 str(i)
2106 except ZeroDivisionError:
2107 pass
2108 else:
2109 raise TestFailed, "expected ZeroDivisionError from bad property"
2110
Georg Brandl533ff6f2006-03-08 18:09:27 +00002111 class E(object):
2112 def getter(self):
2113 "getter method"
2114 return 0
2115 def setter(self, value):
2116 "setter method"
2117 pass
2118 prop = property(getter)
2119 vereq(prop.__doc__, "getter method")
2120 prop2 = property(fset=setter)
2121 vereq(prop2.__doc__, None)
2122
Georg Brandle9462c72006-08-04 18:03:37 +00002123 # this segfaulted in 2.5b2
2124 try:
2125 import _testcapi
2126 except ImportError:
2127 pass
2128 else:
2129 class X(object):
2130 p = property(_testcapi.test_with_docstring)
2131
2132
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002133def properties_plus():
Brett Cannon4e438bc2007-12-25 00:14:34 +00002134 class C(object):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002135 foo = property(doc="hello")
2136 @foo.getter
2137 def foo(self):
2138 return self._foo
2139 @foo.setter
2140 def foo(self, value):
2141 self._foo = abs(value)
2142 @foo.deleter
2143 def foo(self):
2144 del self._foo
2145 c = C()
2146 assert C.foo.__doc__ == "hello"
2147 assert not hasattr(c, "foo")
2148 c.foo = -42
Brett Cannon4e438bc2007-12-25 00:14:34 +00002149 assert hasattr(c, '_foo')
2150 assert c._foo == 42
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002151 assert c.foo == 42
2152 del c.foo
Brett Cannon4e438bc2007-12-25 00:14:34 +00002153 assert not hasattr(c, '_foo')
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002154 assert not hasattr(c, "foo")
2155
2156 class D(C):
2157 @C.foo.deleter
2158 def foo(self):
2159 try:
2160 del self._foo
2161 except AttributeError:
2162 pass
2163 d = D()
2164 d.foo = 24
2165 assert d.foo == 24
2166 del d.foo
2167 del d.foo
2168
Brett Cannon4e438bc2007-12-25 00:14:34 +00002169 class E(object):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002170 @property
2171 def foo(self):
2172 return self._foo
2173 @foo.setter
Brett Cannon4e438bc2007-12-25 00:14:34 +00002174 def foo(self, value):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002175 raise RuntimeError
2176 @foo.setter
Brett Cannon4e438bc2007-12-25 00:14:34 +00002177 def foo(self, value):
2178 self._foo = abs(value)
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002179 @foo.deleter
2180 def foo(self, value=None):
Brett Cannon4e438bc2007-12-25 00:14:34 +00002181 del self._foo
2182
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002183 e = E()
2184 e.foo = -42
2185 assert e.foo == 42
2186 del e.foo
2187
2188 class F(E):
2189 @E.foo.deleter
2190 def foo(self):
2191 del self._foo
2192 @foo.setter
2193 def foo(self, value):
2194 self._foo = max(0, value)
2195 f = F()
2196 f.foo = -10
2197 assert f.foo == 0
2198 del f.foo
Brett Cannon4e438bc2007-12-25 00:14:34 +00002199 print "*** HIT"
Guido van Rossumd1ef7892007-11-10 22:12:24 +00002200
2201
Guido van Rossumc4a18802001-08-24 16:55:27 +00002202def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002203 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002204
2205 class A(object):
2206 def meth(self, a):
2207 return "A(%r)" % a
2208
Guido van Rossum45704552001-10-08 16:35:45 +00002209 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002210
2211 class B(A):
2212 def __init__(self):
2213 self.__super = super(B, self)
2214 def meth(self, a):
2215 return "B(%r)" % a + self.__super.meth(a)
2216
Guido van Rossum45704552001-10-08 16:35:45 +00002217 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002218
2219 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002220 def meth(self, a):
2221 return "C(%r)" % a + self.__super.meth(a)
2222 C._C__super = super(C)
2223
Guido van Rossum45704552001-10-08 16:35:45 +00002224 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002225
2226 class D(C, B):
2227 def meth(self, a):
2228 return "D(%r)" % a + super(D, self).meth(a)
2229
Guido van Rossum5b443c62001-12-03 15:38:28 +00002230 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2231
2232 # Test for subclassing super
2233
2234 class mysuper(super):
2235 def __init__(self, *args):
2236 return super(mysuper, self).__init__(*args)
2237
2238 class E(D):
2239 def meth(self, a):
2240 return "E(%r)" % a + mysuper(E, self).meth(a)
2241
2242 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2243
2244 class F(E):
2245 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002246 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002247 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2248 F._F__super = mysuper(F)
2249
2250 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2251
2252 # Make sure certain errors are raised
2253
2254 try:
2255 super(D, 42)
2256 except TypeError:
2257 pass
2258 else:
2259 raise TestFailed, "shouldn't allow super(D, 42)"
2260
2261 try:
2262 super(D, C())
2263 except TypeError:
2264 pass
2265 else:
2266 raise TestFailed, "shouldn't allow super(D, C())"
2267
2268 try:
2269 super(D).__get__(12)
2270 except TypeError:
2271 pass
2272 else:
2273 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2274
2275 try:
2276 super(D).__get__(C())
2277 except TypeError:
2278 pass
2279 else:
2280 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002281
Guido van Rossuma4541a32003-04-16 20:02:22 +00002282 # Make sure data descriptors can be overridden and accessed via super
2283 # (new feature in Python 2.3)
2284
2285 class DDbase(object):
2286 def getx(self): return 42
2287 x = property(getx)
2288
2289 class DDsub(DDbase):
2290 def getx(self): return "hello"
2291 x = property(getx)
2292
2293 dd = DDsub()
2294 vereq(dd.x, "hello")
2295 vereq(super(DDsub, dd).x, 42)
2296
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002297 # Ensure that super() lookup of descriptor from classmethod
2298 # works (SF ID# 743627)
2299
2300 class Base(object):
2301 aProp = property(lambda self: "foo")
2302
2303 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002304 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002305 def test(klass):
2306 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002307
2308 veris(Sub.test(), Base.aProp)
2309
Georg Brandl5d59c092006-09-30 08:43:30 +00002310 # Verify that super() doesn't allow keyword args
2311 try:
2312 super(Base, kw=1)
2313 except TypeError:
2314 pass
2315 else:
2316 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002317
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002318def inherits():
2319 if verbose: print "Testing inheritance from basic types..."
2320
2321 class hexint(int):
2322 def __repr__(self):
2323 return hex(self)
2324 def __add__(self, other):
2325 return hexint(int.__add__(self, other))
2326 # (Note that overriding __radd__ doesn't work,
2327 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002328 vereq(repr(hexint(7) + 9), "0x10")
2329 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002330 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002331 vereq(a, 12345)
2332 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002333 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002334 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002335 verify((+a).__class__ is int)
2336 verify((a >> 0).__class__ is int)
2337 verify((a << 0).__class__ is int)
2338 verify((hexint(0) << 12).__class__ is int)
2339 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002340
2341 class octlong(long):
2342 __slots__ = []
2343 def __str__(self):
2344 s = oct(self)
2345 if s[-1] == 'L':
2346 s = s[:-1]
2347 return s
2348 def __add__(self, other):
2349 return self.__class__(super(octlong, self).__add__(other))
2350 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002351 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002352 # (Note that overriding __radd__ here only seems to work
2353 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002354 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002355 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002356 vereq(a, 12345L)
2357 vereq(long(a), 12345L)
2358 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002359 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002360 verify((+a).__class__ is long)
2361 verify((-a).__class__ is long)
2362 verify((-octlong(0)).__class__ is long)
2363 verify((a >> 0).__class__ is long)
2364 verify((a << 0).__class__ is long)
2365 verify((a - 0).__class__ is long)
2366 verify((a * 1).__class__ is long)
2367 verify((a ** 1).__class__ is long)
2368 verify((a // 1).__class__ is long)
2369 verify((1 * a).__class__ is long)
2370 verify((a | 0).__class__ is long)
2371 verify((a ^ 0).__class__ is long)
2372 verify((a & -1L).__class__ is long)
2373 verify((octlong(0) << 12).__class__ is long)
2374 verify((octlong(0) >> 12).__class__ is long)
2375 verify(abs(octlong(0)).__class__ is long)
2376
2377 # Because octlong overrides __add__, we can't check the absence of +0
2378 # optimizations using octlong.
2379 class longclone(long):
2380 pass
2381 a = longclone(1)
2382 verify((a + 0).__class__ is long)
2383 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002384
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002385 # Check that negative clones don't segfault
2386 a = longclone(-1)
2387 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002388 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002389
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002390 class precfloat(float):
2391 __slots__ = ['prec']
2392 def __init__(self, value=0.0, prec=12):
2393 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002394 def __repr__(self):
2395 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002396 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002397 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002398 vereq(a, 12345.0)
2399 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002400 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002401 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002402 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002403
Tim Peters2400fa42001-09-12 19:12:49 +00002404 class madcomplex(complex):
2405 def __repr__(self):
2406 return "%.17gj%+.17g" % (self.imag, self.real)
2407 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002408 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002409 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002410 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002411 vereq(a, base)
2412 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002413 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002414 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002415 vereq(repr(a), "4j-3")
2416 vereq(a, base)
2417 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002418 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002419 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002420 veris((+a).__class__, complex)
2421 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002422 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002423 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002424 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002425 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002426 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002427 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002428 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002429
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002430 class madtuple(tuple):
2431 _rev = None
2432 def rev(self):
2433 if self._rev is not None:
2434 return self._rev
2435 L = list(self)
2436 L.reverse()
2437 self._rev = self.__class__(L)
2438 return self._rev
2439 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002440 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2441 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2442 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002443 for i in range(512):
2444 t = madtuple(range(i))
2445 u = t.rev()
2446 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002447 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002448 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002449 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002450 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002451 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002452 verify(a[:].__class__ is tuple)
2453 verify((a * 1).__class__ is tuple)
2454 verify((a * 0).__class__ is tuple)
2455 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002456 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002457 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002458 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002459 verify((a + a).__class__ is tuple)
2460 verify((a * 0).__class__ is tuple)
2461 verify((a * 1).__class__ is tuple)
2462 verify((a * 2).__class__ is tuple)
2463 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002464
2465 class madstring(str):
2466 _rev = None
2467 def rev(self):
2468 if self._rev is not None:
2469 return self._rev
2470 L = list(self)
2471 L.reverse()
2472 self._rev = self.__class__("".join(L))
2473 return self._rev
2474 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002475 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2476 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2477 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002478 for i in range(256):
2479 s = madstring("".join(map(chr, range(i))))
2480 t = s.rev()
2481 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002482 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002483 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002484 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002485 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002486
Tim Peters8fa5dd02001-09-12 02:18:30 +00002487 base = "\x00" * 5
2488 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002489 vereq(s, base)
2490 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002491 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002492 vereq(hash(s), hash(base))
2493 vereq({s: 1}[base], 1)
2494 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002495 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002496 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002497 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002498 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002499 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002500 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002501 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002502 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002503 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002504 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002505 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002506 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002507 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002508 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002509 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002510 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002511 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002512 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002513 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002514 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002515 identitytab = ''.join([chr(i) for i in range(256)])
2516 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002517 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002518 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002519 vereq(s.translate(identitytab, "x"), base)
2520 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002521 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002522 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002523 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002524 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002525 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002526 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002527 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002528 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002529 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002530 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002531
Guido van Rossum91ee7982001-08-30 20:52:40 +00002532 class madunicode(unicode):
2533 _rev = None
2534 def rev(self):
2535 if self._rev is not None:
2536 return self._rev
2537 L = list(self)
2538 L.reverse()
2539 self._rev = self.__class__(u"".join(L))
2540 return self._rev
2541 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002542 vereq(u, u"ABCDEF")
2543 vereq(u.rev(), madunicode(u"FEDCBA"))
2544 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002545 base = u"12345"
2546 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002547 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002548 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002549 vereq(hash(u), hash(base))
2550 vereq({u: 1}[base], 1)
2551 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002552 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002553 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002554 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002555 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002556 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002557 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002558 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002559 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002560 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002561 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002562 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002563 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002564 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002565 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002566 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002567 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002568 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002569 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002570 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002571 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002572 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002573 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002574 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002575 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002576 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002577 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002578 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002579 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002580 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002581 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002582 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002583 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002584 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002585 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002586 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002587 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002588 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002589 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002590
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002591 class sublist(list):
2592 pass
2593 a = sublist(range(5))
2594 vereq(a, range(5))
2595 a.append("hello")
2596 vereq(a, range(5) + ["hello"])
2597 a[5] = 5
2598 vereq(a, range(6))
2599 a.extend(range(6, 20))
2600 vereq(a, range(20))
2601 a[-5:] = []
2602 vereq(a, range(15))
2603 del a[10:15]
2604 vereq(len(a), 10)
2605 vereq(a, range(10))
2606 vereq(list(a), range(10))
2607 vereq(a[0], 0)
2608 vereq(a[9], 9)
2609 vereq(a[-10], 0)
2610 vereq(a[-1], 9)
2611 vereq(a[:5], range(5))
2612
Tim Peters59c9a642001-09-13 05:38:56 +00002613 class CountedInput(file):
2614 """Counts lines read by self.readline().
2615
2616 self.lineno is the 0-based ordinal of the last line read, up to
2617 a maximum of one greater than the number of lines in the file.
2618
2619 self.ateof is true if and only if the final "" line has been read,
2620 at which point self.lineno stops incrementing, and further calls
2621 to readline() continue to return "".
2622 """
2623
2624 lineno = 0
2625 ateof = 0
2626 def readline(self):
2627 if self.ateof:
2628 return ""
2629 s = file.readline(self)
2630 # Next line works too.
2631 # s = super(CountedInput, self).readline()
2632 self.lineno += 1
2633 if s == "":
2634 self.ateof = 1
2635 return s
2636
Tim Peters561f8992001-09-13 19:36:36 +00002637 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002638 lines = ['a\n', 'b\n', 'c\n']
2639 try:
2640 f.writelines(lines)
2641 f.close()
2642 f = CountedInput(TESTFN)
2643 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2644 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002645 vereq(expected, got)
2646 vereq(f.lineno, i)
2647 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002648 f.close()
2649 finally:
2650 try:
2651 f.close()
2652 except:
2653 pass
2654 try:
2655 import os
2656 os.unlink(TESTFN)
2657 except:
2658 pass
2659
Tim Peters808b94e2001-09-13 19:33:07 +00002660def keywords():
2661 if verbose:
2662 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002663 vereq(int(x=1), 1)
2664 vereq(float(x=2), 2.0)
2665 vereq(long(x=3), 3L)
2666 vereq(complex(imag=42, real=666), complex(666, 42))
2667 vereq(str(object=500), '500')
2668 vereq(unicode(string='abc', errors='strict'), u'abc')
2669 vereq(tuple(sequence=range(3)), (0, 1, 2))
2670 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002671 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002672
2673 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002674 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002675 try:
2676 constructor(bogus_keyword_arg=1)
2677 except TypeError:
2678 pass
2679 else:
2680 raise TestFailed("expected TypeError from bogus keyword "
2681 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002682
Tim Peters8fa45672001-09-13 21:01:29 +00002683def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002684 # XXX This test is disabled because rexec is not deemed safe
2685 return
Tim Peters8fa45672001-09-13 21:01:29 +00002686 import rexec
2687 if verbose:
2688 print "Testing interaction with restricted execution ..."
2689
2690 sandbox = rexec.RExec()
2691
2692 code1 = """f = open(%r, 'w')""" % TESTFN
2693 code2 = """f = file(%r, 'w')""" % TESTFN
2694 code3 = """\
2695f = open(%r)
2696t = type(f) # a sneaky way to get the file() constructor
2697f.close()
2698f = t(%r, 'w') # rexec can't catch this by itself
2699""" % (TESTFN, TESTFN)
2700
2701 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2702 f.close()
2703
2704 try:
2705 for code in code1, code2, code3:
2706 try:
2707 sandbox.r_exec(code)
2708 except IOError, msg:
2709 if str(msg).find("restricted") >= 0:
2710 outcome = "OK"
2711 else:
2712 outcome = "got an exception, but not an expected one"
2713 else:
2714 outcome = "expected a restricted-execution exception"
2715
2716 if outcome != "OK":
2717 raise TestFailed("%s, in %r" % (outcome, code))
2718
2719 finally:
2720 try:
2721 import os
2722 os.unlink(TESTFN)
2723 except:
2724 pass
2725
Tim Peters0ab085c2001-09-14 00:25:33 +00002726def str_subclass_as_dict_key():
2727 if verbose:
2728 print "Testing a str subclass used as dict key .."
2729
2730 class cistr(str):
2731 """Sublcass of str that computes __eq__ case-insensitively.
2732
2733 Also computes a hash code of the string in canonical form.
2734 """
2735
2736 def __init__(self, value):
2737 self.canonical = value.lower()
2738 self.hashcode = hash(self.canonical)
2739
2740 def __eq__(self, other):
2741 if not isinstance(other, cistr):
2742 other = cistr(other)
2743 return self.canonical == other.canonical
2744
2745 def __hash__(self):
2746 return self.hashcode
2747
Guido van Rossum45704552001-10-08 16:35:45 +00002748 vereq(cistr('ABC'), 'abc')
2749 vereq('aBc', cistr('ABC'))
2750 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002751
2752 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002753 vereq(d[cistr('one')], 1)
2754 vereq(d[cistr('tWo')], 2)
2755 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002756 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002757 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002758
Guido van Rossumab3b0342001-09-18 20:38:53 +00002759def classic_comparisons():
2760 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002761 class classic:
2762 pass
2763 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002764 if verbose: print " (base = %s)" % base
2765 class C(base):
2766 def __init__(self, value):
2767 self.value = int(value)
2768 def __cmp__(self, other):
2769 if isinstance(other, C):
2770 return cmp(self.value, other.value)
2771 if isinstance(other, int) or isinstance(other, long):
2772 return cmp(self.value, other)
2773 return NotImplemented
2774 c1 = C(1)
2775 c2 = C(2)
2776 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002777 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002778 c = {1: c1, 2: c2, 3: c3}
2779 for x in 1, 2, 3:
2780 for y in 1, 2, 3:
2781 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2782 for op in "<", "<=", "==", "!=", ">", ">=":
2783 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2784 "x=%d, y=%d" % (x, y))
2785 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2786 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2787
Guido van Rossum0639f592001-09-18 21:06:04 +00002788def rich_comparisons():
2789 if verbose:
2790 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002791 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002792 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002793 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002794 vereq(z, 1+0j)
2795 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002796 class ZZ(complex):
2797 def __eq__(self, other):
2798 try:
2799 return abs(self - other) <= 1e-6
2800 except:
2801 return NotImplemented
2802 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002803 vereq(zz, 1+0j)
2804 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002805
Guido van Rossum0639f592001-09-18 21:06:04 +00002806 class classic:
2807 pass
2808 for base in (classic, int, object, list):
2809 if verbose: print " (base = %s)" % base
2810 class C(base):
2811 def __init__(self, value):
2812 self.value = int(value)
2813 def __cmp__(self, other):
2814 raise TestFailed, "shouldn't call __cmp__"
2815 def __eq__(self, other):
2816 if isinstance(other, C):
2817 return self.value == other.value
2818 if isinstance(other, int) or isinstance(other, long):
2819 return self.value == other
2820 return NotImplemented
2821 def __ne__(self, other):
2822 if isinstance(other, C):
2823 return self.value != other.value
2824 if isinstance(other, int) or isinstance(other, long):
2825 return self.value != other
2826 return NotImplemented
2827 def __lt__(self, other):
2828 if isinstance(other, C):
2829 return self.value < other.value
2830 if isinstance(other, int) or isinstance(other, long):
2831 return self.value < other
2832 return NotImplemented
2833 def __le__(self, other):
2834 if isinstance(other, C):
2835 return self.value <= other.value
2836 if isinstance(other, int) or isinstance(other, long):
2837 return self.value <= other
2838 return NotImplemented
2839 def __gt__(self, other):
2840 if isinstance(other, C):
2841 return self.value > other.value
2842 if isinstance(other, int) or isinstance(other, long):
2843 return self.value > other
2844 return NotImplemented
2845 def __ge__(self, other):
2846 if isinstance(other, C):
2847 return self.value >= other.value
2848 if isinstance(other, int) or isinstance(other, long):
2849 return self.value >= other
2850 return NotImplemented
2851 c1 = C(1)
2852 c2 = C(2)
2853 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002854 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002855 c = {1: c1, 2: c2, 3: c3}
2856 for x in 1, 2, 3:
2857 for y in 1, 2, 3:
2858 for op in "<", "<=", "==", "!=", ">", ">=":
2859 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2860 "x=%d, y=%d" % (x, y))
2861 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2862 "x=%d, y=%d" % (x, y))
2863 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2864 "x=%d, y=%d" % (x, y))
2865
Guido van Rossum1952e382001-09-19 01:25:16 +00002866def coercions():
2867 if verbose: print "Testing coercions..."
2868 class I(int): pass
2869 coerce(I(0), 0)
2870 coerce(0, I(0))
2871 class L(long): pass
2872 coerce(L(0), 0)
2873 coerce(L(0), 0L)
2874 coerce(0, L(0))
2875 coerce(0L, L(0))
2876 class F(float): pass
2877 coerce(F(0), 0)
2878 coerce(F(0), 0L)
2879 coerce(F(0), 0.)
2880 coerce(0, F(0))
2881 coerce(0L, F(0))
2882 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002883 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002884 coerce(C(0), 0)
2885 coerce(C(0), 0L)
2886 coerce(C(0), 0.)
2887 coerce(C(0), 0j)
2888 coerce(0, C(0))
2889 coerce(0L, C(0))
2890 coerce(0., C(0))
2891 coerce(0j, C(0))
2892
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002893def descrdoc():
2894 if verbose: print "Testing descriptor doc strings..."
2895 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002896 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002897 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002898 check(file.name, "file name") # member descriptor
2899
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002900def setclass():
2901 if verbose: print "Testing __class__ assignment..."
2902 class C(object): pass
2903 class D(object): pass
2904 class E(object): pass
2905 class F(D, E): pass
2906 for cls in C, D, E, F:
2907 for cls2 in C, D, E, F:
2908 x = cls()
2909 x.__class__ = cls2
2910 verify(x.__class__ is cls2)
2911 x.__class__ = cls
2912 verify(x.__class__ is cls)
2913 def cant(x, C):
2914 try:
2915 x.__class__ = C
2916 except TypeError:
2917 pass
2918 else:
2919 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002920 try:
2921 delattr(x, "__class__")
2922 except TypeError:
2923 pass
2924 else:
2925 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002926 cant(C(), list)
2927 cant(list(), C)
2928 cant(C(), 1)
2929 cant(C(), object)
2930 cant(object(), list)
2931 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002932 class Int(int): __slots__ = []
2933 cant(2, Int)
2934 cant(Int(), int)
2935 cant(True, int)
2936 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002937 o = object()
2938 cant(o, type(1))
2939 cant(o, type(None))
2940 del o
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002941 class G(object):
2942 __slots__ = ["a", "b"]
2943 class H(object):
2944 __slots__ = ["b", "a"]
2945 try:
2946 unicode
2947 except NameError:
2948 class I(object):
2949 __slots__ = ["a", "b"]
2950 else:
2951 class I(object):
2952 __slots__ = [unicode("a"), unicode("b")]
2953 class J(object):
2954 __slots__ = ["c", "b"]
2955 class K(object):
2956 __slots__ = ["a", "b", "d"]
2957 class L(H):
2958 __slots__ = ["e"]
2959 class M(I):
2960 __slots__ = ["e"]
2961 class N(J):
2962 __slots__ = ["__weakref__"]
2963 class P(J):
2964 __slots__ = ["__dict__"]
2965 class Q(J):
2966 pass
2967 class R(J):
2968 __slots__ = ["__dict__", "__weakref__"]
2969
2970 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2971 x = cls()
2972 x.a = 1
2973 x.__class__ = cls2
2974 verify(x.__class__ is cls2,
2975 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2976 vereq(x.a, 1)
2977 x.__class__ = cls
2978 verify(x.__class__ is cls,
2979 "assigning %r as __class__ for %r silently failed" % (cls, x))
2980 vereq(x.a, 1)
2981 for cls in G, J, K, L, M, N, P, R, list, Int:
2982 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2983 if cls is cls2:
2984 continue
2985 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002986
Guido van Rossum6661be32001-10-26 04:26:12 +00002987def setdict():
2988 if verbose: print "Testing __dict__ assignment..."
2989 class C(object): pass
2990 a = C()
2991 a.__dict__ = {'b': 1}
2992 vereq(a.b, 1)
2993 def cant(x, dict):
2994 try:
2995 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002996 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002997 pass
2998 else:
2999 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
3000 cant(a, None)
3001 cant(a, [])
3002 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00003003 del a.__dict__ # Deleting __dict__ is allowed
Armin Rigo9790a272007-05-02 19:23:31 +00003004
3005 class Base(object):
3006 pass
3007 def verify_dict_readonly(x):
3008 """
3009 x has to be an instance of a class inheriting from Base.
3010 """
3011 cant(x, {})
3012 try:
3013 del x.__dict__
3014 except (AttributeError, TypeError):
3015 pass
3016 else:
3017 raise TestFailed, "shouldn't allow del %r.__dict__" % x
3018 dict_descr = Base.__dict__["__dict__"]
3019 try:
3020 dict_descr.__set__(x, {})
3021 except (AttributeError, TypeError):
3022 pass
3023 else:
3024 raise TestFailed, "dict_descr allowed access to %r's dict" % x
3025
3026 # Classes don't allow __dict__ assignment and have readonly dicts
3027 class Meta1(type, Base):
3028 pass
3029 class Meta2(Base, type):
3030 pass
3031 class D(object):
3032 __metaclass__ = Meta1
3033 class E(object):
3034 __metaclass__ = Meta2
3035 for cls in C, D, E:
3036 verify_dict_readonly(cls)
3037 class_dict = cls.__dict__
3038 try:
3039 class_dict["spam"] = "eggs"
3040 except TypeError:
3041 pass
3042 else:
3043 raise TestFailed, "%r's __dict__ can be modified" % cls
3044
3045 # Modules also disallow __dict__ assignment
3046 class Module1(types.ModuleType, Base):
3047 pass
3048 class Module2(Base, types.ModuleType):
3049 pass
3050 for ModuleType in Module1, Module2:
3051 mod = ModuleType("spam")
3052 verify_dict_readonly(mod)
3053 mod.__dict__["spam"] = "eggs"
3054
3055 # Exception's __dict__ can be replaced, but not deleted
3056 class Exception1(Exception, Base):
3057 pass
3058 class Exception2(Base, Exception):
3059 pass
3060 for ExceptionType in Exception, Exception1, Exception2:
3061 e = ExceptionType()
3062 e.__dict__ = {"a": 1}
3063 vereq(e.a, 1)
3064 try:
3065 del e.__dict__
3066 except (TypeError, AttributeError):
3067 pass
3068 else:
3069 raise TestFaied, "%r's __dict__ can be deleted" % e
3070
Guido van Rossum6661be32001-10-26 04:26:12 +00003071
Guido van Rossum3926a632001-09-25 16:25:58 +00003072def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003073 if verbose:
3074 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00003075 import pickle, cPickle
3076
3077 def sorteditems(d):
3078 L = d.items()
3079 L.sort()
3080 return L
3081
3082 global C
3083 class C(object):
3084 def __init__(self, a, b):
3085 super(C, self).__init__()
3086 self.a = a
3087 self.b = b
3088 def __repr__(self):
3089 return "C(%r, %r)" % (self.a, self.b)
3090
3091 global C1
3092 class C1(list):
3093 def __new__(cls, a, b):
3094 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00003095 def __getnewargs__(self):
3096 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00003097 def __init__(self, a, b):
3098 self.a = a
3099 self.b = b
3100 def __repr__(self):
3101 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3102
3103 global C2
3104 class C2(int):
3105 def __new__(cls, a, b, val=0):
3106 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00003107 def __getnewargs__(self):
3108 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00003109 def __init__(self, a, b, val=0):
3110 self.a = a
3111 self.b = b
3112 def __repr__(self):
3113 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3114
Guido van Rossum90c45142001-11-24 21:07:01 +00003115 global C3
3116 class C3(object):
3117 def __init__(self, foo):
3118 self.foo = foo
3119 def __getstate__(self):
3120 return self.foo
3121 def __setstate__(self, foo):
3122 self.foo = foo
3123
3124 global C4classic, C4
3125 class C4classic: # classic
3126 pass
3127 class C4(C4classic, object): # mixed inheritance
3128 pass
3129
Guido van Rossum3926a632001-09-25 16:25:58 +00003130 for p in pickle, cPickle:
3131 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003132 if verbose:
3133 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00003134
3135 for cls in C, C1, C2:
3136 s = p.dumps(cls, bin)
3137 cls2 = p.loads(s)
3138 verify(cls2 is cls)
3139
3140 a = C1(1, 2); a.append(42); a.append(24)
3141 b = C2("hello", "world", 42)
3142 s = p.dumps((a, b), bin)
3143 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00003144 vereq(x.__class__, a.__class__)
3145 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
3146 vereq(y.__class__, b.__class__)
3147 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00003148 vereq(repr(x), repr(a))
3149 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00003150 if verbose:
3151 print "a = x =", a
3152 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00003153 # Test for __getstate__ and __setstate__ on new style class
3154 u = C3(42)
3155 s = p.dumps(u, bin)
3156 v = p.loads(s)
3157 veris(u.__class__, v.__class__)
3158 vereq(u.foo, v.foo)
3159 # Test for picklability of hybrid class
3160 u = C4()
3161 u.foo = 42
3162 s = p.dumps(u, bin)
3163 v = p.loads(s)
3164 veris(u.__class__, v.__class__)
3165 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003166
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003167 # Testing copy.deepcopy()
3168 if verbose:
3169 print "deepcopy"
3170 import copy
3171 for cls in C, C1, C2:
3172 cls2 = copy.deepcopy(cls)
3173 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003174
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003175 a = C1(1, 2); a.append(42); a.append(24)
3176 b = C2("hello", "world", 42)
3177 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003178 vereq(x.__class__, a.__class__)
3179 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
3180 vereq(y.__class__, b.__class__)
3181 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00003182 vereq(repr(x), repr(a))
3183 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003184 if verbose:
3185 print "a = x =", a
3186 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003187
Guido van Rossum8c842552002-03-14 23:05:54 +00003188def pickleslots():
3189 if verbose: print "Testing pickling of classes with __slots__ ..."
3190 import pickle, cPickle
3191 # Pickling of classes with __slots__ but without __getstate__ should fail
3192 global B, C, D, E
3193 class B(object):
3194 pass
3195 for base in [object, B]:
3196 class C(base):
3197 __slots__ = ['a']
3198 class D(C):
3199 pass
3200 try:
3201 pickle.dumps(C())
3202 except TypeError:
3203 pass
3204 else:
3205 raise TestFailed, "should fail: pickle C instance - %s" % base
3206 try:
3207 cPickle.dumps(C())
3208 except TypeError:
3209 pass
3210 else:
3211 raise TestFailed, "should fail: cPickle C instance - %s" % base
3212 try:
3213 pickle.dumps(C())
3214 except TypeError:
3215 pass
3216 else:
3217 raise TestFailed, "should fail: pickle D instance - %s" % base
3218 try:
3219 cPickle.dumps(D())
3220 except TypeError:
3221 pass
3222 else:
3223 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003224 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00003225 class C(base):
3226 __slots__ = ['a']
3227 def __getstate__(self):
3228 try:
3229 d = self.__dict__.copy()
3230 except AttributeError:
3231 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003232 for cls in self.__class__.__mro__:
3233 for sn in cls.__dict__.get('__slots__', ()):
3234 try:
3235 d[sn] = getattr(self, sn)
3236 except AttributeError:
3237 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00003238 return d
3239 def __setstate__(self, d):
3240 for k, v in d.items():
3241 setattr(self, k, v)
3242 class D(C):
3243 pass
3244 # Now it should work
3245 x = C()
3246 y = pickle.loads(pickle.dumps(x))
3247 vereq(hasattr(y, 'a'), 0)
3248 y = cPickle.loads(cPickle.dumps(x))
3249 vereq(hasattr(y, 'a'), 0)
3250 x.a = 42
3251 y = pickle.loads(pickle.dumps(x))
3252 vereq(y.a, 42)
3253 y = cPickle.loads(cPickle.dumps(x))
3254 vereq(y.a, 42)
3255 x = D()
3256 x.a = 42
3257 x.b = 100
3258 y = pickle.loads(pickle.dumps(x))
3259 vereq(y.a + y.b, 142)
3260 y = cPickle.loads(cPickle.dumps(x))
3261 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003262 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003263 class E(C):
3264 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003265 x = E()
3266 x.a = 42
3267 x.b = "foo"
3268 y = pickle.loads(pickle.dumps(x))
3269 vereq(y.a, x.a)
3270 vereq(y.b, x.b)
3271 y = cPickle.loads(cPickle.dumps(x))
3272 vereq(y.a, x.a)
3273 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003274
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003275def copies():
3276 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
3277 import copy
3278 class C(object):
3279 pass
3280
3281 a = C()
3282 a.foo = 12
3283 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003284 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003285
3286 a.bar = [1,2,3]
3287 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003288 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003289 verify(c.bar is a.bar)
3290
3291 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003292 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003293 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003294 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003295
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003296def binopoverride():
3297 if verbose: print "Testing overrides of binary operations..."
3298 class I(int):
3299 def __repr__(self):
3300 return "I(%r)" % int(self)
3301 def __add__(self, other):
3302 return I(int(self) + int(other))
3303 __radd__ = __add__
3304 def __pow__(self, other, mod=None):
3305 if mod is None:
3306 return I(pow(int(self), int(other)))
3307 else:
3308 return I(pow(int(self), int(other), int(mod)))
3309 def __rpow__(self, other, mod=None):
3310 if mod is None:
3311 return I(pow(int(other), int(self), mod))
3312 else:
3313 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003314
Walter Dörwald70a6b492004-02-12 17:35:32 +00003315 vereq(repr(I(1) + I(2)), "I(3)")
3316 vereq(repr(I(1) + 2), "I(3)")
3317 vereq(repr(1 + I(2)), "I(3)")
3318 vereq(repr(I(2) ** I(3)), "I(8)")
3319 vereq(repr(2 ** I(3)), "I(8)")
3320 vereq(repr(I(2) ** 3), "I(8)")
3321 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003322 class S(str):
3323 def __eq__(self, other):
3324 return self.lower() == other.lower()
3325
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003326def subclasspropagation():
3327 if verbose: print "Testing propagation of slot functions to subclasses..."
3328 class A(object):
3329 pass
3330 class B(A):
3331 pass
3332 class C(A):
3333 pass
3334 class D(B, C):
3335 pass
3336 d = D()
Tim Peters171b8682006-04-11 01:59:34 +00003337 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003338 A.__hash__ = lambda self: 42
3339 vereq(hash(d), 42)
3340 C.__hash__ = lambda self: 314
3341 vereq(hash(d), 314)
3342 B.__hash__ = lambda self: 144
3343 vereq(hash(d), 144)
3344 D.__hash__ = lambda self: 100
3345 vereq(hash(d), 100)
3346 del D.__hash__
3347 vereq(hash(d), 144)
3348 del B.__hash__
3349 vereq(hash(d), 314)
3350 del C.__hash__
3351 vereq(hash(d), 42)
3352 del A.__hash__
Tim Peters171b8682006-04-11 01:59:34 +00003353 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003354 d.foo = 42
3355 d.bar = 42
3356 vereq(d.foo, 42)
3357 vereq(d.bar, 42)
3358 def __getattribute__(self, name):
3359 if name == "foo":
3360 return 24
3361 return object.__getattribute__(self, name)
3362 A.__getattribute__ = __getattribute__
3363 vereq(d.foo, 24)
3364 vereq(d.bar, 42)
3365 def __getattr__(self, name):
3366 if name in ("spam", "foo", "bar"):
3367 return "hello"
3368 raise AttributeError, name
3369 B.__getattr__ = __getattr__
3370 vereq(d.spam, "hello")
3371 vereq(d.foo, 24)
3372 vereq(d.bar, 42)
3373 del A.__getattribute__
3374 vereq(d.foo, 42)
3375 del d.foo
3376 vereq(d.foo, "hello")
3377 vereq(d.bar, 42)
3378 del B.__getattr__
3379 try:
3380 d.foo
3381 except AttributeError:
3382 pass
3383 else:
3384 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003385
Guido van Rossume7f3e242002-06-14 02:35:45 +00003386 # Test a nasty bug in recurse_down_subclasses()
3387 import gc
3388 class A(object):
3389 pass
3390 class B(A):
3391 pass
3392 del B
3393 gc.collect()
3394 A.__setitem__ = lambda *a: None # crash
3395
Tim Petersfc57ccb2001-10-12 02:38:24 +00003396def buffer_inherit():
3397 import binascii
3398 # SF bug [#470040] ParseTuple t# vs subclasses.
3399 if verbose:
3400 print "Testing that buffer interface is inherited ..."
3401
3402 class MyStr(str):
3403 pass
3404 base = 'abc'
3405 m = MyStr(base)
3406 # b2a_hex uses the buffer interface to get its argument's value, via
3407 # PyArg_ParseTuple 't#' code.
3408 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3409
3410 # It's not clear that unicode will continue to support the character
3411 # buffer interface, and this test will fail if that's taken away.
3412 class MyUni(unicode):
3413 pass
3414 base = u'abc'
3415 m = MyUni(base)
3416 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3417
3418 class MyInt(int):
3419 pass
3420 m = MyInt(42)
3421 try:
3422 binascii.b2a_hex(m)
3423 raise TestFailed('subclass of int should not have a buffer interface')
3424 except TypeError:
3425 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003426
Tim Petersc9933152001-10-16 20:18:24 +00003427def str_of_str_subclass():
3428 import binascii
3429 import cStringIO
3430
3431 if verbose:
3432 print "Testing __str__ defined in subclass of str ..."
3433
3434 class octetstring(str):
3435 def __str__(self):
3436 return binascii.b2a_hex(self)
3437 def __repr__(self):
3438 return self + " repr"
3439
3440 o = octetstring('A')
3441 vereq(type(o), octetstring)
3442 vereq(type(str(o)), str)
3443 vereq(type(repr(o)), str)
3444 vereq(ord(o), 0x41)
3445 vereq(str(o), '41')
3446 vereq(repr(o), 'A repr')
3447 vereq(o.__str__(), '41')
3448 vereq(o.__repr__(), 'A repr')
3449
3450 capture = cStringIO.StringIO()
3451 # Calling str() or not exercises different internal paths.
3452 print >> capture, o
3453 print >> capture, str(o)
3454 vereq(capture.getvalue(), '41\n41\n')
3455 capture.close()
3456
Guido van Rossumc8e56452001-10-22 00:43:43 +00003457def kwdargs():
3458 if verbose: print "Testing keyword arguments to __init__, __call__..."
3459 def f(a): return a
3460 vereq(f.__call__(a=42), 42)
3461 a = []
3462 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003463 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003464
Brett Cannon22565aa2006-06-09 22:31:23 +00003465def recursive__call__():
3466 if verbose: print ("Testing recursive __call__() by setting to instance of "
3467 "class ...")
3468 class A(object):
3469 pass
3470
3471 A.__call__ = A()
3472 try:
3473 A()()
3474 except RuntimeError:
3475 pass
3476 else:
3477 raise TestFailed("Recursion limit should have been reached for "
3478 "__call__()")
3479
Guido van Rossumed87ad82001-10-30 02:33:02 +00003480def delhook():
3481 if verbose: print "Testing __del__ hook..."
3482 log = []
3483 class C(object):
3484 def __del__(self):
3485 log.append(1)
3486 c = C()
3487 vereq(log, [])
3488 del c
3489 vereq(log, [1])
3490
Guido van Rossum29d26062001-12-11 04:37:34 +00003491 class D(object): pass
3492 d = D()
3493 try: del d[0]
3494 except TypeError: pass
3495 else: raise TestFailed, "invalid del() didn't raise TypeError"
3496
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003497def hashinherit():
3498 if verbose: print "Testing hash of mutable subclasses..."
3499
3500 class mydict(dict):
3501 pass
3502 d = mydict()
3503 try:
3504 hash(d)
3505 except TypeError:
3506 pass
3507 else:
3508 raise TestFailed, "hash() of dict subclass should fail"
3509
3510 class mylist(list):
3511 pass
3512 d = mylist()
3513 try:
3514 hash(d)
3515 except TypeError:
3516 pass
3517 else:
3518 raise TestFailed, "hash() of list subclass should fail"
3519
Guido van Rossum29d26062001-12-11 04:37:34 +00003520def strops():
3521 try: 'a' + 5
3522 except TypeError: pass
3523 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3524
3525 try: ''.split('')
3526 except ValueError: pass
3527 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3528
3529 try: ''.join([0])
3530 except TypeError: pass
3531 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3532
3533 try: ''.rindex('5')
3534 except ValueError: pass
3535 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3536
Guido van Rossum29d26062001-12-11 04:37:34 +00003537 try: '%(n)s' % None
3538 except TypeError: pass
3539 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3540
3541 try: '%(n' % {}
3542 except ValueError: pass
3543 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3544
3545 try: '%*s' % ('abc')
3546 except TypeError: pass
3547 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3548
3549 try: '%*.*s' % ('abc', 5)
3550 except TypeError: pass
3551 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3552
3553 try: '%s' % (1, 2)
3554 except TypeError: pass
3555 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3556
3557 try: '%' % None
3558 except ValueError: pass
3559 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3560
3561 vereq('534253'.isdigit(), 1)
3562 vereq('534253x'.isdigit(), 0)
3563 vereq('%c' % 5, '\x05')
3564 vereq('%c' % '5', '5')
3565
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003566def deepcopyrecursive():
3567 if verbose: print "Testing deepcopy of recursive objects..."
3568 class Node:
3569 pass
3570 a = Node()
3571 b = Node()
3572 a.b = b
3573 b.a = a
3574 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003575
Guido van Rossumd7035672002-03-12 20:43:31 +00003576def modules():
3577 if verbose: print "Testing uninitialized module objects..."
3578 from types import ModuleType as M
3579 m = M.__new__(M)
3580 str(m)
3581 vereq(hasattr(m, "__name__"), 0)
3582 vereq(hasattr(m, "__file__"), 0)
3583 vereq(hasattr(m, "foo"), 0)
3584 vereq(m.__dict__, None)
3585 m.foo = 1
3586 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003587
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003588def dictproxyiterkeys():
3589 class C(object):
3590 def meth(self):
3591 pass
3592 if verbose: print "Testing dict-proxy iterkeys..."
3593 keys = [ key for key in C.__dict__.iterkeys() ]
3594 keys.sort()
3595 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3596
3597def dictproxyitervalues():
3598 class C(object):
3599 def meth(self):
3600 pass
3601 if verbose: print "Testing dict-proxy itervalues..."
3602 values = [ values for values in C.__dict__.itervalues() ]
3603 vereq(len(values), 5)
3604
3605def dictproxyiteritems():
3606 class C(object):
3607 def meth(self):
3608 pass
3609 if verbose: print "Testing dict-proxy iteritems..."
3610 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3611 keys.sort()
3612 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3613
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003614def funnynew():
3615 if verbose: print "Testing __new__ returning something unexpected..."
3616 class C(object):
3617 def __new__(cls, arg):
3618 if isinstance(arg, str): return [1, 2, 3]
3619 elif isinstance(arg, int): return object.__new__(D)
3620 else: return object.__new__(cls)
3621 class D(C):
3622 def __init__(self, arg):
3623 self.foo = arg
3624 vereq(C("1"), [1, 2, 3])
3625 vereq(D("1"), [1, 2, 3])
3626 d = D(None)
3627 veris(d.foo, None)
3628 d = C(1)
3629 vereq(isinstance(d, D), True)
3630 vereq(d.foo, 1)
3631 d = D(1)
3632 vereq(isinstance(d, D), True)
3633 vereq(d.foo, 1)
3634
Guido van Rossume8fc6402002-04-16 16:44:51 +00003635def imulbug():
3636 # SF bug 544647
3637 if verbose: print "Testing for __imul__ problems..."
3638 class C(object):
3639 def __imul__(self, other):
3640 return (self, other)
3641 x = C()
3642 y = x
3643 y *= 1.0
3644 vereq(y, (x, 1.0))
3645 y = x
3646 y *= 2
3647 vereq(y, (x, 2))
3648 y = x
3649 y *= 3L
3650 vereq(y, (x, 3L))
3651 y = x
3652 y *= 1L<<100
3653 vereq(y, (x, 1L<<100))
3654 y = x
3655 y *= None
3656 vereq(y, (x, None))
3657 y = x
3658 y *= "foo"
3659 vereq(y, (x, "foo"))
3660
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003661def docdescriptor():
3662 # SF bug 542984
3663 if verbose: print "Testing __doc__ descriptor..."
3664 class DocDescr(object):
3665 def __get__(self, object, otype):
3666 if object:
3667 object = object.__class__.__name__ + ' instance'
3668 if otype:
3669 otype = otype.__name__
3670 return 'object=%s; type=%s' % (object, otype)
3671 class OldClass:
3672 __doc__ = DocDescr()
3673 class NewClass(object):
3674 __doc__ = DocDescr()
3675 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3676 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3677 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3678 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3679
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003680def copy_setstate():
3681 if verbose:
3682 print "Testing that copy.*copy() correctly uses __setstate__..."
3683 import copy
3684 class C(object):
3685 def __init__(self, foo=None):
3686 self.foo = foo
3687 self.__foo = foo
3688 def setfoo(self, foo=None):
3689 self.foo = foo
3690 def getfoo(self):
3691 return self.__foo
3692 def __getstate__(self):
3693 return [self.foo]
3694 def __setstate__(self, lst):
3695 assert len(lst) == 1
3696 self.__foo = self.foo = lst[0]
3697 a = C(42)
3698 a.setfoo(24)
3699 vereq(a.foo, 24)
3700 vereq(a.getfoo(), 42)
3701 b = copy.copy(a)
3702 vereq(b.foo, 24)
3703 vereq(b.getfoo(), 24)
3704 b = copy.deepcopy(a)
3705 vereq(b.foo, 24)
3706 vereq(b.getfoo(), 24)
3707
Guido van Rossum09638c12002-06-13 19:17:46 +00003708def slices():
3709 if verbose:
3710 print "Testing cases with slices and overridden __getitem__ ..."
3711 # Strings
3712 vereq("hello"[:4], "hell")
3713 vereq("hello"[slice(4)], "hell")
3714 vereq(str.__getitem__("hello", slice(4)), "hell")
3715 class S(str):
3716 def __getitem__(self, x):
3717 return str.__getitem__(self, x)
3718 vereq(S("hello")[:4], "hell")
3719 vereq(S("hello")[slice(4)], "hell")
3720 vereq(S("hello").__getitem__(slice(4)), "hell")
3721 # Tuples
3722 vereq((1,2,3)[:2], (1,2))
3723 vereq((1,2,3)[slice(2)], (1,2))
3724 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3725 class T(tuple):
3726 def __getitem__(self, x):
3727 return tuple.__getitem__(self, x)
3728 vereq(T((1,2,3))[:2], (1,2))
3729 vereq(T((1,2,3))[slice(2)], (1,2))
3730 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3731 # Lists
3732 vereq([1,2,3][:2], [1,2])
3733 vereq([1,2,3][slice(2)], [1,2])
3734 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3735 class L(list):
3736 def __getitem__(self, x):
3737 return list.__getitem__(self, x)
3738 vereq(L([1,2,3])[:2], [1,2])
3739 vereq(L([1,2,3])[slice(2)], [1,2])
3740 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3741 # Now do lists and __setitem__
3742 a = L([1,2,3])
3743 a[slice(1, 3)] = [3,2]
3744 vereq(a, [1,3,2])
3745 a[slice(0, 2, 1)] = [3,1]
3746 vereq(a, [3,1,2])
3747 a.__setitem__(slice(1, 3), [2,1])
3748 vereq(a, [3,2,1])
3749 a.__setitem__(slice(0, 2, 1), [2,3])
3750 vereq(a, [2,3,1])
3751
Tim Peters2484aae2002-07-11 06:56:07 +00003752def subtype_resurrection():
3753 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003754 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003755
3756 class C(object):
3757 container = []
3758
3759 def __del__(self):
3760 # resurrect the instance
3761 C.container.append(self)
3762
3763 c = C()
3764 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003765 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003766 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003767 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003768
3769 # If that didn't blow up, it's also interesting to see whether clearing
3770 # the last container slot works: that will attempt to delete c again,
3771 # which will cause c to get appended back to the container again "during"
3772 # the del.
3773 del C.container[-1]
3774 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003775 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003776
Tim Peters14cb1e12002-07-11 18:26:21 +00003777 # Make c mortal again, so that the test framework with -l doesn't report
3778 # it as a leak.
3779 del C.__del__
3780
Guido van Rossum2d702462002-08-06 21:28:28 +00003781def slottrash():
3782 # Deallocating deeply nested slotted trash caused stack overflows
3783 if verbose:
3784 print "Testing slot trash..."
3785 class trash(object):
3786 __slots__ = ['x']
3787 def __init__(self, x):
3788 self.x = x
3789 o = None
3790 for i in xrange(50000):
3791 o = trash(o)
3792 del o
3793
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003794def slotmultipleinheritance():
3795 # SF bug 575229, multiple inheritance w/ slots dumps core
3796 class A(object):
3797 __slots__=()
3798 class B(object):
3799 pass
3800 class C(A,B) :
3801 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003802 vereq(C.__basicsize__, B.__basicsize__)
3803 verify(hasattr(C, '__dict__'))
3804 verify(hasattr(C, '__weakref__'))
3805 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003806
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003807def testrmul():
3808 # SF patch 592646
3809 if verbose:
3810 print "Testing correct invocation of __rmul__..."
3811 class C(object):
3812 def __mul__(self, other):
3813 return "mul"
3814 def __rmul__(self, other):
3815 return "rmul"
3816 a = C()
3817 vereq(a*2, "mul")
3818 vereq(a*2.2, "mul")
3819 vereq(2*a, "rmul")
3820 vereq(2.2*a, "rmul")
3821
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003822def testipow():
3823 # [SF bug 620179]
3824 if verbose:
3825 print "Testing correct invocation of __ipow__..."
3826 class C(object):
3827 def __ipow__(self, other):
3828 pass
3829 a = C()
3830 a **= 2
3831
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003832def do_this_first():
3833 if verbose:
3834 print "Testing SF bug 551412 ..."
3835 # This dumps core when SF bug 551412 isn't fixed --
3836 # but only when test_descr.py is run separately.
3837 # (That can't be helped -- as soon as PyType_Ready()
3838 # is called for PyLong_Type, the bug is gone.)
3839 class UserLong(object):
3840 def __pow__(self, *args):
3841 pass
3842 try:
3843 pow(0L, UserLong(), 0L)
3844 except:
3845 pass
3846
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003847 if verbose:
3848 print "Testing SF bug 570483..."
3849 # Another segfault only when run early
3850 # (before PyType_Ready(tuple) is called)
3851 type.mro(tuple)
3852
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003853def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003854 if verbose:
3855 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003856 # stuff that should work:
3857 class C(object):
3858 pass
3859 class C2(object):
3860 def __getattribute__(self, attr):
3861 if attr == 'a':
3862 return 2
3863 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003864 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003865 def meth(self):
3866 return 1
3867 class D(C):
3868 pass
3869 class E(D):
3870 pass
3871 d = D()
3872 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003873 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003874 D.__bases__ = (C2,)
3875 vereq(d.meth(), 1)
3876 vereq(e.meth(), 1)
3877 vereq(d.a, 2)
3878 vereq(e.a, 2)
3879 vereq(C2.__subclasses__(), [D])
3880
3881 # stuff that shouldn't:
3882 class L(list):
3883 pass
3884
3885 try:
3886 L.__bases__ = (dict,)
3887 except TypeError:
3888 pass
3889 else:
3890 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3891
3892 try:
3893 list.__bases__ = (dict,)
3894 except TypeError:
3895 pass
3896 else:
3897 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3898
3899 try:
Michael W. Hudsonf3904422006-11-23 13:54:04 +00003900 D.__bases__ = (C2, list)
3901 except TypeError:
3902 pass
3903 else:
3904 assert 0, "best_base calculation found wanting"
3905
3906 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003907 del D.__bases__
3908 except TypeError:
3909 pass
3910 else:
3911 raise TestFailed, "shouldn't be able to delete .__bases__"
3912
3913 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003914 D.__bases__ = ()
3915 except TypeError, msg:
3916 if str(msg) == "a new-style class can't have only classic bases":
3917 raise TestFailed, "wrong error message for .__bases__ = ()"
3918 else:
3919 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3920
3921 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003922 D.__bases__ = (D,)
3923 except TypeError:
3924 pass
3925 else:
3926 # actually, we'll have crashed by here...
3927 raise TestFailed, "shouldn't be able to create inheritance cycles"
3928
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003929 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003930 D.__bases__ = (C, C)
3931 except TypeError:
3932 pass
3933 else:
3934 raise TestFailed, "didn't detect repeated base classes"
3935
3936 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003937 D.__bases__ = (E,)
3938 except TypeError:
3939 pass
3940 else:
3941 raise TestFailed, "shouldn't be able to create inheritance cycles"
3942
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003943 # let's throw a classic class into the mix:
3944 class Classic:
3945 def meth2(self):
3946 return 3
3947
3948 D.__bases__ = (C, Classic)
3949
3950 vereq(d.meth2(), 3)
3951 vereq(e.meth2(), 3)
3952 try:
3953 d.a
3954 except AttributeError:
3955 pass
3956 else:
3957 raise TestFailed, "attribute should have vanished"
3958
3959 try:
3960 D.__bases__ = (Classic,)
3961 except TypeError:
3962 pass
3963 else:
3964 raise TestFailed, "new-style class must have a new-style base"
3965
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003966def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003967 if verbose:
3968 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003969 class WorkOnce(type):
3970 def __new__(self, name, bases, ns):
3971 self.flag = 0
3972 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3973 def mro(self):
3974 if self.flag > 0:
3975 raise RuntimeError, "bozo"
3976 else:
3977 self.flag += 1
3978 return type.mro(self)
3979
3980 class WorkAlways(type):
3981 def mro(self):
3982 # this is here to make sure that .mro()s aren't called
3983 # with an exception set (which was possible at one point).
3984 # An error message will be printed in a debug build.
3985 # What's a good way to test for this?
3986 return type.mro(self)
3987
3988 class C(object):
3989 pass
3990
3991 class C2(object):
3992 pass
3993
3994 class D(C):
3995 pass
3996
3997 class E(D):
3998 pass
3999
4000 class F(D):
4001 __metaclass__ = WorkOnce
4002
4003 class G(D):
4004 __metaclass__ = WorkAlways
4005
4006 # Immediate subclasses have their mro's adjusted in alphabetical
4007 # order, so E's will get adjusted before adjusting F's fails. We
4008 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00004009
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004010 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00004011 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004012
4013 try:
4014 D.__bases__ = (C2,)
4015 except RuntimeError:
4016 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00004017 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004018 else:
4019 raise TestFailed, "exception not propagated"
4020
4021def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00004022 if verbose:
4023 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004024 class A(object):
4025 pass
4026
4027 class B(object):
4028 pass
4029
4030 class C(A, B):
4031 pass
4032
4033 class D(A, B):
4034 pass
4035
4036 class E(C, D):
4037 pass
4038
4039 try:
4040 C.__bases__ = (B, A)
4041 except TypeError:
4042 pass
4043 else:
4044 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00004045
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004046def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00004047 if verbose:
4048 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004049 class C(object):
4050 pass
4051
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00004052 # C.__module__ could be 'test_descr' or '__main__'
4053 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00004054
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00004055 C.__name__ = 'D'
4056 vereq((C.__module__, C.__name__), (mod, 'D'))
4057
4058 C.__name__ = 'D.E'
4059 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00004060
Guido van Rossum613f24f2003-01-06 23:00:59 +00004061def subclass_right_op():
4062 if verbose:
4063 print "Testing correct dispatch of subclass overloading __r<op>__..."
4064
4065 # This code tests various cases where right-dispatch of a subclass
4066 # should be preferred over left-dispatch of a base class.
4067
4068 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4069
4070 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00004071 def __floordiv__(self, other):
4072 return "B.__floordiv__"
4073 def __rfloordiv__(self, other):
4074 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00004075
Guido van Rossumf389c772003-02-27 20:04:19 +00004076 vereq(B(1) // 1, "B.__floordiv__")
4077 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00004078
4079 # Case 2: subclass of object; this is just the baseline for case 3
4080
4081 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00004082 def __floordiv__(self, other):
4083 return "C.__floordiv__"
4084 def __rfloordiv__(self, other):
4085 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00004086
Guido van Rossumf389c772003-02-27 20:04:19 +00004087 vereq(C() // 1, "C.__floordiv__")
4088 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00004089
4090 # Case 3: subclass of new-style class; here it gets interesting
4091
4092 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00004093 def __floordiv__(self, other):
4094 return "D.__floordiv__"
4095 def __rfloordiv__(self, other):
4096 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00004097
Guido van Rossumf389c772003-02-27 20:04:19 +00004098 vereq(D() // C(), "D.__floordiv__")
4099 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00004100
4101 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4102
4103 class E(C):
4104 pass
4105
Guido van Rossumf389c772003-02-27 20:04:19 +00004106 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00004107
Guido van Rossumf389c772003-02-27 20:04:19 +00004108 vereq(E() // 1, "C.__floordiv__")
4109 vereq(1 // E(), "C.__rfloordiv__")
4110 vereq(E() // C(), "C.__floordiv__")
4111 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00004112
Guido van Rossum373c7412003-01-07 13:41:37 +00004113def dict_type_with_metaclass():
4114 if verbose:
4115 print "Testing type of __dict__ when __metaclass__ set..."
4116
4117 class B(object):
4118 pass
4119 class M(type):
4120 pass
4121 class C:
4122 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4123 __metaclass__ = M
4124 veris(type(C.__dict__), type(B.__dict__))
4125
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004126def meth_class_get():
4127 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004128 if verbose:
4129 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004130 # Baseline
4131 arg = [1, 2, 3]
4132 res = {1: None, 2: None, 3: None}
4133 vereq(dict.fromkeys(arg), res)
4134 vereq({}.fromkeys(arg), res)
4135 # Now get the descriptor
4136 descr = dict.__dict__["fromkeys"]
4137 # More baseline using the descriptor directly
4138 vereq(descr.__get__(None, dict)(arg), res)
4139 vereq(descr.__get__({})(arg), res)
4140 # Now check various error cases
4141 try:
4142 descr.__get__(None, None)
4143 except TypeError:
4144 pass
4145 else:
4146 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
4147 try:
4148 descr.__get__(42)
4149 except TypeError:
4150 pass
4151 else:
4152 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
4153 try:
4154 descr.__get__(None, 42)
4155 except TypeError:
4156 pass
4157 else:
4158 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
4159 try:
4160 descr.__get__(None, int)
4161 except TypeError:
4162 pass
4163 else:
4164 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
4165
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004166def isinst_isclass():
4167 if verbose:
4168 print "Testing proxy isinstance() and isclass()..."
4169 class Proxy(object):
4170 def __init__(self, obj):
4171 self.__obj = obj
4172 def __getattribute__(self, name):
4173 if name.startswith("_Proxy__"):
4174 return object.__getattribute__(self, name)
4175 else:
4176 return getattr(self.__obj, name)
4177 # Test with a classic class
4178 class C:
4179 pass
4180 a = C()
4181 pa = Proxy(a)
4182 verify(isinstance(a, C)) # Baseline
4183 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004184 # Test with a classic subclass
4185 class D(C):
4186 pass
4187 a = D()
4188 pa = Proxy(a)
4189 verify(isinstance(a, C)) # Baseline
4190 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004191 # Test with a new-style class
4192 class C(object):
4193 pass
4194 a = C()
4195 pa = Proxy(a)
4196 verify(isinstance(a, C)) # Baseline
4197 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004198 # Test with a new-style subclass
4199 class D(C):
4200 pass
4201 a = D()
4202 pa = Proxy(a)
4203 verify(isinstance(a, C)) # Baseline
4204 verify(isinstance(pa, C)) # Test
4205
4206def proxysuper():
4207 if verbose:
4208 print "Testing super() for a proxy object..."
4209 class Proxy(object):
4210 def __init__(self, obj):
4211 self.__obj = obj
4212 def __getattribute__(self, name):
4213 if name.startswith("_Proxy__"):
4214 return object.__getattribute__(self, name)
4215 else:
4216 return getattr(self.__obj, name)
4217
4218 class B(object):
4219 def f(self):
4220 return "B.f"
4221
4222 class C(B):
4223 def f(self):
4224 return super(C, self).f() + "->C.f"
4225
4226 obj = C()
4227 p = Proxy(obj)
4228 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004229
Guido van Rossum52b27052003-04-15 20:05:10 +00004230def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004231 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00004232 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004233 try:
4234 object.__setattr__(str, "foo", 42)
4235 except TypeError:
4236 pass
4237 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004238 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004239 try:
4240 object.__delattr__(str, "lower")
4241 except TypeError:
4242 pass
4243 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004244 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004245
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004246def weakref_segfault():
4247 # SF 742911
4248 if verbose:
4249 print "Testing weakref segfault..."
4250
4251 import weakref
4252
4253 class Provoker:
4254 def __init__(self, referrent):
4255 self.ref = weakref.ref(referrent)
4256
4257 def __del__(self):
4258 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004259
4260 class Oops(object):
4261 pass
4262
4263 o = Oops()
4264 o.whatever = Provoker(o)
4265 del o
4266
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004267def wrapper_segfault():
4268 # SF 927248: deeply nested wrappers could cause stack overflow
4269 f = lambda:None
4270 for i in xrange(1000000):
4271 f = f.__call__
4272 f = None
4273
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004274# Fix SF #762455, segfault when sys.stdout is changed in getattr
4275def filefault():
4276 if verbose:
4277 print "Testing sys.stdout is changed in getattr..."
4278 import sys
4279 class StdoutGuard:
4280 def __getattr__(self, attr):
4281 sys.stdout = sys.__stdout__
4282 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4283 sys.stdout = StdoutGuard()
4284 try:
4285 print "Oops!"
4286 except RuntimeError:
4287 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004288
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004289def vicious_descriptor_nonsense():
4290 # A potential segfault spotted by Thomas Wouters in mail to
4291 # python-dev 2003-04-17, turned into an example & fixed by Michael
4292 # Hudson just less than four months later...
4293 if verbose:
4294 print "Testing vicious_descriptor_nonsense..."
4295
4296 class Evil(object):
4297 def __hash__(self):
4298 return hash('attr')
4299 def __eq__(self, other):
4300 del C.attr
4301 return 0
4302
4303 class Descr(object):
4304 def __get__(self, ob, type=None):
4305 return 1
4306
4307 class C(object):
4308 attr = Descr()
4309
4310 c = C()
4311 c.__dict__[Evil()] = 0
4312
4313 vereq(c.attr, 1)
4314 # this makes a crash more likely:
4315 import gc; gc.collect()
4316 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004317
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004318def test_init():
4319 # SF 1155938
4320 class Foo(object):
4321 def __init__(self):
4322 return 10
4323 try:
4324 Foo()
4325 except TypeError:
4326 pass
4327 else:
4328 raise TestFailed, "did not test __init__() for None return"
4329
Armin Rigoc6686b72005-11-07 08:38:00 +00004330def methodwrapper():
4331 # <type 'method-wrapper'> did not support any reflection before 2.5
4332 if verbose:
4333 print "Testing method-wrapper objects..."
4334
4335 l = []
4336 vereq(l.__add__, l.__add__)
Armin Rigofd01d792006-06-08 10:56:24 +00004337 vereq(l.__add__, [].__add__)
4338 verify(l.__add__ != [5].__add__)
4339 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004340 verify(l.__add__.__name__ == '__add__')
4341 verify(l.__add__.__self__ is l)
4342 verify(l.__add__.__objclass__ is list)
4343 vereq(l.__add__.__doc__, list.__add__.__doc__)
Armin Rigofd01d792006-06-08 10:56:24 +00004344 try:
4345 hash(l.__add__)
4346 except TypeError:
4347 pass
4348 else:
4349 raise TestFailed("no TypeError from hash([].__add__)")
4350
4351 t = ()
4352 t += (7,)
4353 vereq(t.__add__, (7,).__add__)
4354 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004355
Armin Rigofd163f92005-12-29 15:59:19 +00004356def notimplemented():
4357 # all binary methods should be able to return a NotImplemented
4358 if verbose:
4359 print "Testing NotImplemented..."
4360
4361 import sys
4362 import types
4363 import operator
4364
4365 def specialmethod(self, other):
4366 return NotImplemented
4367
4368 def check(expr, x, y):
4369 try:
4370 exec expr in {'x': x, 'y': y, 'operator': operator}
4371 except TypeError:
4372 pass
4373 else:
4374 raise TestFailed("no TypeError from %r" % (expr,))
4375
4376 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4377 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4378 # ValueErrors instead of TypeErrors
4379 for metaclass in [type, types.ClassType]:
4380 for name, expr, iexpr in [
4381 ('__add__', 'x + y', 'x += y'),
4382 ('__sub__', 'x - y', 'x -= y'),
4383 ('__mul__', 'x * y', 'x *= y'),
4384 ('__truediv__', 'operator.truediv(x, y)', None),
4385 ('__floordiv__', 'operator.floordiv(x, y)', None),
4386 ('__div__', 'x / y', 'x /= y'),
4387 ('__mod__', 'x % y', 'x %= y'),
4388 ('__divmod__', 'divmod(x, y)', None),
4389 ('__pow__', 'x ** y', 'x **= y'),
4390 ('__lshift__', 'x << y', 'x <<= y'),
4391 ('__rshift__', 'x >> y', 'x >>= y'),
4392 ('__and__', 'x & y', 'x &= y'),
4393 ('__or__', 'x | y', 'x |= y'),
4394 ('__xor__', 'x ^ y', 'x ^= y'),
4395 ('__coerce__', 'coerce(x, y)', None)]:
4396 if name == '__coerce__':
4397 rname = name
4398 else:
4399 rname = '__r' + name[2:]
4400 A = metaclass('A', (), {name: specialmethod})
4401 B = metaclass('B', (), {rname: specialmethod})
4402 a = A()
4403 b = B()
4404 check(expr, a, a)
4405 check(expr, a, b)
4406 check(expr, b, a)
4407 check(expr, b, b)
4408 check(expr, a, N1)
4409 check(expr, a, N2)
4410 check(expr, N1, b)
4411 check(expr, N2, b)
4412 if iexpr:
4413 check(iexpr, a, a)
4414 check(iexpr, a, b)
4415 check(iexpr, b, a)
4416 check(iexpr, b, b)
4417 check(iexpr, a, N1)
4418 check(iexpr, a, N2)
4419 iname = '__i' + name[2:]
4420 C = metaclass('C', (), {iname: specialmethod})
4421 c = C()
4422 check(iexpr, c, a)
4423 check(iexpr, c, b)
4424 check(iexpr, c, N1)
4425 check(iexpr, c, N2)
4426
Georg Brandl0fca97a2007-03-05 22:28:08 +00004427def test_assign_slice():
4428 # ceval.c's assign_slice used to check for
4429 # tp->tp_as_sequence->sq_slice instead of
4430 # tp->tp_as_sequence->sq_ass_slice
4431
4432 class C(object):
4433 def __setslice__(self, start, stop, value):
4434 self.value = value
4435
4436 c = C()
4437 c[1:2] = 3
4438 vereq(c.value, 3)
4439
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004440def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004441 weakref_segfault() # Must be first, somehow
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004442 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004443 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004444 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445 lists()
4446 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004447 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004448 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449 ints()
4450 longs()
4451 floats()
4452 complexes()
4453 spamlists()
4454 spamdicts()
4455 pydicts()
4456 pylists()
4457 metaclass()
4458 pymods()
4459 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004460 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004462 ex5()
4463 monotonicity()
4464 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004465 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004466 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004467 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468 dynamics()
Armin Rigoc0ba52d2007-04-19 14:44:48 +00004469 errors()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004470 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004471 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004472 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004473 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474 classic()
4475 compattr()
4476 newslot()
4477 altmro()
4478 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004479 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004480 specials()
Brett Cannon1e534b52007-09-07 04:18:30 +00004481 recursions()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004482 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004483 properties()
Brett Cannon4e438bc2007-12-25 00:14:34 +00004484 properties_plus()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004485 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004486 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004487 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004488 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004489 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004490 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004491 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004492 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004493 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004494 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004495 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004496 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004497 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004498 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004499 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004500 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004501 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004502 kwdargs()
Brett Cannon22565aa2006-06-09 22:31:23 +00004503 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004504 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004505 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004506 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004507 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004508 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004509 dictproxyiterkeys()
4510 dictproxyitervalues()
4511 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004512 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004513 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004514 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004515 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004516 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004517 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004518 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004519 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004520 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004521 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004522 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004523 test_mutable_bases()
4524 test_mutable_bases_with_failing_mro()
4525 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004526 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004527 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004528 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004529 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004530 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004531 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004532 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004533 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004534 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004535 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004536 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004537 notimplemented()
Georg Brandl0fca97a2007-03-05 22:28:08 +00004538 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004539
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004540 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004541
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004542if __name__ == "__main__":
4543 test_main()