blob: c6a42469907287b4de02f1dae5b896811bdd1f6b [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
2199
2200
Guido van Rossumc4a18802001-08-24 16:55:27 +00002201def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002202 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002203
2204 class A(object):
2205 def meth(self, a):
2206 return "A(%r)" % a
2207
Guido van Rossum45704552001-10-08 16:35:45 +00002208 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002209
2210 class B(A):
2211 def __init__(self):
2212 self.__super = super(B, self)
2213 def meth(self, a):
2214 return "B(%r)" % a + self.__super.meth(a)
2215
Guido van Rossum45704552001-10-08 16:35:45 +00002216 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002217
2218 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002219 def meth(self, a):
2220 return "C(%r)" % a + self.__super.meth(a)
2221 C._C__super = super(C)
2222
Guido van Rossum45704552001-10-08 16:35:45 +00002223 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002224
2225 class D(C, B):
2226 def meth(self, a):
2227 return "D(%r)" % a + super(D, self).meth(a)
2228
Guido van Rossum5b443c62001-12-03 15:38:28 +00002229 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2230
2231 # Test for subclassing super
2232
2233 class mysuper(super):
2234 def __init__(self, *args):
2235 return super(mysuper, self).__init__(*args)
2236
2237 class E(D):
2238 def meth(self, a):
2239 return "E(%r)" % a + mysuper(E, self).meth(a)
2240
2241 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2242
2243 class F(E):
2244 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002245 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002246 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2247 F._F__super = mysuper(F)
2248
2249 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2250
2251 # Make sure certain errors are raised
2252
2253 try:
2254 super(D, 42)
2255 except TypeError:
2256 pass
2257 else:
2258 raise TestFailed, "shouldn't allow super(D, 42)"
2259
2260 try:
2261 super(D, C())
2262 except TypeError:
2263 pass
2264 else:
2265 raise TestFailed, "shouldn't allow super(D, C())"
2266
2267 try:
2268 super(D).__get__(12)
2269 except TypeError:
2270 pass
2271 else:
2272 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2273
2274 try:
2275 super(D).__get__(C())
2276 except TypeError:
2277 pass
2278 else:
2279 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002280
Guido van Rossuma4541a32003-04-16 20:02:22 +00002281 # Make sure data descriptors can be overridden and accessed via super
2282 # (new feature in Python 2.3)
2283
2284 class DDbase(object):
2285 def getx(self): return 42
2286 x = property(getx)
2287
2288 class DDsub(DDbase):
2289 def getx(self): return "hello"
2290 x = property(getx)
2291
2292 dd = DDsub()
2293 vereq(dd.x, "hello")
2294 vereq(super(DDsub, dd).x, 42)
2295
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002296 # Ensure that super() lookup of descriptor from classmethod
2297 # works (SF ID# 743627)
2298
2299 class Base(object):
2300 aProp = property(lambda self: "foo")
2301
2302 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002303 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002304 def test(klass):
2305 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002306
2307 veris(Sub.test(), Base.aProp)
2308
Georg Brandl5d59c092006-09-30 08:43:30 +00002309 # Verify that super() doesn't allow keyword args
2310 try:
2311 super(Base, kw=1)
2312 except TypeError:
2313 pass
2314 else:
2315 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002316
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002317def inherits():
2318 if verbose: print "Testing inheritance from basic types..."
2319
2320 class hexint(int):
2321 def __repr__(self):
2322 return hex(self)
2323 def __add__(self, other):
2324 return hexint(int.__add__(self, other))
2325 # (Note that overriding __radd__ doesn't work,
2326 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002327 vereq(repr(hexint(7) + 9), "0x10")
2328 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002329 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002330 vereq(a, 12345)
2331 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002332 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002333 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002334 verify((+a).__class__ is int)
2335 verify((a >> 0).__class__ is int)
2336 verify((a << 0).__class__ is int)
2337 verify((hexint(0) << 12).__class__ is int)
2338 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002339
2340 class octlong(long):
2341 __slots__ = []
2342 def __str__(self):
2343 s = oct(self)
2344 if s[-1] == 'L':
2345 s = s[:-1]
2346 return s
2347 def __add__(self, other):
2348 return self.__class__(super(octlong, self).__add__(other))
2349 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002350 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002351 # (Note that overriding __radd__ here only seems to work
2352 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002353 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002354 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002355 vereq(a, 12345L)
2356 vereq(long(a), 12345L)
2357 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002358 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002359 verify((+a).__class__ is long)
2360 verify((-a).__class__ is long)
2361 verify((-octlong(0)).__class__ is long)
2362 verify((a >> 0).__class__ is long)
2363 verify((a << 0).__class__ is long)
2364 verify((a - 0).__class__ is long)
2365 verify((a * 1).__class__ is long)
2366 verify((a ** 1).__class__ is long)
2367 verify((a // 1).__class__ is long)
2368 verify((1 * a).__class__ is long)
2369 verify((a | 0).__class__ is long)
2370 verify((a ^ 0).__class__ is long)
2371 verify((a & -1L).__class__ is long)
2372 verify((octlong(0) << 12).__class__ is long)
2373 verify((octlong(0) >> 12).__class__ is long)
2374 verify(abs(octlong(0)).__class__ is long)
2375
2376 # Because octlong overrides __add__, we can't check the absence of +0
2377 # optimizations using octlong.
2378 class longclone(long):
2379 pass
2380 a = longclone(1)
2381 verify((a + 0).__class__ is long)
2382 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002383
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002384 # Check that negative clones don't segfault
2385 a = longclone(-1)
2386 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002387 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002388
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002389 class precfloat(float):
2390 __slots__ = ['prec']
2391 def __init__(self, value=0.0, prec=12):
2392 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002393 def __repr__(self):
2394 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002395 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002396 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002397 vereq(a, 12345.0)
2398 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002399 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002400 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002401 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002402
Tim Peters2400fa42001-09-12 19:12:49 +00002403 class madcomplex(complex):
2404 def __repr__(self):
2405 return "%.17gj%+.17g" % (self.imag, self.real)
2406 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002407 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002408 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002409 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002410 vereq(a, base)
2411 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002412 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002413 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002414 vereq(repr(a), "4j-3")
2415 vereq(a, base)
2416 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002417 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002418 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002419 veris((+a).__class__, complex)
2420 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002421 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002422 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002423 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002424 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002425 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002426 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002427 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002428
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002429 class madtuple(tuple):
2430 _rev = None
2431 def rev(self):
2432 if self._rev is not None:
2433 return self._rev
2434 L = list(self)
2435 L.reverse()
2436 self._rev = self.__class__(L)
2437 return self._rev
2438 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002439 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2440 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2441 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002442 for i in range(512):
2443 t = madtuple(range(i))
2444 u = t.rev()
2445 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002446 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002447 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002448 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002449 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002450 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002451 verify(a[:].__class__ is tuple)
2452 verify((a * 1).__class__ is tuple)
2453 verify((a * 0).__class__ is tuple)
2454 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002455 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002456 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002457 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002458 verify((a + a).__class__ is tuple)
2459 verify((a * 0).__class__ is tuple)
2460 verify((a * 1).__class__ is tuple)
2461 verify((a * 2).__class__ is tuple)
2462 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002463
2464 class madstring(str):
2465 _rev = None
2466 def rev(self):
2467 if self._rev is not None:
2468 return self._rev
2469 L = list(self)
2470 L.reverse()
2471 self._rev = self.__class__("".join(L))
2472 return self._rev
2473 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002474 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2475 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2476 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002477 for i in range(256):
2478 s = madstring("".join(map(chr, range(i))))
2479 t = s.rev()
2480 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002481 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002482 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002483 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002484 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002485
Tim Peters8fa5dd02001-09-12 02:18:30 +00002486 base = "\x00" * 5
2487 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002488 vereq(s, base)
2489 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002490 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002491 vereq(hash(s), hash(base))
2492 vereq({s: 1}[base], 1)
2493 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002494 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002495 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002496 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002497 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002498 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002499 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002500 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002501 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002502 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002503 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002504 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002505 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002506 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002507 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002508 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002509 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002510 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002511 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002512 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002513 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002514 identitytab = ''.join([chr(i) for i in range(256)])
2515 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002516 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002517 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002518 vereq(s.translate(identitytab, "x"), base)
2519 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002520 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002521 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002522 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002523 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002524 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002525 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002526 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002527 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002528 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002529 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002530
Guido van Rossum91ee7982001-08-30 20:52:40 +00002531 class madunicode(unicode):
2532 _rev = None
2533 def rev(self):
2534 if self._rev is not None:
2535 return self._rev
2536 L = list(self)
2537 L.reverse()
2538 self._rev = self.__class__(u"".join(L))
2539 return self._rev
2540 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002541 vereq(u, u"ABCDEF")
2542 vereq(u.rev(), madunicode(u"FEDCBA"))
2543 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002544 base = u"12345"
2545 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002546 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002547 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002548 vereq(hash(u), hash(base))
2549 vereq({u: 1}[base], 1)
2550 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002551 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002552 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002553 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002554 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002555 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002556 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002557 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002558 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002559 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002560 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002561 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002562 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002563 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002564 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002565 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002566 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002567 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002568 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002569 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002570 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002571 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002572 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002573 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002574 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002575 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002576 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002577 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002578 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002579 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002580 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002581 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002582 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002583 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002584 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002585 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002586 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002587 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002588 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002589
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002590 class sublist(list):
2591 pass
2592 a = sublist(range(5))
2593 vereq(a, range(5))
2594 a.append("hello")
2595 vereq(a, range(5) + ["hello"])
2596 a[5] = 5
2597 vereq(a, range(6))
2598 a.extend(range(6, 20))
2599 vereq(a, range(20))
2600 a[-5:] = []
2601 vereq(a, range(15))
2602 del a[10:15]
2603 vereq(len(a), 10)
2604 vereq(a, range(10))
2605 vereq(list(a), range(10))
2606 vereq(a[0], 0)
2607 vereq(a[9], 9)
2608 vereq(a[-10], 0)
2609 vereq(a[-1], 9)
2610 vereq(a[:5], range(5))
2611
Tim Peters59c9a642001-09-13 05:38:56 +00002612 class CountedInput(file):
2613 """Counts lines read by self.readline().
2614
2615 self.lineno is the 0-based ordinal of the last line read, up to
2616 a maximum of one greater than the number of lines in the file.
2617
2618 self.ateof is true if and only if the final "" line has been read,
2619 at which point self.lineno stops incrementing, and further calls
2620 to readline() continue to return "".
2621 """
2622
2623 lineno = 0
2624 ateof = 0
2625 def readline(self):
2626 if self.ateof:
2627 return ""
2628 s = file.readline(self)
2629 # Next line works too.
2630 # s = super(CountedInput, self).readline()
2631 self.lineno += 1
2632 if s == "":
2633 self.ateof = 1
2634 return s
2635
Tim Peters561f8992001-09-13 19:36:36 +00002636 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002637 lines = ['a\n', 'b\n', 'c\n']
2638 try:
2639 f.writelines(lines)
2640 f.close()
2641 f = CountedInput(TESTFN)
2642 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2643 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002644 vereq(expected, got)
2645 vereq(f.lineno, i)
2646 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002647 f.close()
2648 finally:
2649 try:
2650 f.close()
2651 except:
2652 pass
2653 try:
2654 import os
2655 os.unlink(TESTFN)
2656 except:
2657 pass
2658
Tim Peters808b94e2001-09-13 19:33:07 +00002659def keywords():
2660 if verbose:
2661 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002662 vereq(int(x=1), 1)
2663 vereq(float(x=2), 2.0)
2664 vereq(long(x=3), 3L)
2665 vereq(complex(imag=42, real=666), complex(666, 42))
2666 vereq(str(object=500), '500')
2667 vereq(unicode(string='abc', errors='strict'), u'abc')
2668 vereq(tuple(sequence=range(3)), (0, 1, 2))
2669 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002670 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002671
2672 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002673 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002674 try:
2675 constructor(bogus_keyword_arg=1)
2676 except TypeError:
2677 pass
2678 else:
2679 raise TestFailed("expected TypeError from bogus keyword "
2680 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002681
Tim Peters8fa45672001-09-13 21:01:29 +00002682def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002683 # XXX This test is disabled because rexec is not deemed safe
2684 return
Tim Peters8fa45672001-09-13 21:01:29 +00002685 import rexec
2686 if verbose:
2687 print "Testing interaction with restricted execution ..."
2688
2689 sandbox = rexec.RExec()
2690
2691 code1 = """f = open(%r, 'w')""" % TESTFN
2692 code2 = """f = file(%r, 'w')""" % TESTFN
2693 code3 = """\
2694f = open(%r)
2695t = type(f) # a sneaky way to get the file() constructor
2696f.close()
2697f = t(%r, 'w') # rexec can't catch this by itself
2698""" % (TESTFN, TESTFN)
2699
2700 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2701 f.close()
2702
2703 try:
2704 for code in code1, code2, code3:
2705 try:
2706 sandbox.r_exec(code)
2707 except IOError, msg:
2708 if str(msg).find("restricted") >= 0:
2709 outcome = "OK"
2710 else:
2711 outcome = "got an exception, but not an expected one"
2712 else:
2713 outcome = "expected a restricted-execution exception"
2714
2715 if outcome != "OK":
2716 raise TestFailed("%s, in %r" % (outcome, code))
2717
2718 finally:
2719 try:
2720 import os
2721 os.unlink(TESTFN)
2722 except:
2723 pass
2724
Tim Peters0ab085c2001-09-14 00:25:33 +00002725def str_subclass_as_dict_key():
2726 if verbose:
2727 print "Testing a str subclass used as dict key .."
2728
2729 class cistr(str):
2730 """Sublcass of str that computes __eq__ case-insensitively.
2731
2732 Also computes a hash code of the string in canonical form.
2733 """
2734
2735 def __init__(self, value):
2736 self.canonical = value.lower()
2737 self.hashcode = hash(self.canonical)
2738
2739 def __eq__(self, other):
2740 if not isinstance(other, cistr):
2741 other = cistr(other)
2742 return self.canonical == other.canonical
2743
2744 def __hash__(self):
2745 return self.hashcode
2746
Guido van Rossum45704552001-10-08 16:35:45 +00002747 vereq(cistr('ABC'), 'abc')
2748 vereq('aBc', cistr('ABC'))
2749 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002750
2751 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002752 vereq(d[cistr('one')], 1)
2753 vereq(d[cistr('tWo')], 2)
2754 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002755 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002756 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002757
Guido van Rossumab3b0342001-09-18 20:38:53 +00002758def classic_comparisons():
2759 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002760 class classic:
2761 pass
2762 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002763 if verbose: print " (base = %s)" % base
2764 class C(base):
2765 def __init__(self, value):
2766 self.value = int(value)
2767 def __cmp__(self, other):
2768 if isinstance(other, C):
2769 return cmp(self.value, other.value)
2770 if isinstance(other, int) or isinstance(other, long):
2771 return cmp(self.value, other)
2772 return NotImplemented
2773 c1 = C(1)
2774 c2 = C(2)
2775 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002776 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002777 c = {1: c1, 2: c2, 3: c3}
2778 for x in 1, 2, 3:
2779 for y in 1, 2, 3:
2780 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2781 for op in "<", "<=", "==", "!=", ">", ">=":
2782 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2783 "x=%d, y=%d" % (x, y))
2784 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2785 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2786
Guido van Rossum0639f592001-09-18 21:06:04 +00002787def rich_comparisons():
2788 if verbose:
2789 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002790 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002791 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002792 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002793 vereq(z, 1+0j)
2794 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002795 class ZZ(complex):
2796 def __eq__(self, other):
2797 try:
2798 return abs(self - other) <= 1e-6
2799 except:
2800 return NotImplemented
2801 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002802 vereq(zz, 1+0j)
2803 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002804
Guido van Rossum0639f592001-09-18 21:06:04 +00002805 class classic:
2806 pass
2807 for base in (classic, int, object, list):
2808 if verbose: print " (base = %s)" % base
2809 class C(base):
2810 def __init__(self, value):
2811 self.value = int(value)
2812 def __cmp__(self, other):
2813 raise TestFailed, "shouldn't call __cmp__"
2814 def __eq__(self, other):
2815 if isinstance(other, C):
2816 return self.value == other.value
2817 if isinstance(other, int) or isinstance(other, long):
2818 return self.value == other
2819 return NotImplemented
2820 def __ne__(self, other):
2821 if isinstance(other, C):
2822 return self.value != other.value
2823 if isinstance(other, int) or isinstance(other, long):
2824 return self.value != other
2825 return NotImplemented
2826 def __lt__(self, other):
2827 if isinstance(other, C):
2828 return self.value < other.value
2829 if isinstance(other, int) or isinstance(other, long):
2830 return self.value < other
2831 return NotImplemented
2832 def __le__(self, other):
2833 if isinstance(other, C):
2834 return self.value <= other.value
2835 if isinstance(other, int) or isinstance(other, long):
2836 return self.value <= other
2837 return NotImplemented
2838 def __gt__(self, other):
2839 if isinstance(other, C):
2840 return self.value > other.value
2841 if isinstance(other, int) or isinstance(other, long):
2842 return self.value > other
2843 return NotImplemented
2844 def __ge__(self, other):
2845 if isinstance(other, C):
2846 return self.value >= other.value
2847 if isinstance(other, int) or isinstance(other, long):
2848 return self.value >= other
2849 return NotImplemented
2850 c1 = C(1)
2851 c2 = C(2)
2852 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002853 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002854 c = {1: c1, 2: c2, 3: c3}
2855 for x in 1, 2, 3:
2856 for y in 1, 2, 3:
2857 for op in "<", "<=", "==", "!=", ">", ">=":
2858 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2859 "x=%d, y=%d" % (x, y))
2860 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2861 "x=%d, y=%d" % (x, y))
2862 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2863 "x=%d, y=%d" % (x, y))
2864
Guido van Rossum1952e382001-09-19 01:25:16 +00002865def coercions():
2866 if verbose: print "Testing coercions..."
2867 class I(int): pass
2868 coerce(I(0), 0)
2869 coerce(0, I(0))
2870 class L(long): pass
2871 coerce(L(0), 0)
2872 coerce(L(0), 0L)
2873 coerce(0, L(0))
2874 coerce(0L, L(0))
2875 class F(float): pass
2876 coerce(F(0), 0)
2877 coerce(F(0), 0L)
2878 coerce(F(0), 0.)
2879 coerce(0, F(0))
2880 coerce(0L, F(0))
2881 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002882 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002883 coerce(C(0), 0)
2884 coerce(C(0), 0L)
2885 coerce(C(0), 0.)
2886 coerce(C(0), 0j)
2887 coerce(0, C(0))
2888 coerce(0L, C(0))
2889 coerce(0., C(0))
2890 coerce(0j, C(0))
2891
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002892def descrdoc():
2893 if verbose: print "Testing descriptor doc strings..."
2894 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002895 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002896 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002897 check(file.name, "file name") # member descriptor
2898
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002899def setclass():
2900 if verbose: print "Testing __class__ assignment..."
2901 class C(object): pass
2902 class D(object): pass
2903 class E(object): pass
2904 class F(D, E): pass
2905 for cls in C, D, E, F:
2906 for cls2 in C, D, E, F:
2907 x = cls()
2908 x.__class__ = cls2
2909 verify(x.__class__ is cls2)
2910 x.__class__ = cls
2911 verify(x.__class__ is cls)
2912 def cant(x, C):
2913 try:
2914 x.__class__ = C
2915 except TypeError:
2916 pass
2917 else:
2918 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002919 try:
2920 delattr(x, "__class__")
2921 except TypeError:
2922 pass
2923 else:
2924 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002925 cant(C(), list)
2926 cant(list(), C)
2927 cant(C(), 1)
2928 cant(C(), object)
2929 cant(object(), list)
2930 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002931 class Int(int): __slots__ = []
2932 cant(2, Int)
2933 cant(Int(), int)
2934 cant(True, int)
2935 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002936 o = object()
2937 cant(o, type(1))
2938 cant(o, type(None))
2939 del o
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002940 class G(object):
2941 __slots__ = ["a", "b"]
2942 class H(object):
2943 __slots__ = ["b", "a"]
2944 try:
2945 unicode
2946 except NameError:
2947 class I(object):
2948 __slots__ = ["a", "b"]
2949 else:
2950 class I(object):
2951 __slots__ = [unicode("a"), unicode("b")]
2952 class J(object):
2953 __slots__ = ["c", "b"]
2954 class K(object):
2955 __slots__ = ["a", "b", "d"]
2956 class L(H):
2957 __slots__ = ["e"]
2958 class M(I):
2959 __slots__ = ["e"]
2960 class N(J):
2961 __slots__ = ["__weakref__"]
2962 class P(J):
2963 __slots__ = ["__dict__"]
2964 class Q(J):
2965 pass
2966 class R(J):
2967 __slots__ = ["__dict__", "__weakref__"]
2968
2969 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2970 x = cls()
2971 x.a = 1
2972 x.__class__ = cls2
2973 verify(x.__class__ is cls2,
2974 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2975 vereq(x.a, 1)
2976 x.__class__ = cls
2977 verify(x.__class__ is cls,
2978 "assigning %r as __class__ for %r silently failed" % (cls, x))
2979 vereq(x.a, 1)
2980 for cls in G, J, K, L, M, N, P, R, list, Int:
2981 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2982 if cls is cls2:
2983 continue
2984 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002985
Guido van Rossum6661be32001-10-26 04:26:12 +00002986def setdict():
2987 if verbose: print "Testing __dict__ assignment..."
2988 class C(object): pass
2989 a = C()
2990 a.__dict__ = {'b': 1}
2991 vereq(a.b, 1)
2992 def cant(x, dict):
2993 try:
2994 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002995 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002996 pass
2997 else:
2998 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2999 cant(a, None)
3000 cant(a, [])
3001 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00003002 del a.__dict__ # Deleting __dict__ is allowed
Armin Rigo9790a272007-05-02 19:23:31 +00003003
3004 class Base(object):
3005 pass
3006 def verify_dict_readonly(x):
3007 """
3008 x has to be an instance of a class inheriting from Base.
3009 """
3010 cant(x, {})
3011 try:
3012 del x.__dict__
3013 except (AttributeError, TypeError):
3014 pass
3015 else:
3016 raise TestFailed, "shouldn't allow del %r.__dict__" % x
3017 dict_descr = Base.__dict__["__dict__"]
3018 try:
3019 dict_descr.__set__(x, {})
3020 except (AttributeError, TypeError):
3021 pass
3022 else:
3023 raise TestFailed, "dict_descr allowed access to %r's dict" % x
3024
3025 # Classes don't allow __dict__ assignment and have readonly dicts
3026 class Meta1(type, Base):
3027 pass
3028 class Meta2(Base, type):
3029 pass
3030 class D(object):
3031 __metaclass__ = Meta1
3032 class E(object):
3033 __metaclass__ = Meta2
3034 for cls in C, D, E:
3035 verify_dict_readonly(cls)
3036 class_dict = cls.__dict__
3037 try:
3038 class_dict["spam"] = "eggs"
3039 except TypeError:
3040 pass
3041 else:
3042 raise TestFailed, "%r's __dict__ can be modified" % cls
3043
3044 # Modules also disallow __dict__ assignment
3045 class Module1(types.ModuleType, Base):
3046 pass
3047 class Module2(Base, types.ModuleType):
3048 pass
3049 for ModuleType in Module1, Module2:
3050 mod = ModuleType("spam")
3051 verify_dict_readonly(mod)
3052 mod.__dict__["spam"] = "eggs"
3053
3054 # Exception's __dict__ can be replaced, but not deleted
3055 class Exception1(Exception, Base):
3056 pass
3057 class Exception2(Base, Exception):
3058 pass
3059 for ExceptionType in Exception, Exception1, Exception2:
3060 e = ExceptionType()
3061 e.__dict__ = {"a": 1}
3062 vereq(e.a, 1)
3063 try:
3064 del e.__dict__
3065 except (TypeError, AttributeError):
3066 pass
3067 else:
3068 raise TestFaied, "%r's __dict__ can be deleted" % e
3069
Guido van Rossum6661be32001-10-26 04:26:12 +00003070
Guido van Rossum3926a632001-09-25 16:25:58 +00003071def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003072 if verbose:
3073 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00003074 import pickle, cPickle
3075
3076 def sorteditems(d):
3077 L = d.items()
3078 L.sort()
3079 return L
3080
3081 global C
3082 class C(object):
3083 def __init__(self, a, b):
3084 super(C, self).__init__()
3085 self.a = a
3086 self.b = b
3087 def __repr__(self):
3088 return "C(%r, %r)" % (self.a, self.b)
3089
3090 global C1
3091 class C1(list):
3092 def __new__(cls, a, b):
3093 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00003094 def __getnewargs__(self):
3095 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00003096 def __init__(self, a, b):
3097 self.a = a
3098 self.b = b
3099 def __repr__(self):
3100 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3101
3102 global C2
3103 class C2(int):
3104 def __new__(cls, a, b, val=0):
3105 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00003106 def __getnewargs__(self):
3107 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00003108 def __init__(self, a, b, val=0):
3109 self.a = a
3110 self.b = b
3111 def __repr__(self):
3112 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3113
Guido van Rossum90c45142001-11-24 21:07:01 +00003114 global C3
3115 class C3(object):
3116 def __init__(self, foo):
3117 self.foo = foo
3118 def __getstate__(self):
3119 return self.foo
3120 def __setstate__(self, foo):
3121 self.foo = foo
3122
3123 global C4classic, C4
3124 class C4classic: # classic
3125 pass
3126 class C4(C4classic, object): # mixed inheritance
3127 pass
3128
Guido van Rossum3926a632001-09-25 16:25:58 +00003129 for p in pickle, cPickle:
3130 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003131 if verbose:
3132 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00003133
3134 for cls in C, C1, C2:
3135 s = p.dumps(cls, bin)
3136 cls2 = p.loads(s)
3137 verify(cls2 is cls)
3138
3139 a = C1(1, 2); a.append(42); a.append(24)
3140 b = C2("hello", "world", 42)
3141 s = p.dumps((a, b), bin)
3142 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00003143 vereq(x.__class__, a.__class__)
3144 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
3145 vereq(y.__class__, b.__class__)
3146 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00003147 vereq(repr(x), repr(a))
3148 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00003149 if verbose:
3150 print "a = x =", a
3151 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00003152 # Test for __getstate__ and __setstate__ on new style class
3153 u = C3(42)
3154 s = p.dumps(u, bin)
3155 v = p.loads(s)
3156 veris(u.__class__, v.__class__)
3157 vereq(u.foo, v.foo)
3158 # Test for picklability of hybrid class
3159 u = C4()
3160 u.foo = 42
3161 s = p.dumps(u, bin)
3162 v = p.loads(s)
3163 veris(u.__class__, v.__class__)
3164 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003165
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003166 # Testing copy.deepcopy()
3167 if verbose:
3168 print "deepcopy"
3169 import copy
3170 for cls in C, C1, C2:
3171 cls2 = copy.deepcopy(cls)
3172 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003173
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003174 a = C1(1, 2); a.append(42); a.append(24)
3175 b = C2("hello", "world", 42)
3176 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003177 vereq(x.__class__, a.__class__)
3178 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
3179 vereq(y.__class__, b.__class__)
3180 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00003181 vereq(repr(x), repr(a))
3182 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003183 if verbose:
3184 print "a = x =", a
3185 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003186
Guido van Rossum8c842552002-03-14 23:05:54 +00003187def pickleslots():
3188 if verbose: print "Testing pickling of classes with __slots__ ..."
3189 import pickle, cPickle
3190 # Pickling of classes with __slots__ but without __getstate__ should fail
3191 global B, C, D, E
3192 class B(object):
3193 pass
3194 for base in [object, B]:
3195 class C(base):
3196 __slots__ = ['a']
3197 class D(C):
3198 pass
3199 try:
3200 pickle.dumps(C())
3201 except TypeError:
3202 pass
3203 else:
3204 raise TestFailed, "should fail: pickle C instance - %s" % base
3205 try:
3206 cPickle.dumps(C())
3207 except TypeError:
3208 pass
3209 else:
3210 raise TestFailed, "should fail: cPickle C instance - %s" % base
3211 try:
3212 pickle.dumps(C())
3213 except TypeError:
3214 pass
3215 else:
3216 raise TestFailed, "should fail: pickle D instance - %s" % base
3217 try:
3218 cPickle.dumps(D())
3219 except TypeError:
3220 pass
3221 else:
3222 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003223 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00003224 class C(base):
3225 __slots__ = ['a']
3226 def __getstate__(self):
3227 try:
3228 d = self.__dict__.copy()
3229 except AttributeError:
3230 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003231 for cls in self.__class__.__mro__:
3232 for sn in cls.__dict__.get('__slots__', ()):
3233 try:
3234 d[sn] = getattr(self, sn)
3235 except AttributeError:
3236 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00003237 return d
3238 def __setstate__(self, d):
3239 for k, v in d.items():
3240 setattr(self, k, v)
3241 class D(C):
3242 pass
3243 # Now it should work
3244 x = C()
3245 y = pickle.loads(pickle.dumps(x))
3246 vereq(hasattr(y, 'a'), 0)
3247 y = cPickle.loads(cPickle.dumps(x))
3248 vereq(hasattr(y, 'a'), 0)
3249 x.a = 42
3250 y = pickle.loads(pickle.dumps(x))
3251 vereq(y.a, 42)
3252 y = cPickle.loads(cPickle.dumps(x))
3253 vereq(y.a, 42)
3254 x = D()
3255 x.a = 42
3256 x.b = 100
3257 y = pickle.loads(pickle.dumps(x))
3258 vereq(y.a + y.b, 142)
3259 y = cPickle.loads(cPickle.dumps(x))
3260 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003261 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003262 class E(C):
3263 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003264 x = E()
3265 x.a = 42
3266 x.b = "foo"
3267 y = pickle.loads(pickle.dumps(x))
3268 vereq(y.a, x.a)
3269 vereq(y.b, x.b)
3270 y = cPickle.loads(cPickle.dumps(x))
3271 vereq(y.a, x.a)
3272 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003273
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003274def copies():
3275 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
3276 import copy
3277 class C(object):
3278 pass
3279
3280 a = C()
3281 a.foo = 12
3282 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003283 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003284
3285 a.bar = [1,2,3]
3286 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003287 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003288 verify(c.bar is a.bar)
3289
3290 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003291 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003292 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003293 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003294
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003295def binopoverride():
3296 if verbose: print "Testing overrides of binary operations..."
3297 class I(int):
3298 def __repr__(self):
3299 return "I(%r)" % int(self)
3300 def __add__(self, other):
3301 return I(int(self) + int(other))
3302 __radd__ = __add__
3303 def __pow__(self, other, mod=None):
3304 if mod is None:
3305 return I(pow(int(self), int(other)))
3306 else:
3307 return I(pow(int(self), int(other), int(mod)))
3308 def __rpow__(self, other, mod=None):
3309 if mod is None:
3310 return I(pow(int(other), int(self), mod))
3311 else:
3312 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003313
Walter Dörwald70a6b492004-02-12 17:35:32 +00003314 vereq(repr(I(1) + I(2)), "I(3)")
3315 vereq(repr(I(1) + 2), "I(3)")
3316 vereq(repr(1 + I(2)), "I(3)")
3317 vereq(repr(I(2) ** I(3)), "I(8)")
3318 vereq(repr(2 ** I(3)), "I(8)")
3319 vereq(repr(I(2) ** 3), "I(8)")
3320 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003321 class S(str):
3322 def __eq__(self, other):
3323 return self.lower() == other.lower()
3324
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003325def subclasspropagation():
3326 if verbose: print "Testing propagation of slot functions to subclasses..."
3327 class A(object):
3328 pass
3329 class B(A):
3330 pass
3331 class C(A):
3332 pass
3333 class D(B, C):
3334 pass
3335 d = D()
Tim Peters171b8682006-04-11 01:59:34 +00003336 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003337 A.__hash__ = lambda self: 42
3338 vereq(hash(d), 42)
3339 C.__hash__ = lambda self: 314
3340 vereq(hash(d), 314)
3341 B.__hash__ = lambda self: 144
3342 vereq(hash(d), 144)
3343 D.__hash__ = lambda self: 100
3344 vereq(hash(d), 100)
3345 del D.__hash__
3346 vereq(hash(d), 144)
3347 del B.__hash__
3348 vereq(hash(d), 314)
3349 del C.__hash__
3350 vereq(hash(d), 42)
3351 del A.__hash__
Tim Peters171b8682006-04-11 01:59:34 +00003352 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003353 d.foo = 42
3354 d.bar = 42
3355 vereq(d.foo, 42)
3356 vereq(d.bar, 42)
3357 def __getattribute__(self, name):
3358 if name == "foo":
3359 return 24
3360 return object.__getattribute__(self, name)
3361 A.__getattribute__ = __getattribute__
3362 vereq(d.foo, 24)
3363 vereq(d.bar, 42)
3364 def __getattr__(self, name):
3365 if name in ("spam", "foo", "bar"):
3366 return "hello"
3367 raise AttributeError, name
3368 B.__getattr__ = __getattr__
3369 vereq(d.spam, "hello")
3370 vereq(d.foo, 24)
3371 vereq(d.bar, 42)
3372 del A.__getattribute__
3373 vereq(d.foo, 42)
3374 del d.foo
3375 vereq(d.foo, "hello")
3376 vereq(d.bar, 42)
3377 del B.__getattr__
3378 try:
3379 d.foo
3380 except AttributeError:
3381 pass
3382 else:
3383 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003384
Guido van Rossume7f3e242002-06-14 02:35:45 +00003385 # Test a nasty bug in recurse_down_subclasses()
3386 import gc
3387 class A(object):
3388 pass
3389 class B(A):
3390 pass
3391 del B
3392 gc.collect()
3393 A.__setitem__ = lambda *a: None # crash
3394
Tim Petersfc57ccb2001-10-12 02:38:24 +00003395def buffer_inherit():
3396 import binascii
3397 # SF bug [#470040] ParseTuple t# vs subclasses.
3398 if verbose:
3399 print "Testing that buffer interface is inherited ..."
3400
3401 class MyStr(str):
3402 pass
3403 base = 'abc'
3404 m = MyStr(base)
3405 # b2a_hex uses the buffer interface to get its argument's value, via
3406 # PyArg_ParseTuple 't#' code.
3407 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3408
3409 # It's not clear that unicode will continue to support the character
3410 # buffer interface, and this test will fail if that's taken away.
3411 class MyUni(unicode):
3412 pass
3413 base = u'abc'
3414 m = MyUni(base)
3415 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3416
3417 class MyInt(int):
3418 pass
3419 m = MyInt(42)
3420 try:
3421 binascii.b2a_hex(m)
3422 raise TestFailed('subclass of int should not have a buffer interface')
3423 except TypeError:
3424 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003425
Tim Petersc9933152001-10-16 20:18:24 +00003426def str_of_str_subclass():
3427 import binascii
3428 import cStringIO
3429
3430 if verbose:
3431 print "Testing __str__ defined in subclass of str ..."
3432
3433 class octetstring(str):
3434 def __str__(self):
3435 return binascii.b2a_hex(self)
3436 def __repr__(self):
3437 return self + " repr"
3438
3439 o = octetstring('A')
3440 vereq(type(o), octetstring)
3441 vereq(type(str(o)), str)
3442 vereq(type(repr(o)), str)
3443 vereq(ord(o), 0x41)
3444 vereq(str(o), '41')
3445 vereq(repr(o), 'A repr')
3446 vereq(o.__str__(), '41')
3447 vereq(o.__repr__(), 'A repr')
3448
3449 capture = cStringIO.StringIO()
3450 # Calling str() or not exercises different internal paths.
3451 print >> capture, o
3452 print >> capture, str(o)
3453 vereq(capture.getvalue(), '41\n41\n')
3454 capture.close()
3455
Guido van Rossumc8e56452001-10-22 00:43:43 +00003456def kwdargs():
3457 if verbose: print "Testing keyword arguments to __init__, __call__..."
3458 def f(a): return a
3459 vereq(f.__call__(a=42), 42)
3460 a = []
3461 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003462 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003463
Brett Cannon22565aa2006-06-09 22:31:23 +00003464def recursive__call__():
3465 if verbose: print ("Testing recursive __call__() by setting to instance of "
3466 "class ...")
3467 class A(object):
3468 pass
3469
3470 A.__call__ = A()
3471 try:
3472 A()()
3473 except RuntimeError:
3474 pass
3475 else:
3476 raise TestFailed("Recursion limit should have been reached for "
3477 "__call__()")
3478
Guido van Rossumed87ad82001-10-30 02:33:02 +00003479def delhook():
3480 if verbose: print "Testing __del__ hook..."
3481 log = []
3482 class C(object):
3483 def __del__(self):
3484 log.append(1)
3485 c = C()
3486 vereq(log, [])
3487 del c
3488 vereq(log, [1])
3489
Guido van Rossum29d26062001-12-11 04:37:34 +00003490 class D(object): pass
3491 d = D()
3492 try: del d[0]
3493 except TypeError: pass
3494 else: raise TestFailed, "invalid del() didn't raise TypeError"
3495
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003496def hashinherit():
3497 if verbose: print "Testing hash of mutable subclasses..."
3498
3499 class mydict(dict):
3500 pass
3501 d = mydict()
3502 try:
3503 hash(d)
3504 except TypeError:
3505 pass
3506 else:
3507 raise TestFailed, "hash() of dict subclass should fail"
3508
3509 class mylist(list):
3510 pass
3511 d = mylist()
3512 try:
3513 hash(d)
3514 except TypeError:
3515 pass
3516 else:
3517 raise TestFailed, "hash() of list subclass should fail"
3518
Guido van Rossum29d26062001-12-11 04:37:34 +00003519def strops():
3520 try: 'a' + 5
3521 except TypeError: pass
3522 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3523
3524 try: ''.split('')
3525 except ValueError: pass
3526 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3527
3528 try: ''.join([0])
3529 except TypeError: pass
3530 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3531
3532 try: ''.rindex('5')
3533 except ValueError: pass
3534 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3535
Guido van Rossum29d26062001-12-11 04:37:34 +00003536 try: '%(n)s' % None
3537 except TypeError: pass
3538 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3539
3540 try: '%(n' % {}
3541 except ValueError: pass
3542 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3543
3544 try: '%*s' % ('abc')
3545 except TypeError: pass
3546 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3547
3548 try: '%*.*s' % ('abc', 5)
3549 except TypeError: pass
3550 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3551
3552 try: '%s' % (1, 2)
3553 except TypeError: pass
3554 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3555
3556 try: '%' % None
3557 except ValueError: pass
3558 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3559
3560 vereq('534253'.isdigit(), 1)
3561 vereq('534253x'.isdigit(), 0)
3562 vereq('%c' % 5, '\x05')
3563 vereq('%c' % '5', '5')
3564
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003565def deepcopyrecursive():
3566 if verbose: print "Testing deepcopy of recursive objects..."
3567 class Node:
3568 pass
3569 a = Node()
3570 b = Node()
3571 a.b = b
3572 b.a = a
3573 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003574
Guido van Rossumd7035672002-03-12 20:43:31 +00003575def modules():
3576 if verbose: print "Testing uninitialized module objects..."
3577 from types import ModuleType as M
3578 m = M.__new__(M)
3579 str(m)
3580 vereq(hasattr(m, "__name__"), 0)
3581 vereq(hasattr(m, "__file__"), 0)
3582 vereq(hasattr(m, "foo"), 0)
3583 vereq(m.__dict__, None)
3584 m.foo = 1
3585 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003586
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003587def dictproxyiterkeys():
3588 class C(object):
3589 def meth(self):
3590 pass
3591 if verbose: print "Testing dict-proxy iterkeys..."
3592 keys = [ key for key in C.__dict__.iterkeys() ]
3593 keys.sort()
3594 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3595
3596def dictproxyitervalues():
3597 class C(object):
3598 def meth(self):
3599 pass
3600 if verbose: print "Testing dict-proxy itervalues..."
3601 values = [ values for values in C.__dict__.itervalues() ]
3602 vereq(len(values), 5)
3603
3604def dictproxyiteritems():
3605 class C(object):
3606 def meth(self):
3607 pass
3608 if verbose: print "Testing dict-proxy iteritems..."
3609 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3610 keys.sort()
3611 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3612
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003613def funnynew():
3614 if verbose: print "Testing __new__ returning something unexpected..."
3615 class C(object):
3616 def __new__(cls, arg):
3617 if isinstance(arg, str): return [1, 2, 3]
3618 elif isinstance(arg, int): return object.__new__(D)
3619 else: return object.__new__(cls)
3620 class D(C):
3621 def __init__(self, arg):
3622 self.foo = arg
3623 vereq(C("1"), [1, 2, 3])
3624 vereq(D("1"), [1, 2, 3])
3625 d = D(None)
3626 veris(d.foo, None)
3627 d = C(1)
3628 vereq(isinstance(d, D), True)
3629 vereq(d.foo, 1)
3630 d = D(1)
3631 vereq(isinstance(d, D), True)
3632 vereq(d.foo, 1)
3633
Guido van Rossume8fc6402002-04-16 16:44:51 +00003634def imulbug():
3635 # SF bug 544647
3636 if verbose: print "Testing for __imul__ problems..."
3637 class C(object):
3638 def __imul__(self, other):
3639 return (self, other)
3640 x = C()
3641 y = x
3642 y *= 1.0
3643 vereq(y, (x, 1.0))
3644 y = x
3645 y *= 2
3646 vereq(y, (x, 2))
3647 y = x
3648 y *= 3L
3649 vereq(y, (x, 3L))
3650 y = x
3651 y *= 1L<<100
3652 vereq(y, (x, 1L<<100))
3653 y = x
3654 y *= None
3655 vereq(y, (x, None))
3656 y = x
3657 y *= "foo"
3658 vereq(y, (x, "foo"))
3659
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003660def docdescriptor():
3661 # SF bug 542984
3662 if verbose: print "Testing __doc__ descriptor..."
3663 class DocDescr(object):
3664 def __get__(self, object, otype):
3665 if object:
3666 object = object.__class__.__name__ + ' instance'
3667 if otype:
3668 otype = otype.__name__
3669 return 'object=%s; type=%s' % (object, otype)
3670 class OldClass:
3671 __doc__ = DocDescr()
3672 class NewClass(object):
3673 __doc__ = DocDescr()
3674 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3675 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3676 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3677 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3678
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003679def copy_setstate():
3680 if verbose:
3681 print "Testing that copy.*copy() correctly uses __setstate__..."
3682 import copy
3683 class C(object):
3684 def __init__(self, foo=None):
3685 self.foo = foo
3686 self.__foo = foo
3687 def setfoo(self, foo=None):
3688 self.foo = foo
3689 def getfoo(self):
3690 return self.__foo
3691 def __getstate__(self):
3692 return [self.foo]
3693 def __setstate__(self, lst):
3694 assert len(lst) == 1
3695 self.__foo = self.foo = lst[0]
3696 a = C(42)
3697 a.setfoo(24)
3698 vereq(a.foo, 24)
3699 vereq(a.getfoo(), 42)
3700 b = copy.copy(a)
3701 vereq(b.foo, 24)
3702 vereq(b.getfoo(), 24)
3703 b = copy.deepcopy(a)
3704 vereq(b.foo, 24)
3705 vereq(b.getfoo(), 24)
3706
Guido van Rossum09638c12002-06-13 19:17:46 +00003707def slices():
3708 if verbose:
3709 print "Testing cases with slices and overridden __getitem__ ..."
3710 # Strings
3711 vereq("hello"[:4], "hell")
3712 vereq("hello"[slice(4)], "hell")
3713 vereq(str.__getitem__("hello", slice(4)), "hell")
3714 class S(str):
3715 def __getitem__(self, x):
3716 return str.__getitem__(self, x)
3717 vereq(S("hello")[:4], "hell")
3718 vereq(S("hello")[slice(4)], "hell")
3719 vereq(S("hello").__getitem__(slice(4)), "hell")
3720 # Tuples
3721 vereq((1,2,3)[:2], (1,2))
3722 vereq((1,2,3)[slice(2)], (1,2))
3723 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3724 class T(tuple):
3725 def __getitem__(self, x):
3726 return tuple.__getitem__(self, x)
3727 vereq(T((1,2,3))[:2], (1,2))
3728 vereq(T((1,2,3))[slice(2)], (1,2))
3729 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3730 # Lists
3731 vereq([1,2,3][:2], [1,2])
3732 vereq([1,2,3][slice(2)], [1,2])
3733 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3734 class L(list):
3735 def __getitem__(self, x):
3736 return list.__getitem__(self, x)
3737 vereq(L([1,2,3])[:2], [1,2])
3738 vereq(L([1,2,3])[slice(2)], [1,2])
3739 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3740 # Now do lists and __setitem__
3741 a = L([1,2,3])
3742 a[slice(1, 3)] = [3,2]
3743 vereq(a, [1,3,2])
3744 a[slice(0, 2, 1)] = [3,1]
3745 vereq(a, [3,1,2])
3746 a.__setitem__(slice(1, 3), [2,1])
3747 vereq(a, [3,2,1])
3748 a.__setitem__(slice(0, 2, 1), [2,3])
3749 vereq(a, [2,3,1])
3750
Tim Peters2484aae2002-07-11 06:56:07 +00003751def subtype_resurrection():
3752 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003753 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003754
3755 class C(object):
3756 container = []
3757
3758 def __del__(self):
3759 # resurrect the instance
3760 C.container.append(self)
3761
3762 c = C()
3763 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003764 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003765 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003766 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003767
3768 # If that didn't blow up, it's also interesting to see whether clearing
3769 # the last container slot works: that will attempt to delete c again,
3770 # which will cause c to get appended back to the container again "during"
3771 # the del.
3772 del C.container[-1]
3773 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003774 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003775
Tim Peters14cb1e12002-07-11 18:26:21 +00003776 # Make c mortal again, so that the test framework with -l doesn't report
3777 # it as a leak.
3778 del C.__del__
3779
Guido van Rossum2d702462002-08-06 21:28:28 +00003780def slottrash():
3781 # Deallocating deeply nested slotted trash caused stack overflows
3782 if verbose:
3783 print "Testing slot trash..."
3784 class trash(object):
3785 __slots__ = ['x']
3786 def __init__(self, x):
3787 self.x = x
3788 o = None
3789 for i in xrange(50000):
3790 o = trash(o)
3791 del o
3792
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003793def slotmultipleinheritance():
3794 # SF bug 575229, multiple inheritance w/ slots dumps core
3795 class A(object):
3796 __slots__=()
3797 class B(object):
3798 pass
3799 class C(A,B) :
3800 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003801 vereq(C.__basicsize__, B.__basicsize__)
3802 verify(hasattr(C, '__dict__'))
3803 verify(hasattr(C, '__weakref__'))
3804 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003805
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003806def testrmul():
3807 # SF patch 592646
3808 if verbose:
3809 print "Testing correct invocation of __rmul__..."
3810 class C(object):
3811 def __mul__(self, other):
3812 return "mul"
3813 def __rmul__(self, other):
3814 return "rmul"
3815 a = C()
3816 vereq(a*2, "mul")
3817 vereq(a*2.2, "mul")
3818 vereq(2*a, "rmul")
3819 vereq(2.2*a, "rmul")
3820
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003821def testipow():
3822 # [SF bug 620179]
3823 if verbose:
3824 print "Testing correct invocation of __ipow__..."
3825 class C(object):
3826 def __ipow__(self, other):
3827 pass
3828 a = C()
3829 a **= 2
3830
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003831def do_this_first():
3832 if verbose:
3833 print "Testing SF bug 551412 ..."
3834 # This dumps core when SF bug 551412 isn't fixed --
3835 # but only when test_descr.py is run separately.
3836 # (That can't be helped -- as soon as PyType_Ready()
3837 # is called for PyLong_Type, the bug is gone.)
3838 class UserLong(object):
3839 def __pow__(self, *args):
3840 pass
3841 try:
3842 pow(0L, UserLong(), 0L)
3843 except:
3844 pass
3845
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003846 if verbose:
3847 print "Testing SF bug 570483..."
3848 # Another segfault only when run early
3849 # (before PyType_Ready(tuple) is called)
3850 type.mro(tuple)
3851
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003852def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003853 if verbose:
3854 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003855 # stuff that should work:
3856 class C(object):
3857 pass
3858 class C2(object):
3859 def __getattribute__(self, attr):
3860 if attr == 'a':
3861 return 2
3862 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003863 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003864 def meth(self):
3865 return 1
3866 class D(C):
3867 pass
3868 class E(D):
3869 pass
3870 d = D()
3871 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003872 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003873 D.__bases__ = (C2,)
3874 vereq(d.meth(), 1)
3875 vereq(e.meth(), 1)
3876 vereq(d.a, 2)
3877 vereq(e.a, 2)
3878 vereq(C2.__subclasses__(), [D])
3879
3880 # stuff that shouldn't:
3881 class L(list):
3882 pass
3883
3884 try:
3885 L.__bases__ = (dict,)
3886 except TypeError:
3887 pass
3888 else:
3889 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3890
3891 try:
3892 list.__bases__ = (dict,)
3893 except TypeError:
3894 pass
3895 else:
3896 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3897
3898 try:
Michael W. Hudsonf3904422006-11-23 13:54:04 +00003899 D.__bases__ = (C2, list)
3900 except TypeError:
3901 pass
3902 else:
3903 assert 0, "best_base calculation found wanting"
3904
3905 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003906 del D.__bases__
3907 except TypeError:
3908 pass
3909 else:
3910 raise TestFailed, "shouldn't be able to delete .__bases__"
3911
3912 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003913 D.__bases__ = ()
3914 except TypeError, msg:
3915 if str(msg) == "a new-style class can't have only classic bases":
3916 raise TestFailed, "wrong error message for .__bases__ = ()"
3917 else:
3918 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3919
3920 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003921 D.__bases__ = (D,)
3922 except TypeError:
3923 pass
3924 else:
3925 # actually, we'll have crashed by here...
3926 raise TestFailed, "shouldn't be able to create inheritance cycles"
3927
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003928 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003929 D.__bases__ = (C, C)
3930 except TypeError:
3931 pass
3932 else:
3933 raise TestFailed, "didn't detect repeated base classes"
3934
3935 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003936 D.__bases__ = (E,)
3937 except TypeError:
3938 pass
3939 else:
3940 raise TestFailed, "shouldn't be able to create inheritance cycles"
3941
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003942 # let's throw a classic class into the mix:
3943 class Classic:
3944 def meth2(self):
3945 return 3
3946
3947 D.__bases__ = (C, Classic)
3948
3949 vereq(d.meth2(), 3)
3950 vereq(e.meth2(), 3)
3951 try:
3952 d.a
3953 except AttributeError:
3954 pass
3955 else:
3956 raise TestFailed, "attribute should have vanished"
3957
3958 try:
3959 D.__bases__ = (Classic,)
3960 except TypeError:
3961 pass
3962 else:
3963 raise TestFailed, "new-style class must have a new-style base"
3964
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003965def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003966 if verbose:
3967 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003968 class WorkOnce(type):
3969 def __new__(self, name, bases, ns):
3970 self.flag = 0
3971 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3972 def mro(self):
3973 if self.flag > 0:
3974 raise RuntimeError, "bozo"
3975 else:
3976 self.flag += 1
3977 return type.mro(self)
3978
3979 class WorkAlways(type):
3980 def mro(self):
3981 # this is here to make sure that .mro()s aren't called
3982 # with an exception set (which was possible at one point).
3983 # An error message will be printed in a debug build.
3984 # What's a good way to test for this?
3985 return type.mro(self)
3986
3987 class C(object):
3988 pass
3989
3990 class C2(object):
3991 pass
3992
3993 class D(C):
3994 pass
3995
3996 class E(D):
3997 pass
3998
3999 class F(D):
4000 __metaclass__ = WorkOnce
4001
4002 class G(D):
4003 __metaclass__ = WorkAlways
4004
4005 # Immediate subclasses have their mro's adjusted in alphabetical
4006 # order, so E's will get adjusted before adjusting F's fails. We
4007 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00004008
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004009 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00004010 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004011
4012 try:
4013 D.__bases__ = (C2,)
4014 except RuntimeError:
4015 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00004016 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004017 else:
4018 raise TestFailed, "exception not propagated"
4019
4020def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00004021 if verbose:
4022 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004023 class A(object):
4024 pass
4025
4026 class B(object):
4027 pass
4028
4029 class C(A, B):
4030 pass
4031
4032 class D(A, B):
4033 pass
4034
4035 class E(C, D):
4036 pass
4037
4038 try:
4039 C.__bases__ = (B, A)
4040 except TypeError:
4041 pass
4042 else:
4043 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00004044
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004045def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00004046 if verbose:
4047 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004048 class C(object):
4049 pass
4050
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00004051 # C.__module__ could be 'test_descr' or '__main__'
4052 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00004053
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00004054 C.__name__ = 'D'
4055 vereq((C.__module__, C.__name__), (mod, 'D'))
4056
4057 C.__name__ = 'D.E'
4058 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00004059
Guido van Rossum613f24f2003-01-06 23:00:59 +00004060def subclass_right_op():
4061 if verbose:
4062 print "Testing correct dispatch of subclass overloading __r<op>__..."
4063
4064 # This code tests various cases where right-dispatch of a subclass
4065 # should be preferred over left-dispatch of a base class.
4066
4067 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4068
4069 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00004070 def __floordiv__(self, other):
4071 return "B.__floordiv__"
4072 def __rfloordiv__(self, other):
4073 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00004074
Guido van Rossumf389c772003-02-27 20:04:19 +00004075 vereq(B(1) // 1, "B.__floordiv__")
4076 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00004077
4078 # Case 2: subclass of object; this is just the baseline for case 3
4079
4080 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00004081 def __floordiv__(self, other):
4082 return "C.__floordiv__"
4083 def __rfloordiv__(self, other):
4084 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00004085
Guido van Rossumf389c772003-02-27 20:04:19 +00004086 vereq(C() // 1, "C.__floordiv__")
4087 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00004088
4089 # Case 3: subclass of new-style class; here it gets interesting
4090
4091 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00004092 def __floordiv__(self, other):
4093 return "D.__floordiv__"
4094 def __rfloordiv__(self, other):
4095 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00004096
Guido van Rossumf389c772003-02-27 20:04:19 +00004097 vereq(D() // C(), "D.__floordiv__")
4098 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00004099
4100 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4101
4102 class E(C):
4103 pass
4104
Guido van Rossumf389c772003-02-27 20:04:19 +00004105 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00004106
Guido van Rossumf389c772003-02-27 20:04:19 +00004107 vereq(E() // 1, "C.__floordiv__")
4108 vereq(1 // E(), "C.__rfloordiv__")
4109 vereq(E() // C(), "C.__floordiv__")
4110 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00004111
Guido van Rossum373c7412003-01-07 13:41:37 +00004112def dict_type_with_metaclass():
4113 if verbose:
4114 print "Testing type of __dict__ when __metaclass__ set..."
4115
4116 class B(object):
4117 pass
4118 class M(type):
4119 pass
4120 class C:
4121 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4122 __metaclass__ = M
4123 veris(type(C.__dict__), type(B.__dict__))
4124
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004125def meth_class_get():
4126 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004127 if verbose:
4128 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004129 # Baseline
4130 arg = [1, 2, 3]
4131 res = {1: None, 2: None, 3: None}
4132 vereq(dict.fromkeys(arg), res)
4133 vereq({}.fromkeys(arg), res)
4134 # Now get the descriptor
4135 descr = dict.__dict__["fromkeys"]
4136 # More baseline using the descriptor directly
4137 vereq(descr.__get__(None, dict)(arg), res)
4138 vereq(descr.__get__({})(arg), res)
4139 # Now check various error cases
4140 try:
4141 descr.__get__(None, None)
4142 except TypeError:
4143 pass
4144 else:
4145 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
4146 try:
4147 descr.__get__(42)
4148 except TypeError:
4149 pass
4150 else:
4151 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
4152 try:
4153 descr.__get__(None, 42)
4154 except TypeError:
4155 pass
4156 else:
4157 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
4158 try:
4159 descr.__get__(None, int)
4160 except TypeError:
4161 pass
4162 else:
4163 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
4164
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004165def isinst_isclass():
4166 if verbose:
4167 print "Testing proxy isinstance() and isclass()..."
4168 class Proxy(object):
4169 def __init__(self, obj):
4170 self.__obj = obj
4171 def __getattribute__(self, name):
4172 if name.startswith("_Proxy__"):
4173 return object.__getattribute__(self, name)
4174 else:
4175 return getattr(self.__obj, name)
4176 # Test with a classic class
4177 class C:
4178 pass
4179 a = C()
4180 pa = Proxy(a)
4181 verify(isinstance(a, C)) # Baseline
4182 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004183 # Test with a classic subclass
4184 class D(C):
4185 pass
4186 a = D()
4187 pa = Proxy(a)
4188 verify(isinstance(a, C)) # Baseline
4189 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004190 # Test with a new-style class
4191 class C(object):
4192 pass
4193 a = C()
4194 pa = Proxy(a)
4195 verify(isinstance(a, C)) # Baseline
4196 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004197 # Test with a new-style subclass
4198 class D(C):
4199 pass
4200 a = D()
4201 pa = Proxy(a)
4202 verify(isinstance(a, C)) # Baseline
4203 verify(isinstance(pa, C)) # Test
4204
4205def proxysuper():
4206 if verbose:
4207 print "Testing super() for a proxy object..."
4208 class Proxy(object):
4209 def __init__(self, obj):
4210 self.__obj = obj
4211 def __getattribute__(self, name):
4212 if name.startswith("_Proxy__"):
4213 return object.__getattribute__(self, name)
4214 else:
4215 return getattr(self.__obj, name)
4216
4217 class B(object):
4218 def f(self):
4219 return "B.f"
4220
4221 class C(B):
4222 def f(self):
4223 return super(C, self).f() + "->C.f"
4224
4225 obj = C()
4226 p = Proxy(obj)
4227 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004228
Guido van Rossum52b27052003-04-15 20:05:10 +00004229def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004230 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00004231 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004232 try:
4233 object.__setattr__(str, "foo", 42)
4234 except TypeError:
4235 pass
4236 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004237 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004238 try:
4239 object.__delattr__(str, "lower")
4240 except TypeError:
4241 pass
4242 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004243 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004244
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004245def weakref_segfault():
4246 # SF 742911
4247 if verbose:
4248 print "Testing weakref segfault..."
4249
4250 import weakref
4251
4252 class Provoker:
4253 def __init__(self, referrent):
4254 self.ref = weakref.ref(referrent)
4255
4256 def __del__(self):
4257 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004258
4259 class Oops(object):
4260 pass
4261
4262 o = Oops()
4263 o.whatever = Provoker(o)
4264 del o
4265
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004266def wrapper_segfault():
4267 # SF 927248: deeply nested wrappers could cause stack overflow
4268 f = lambda:None
4269 for i in xrange(1000000):
4270 f = f.__call__
4271 f = None
4272
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004273# Fix SF #762455, segfault when sys.stdout is changed in getattr
4274def filefault():
4275 if verbose:
4276 print "Testing sys.stdout is changed in getattr..."
4277 import sys
4278 class StdoutGuard:
4279 def __getattr__(self, attr):
4280 sys.stdout = sys.__stdout__
4281 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4282 sys.stdout = StdoutGuard()
4283 try:
4284 print "Oops!"
4285 except RuntimeError:
4286 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004287
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004288def vicious_descriptor_nonsense():
4289 # A potential segfault spotted by Thomas Wouters in mail to
4290 # python-dev 2003-04-17, turned into an example & fixed by Michael
4291 # Hudson just less than four months later...
4292 if verbose:
4293 print "Testing vicious_descriptor_nonsense..."
4294
4295 class Evil(object):
4296 def __hash__(self):
4297 return hash('attr')
4298 def __eq__(self, other):
4299 del C.attr
4300 return 0
4301
4302 class Descr(object):
4303 def __get__(self, ob, type=None):
4304 return 1
4305
4306 class C(object):
4307 attr = Descr()
4308
4309 c = C()
4310 c.__dict__[Evil()] = 0
4311
4312 vereq(c.attr, 1)
4313 # this makes a crash more likely:
4314 import gc; gc.collect()
4315 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004316
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004317def test_init():
4318 # SF 1155938
4319 class Foo(object):
4320 def __init__(self):
4321 return 10
4322 try:
4323 Foo()
4324 except TypeError:
4325 pass
4326 else:
4327 raise TestFailed, "did not test __init__() for None return"
4328
Armin Rigoc6686b72005-11-07 08:38:00 +00004329def methodwrapper():
4330 # <type 'method-wrapper'> did not support any reflection before 2.5
4331 if verbose:
4332 print "Testing method-wrapper objects..."
4333
4334 l = []
4335 vereq(l.__add__, l.__add__)
Armin Rigofd01d792006-06-08 10:56:24 +00004336 vereq(l.__add__, [].__add__)
4337 verify(l.__add__ != [5].__add__)
4338 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004339 verify(l.__add__.__name__ == '__add__')
4340 verify(l.__add__.__self__ is l)
4341 verify(l.__add__.__objclass__ is list)
4342 vereq(l.__add__.__doc__, list.__add__.__doc__)
Armin Rigofd01d792006-06-08 10:56:24 +00004343 try:
4344 hash(l.__add__)
4345 except TypeError:
4346 pass
4347 else:
4348 raise TestFailed("no TypeError from hash([].__add__)")
4349
4350 t = ()
4351 t += (7,)
4352 vereq(t.__add__, (7,).__add__)
4353 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004354
Armin Rigofd163f92005-12-29 15:59:19 +00004355def notimplemented():
4356 # all binary methods should be able to return a NotImplemented
4357 if verbose:
4358 print "Testing NotImplemented..."
4359
4360 import sys
4361 import types
4362 import operator
4363
4364 def specialmethod(self, other):
4365 return NotImplemented
4366
4367 def check(expr, x, y):
4368 try:
4369 exec expr in {'x': x, 'y': y, 'operator': operator}
4370 except TypeError:
4371 pass
4372 else:
4373 raise TestFailed("no TypeError from %r" % (expr,))
4374
4375 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4376 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4377 # ValueErrors instead of TypeErrors
4378 for metaclass in [type, types.ClassType]:
4379 for name, expr, iexpr in [
4380 ('__add__', 'x + y', 'x += y'),
4381 ('__sub__', 'x - y', 'x -= y'),
4382 ('__mul__', 'x * y', 'x *= y'),
4383 ('__truediv__', 'operator.truediv(x, y)', None),
4384 ('__floordiv__', 'operator.floordiv(x, y)', None),
4385 ('__div__', 'x / y', 'x /= y'),
4386 ('__mod__', 'x % y', 'x %= y'),
4387 ('__divmod__', 'divmod(x, y)', None),
4388 ('__pow__', 'x ** y', 'x **= y'),
4389 ('__lshift__', 'x << y', 'x <<= y'),
4390 ('__rshift__', 'x >> y', 'x >>= y'),
4391 ('__and__', 'x & y', 'x &= y'),
4392 ('__or__', 'x | y', 'x |= y'),
4393 ('__xor__', 'x ^ y', 'x ^= y'),
4394 ('__coerce__', 'coerce(x, y)', None)]:
4395 if name == '__coerce__':
4396 rname = name
4397 else:
4398 rname = '__r' + name[2:]
4399 A = metaclass('A', (), {name: specialmethod})
4400 B = metaclass('B', (), {rname: specialmethod})
4401 a = A()
4402 b = B()
4403 check(expr, a, a)
4404 check(expr, a, b)
4405 check(expr, b, a)
4406 check(expr, b, b)
4407 check(expr, a, N1)
4408 check(expr, a, N2)
4409 check(expr, N1, b)
4410 check(expr, N2, b)
4411 if iexpr:
4412 check(iexpr, a, a)
4413 check(iexpr, a, b)
4414 check(iexpr, b, a)
4415 check(iexpr, b, b)
4416 check(iexpr, a, N1)
4417 check(iexpr, a, N2)
4418 iname = '__i' + name[2:]
4419 C = metaclass('C', (), {iname: specialmethod})
4420 c = C()
4421 check(iexpr, c, a)
4422 check(iexpr, c, b)
4423 check(iexpr, c, N1)
4424 check(iexpr, c, N2)
4425
Georg Brandl0fca97a2007-03-05 22:28:08 +00004426def test_assign_slice():
4427 # ceval.c's assign_slice used to check for
4428 # tp->tp_as_sequence->sq_slice instead of
4429 # tp->tp_as_sequence->sq_ass_slice
4430
4431 class C(object):
4432 def __setslice__(self, start, stop, value):
4433 self.value = value
4434
4435 c = C()
4436 c[1:2] = 3
4437 vereq(c.value, 3)
4438
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004439def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004440 weakref_segfault() # Must be first, somehow
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004441 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004442 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004443 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444 lists()
4445 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004446 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004447 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004448 ints()
4449 longs()
4450 floats()
4451 complexes()
4452 spamlists()
4453 spamdicts()
4454 pydicts()
4455 pylists()
4456 metaclass()
4457 pymods()
4458 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004459 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004461 ex5()
4462 monotonicity()
4463 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004464 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004466 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467 dynamics()
Armin Rigoc0ba52d2007-04-19 14:44:48 +00004468 errors()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004470 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004471 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004472 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473 classic()
4474 compattr()
4475 newslot()
4476 altmro()
4477 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004478 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004479 specials()
Brett Cannon1e534b52007-09-07 04:18:30 +00004480 recursions()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004481 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004482 properties()
Brett Cannon4e438bc2007-12-25 00:14:34 +00004483 properties_plus()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004484 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004485 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004486 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004487 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004488 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004489 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004490 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004491 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004492 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004493 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004494 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004495 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004496 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004497 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004498 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004499 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004500 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004501 kwdargs()
Brett Cannon22565aa2006-06-09 22:31:23 +00004502 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004503 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004504 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004505 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004506 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004507 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004508 dictproxyiterkeys()
4509 dictproxyitervalues()
4510 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004511 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004512 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004513 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004514 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004515 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004516 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004517 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004518 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004519 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004520 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004521 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004522 test_mutable_bases()
4523 test_mutable_bases_with_failing_mro()
4524 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004525 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004526 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004527 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004528 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004529 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004530 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004531 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004532 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004533 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004534 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004535 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004536 notimplemented()
Georg Brandl0fca97a2007-03-05 22:28:08 +00004537 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004538
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004539 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004540
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004541if __name__ == "__main__":
4542 test_main()