blob: 108d95e32481707a7b61e38db6c70de472c3d2a6 [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
Neal Norwitz1a997502003-01-13 20:13:12 +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
6
7warnings.filterwarnings("ignore",
8 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +00009 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Guido van Rossum875eeaa2001-10-11 18:33:53 +000011def veris(a, b):
12 if a is not b:
13 raise TestFailed, "%r is %r" % (a, b)
14
Tim Peters6d6c1a32001-08-02 04:15:00 +000015def testunop(a, res, expr="len(a)", meth="__len__"):
16 if verbose: print "checking", expr
17 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000018 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000019 t = type(a)
20 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000021 while meth not in t.__dict__:
22 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000023 vereq(m, t.__dict__[meth])
24 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000025 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000026 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000027
28def testbinop(a, b, res, expr="a+b", meth="__add__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000031
Guido van Rossum45704552001-10-08 16:35:45 +000032 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000033 t = type(a)
34 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000035 while meth not in t.__dict__:
36 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000037 vereq(m, t.__dict__[meth])
38 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000039 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000040 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000041
42def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
43 if verbose: print "checking", expr
44 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000045 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000046 t = type(a)
47 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000048 while meth not in t.__dict__:
49 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000050 vereq(m, t.__dict__[meth])
51 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000052 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000053 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000054
55def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
56 if verbose: print "checking", stmt
57 dict = {'a': deepcopy(a), 'b': b}
58 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000059 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000060 t = type(a)
61 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000062 while meth not in t.__dict__:
63 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000064 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000065 dict['a'] = deepcopy(a)
66 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000067 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000068 dict['a'] = deepcopy(a)
69 bm = getattr(dict['a'], meth)
70 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000071 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000072
73def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
74 if verbose: print "checking", stmt
75 dict = {'a': deepcopy(a), 'b': b, 'c': c}
76 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000077 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000078 t = type(a)
79 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000080 while meth not in t.__dict__:
81 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000082 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000083 dict['a'] = deepcopy(a)
84 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000085 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 dict['a'] = deepcopy(a)
87 bm = getattr(dict['a'], meth)
88 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000089 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000090
91def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
92 if verbose: print "checking", stmt
93 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
94 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000095 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000097 while meth not in t.__dict__:
98 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +000099 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000100 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101 dict['a'] = deepcopy(a)
102 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000103 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104 dict['a'] = deepcopy(a)
105 bm = getattr(dict['a'], meth)
106 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000107 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108
Tim Peters2f93e282001-10-04 05:27:00 +0000109def class_docstrings():
110 class Classic:
111 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000112 vereq(Classic.__doc__, "A classic docstring.")
113 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000114
115 class Classic2:
116 pass
117 verify(Classic2.__doc__ is None)
118
Tim Peters4fb1fe82001-10-04 05:48:13 +0000119 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000120 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000121 vereq(NewStatic.__doc__, "Another docstring.")
122 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000123
Tim Peters4fb1fe82001-10-04 05:48:13 +0000124 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000125 pass
126 verify(NewStatic2.__doc__ is None)
127
Tim Peters4fb1fe82001-10-04 05:48:13 +0000128 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000129 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000130 vereq(NewDynamic.__doc__, "Another docstring.")
131 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000132
Tim Peters4fb1fe82001-10-04 05:48:13 +0000133 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000134 pass
135 verify(NewDynamic2.__doc__ is None)
136
Tim Peters6d6c1a32001-08-02 04:15:00 +0000137def lists():
138 if verbose: print "Testing list operations..."
139 testbinop([1], [2], [1,2], "a+b", "__add__")
140 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
141 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
142 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
143 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
144 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
145 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
146 testunop([1,2,3], 3, "len(a)", "__len__")
147 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
148 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
149 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
150 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
151
152def dicts():
153 if verbose: print "Testing dict operations..."
154 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
155 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
156 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
157 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
158 d = {1:2,3:4}
159 l1 = []
160 for i in d.keys(): l1.append(i)
161 l = []
162 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000163 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000164 l = []
165 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000166 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000167 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000168 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000169 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170 d = {1:2, 3:4}
171 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000172 vereq(eval(repr(d), {}), d)
173 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
175
Tim Peters25786c02001-09-02 08:22:48 +0000176def dict_constructor():
177 if verbose:
Tim Petersa427a2b2001-10-29 22:25:45 +0000178 print "Testing dict constructor ..."
179 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000180 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000181 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000182 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000183 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000184 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000185 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000186 vereq(d, dict(d.iteritems()))
187 d = dict({'one':1, 'two':2})
188 vereq(d, dict(one=1, two=2))
189 vereq(d, dict(**d))
190 vereq(d, dict({"one": 1}, two=2))
191 vereq(d, dict([("two", 2)], one=1))
192 vereq(d, dict([("one", 100), ("two", 200)], **d))
193 verify(d is not dict(**d))
Tim Peters25786c02001-09-02 08:22:48 +0000194 for badarg in 0, 0L, 0j, "0", [0], (0,):
195 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000196 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000197 except TypeError:
198 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000199 except ValueError:
200 if badarg == "0":
201 # It's a sequence, and its elements are also sequences (gotta
202 # love strings <wink>), but they aren't of length 2, so this
203 # one seemed better as a ValueError than a TypeError.
204 pass
205 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000206 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000207 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000208 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000209
210 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000211 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000212 except TypeError:
213 pass
214 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000215 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000216
217 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000218 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000219 dict = {1:2, 3:4, 'a':1j}
220
Tim Peters25786c02001-09-02 08:22:48 +0000221 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000222 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000223 except TypeError:
224 pass
225 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000226 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000227
228 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000229 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000230 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000231 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000232
Tim Peters1fc240e2001-10-26 05:06:50 +0000233 # Init from sequence of iterable objects, each producing a 2-sequence.
234 class AddressBookEntry:
235 def __init__(self, first, last):
236 self.first = first
237 self.last = last
238 def __iter__(self):
239 return iter([self.first, self.last])
240
Tim Petersa427a2b2001-10-29 22:25:45 +0000241 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000242 AddressBookEntry('Barry', 'Peters'),
243 AddressBookEntry('Tim', 'Peters'),
244 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000245 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
246
Tim Petersa427a2b2001-10-29 22:25:45 +0000247 d = dict(zip(range(4), range(1, 5)))
248 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000249
250 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000251 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000252 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000253 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000254 except ValueError:
255 pass
256 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000257 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000258
Tim Peters5d2b77c2001-09-03 05:47:38 +0000259def test_dir():
260 if verbose:
261 print "Testing dir() ..."
262 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000263 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000264 del junk
265
266 # Just make sure these don't blow up!
267 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
268 dir(arg)
269
Tim Peters37a309d2001-09-04 01:20:04 +0000270 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000271 class C:
272 Cdata = 1
273 def Cmethod(self): pass
274
275 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
Guido van Rossum45704552001-10-08 16:35:45 +0000276 vereq(dir(C), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000277 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000278
279 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
Guido van Rossum45704552001-10-08 16:35:45 +0000280 vereq(dir(c), cstuff)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000281
282 c.cdata = 2
283 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000284 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000285 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000286
287 class A(C):
288 Adata = 1
289 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000290
Tim Peters37a309d2001-09-04 01:20:04 +0000291 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000292 vereq(dir(A), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000293 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000294 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000295 vereq(dir(a), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000296 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000297 a.adata = 42
298 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000299 vereq(dir(a), astuff + ['adata', 'amethod'])
Tim Peters37a309d2001-09-04 01:20:04 +0000300
301 # The same, but with new-style classes. Since these have object as a
302 # base class, a lot more gets sucked in.
303 def interesting(strings):
304 return [s for s in strings if not s.startswith('_')]
305
Tim Peters5d2b77c2001-09-03 05:47:38 +0000306 class C(object):
307 Cdata = 1
308 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000309
310 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000311 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000312
313 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000314 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000315 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000316
317 c.cdata = 2
318 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000319 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000320 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000321
Tim Peters5d2b77c2001-09-03 05:47:38 +0000322 class A(C):
323 Adata = 1
324 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000325
326 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000327 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000328 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000329 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000330 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000331 a.adata = 42
332 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000333 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000334 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000335
Tim Peterscaaff8d2001-09-10 23:12:14 +0000336 # Try a module subclass.
337 import sys
338 class M(type(sys)):
339 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000340 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000341 minstance.b = 2
342 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000343 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
344 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000345
346 class M2(M):
347 def getdict(self):
348 return "Not a dict!"
349 __dict__ = property(getdict)
350
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000351 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000352 m2instance.b = 2
353 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000354 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000355 try:
356 dir(m2instance)
357 except TypeError:
358 pass
359
Tim Peters9e6a3992001-10-30 05:45:26 +0000360 # Two essentially featureless objects, just inheriting stuff from
361 # object.
362 vereq(dir(None), dir(Ellipsis))
363
Guido van Rossum44022412002-05-13 18:29:46 +0000364 # Nasty test case for proxied objects
365 class Wrapper(object):
366 def __init__(self, obj):
367 self.__obj = obj
368 def __repr__(self):
369 return "Wrapper(%s)" % repr(self.__obj)
370 def __getitem__(self, key):
371 return Wrapper(self.__obj[key])
372 def __len__(self):
373 return len(self.__obj)
374 def __getattr__(self, name):
375 return Wrapper(getattr(self.__obj, name))
376
377 class C(object):
378 def __getclass(self):
379 return Wrapper(type(self))
380 __class__ = property(__getclass)
381
382 dir(C()) # This used to segfault
383
Tim Peters6d6c1a32001-08-02 04:15:00 +0000384binops = {
385 'add': '+',
386 'sub': '-',
387 'mul': '*',
388 'div': '/',
389 'mod': '%',
390 'divmod': 'divmod',
391 'pow': '**',
392 'lshift': '<<',
393 'rshift': '>>',
394 'and': '&',
395 'xor': '^',
396 'or': '|',
397 'cmp': 'cmp',
398 'lt': '<',
399 'le': '<=',
400 'eq': '==',
401 'ne': '!=',
402 'gt': '>',
403 'ge': '>=',
404 }
405
406for name, expr in binops.items():
407 if expr.islower():
408 expr = expr + "(a, b)"
409 else:
410 expr = 'a %s b' % expr
411 binops[name] = expr
412
413unops = {
414 'pos': '+',
415 'neg': '-',
416 'abs': 'abs',
417 'invert': '~',
418 'int': 'int',
419 'long': 'long',
420 'float': 'float',
421 'oct': 'oct',
422 'hex': 'hex',
423 }
424
425for name, expr in unops.items():
426 if expr.islower():
427 expr = expr + "(a)"
428 else:
429 expr = '%s a' % expr
430 unops[name] = expr
431
432def numops(a, b, skip=[]):
433 dict = {'a': a, 'b': b}
434 for name, expr in binops.items():
435 if name not in skip:
436 name = "__%s__" % name
437 if hasattr(a, name):
438 res = eval(expr, dict)
439 testbinop(a, b, res, expr, name)
440 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000441 if name not in skip:
442 name = "__%s__" % name
443 if hasattr(a, name):
444 res = eval(expr, dict)
445 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000446
447def ints():
448 if verbose: print "Testing int operations..."
449 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000450 # The following crashes in Python 2.2
451 vereq((1).__nonzero__(), 1)
452 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000453 # This returns 'NotImplemented' in Python 2.2
454 class C(int):
455 def __add__(self, other):
456 return NotImplemented
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000457 vereq(C(5L), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000458 try:
459 C() + ""
460 except TypeError:
461 pass
462 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000463 raise TestFailed, "NotImplemented should have caused TypeError"
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000464 import sys
465 try:
466 C(sys.maxint+1)
467 except OverflowError:
468 pass
469 else:
470 raise TestFailed, "should have raised OverflowError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471
472def longs():
473 if verbose: print "Testing long operations..."
474 numops(100L, 3L)
475
476def floats():
477 if verbose: print "Testing float operations..."
478 numops(100.0, 3.0)
479
480def complexes():
481 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000482 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483 class Number(complex):
484 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000485 def __new__(cls, *args, **kwds):
486 result = complex.__new__(cls, *args)
487 result.prec = kwds.get('prec', 12)
488 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000489 def __repr__(self):
490 prec = self.prec
491 if self.imag == 0.0:
492 return "%.*g" % (prec, self.real)
493 if self.real == 0.0:
494 return "%.*gj" % (prec, self.imag)
495 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
496 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000497
Tim Peters6d6c1a32001-08-02 04:15:00 +0000498 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000499 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000500 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000501
Tim Peters3f996e72001-09-13 19:18:27 +0000502 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000503 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000504 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000505
506 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000507 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000508 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000509
Tim Peters6d6c1a32001-08-02 04:15:00 +0000510def spamlists():
511 if verbose: print "Testing spamlist operations..."
512 import copy, xxsubtype as spam
513 def spamlist(l, memo=None):
514 import xxsubtype as spam
515 return spam.spamlist(l)
516 # This is an ugly hack:
517 copy._deepcopy_dispatch[spam.spamlist] = spamlist
518
519 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
520 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
521 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
522 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
523 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
524 "a[b:c]", "__getslice__")
525 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
526 "a+=b", "__iadd__")
527 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
528 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
529 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
530 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
531 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
532 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
533 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
534 # Test subclassing
535 class C(spam.spamlist):
536 def foo(self): return 1
537 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000538 vereq(a, [])
539 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000540 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000541 vereq(a, [100])
542 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000543 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000544 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545
546def spamdicts():
547 if verbose: print "Testing spamdict operations..."
548 import copy, xxsubtype as spam
549 def spamdict(d, memo=None):
550 import xxsubtype as spam
551 sd = spam.spamdict()
552 for k, v in d.items(): sd[k] = v
553 return sd
554 # This is an ugly hack:
555 copy._deepcopy_dispatch[spam.spamdict] = spamdict
556
557 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
558 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
559 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
560 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
561 d = spamdict({1:2,3:4})
562 l1 = []
563 for i in d.keys(): l1.append(i)
564 l = []
565 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000566 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000567 l = []
568 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000569 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000570 l = []
571 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000572 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000573 straightd = {1:2, 3:4}
574 spamd = spamdict(straightd)
575 testunop(spamd, 2, "len(a)", "__len__")
576 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
577 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
578 "a[b]=c", "__setitem__")
579 # Test subclassing
580 class C(spam.spamdict):
581 def foo(self): return 1
582 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000583 vereq(a.items(), [])
584 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000586 vereq(a.items(), [('foo', 'bar')])
587 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000589 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000590
591def pydicts():
592 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000593 verify(issubclass(dict, dict))
594 verify(isinstance({}, dict))
595 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000596 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000597 verify(d.__class__ is dict)
598 verify(isinstance(d, dict))
599 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000600 state = -1
601 def __init__(self, *a, **kw):
602 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000603 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604 self.state = a[0]
605 if kw:
606 for k, v in kw.items(): self[v] = k
607 def __getitem__(self, key):
608 return self.get(key, 0)
609 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000610 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000611 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000612 def setstate(self, state):
613 self.state = state
614 def getstate(self):
615 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000616 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000617 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000618 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000619 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000620 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000622 vereq(a.state, -1)
623 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000625 vereq(a.state, 0)
626 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000628 vereq(a.state, 10)
629 vereq(a.getstate(), 10)
630 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000632 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000633 if verbose: print "pydict stress test ..."
634 N = 50
635 for i in range(N):
636 a[i] = C()
637 for j in range(N):
638 a[i][j] = i*j
639 for i in range(N):
640 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000641 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642
643def pylists():
644 if verbose: print "Testing Python subclass of list..."
645 class C(list):
646 def __getitem__(self, i):
647 return list.__getitem__(self, i) + 100
648 def __getslice__(self, i, j):
649 return (i, j)
650 a = C()
651 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000652 vereq(a[0], 100)
653 vereq(a[1], 101)
654 vereq(a[2], 102)
655 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656
657def metaclass():
658 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 class C:
660 __metaclass__ = type
661 def __init__(self):
662 self.__state = 0
663 def getstate(self):
664 return self.__state
665 def setstate(self, state):
666 self.__state = state
667 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000668 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000669 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000670 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671 class D:
672 class __metaclass__(type):
673 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000674 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000675 d = D()
676 verify(d.__class__ is D)
677 class M1(type):
678 def __new__(cls, name, bases, dict):
679 dict['__spam__'] = 1
680 return type.__new__(cls, name, bases, dict)
681 class C:
682 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000683 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000684 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000685 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000686
Guido van Rossum309b5662001-08-17 11:43:17 +0000687 class _instance(object):
688 pass
689 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000690 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000691 def __new__(cls, name, bases, dict):
692 self = object.__new__(cls)
693 self.name = name
694 self.bases = bases
695 self.dict = dict
696 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000697 def __call__(self):
698 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000699 # Early binding of methods
700 for key in self.dict:
701 if key.startswith("__"):
702 continue
703 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000704 return it
705 class C:
706 __metaclass__ = M2
707 def spam(self):
708 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000709 vereq(C.name, 'C')
710 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000711 verify('spam' in C.dict)
712 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000713 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714
Guido van Rossum91ee7982001-08-30 20:52:40 +0000715 # More metaclass examples
716
717 class autosuper(type):
718 # Automatically add __super to the class
719 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000720 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000721 cls = super(autosuper, metaclass).__new__(metaclass,
722 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000723 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000724 while name[:1] == "_":
725 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000726 if name:
727 name = "_%s__super" % name
728 else:
729 name = "__super"
730 setattr(cls, name, super(cls))
731 return cls
732 class A:
733 __metaclass__ = autosuper
734 def meth(self):
735 return "A"
736 class B(A):
737 def meth(self):
738 return "B" + self.__super.meth()
739 class C(A):
740 def meth(self):
741 return "C" + self.__super.meth()
742 class D(C, B):
743 def meth(self):
744 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000745 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000746 class E(B, C):
747 def meth(self):
748 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000749 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000750
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000751 class autoproperty(type):
752 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000753 # named _get_x and/or _set_x are found
754 def __new__(metaclass, name, bases, dict):
755 hits = {}
756 for key, val in dict.iteritems():
757 if key.startswith("_get_"):
758 key = key[5:]
759 get, set = hits.get(key, (None, None))
760 get = val
761 hits[key] = get, set
762 elif key.startswith("_set_"):
763 key = key[5:]
764 get, set = hits.get(key, (None, None))
765 set = val
766 hits[key] = get, set
767 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000768 dict[key] = property(get, set)
769 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000770 name, bases, dict)
771 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000772 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000773 def _get_x(self):
774 return -self.__x
775 def _set_x(self, x):
776 self.__x = -x
777 a = A()
778 verify(not hasattr(a, "x"))
779 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000780 vereq(a.x, 12)
781 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000782
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000783 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000784 # Merge of multiple cooperating metaclasses
785 pass
786 class A:
787 __metaclass__ = multimetaclass
788 def _get_x(self):
789 return "A"
790 class B(A):
791 def _get_x(self):
792 return "B" + self.__super._get_x()
793 class C(A):
794 def _get_x(self):
795 return "C" + self.__super._get_x()
796 class D(C, B):
797 def _get_x(self):
798 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000799 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000800
Guido van Rossumf76de622001-10-18 15:49:21 +0000801 # Make sure type(x) doesn't call x.__class__.__init__
802 class T(type):
803 counter = 0
804 def __init__(self, *args):
805 T.counter += 1
806 class C:
807 __metaclass__ = T
808 vereq(T.counter, 1)
809 a = C()
810 vereq(type(a), C)
811 vereq(T.counter, 1)
812
Guido van Rossum29d26062001-12-11 04:37:34 +0000813 class C(object): pass
814 c = C()
815 try: c()
816 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000817 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000818
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819def pymods():
820 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000822 import sys
823 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000825 def __init__(self, name):
826 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000827 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000829 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 def __setattr__(self, name, value):
831 log.append(("setattr", name, value))
832 MT.__setattr__(self, name, value)
833 def __delattr__(self, name):
834 log.append(("delattr", name))
835 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000836 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000837 a.foo = 12
838 x = a.foo
839 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000840 vereq(log, [("setattr", "foo", 12),
841 ("getattr", "foo"),
842 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843
844def multi():
845 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000846 class C(object):
847 def __init__(self):
848 self.__state = 0
849 def getstate(self):
850 return self.__state
851 def setstate(self, state):
852 self.__state = state
853 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000854 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000856 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000857 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000858 def __init__(self):
859 type({}).__init__(self)
860 C.__init__(self)
861 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000862 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000864 vereq(d.items(), [("hello", "world")])
865 vereq(d["hello"], "world")
866 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000868 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000869 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000870
Guido van Rossume45763a2001-08-10 21:28:46 +0000871 # SF bug #442833
872 class Node(object):
873 def __int__(self):
874 return int(self.foo())
875 def foo(self):
876 return "23"
877 class Frag(Node, list):
878 def foo(self):
879 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000880 vereq(Node().__int__(), 23)
881 vereq(int(Node()), 23)
882 vereq(Frag().__int__(), 42)
883 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000884
Tim Petersa91e9642001-11-14 23:32:33 +0000885 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000886
887 class A:
888 x = 1
889
890 class B(A):
891 pass
892
893 class C(A):
894 x = 2
895
896 class D(B, C):
897 pass
898 vereq(D.x, 1)
899
900 # Classic MRO is preserved for a classic base class.
901 class E(D, object):
902 pass
903 vereq(E.__mro__, (E, D, B, A, C, object))
904 vereq(E.x, 1)
905
906 # But with a mix of classic bases, their MROs are combined using
907 # new-style MRO.
908 class F(B, C, object):
909 pass
910 vereq(F.__mro__, (F, B, C, A, object))
911 vereq(F.x, 2)
912
913 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000914 class C:
915 def cmethod(self):
916 return "C a"
917 def all_method(self):
918 return "C b"
919
920 class M1(C, object):
921 def m1method(self):
922 return "M1 a"
923 def all_method(self):
924 return "M1 b"
925
926 vereq(M1.__mro__, (M1, C, object))
927 m = M1()
928 vereq(m.cmethod(), "C a")
929 vereq(m.m1method(), "M1 a")
930 vereq(m.all_method(), "M1 b")
931
932 class D(C):
933 def dmethod(self):
934 return "D a"
935 def all_method(self):
936 return "D b"
937
Guido van Rossum9a818922002-11-14 19:50:14 +0000938 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000939 def m2method(self):
940 return "M2 a"
941 def all_method(self):
942 return "M2 b"
943
Guido van Rossum9a818922002-11-14 19:50:14 +0000944 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000945 m = M2()
946 vereq(m.cmethod(), "C a")
947 vereq(m.dmethod(), "D a")
948 vereq(m.m2method(), "M2 a")
949 vereq(m.all_method(), "M2 b")
950
Guido van Rossum9a818922002-11-14 19:50:14 +0000951 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000952 def m3method(self):
953 return "M3 a"
954 def all_method(self):
955 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000956 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000957 m = M3()
958 vereq(m.cmethod(), "C a")
959 vereq(m.dmethod(), "D a")
960 vereq(m.m1method(), "M1 a")
961 vereq(m.m2method(), "M2 a")
962 vereq(m.m3method(), "M3 a")
963 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000964
Guido van Rossume54616c2001-12-14 04:19:56 +0000965 class Classic:
966 pass
967 try:
968 class New(Classic):
969 __metaclass__ = type
970 except TypeError:
971 pass
972 else:
973 raise TestFailed, "new class with only classic bases - shouldn't be"
974
Tim Peters6d6c1a32001-08-02 04:15:00 +0000975def diamond():
976 if verbose: print "Testing multiple inheritance special cases..."
977 class A(object):
978 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000979 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000980 class B(A):
981 def boo(self): return "B"
982 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000983 vereq(B().spam(), "B")
984 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 class C(A):
986 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000987 vereq(C().spam(), "A")
988 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000990 vereq(D().spam(), "B")
991 vereq(D().boo(), "B")
992 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000994 vereq(E().spam(), "B")
995 vereq(E().boo(), "C")
996 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000997 # MRO order disagreement
998 try:
999 class F(D, E): pass
1000 except TypeError:
1001 pass
1002 else:
1003 raise TestFailed, "expected MRO order disagreement (F)"
1004 try:
1005 class G(E, D): pass
1006 except TypeError:
1007 pass
1008 else:
1009 raise TestFailed, "expected MRO order disagreement (G)"
1010
1011
1012# see thread python-dev/2002-October/029035.html
1013def ex5():
1014 if verbose: print "Testing ex5 from C3 switch discussion..."
1015 class A(object): pass
1016 class B(object): pass
1017 class C(object): pass
1018 class X(A): pass
1019 class Y(A): pass
1020 class Z(X,B,Y,C): pass
1021 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1022
1023# see "A Monotonic Superclass Linearization for Dylan",
1024# by Kim Barrett et al. (OOPSLA 1996)
1025def monotonicity():
1026 if verbose: print "Testing MRO monotonicity..."
1027 class Boat(object): pass
1028 class DayBoat(Boat): pass
1029 class WheelBoat(Boat): pass
1030 class EngineLess(DayBoat): pass
1031 class SmallMultihull(DayBoat): pass
1032 class PedalWheelBoat(EngineLess,WheelBoat): pass
1033 class SmallCatamaran(SmallMultihull): pass
1034 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1035
1036 vereq(PedalWheelBoat.__mro__,
1037 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1038 object))
1039 vereq(SmallCatamaran.__mro__,
1040 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1041
1042 vereq(Pedalo.__mro__,
1043 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1044 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1045
1046# see "A Monotonic Superclass Linearization for Dylan",
1047# by Kim Barrett et al. (OOPSLA 1996)
1048def consistency_with_epg():
1049 if verbose: print "Testing consistentcy with EPG..."
1050 class Pane(object): pass
1051 class ScrollingMixin(object): pass
1052 class EditingMixin(object): pass
1053 class ScrollablePane(Pane,ScrollingMixin): pass
1054 class EditablePane(Pane,EditingMixin): pass
1055 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1056
1057 vereq(EditableScrollablePane.__mro__,
1058 (EditableScrollablePane, ScrollablePane, EditablePane,
1059 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001060
Raymond Hettingerf394df42003-04-06 19:13:41 +00001061mro_err_msg = """Cannot create a consistent method resolution
1062order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +00001063
Guido van Rossumd32047f2002-11-25 21:38:52 +00001064def mro_disagreement():
1065 if verbose: print "Testing error messages for MRO disagreement..."
1066 def raises(exc, expected, callable, *args):
1067 try:
1068 callable(*args)
1069 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001070 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001071 raise TestFailed, "Message %r, expected %r" % (str(msg),
1072 expected)
1073 else:
1074 raise TestFailed, "Expected %s" % exc
1075 class A(object): pass
1076 class B(A): pass
1077 class C(object): pass
1078 # Test some very simple errors
1079 raises(TypeError, "duplicate base class A",
1080 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001081 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001082 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001083 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001084 type, "X", (A, C, B), {})
1085 # Test a slightly more complex error
1086 class GridLayout(object): pass
1087 class HorizontalGrid(GridLayout): pass
1088 class VerticalGrid(GridLayout): pass
1089 class HVGrid(HorizontalGrid, VerticalGrid): pass
1090 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +00001091 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001092 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1093
Guido van Rossum37202612001-08-09 19:45:21 +00001094def objects():
1095 if verbose: print "Testing object class..."
1096 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001097 vereq(a.__class__, object)
1098 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001099 b = object()
1100 verify(a is not b)
1101 verify(not hasattr(a, "foo"))
1102 try:
1103 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001104 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001105 pass
1106 else:
1107 verify(0, "object() should not allow setting a foo attribute")
1108 verify(not hasattr(object(), "__dict__"))
1109
1110 class Cdict(object):
1111 pass
1112 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001113 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001114 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001115 vereq(x.foo, 1)
1116 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001117
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118def slots():
1119 if verbose: print "Testing __slots__..."
1120 class C0(object):
1121 __slots__ = []
1122 x = C0()
1123 verify(not hasattr(x, "__dict__"))
1124 verify(not hasattr(x, "foo"))
1125
1126 class C1(object):
1127 __slots__ = ['a']
1128 x = C1()
1129 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001130 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001132 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001133 x.a = None
1134 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001136 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001137
1138 class C3(object):
1139 __slots__ = ['a', 'b', 'c']
1140 x = C3()
1141 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001142 verify(not hasattr(x, 'a'))
1143 verify(not hasattr(x, 'b'))
1144 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145 x.a = 1
1146 x.b = 2
1147 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001148 vereq(x.a, 1)
1149 vereq(x.b, 2)
1150 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001152 class C4(object):
1153 """Validate name mangling"""
1154 __slots__ = ['__a']
1155 def __init__(self, value):
1156 self.__a = value
1157 def get(self):
1158 return self.__a
1159 x = C4(5)
1160 verify(not hasattr(x, '__dict__'))
1161 verify(not hasattr(x, '__a'))
1162 vereq(x.get(), 5)
1163 try:
1164 x.__a = 6
1165 except AttributeError:
1166 pass
1167 else:
1168 raise TestFailed, "Double underscored names not mangled"
1169
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001170 # Make sure slot names are proper identifiers
1171 try:
1172 class C(object):
1173 __slots__ = [None]
1174 except TypeError:
1175 pass
1176 else:
1177 raise TestFailed, "[None] slots not caught"
1178 try:
1179 class C(object):
1180 __slots__ = ["foo bar"]
1181 except TypeError:
1182 pass
1183 else:
1184 raise TestFailed, "['foo bar'] slots not caught"
1185 try:
1186 class C(object):
1187 __slots__ = ["foo\0bar"]
1188 except TypeError:
1189 pass
1190 else:
1191 raise TestFailed, "['foo\\0bar'] slots not caught"
1192 try:
1193 class C(object):
1194 __slots__ = ["1"]
1195 except TypeError:
1196 pass
1197 else:
1198 raise TestFailed, "['1'] slots not caught"
1199 try:
1200 class C(object):
1201 __slots__ = [""]
1202 except TypeError:
1203 pass
1204 else:
1205 raise TestFailed, "[''] slots not caught"
1206 class C(object):
1207 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1208
Guido van Rossum33bab012001-12-05 22:45:48 +00001209 # Test leaks
1210 class Counted(object):
1211 counter = 0 # counts the number of instances alive
1212 def __init__(self):
1213 Counted.counter += 1
1214 def __del__(self):
1215 Counted.counter -= 1
1216 class C(object):
1217 __slots__ = ['a', 'b', 'c']
1218 x = C()
1219 x.a = Counted()
1220 x.b = Counted()
1221 x.c = Counted()
1222 vereq(Counted.counter, 3)
1223 del x
1224 vereq(Counted.counter, 0)
1225 class D(C):
1226 pass
1227 x = D()
1228 x.a = Counted()
1229 x.z = Counted()
1230 vereq(Counted.counter, 2)
1231 del x
1232 vereq(Counted.counter, 0)
1233 class E(D):
1234 __slots__ = ['e']
1235 x = E()
1236 x.a = Counted()
1237 x.z = Counted()
1238 x.e = Counted()
1239 vereq(Counted.counter, 3)
1240 del x
1241 vereq(Counted.counter, 0)
1242
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001243 # Test cyclical leaks [SF bug 519621]
1244 class F(object):
1245 __slots__ = ['a', 'b']
1246 log = []
1247 s = F()
1248 s.a = [Counted(), s]
1249 vereq(Counted.counter, 1)
1250 s = None
1251 import gc
1252 gc.collect()
1253 vereq(Counted.counter, 0)
1254
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001255 # Test lookup leaks [SF bug 572567]
1256 import sys,gc
1257 class G(object):
1258 def __cmp__(self, other):
1259 return 0
1260 g = G()
1261 orig_objects = len(gc.get_objects())
1262 for i in xrange(10):
1263 g==g
1264 new_objects = len(gc.get_objects())
1265 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001266 class H(object):
1267 __slots__ = ['a', 'b']
1268 def __init__(self):
1269 self.a = 1
1270 self.b = 2
1271 def __del__(self):
1272 assert self.a == 1
1273 assert self.b == 2
1274
1275 save_stderr = sys.stderr
1276 sys.stderr = sys.stdout
1277 h = H()
1278 try:
1279 del h
1280 finally:
1281 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001282
Guido van Rossum8b056da2002-08-13 18:26:26 +00001283def slotspecials():
1284 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1285
1286 class D(object):
1287 __slots__ = ["__dict__"]
1288 a = D()
1289 verify(hasattr(a, "__dict__"))
1290 verify(not hasattr(a, "__weakref__"))
1291 a.foo = 42
1292 vereq(a.__dict__, {"foo": 42})
1293
1294 class W(object):
1295 __slots__ = ["__weakref__"]
1296 a = W()
1297 verify(hasattr(a, "__weakref__"))
1298 verify(not hasattr(a, "__dict__"))
1299 try:
1300 a.foo = 42
1301 except AttributeError:
1302 pass
1303 else:
1304 raise TestFailed, "shouldn't be allowed to set a.foo"
1305
1306 class C1(W, D):
1307 __slots__ = []
1308 a = C1()
1309 verify(hasattr(a, "__dict__"))
1310 verify(hasattr(a, "__weakref__"))
1311 a.foo = 42
1312 vereq(a.__dict__, {"foo": 42})
1313
1314 class C2(D, W):
1315 __slots__ = []
1316 a = C2()
1317 verify(hasattr(a, "__dict__"))
1318 verify(hasattr(a, "__weakref__"))
1319 a.foo = 42
1320 vereq(a.__dict__, {"foo": 42})
1321
Guido van Rossum9a818922002-11-14 19:50:14 +00001322# MRO order disagreement
1323#
1324# class C3(C1, C2):
1325# __slots__ = []
1326#
1327# class C4(C2, C1):
1328# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001329
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001331 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001334 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001336 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001339 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001341 vereq(E.foo, 1)
1342 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001343 # Test dynamic instances
1344 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001345 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001346 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001347 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001348 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001349 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001350 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001351 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001352 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001353 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001354 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001355 vereq(int(a), 100)
1356 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001357 verify(not hasattr(a, "spam"))
1358 def mygetattr(self, name):
1359 if name == "spam":
1360 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001361 raise AttributeError
1362 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001363 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001364 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001365 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001366 def mysetattr(self, name, value):
1367 if name == "spam":
1368 raise AttributeError
1369 return object.__setattr__(self, name, value)
1370 C.__setattr__ = mysetattr
1371 try:
1372 a.spam = "not spam"
1373 except AttributeError:
1374 pass
1375 else:
1376 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001377 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001378 class D(C):
1379 pass
1380 d = D()
1381 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001382 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383
Guido van Rossum7e35d572001-09-15 03:14:32 +00001384 # Test handling of int*seq and seq*int
1385 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001386 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001387 vereq("a"*I(2), "aa")
1388 vereq(I(2)*"a", "aa")
1389 vereq(2*I(3), 6)
1390 vereq(I(3)*2, 6)
1391 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001392
1393 # Test handling of long*seq and seq*long
1394 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001395 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001396 vereq("a"*L(2L), "aa")
1397 vereq(L(2L)*"a", "aa")
1398 vereq(2*L(3), 6)
1399 vereq(L(3)*2, 6)
1400 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001401
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001402 # Test comparison of classes with dynamic metaclasses
1403 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001404 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001405 class someclass:
1406 __metaclass__ = dynamicmetaclass
1407 verify(someclass != object)
1408
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409def errors():
1410 if verbose: print "Testing errors..."
1411
1412 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001413 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 pass
1415 except TypeError:
1416 pass
1417 else:
1418 verify(0, "inheritance from both list and dict should be illegal")
1419
1420 try:
1421 class C(object, None):
1422 pass
1423 except TypeError:
1424 pass
1425 else:
1426 verify(0, "inheritance from non-type should be illegal")
1427 class Classic:
1428 pass
1429
1430 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001431 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001432 pass
1433 except TypeError:
1434 pass
1435 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001436 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437
1438 try:
1439 class C(object):
1440 __slots__ = 1
1441 except TypeError:
1442 pass
1443 else:
1444 verify(0, "__slots__ = 1 should be illegal")
1445
1446 try:
1447 class C(object):
1448 __slots__ = [1]
1449 except TypeError:
1450 pass
1451 else:
1452 verify(0, "__slots__ = [1] should be illegal")
1453
1454def classmethods():
1455 if verbose: print "Testing class methods..."
1456 class C(object):
1457 def foo(*a): return a
1458 goo = classmethod(foo)
1459 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001460 vereq(C.goo(1), (C, 1))
1461 vereq(c.goo(1), (C, 1))
1462 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 class D(C):
1464 pass
1465 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001466 vereq(D.goo(1), (D, 1))
1467 vereq(d.goo(1), (D, 1))
1468 vereq(d.foo(1), (d, 1))
1469 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001470 # Test for a specific crash (SF bug 528132)
1471 def f(cls, arg): return (cls, arg)
1472 ff = classmethod(f)
1473 vereq(ff.__get__(0, int)(42), (int, 42))
1474 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475
Guido van Rossum155db9a2002-04-02 17:53:47 +00001476 # Test super() with classmethods (SF bug 535444)
1477 veris(C.goo.im_self, C)
1478 veris(D.goo.im_self, D)
1479 veris(super(D,D).goo.im_self, D)
1480 veris(super(D,d).goo.im_self, D)
1481 vereq(super(D,D).goo(), (D,))
1482 vereq(super(D,d).goo(), (D,))
1483
Raymond Hettingerbe971532003-06-18 01:13:41 +00001484 # Verify that argument is checked for callability (SF bug 753451)
1485 try:
1486 classmethod(1).__get__(1)
1487 except TypeError:
1488 pass
1489 else:
1490 raise TestFailed, "classmethod should check for callability"
1491
Georg Brandl6a29c322006-02-21 22:17:46 +00001492 # Verify that classmethod() doesn't allow keyword args
1493 try:
1494 classmethod(f, kw=1)
1495 except TypeError:
1496 pass
1497 else:
1498 raise TestFailed, "classmethod shouldn't accept keyword args"
1499
Fred Drakef841aa62002-03-28 15:49:54 +00001500def classmethods_in_c():
1501 if verbose: print "Testing C-based class methods..."
1502 import xxsubtype as spam
1503 a = (1, 2, 3)
1504 d = {'abc': 123}
1505 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001506 veris(x, spam.spamlist)
1507 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001508 vereq(d, d1)
1509 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001510 veris(x, spam.spamlist)
1511 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001512 vereq(d, d1)
1513
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514def staticmethods():
1515 if verbose: print "Testing static methods..."
1516 class C(object):
1517 def foo(*a): return a
1518 goo = staticmethod(foo)
1519 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001520 vereq(C.goo(1), (1,))
1521 vereq(c.goo(1), (1,))
1522 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 class D(C):
1524 pass
1525 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001526 vereq(D.goo(1), (1,))
1527 vereq(d.goo(1), (1,))
1528 vereq(d.foo(1), (d, 1))
1529 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001530
Fred Drakef841aa62002-03-28 15:49:54 +00001531def staticmethods_in_c():
1532 if verbose: print "Testing C-based static methods..."
1533 import xxsubtype as spam
1534 a = (1, 2, 3)
1535 d = {"abc": 123}
1536 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1537 veris(x, None)
1538 vereq(a, a1)
1539 vereq(d, d1)
1540 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1541 veris(x, None)
1542 vereq(a, a1)
1543 vereq(d, d1)
1544
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545def classic():
1546 if verbose: print "Testing classic classes..."
1547 class C:
1548 def foo(*a): return a
1549 goo = classmethod(foo)
1550 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001551 vereq(C.goo(1), (C, 1))
1552 vereq(c.goo(1), (C, 1))
1553 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 class D(C):
1555 pass
1556 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001557 vereq(D.goo(1), (D, 1))
1558 vereq(d.goo(1), (D, 1))
1559 vereq(d.foo(1), (d, 1))
1560 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001561 class E: # *not* subclassing from C
1562 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001563 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001564 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565
1566def compattr():
1567 if verbose: print "Testing computed attributes..."
1568 class C(object):
1569 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001570 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 self.__get = get
1572 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001573 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 def __get__(self, obj, type=None):
1575 return self.__get(obj)
1576 def __set__(self, obj, value):
1577 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001578 def __delete__(self, obj):
1579 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 def __init__(self):
1581 self.__x = 0
1582 def __get_x(self):
1583 x = self.__x
1584 self.__x = x+1
1585 return x
1586 def __set_x(self, x):
1587 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001588 def __delete_x(self):
1589 del self.__x
1590 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001592 vereq(a.x, 0)
1593 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001595 vereq(a.x, 10)
1596 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001597 del a.x
1598 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599
1600def newslot():
1601 if verbose: print "Testing __new__ slot override..."
1602 class C(list):
1603 def __new__(cls):
1604 self = list.__new__(cls)
1605 self.foo = 1
1606 return self
1607 def __init__(self):
1608 self.foo = self.foo + 2
1609 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001610 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611 verify(a.__class__ is C)
1612 class D(C):
1613 pass
1614 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001615 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616 verify(b.__class__ is D)
1617
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618def altmro():
1619 if verbose: print "Testing mro() and overriding it..."
1620 class A(object):
1621 def f(self): return "A"
1622 class B(A):
1623 pass
1624 class C(A):
1625 def f(self): return "C"
1626 class D(B, C):
1627 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001628 vereq(D.mro(), [D, B, C, A, object])
1629 vereq(D.__mro__, (D, B, C, A, object))
1630 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001631
Guido van Rossumd3077402001-08-12 05:24:18 +00001632 class PerverseMetaType(type):
1633 def mro(cls):
1634 L = type.mro(cls)
1635 L.reverse()
1636 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001637 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001639 vereq(X.__mro__, (object, A, C, B, D, X))
1640 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641
Armin Rigo037d1e02005-12-29 17:07:39 +00001642 try:
1643 class X(object):
1644 class __metaclass__(type):
1645 def mro(self):
1646 return [self, dict, object]
1647 except TypeError:
1648 pass
1649 else:
1650 raise TestFailed, "devious mro() return not caught"
1651
1652 try:
1653 class X(object):
1654 class __metaclass__(type):
1655 def mro(self):
1656 return [1]
1657 except TypeError:
1658 pass
1659 else:
1660 raise TestFailed, "non-class mro() return not caught"
1661
1662 try:
1663 class X(object):
1664 class __metaclass__(type):
1665 def mro(self):
1666 return 1
1667 except TypeError:
1668 pass
1669 else:
1670 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001671
Armin Rigo037d1e02005-12-29 17:07:39 +00001672
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001674 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675
1676 class B(object):
1677 "Intermediate class because object doesn't have a __setattr__"
1678
1679 class C(B):
1680
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001681 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 if name == "foo":
1683 return ("getattr", name)
1684 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001685 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 def __setattr__(self, name, value):
1687 if name == "foo":
1688 self.setattr = (name, value)
1689 else:
1690 return B.__setattr__(self, name, value)
1691 def __delattr__(self, name):
1692 if name == "foo":
1693 self.delattr = name
1694 else:
1695 return B.__delattr__(self, name)
1696
1697 def __getitem__(self, key):
1698 return ("getitem", key)
1699 def __setitem__(self, key, value):
1700 self.setitem = (key, value)
1701 def __delitem__(self, key):
1702 self.delitem = key
1703
1704 def __getslice__(self, i, j):
1705 return ("getslice", i, j)
1706 def __setslice__(self, i, j, value):
1707 self.setslice = (i, j, value)
1708 def __delslice__(self, i, j):
1709 self.delslice = (i, j)
1710
1711 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001712 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001714 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001716 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717
Guido van Rossum45704552001-10-08 16:35:45 +00001718 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001720 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001722 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723
Guido van Rossum45704552001-10-08 16:35:45 +00001724 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001725 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001726 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001728 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001730def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001731 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001732 class C(object):
1733 def __init__(self, x):
1734 self.x = x
1735 def foo(self):
1736 return self.x
1737 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001738 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001739 class D(C):
1740 boo = C.foo
1741 goo = c1.foo
1742 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001743 vereq(d2.foo(), 2)
1744 vereq(d2.boo(), 2)
1745 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001746 class E(object):
1747 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001748 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001749 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001750
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001751def specials():
1752 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001753 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001754 # Test the default behavior for static classes
1755 class C(object):
1756 def __getitem__(self, i):
1757 if 0 <= i < 10: return i
1758 raise IndexError
1759 c1 = C()
1760 c2 = C()
1761 verify(not not c1)
Guido van Rossum45704552001-10-08 16:35:45 +00001762 vereq(hash(c1), id(c1))
1763 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1764 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001765 verify(c1 != c2)
1766 verify(not c1 != c1)
1767 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001768 # Note that the module name appears in str/repr, and that varies
1769 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001770 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001771 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001772 verify(-1 not in c1)
1773 for i in range(10):
1774 verify(i in c1)
1775 verify(10 not in c1)
1776 # Test the default behavior for dynamic classes
1777 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001778 def __getitem__(self, i):
1779 if 0 <= i < 10: return i
1780 raise IndexError
1781 d1 = D()
1782 d2 = D()
1783 verify(not not d1)
Guido van Rossum45704552001-10-08 16:35:45 +00001784 vereq(hash(d1), id(d1))
1785 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1786 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001787 verify(d1 != d2)
1788 verify(not d1 != d1)
1789 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001790 # Note that the module name appears in str/repr, and that varies
1791 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001792 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001793 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001794 verify(-1 not in d1)
1795 for i in range(10):
1796 verify(i in d1)
1797 verify(10 not in d1)
1798 # Test overridden behavior for static classes
1799 class Proxy(object):
1800 def __init__(self, x):
1801 self.x = x
1802 def __nonzero__(self):
1803 return not not self.x
1804 def __hash__(self):
1805 return hash(self.x)
1806 def __eq__(self, other):
1807 return self.x == other
1808 def __ne__(self, other):
1809 return self.x != other
1810 def __cmp__(self, other):
1811 return cmp(self.x, other.x)
1812 def __str__(self):
1813 return "Proxy:%s" % self.x
1814 def __repr__(self):
1815 return "Proxy(%r)" % self.x
1816 def __contains__(self, value):
1817 return value in self.x
1818 p0 = Proxy(0)
1819 p1 = Proxy(1)
1820 p_1 = Proxy(-1)
1821 verify(not p0)
1822 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001823 vereq(hash(p0), hash(0))
1824 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001825 verify(p0 != p1)
1826 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001827 vereq(not p0, p1)
1828 vereq(cmp(p0, p1), -1)
1829 vereq(cmp(p0, p0), 0)
1830 vereq(cmp(p0, p_1), 1)
1831 vereq(str(p0), "Proxy:0")
1832 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001833 p10 = Proxy(range(10))
1834 verify(-1 not in p10)
1835 for i in range(10):
1836 verify(i in p10)
1837 verify(10 not in p10)
1838 # Test overridden behavior for dynamic classes
1839 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001840 def __init__(self, x):
1841 self.x = x
1842 def __nonzero__(self):
1843 return not not self.x
1844 def __hash__(self):
1845 return hash(self.x)
1846 def __eq__(self, other):
1847 return self.x == other
1848 def __ne__(self, other):
1849 return self.x != other
1850 def __cmp__(self, other):
1851 return cmp(self.x, other.x)
1852 def __str__(self):
1853 return "DProxy:%s" % self.x
1854 def __repr__(self):
1855 return "DProxy(%r)" % self.x
1856 def __contains__(self, value):
1857 return value in self.x
1858 p0 = DProxy(0)
1859 p1 = DProxy(1)
1860 p_1 = DProxy(-1)
1861 verify(not p0)
1862 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001863 vereq(hash(p0), hash(0))
1864 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001865 verify(p0 != p1)
1866 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001867 vereq(not p0, p1)
1868 vereq(cmp(p0, p1), -1)
1869 vereq(cmp(p0, p0), 0)
1870 vereq(cmp(p0, p_1), 1)
1871 vereq(str(p0), "DProxy:0")
1872 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001873 p10 = DProxy(range(10))
1874 verify(-1 not in p10)
1875 for i in range(10):
1876 verify(i in p10)
1877 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001878 # Safety test for __cmp__
1879 def unsafecmp(a, b):
1880 try:
1881 a.__class__.__cmp__(a, b)
1882 except TypeError:
1883 pass
1884 else:
1885 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1886 a.__class__, a, b)
1887 unsafecmp(u"123", "123")
1888 unsafecmp("123", u"123")
1889 unsafecmp(1, 1.0)
1890 unsafecmp(1.0, 1)
1891 unsafecmp(1, 1L)
1892 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001893
Neal Norwitz1a997502003-01-13 20:13:12 +00001894 class Letter(str):
1895 def __new__(cls, letter):
1896 if letter == 'EPS':
1897 return str.__new__(cls)
1898 return str.__new__(cls, letter)
1899 def __str__(self):
1900 if not self:
1901 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001902 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001903
1904 # sys.stdout needs to be the original to trigger the recursion bug
1905 import sys
1906 test_stdout = sys.stdout
1907 sys.stdout = get_original_stdout()
1908 try:
1909 # nothing should actually be printed, this should raise an exception
1910 print Letter('w')
1911 except RuntimeError:
1912 pass
1913 else:
1914 raise TestFailed, "expected a RuntimeError for print recursion"
1915 sys.stdout = test_stdout
1916
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001917def weakrefs():
1918 if verbose: print "Testing weak references..."
1919 import weakref
1920 class C(object):
1921 pass
1922 c = C()
1923 r = weakref.ref(c)
1924 verify(r() is c)
1925 del c
1926 verify(r() is None)
1927 del r
1928 class NoWeak(object):
1929 __slots__ = ['foo']
1930 no = NoWeak()
1931 try:
1932 weakref.ref(no)
1933 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001934 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001935 else:
1936 verify(0, "weakref.ref(no) should be illegal")
1937 class Weak(object):
1938 __slots__ = ['foo', '__weakref__']
1939 yes = Weak()
1940 r = weakref.ref(yes)
1941 verify(r() is yes)
1942 del yes
1943 verify(r() is None)
1944 del r
1945
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001946def properties():
1947 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001948 class C(object):
1949 def getx(self):
1950 return self.__x
1951 def setx(self, value):
1952 self.__x = value
1953 def delx(self):
1954 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001955 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001956 a = C()
1957 verify(not hasattr(a, "x"))
1958 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001959 vereq(a._C__x, 42)
1960 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001961 del a.x
1962 verify(not hasattr(a, "x"))
1963 verify(not hasattr(a, "_C__x"))
1964 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001965 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001966 C.x.__delete__(a)
1967 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001968
Tim Peters66c1a522001-09-24 21:17:50 +00001969 raw = C.__dict__['x']
1970 verify(isinstance(raw, property))
1971
1972 attrs = dir(raw)
1973 verify("__doc__" in attrs)
1974 verify("fget" in attrs)
1975 verify("fset" in attrs)
1976 verify("fdel" in attrs)
1977
Guido van Rossum45704552001-10-08 16:35:45 +00001978 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001979 verify(raw.fget is C.__dict__['getx'])
1980 verify(raw.fset is C.__dict__['setx'])
1981 verify(raw.fdel is C.__dict__['delx'])
1982
1983 for attr in "__doc__", "fget", "fset", "fdel":
1984 try:
1985 setattr(raw, attr, 42)
1986 except TypeError, msg:
1987 if str(msg).find('readonly') < 0:
1988 raise TestFailed("when setting readonly attr %r on a "
1989 "property, got unexpected TypeError "
1990 "msg %r" % (attr, str(msg)))
1991 else:
1992 raise TestFailed("expected TypeError from trying to set "
1993 "readonly %r attr on a property" % attr)
1994
Neal Norwitz673cd822002-10-18 16:33:13 +00001995 class D(object):
1996 __getitem__ = property(lambda s: 1/0)
1997
1998 d = D()
1999 try:
2000 for i in d:
2001 str(i)
2002 except ZeroDivisionError:
2003 pass
2004 else:
2005 raise TestFailed, "expected ZeroDivisionError from bad property"
2006
Georg Brandl533ff6f2006-03-08 18:09:27 +00002007 class E(object):
2008 def getter(self):
2009 "getter method"
2010 return 0
2011 def setter(self, value):
2012 "setter method"
2013 pass
2014 prop = property(getter)
2015 vereq(prop.__doc__, "getter method")
2016 prop2 = property(fset=setter)
2017 vereq(prop2.__doc__, None)
2018
Guido van Rossumc4a18802001-08-24 16:55:27 +00002019def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002020 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002021
2022 class A(object):
2023 def meth(self, a):
2024 return "A(%r)" % a
2025
Guido van Rossum45704552001-10-08 16:35:45 +00002026 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002027
2028 class B(A):
2029 def __init__(self):
2030 self.__super = super(B, self)
2031 def meth(self, a):
2032 return "B(%r)" % a + self.__super.meth(a)
2033
Guido van Rossum45704552001-10-08 16:35:45 +00002034 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002035
2036 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002037 def meth(self, a):
2038 return "C(%r)" % a + self.__super.meth(a)
2039 C._C__super = super(C)
2040
Guido van Rossum45704552001-10-08 16:35:45 +00002041 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002042
2043 class D(C, B):
2044 def meth(self, a):
2045 return "D(%r)" % a + super(D, self).meth(a)
2046
Guido van Rossum5b443c62001-12-03 15:38:28 +00002047 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2048
2049 # Test for subclassing super
2050
2051 class mysuper(super):
2052 def __init__(self, *args):
2053 return super(mysuper, self).__init__(*args)
2054
2055 class E(D):
2056 def meth(self, a):
2057 return "E(%r)" % a + mysuper(E, self).meth(a)
2058
2059 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2060
2061 class F(E):
2062 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002063 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002064 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2065 F._F__super = mysuper(F)
2066
2067 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2068
2069 # Make sure certain errors are raised
2070
2071 try:
2072 super(D, 42)
2073 except TypeError:
2074 pass
2075 else:
2076 raise TestFailed, "shouldn't allow super(D, 42)"
2077
2078 try:
2079 super(D, C())
2080 except TypeError:
2081 pass
2082 else:
2083 raise TestFailed, "shouldn't allow super(D, C())"
2084
2085 try:
2086 super(D).__get__(12)
2087 except TypeError:
2088 pass
2089 else:
2090 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2091
2092 try:
2093 super(D).__get__(C())
2094 except TypeError:
2095 pass
2096 else:
2097 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002098
Guido van Rossuma4541a32003-04-16 20:02:22 +00002099 # Make sure data descriptors can be overridden and accessed via super
2100 # (new feature in Python 2.3)
2101
2102 class DDbase(object):
2103 def getx(self): return 42
2104 x = property(getx)
2105
2106 class DDsub(DDbase):
2107 def getx(self): return "hello"
2108 x = property(getx)
2109
2110 dd = DDsub()
2111 vereq(dd.x, "hello")
2112 vereq(super(DDsub, dd).x, 42)
2113
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002114 # Ensure that super() lookup of descriptor from classmethod
2115 # works (SF ID# 743627)
2116
2117 class Base(object):
2118 aProp = property(lambda self: "foo")
2119
2120 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002121 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002122 def test(klass):
2123 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002124
2125 veris(Sub.test(), Base.aProp)
2126
2127
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002128def inherits():
2129 if verbose: print "Testing inheritance from basic types..."
2130
2131 class hexint(int):
2132 def __repr__(self):
2133 return hex(self)
2134 def __add__(self, other):
2135 return hexint(int.__add__(self, other))
2136 # (Note that overriding __radd__ doesn't work,
2137 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002138 vereq(repr(hexint(7) + 9), "0x10")
2139 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002140 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002141 vereq(a, 12345)
2142 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002143 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002144 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002145 verify((+a).__class__ is int)
2146 verify((a >> 0).__class__ is int)
2147 verify((a << 0).__class__ is int)
2148 verify((hexint(0) << 12).__class__ is int)
2149 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002150
2151 class octlong(long):
2152 __slots__ = []
2153 def __str__(self):
2154 s = oct(self)
2155 if s[-1] == 'L':
2156 s = s[:-1]
2157 return s
2158 def __add__(self, other):
2159 return self.__class__(super(octlong, self).__add__(other))
2160 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002161 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002162 # (Note that overriding __radd__ here only seems to work
2163 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002164 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002165 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002166 vereq(a, 12345L)
2167 vereq(long(a), 12345L)
2168 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002169 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002170 verify((+a).__class__ is long)
2171 verify((-a).__class__ is long)
2172 verify((-octlong(0)).__class__ is long)
2173 verify((a >> 0).__class__ is long)
2174 verify((a << 0).__class__ is long)
2175 verify((a - 0).__class__ is long)
2176 verify((a * 1).__class__ is long)
2177 verify((a ** 1).__class__ is long)
2178 verify((a // 1).__class__ is long)
2179 verify((1 * a).__class__ is long)
2180 verify((a | 0).__class__ is long)
2181 verify((a ^ 0).__class__ is long)
2182 verify((a & -1L).__class__ is long)
2183 verify((octlong(0) << 12).__class__ is long)
2184 verify((octlong(0) >> 12).__class__ is long)
2185 verify(abs(octlong(0)).__class__ is long)
2186
2187 # Because octlong overrides __add__, we can't check the absence of +0
2188 # optimizations using octlong.
2189 class longclone(long):
2190 pass
2191 a = longclone(1)
2192 verify((a + 0).__class__ is long)
2193 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002194
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002195 # Check that negative clones don't segfault
2196 a = longclone(-1)
2197 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002198 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002199
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002200 class precfloat(float):
2201 __slots__ = ['prec']
2202 def __init__(self, value=0.0, prec=12):
2203 self.prec = int(prec)
2204 float.__init__(value)
2205 def __repr__(self):
2206 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002207 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002208 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002209 vereq(a, 12345.0)
2210 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002211 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002212 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002213 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002214
Tim Peters2400fa42001-09-12 19:12:49 +00002215 class madcomplex(complex):
2216 def __repr__(self):
2217 return "%.17gj%+.17g" % (self.imag, self.real)
2218 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002219 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002220 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002221 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002222 vereq(a, base)
2223 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002224 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002225 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002226 vereq(repr(a), "4j-3")
2227 vereq(a, base)
2228 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002229 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002230 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002231 veris((+a).__class__, complex)
2232 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002233 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002234 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002235 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002236 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002237 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002238 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002239 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002240
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002241 class madtuple(tuple):
2242 _rev = None
2243 def rev(self):
2244 if self._rev is not None:
2245 return self._rev
2246 L = list(self)
2247 L.reverse()
2248 self._rev = self.__class__(L)
2249 return self._rev
2250 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002251 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2252 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2253 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002254 for i in range(512):
2255 t = madtuple(range(i))
2256 u = t.rev()
2257 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002258 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002259 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002260 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002261 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002262 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002263 verify(a[:].__class__ is tuple)
2264 verify((a * 1).__class__ is tuple)
2265 verify((a * 0).__class__ is tuple)
2266 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002267 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002268 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002269 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002270 verify((a + a).__class__ is tuple)
2271 verify((a * 0).__class__ is tuple)
2272 verify((a * 1).__class__ is tuple)
2273 verify((a * 2).__class__ is tuple)
2274 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002275
2276 class madstring(str):
2277 _rev = None
2278 def rev(self):
2279 if self._rev is not None:
2280 return self._rev
2281 L = list(self)
2282 L.reverse()
2283 self._rev = self.__class__("".join(L))
2284 return self._rev
2285 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002286 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2287 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2288 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002289 for i in range(256):
2290 s = madstring("".join(map(chr, range(i))))
2291 t = s.rev()
2292 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002293 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002294 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002295 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002296 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002297
Tim Peters8fa5dd02001-09-12 02:18:30 +00002298 base = "\x00" * 5
2299 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002300 vereq(s, base)
2301 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002302 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002303 vereq(hash(s), hash(base))
2304 vereq({s: 1}[base], 1)
2305 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002306 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002308 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002309 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002310 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002312 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002313 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002314 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002315 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002316 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002317 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002318 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002319 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002320 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002321 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002322 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002323 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002324 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002325 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002326 identitytab = ''.join([chr(i) for i in range(256)])
2327 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002328 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002329 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002330 vereq(s.translate(identitytab, "x"), base)
2331 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002332 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002333 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002334 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002335 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002336 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002337 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002338 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002339 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002340 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002341 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002342
Guido van Rossum91ee7982001-08-30 20:52:40 +00002343 class madunicode(unicode):
2344 _rev = None
2345 def rev(self):
2346 if self._rev is not None:
2347 return self._rev
2348 L = list(self)
2349 L.reverse()
2350 self._rev = self.__class__(u"".join(L))
2351 return self._rev
2352 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002353 vereq(u, u"ABCDEF")
2354 vereq(u.rev(), madunicode(u"FEDCBA"))
2355 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002356 base = u"12345"
2357 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002358 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002359 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002360 vereq(hash(u), hash(base))
2361 vereq({u: 1}[base], 1)
2362 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002363 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002364 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002365 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002366 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002367 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002368 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002369 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002370 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002371 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002372 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002373 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002374 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002375 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002376 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002377 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002378 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002379 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002380 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002381 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002382 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002383 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002384 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002385 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002386 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002387 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002388 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002389 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002390 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002391 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002392 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002393 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002394 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002395 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002396 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002397 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002398 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002399 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002400 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002401
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002402 class sublist(list):
2403 pass
2404 a = sublist(range(5))
2405 vereq(a, range(5))
2406 a.append("hello")
2407 vereq(a, range(5) + ["hello"])
2408 a[5] = 5
2409 vereq(a, range(6))
2410 a.extend(range(6, 20))
2411 vereq(a, range(20))
2412 a[-5:] = []
2413 vereq(a, range(15))
2414 del a[10:15]
2415 vereq(len(a), 10)
2416 vereq(a, range(10))
2417 vereq(list(a), range(10))
2418 vereq(a[0], 0)
2419 vereq(a[9], 9)
2420 vereq(a[-10], 0)
2421 vereq(a[-1], 9)
2422 vereq(a[:5], range(5))
2423
Tim Peters59c9a642001-09-13 05:38:56 +00002424 class CountedInput(file):
2425 """Counts lines read by self.readline().
2426
2427 self.lineno is the 0-based ordinal of the last line read, up to
2428 a maximum of one greater than the number of lines in the file.
2429
2430 self.ateof is true if and only if the final "" line has been read,
2431 at which point self.lineno stops incrementing, and further calls
2432 to readline() continue to return "".
2433 """
2434
2435 lineno = 0
2436 ateof = 0
2437 def readline(self):
2438 if self.ateof:
2439 return ""
2440 s = file.readline(self)
2441 # Next line works too.
2442 # s = super(CountedInput, self).readline()
2443 self.lineno += 1
2444 if s == "":
2445 self.ateof = 1
2446 return s
2447
Tim Peters561f8992001-09-13 19:36:36 +00002448 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002449 lines = ['a\n', 'b\n', 'c\n']
2450 try:
2451 f.writelines(lines)
2452 f.close()
2453 f = CountedInput(TESTFN)
2454 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2455 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002456 vereq(expected, got)
2457 vereq(f.lineno, i)
2458 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002459 f.close()
2460 finally:
2461 try:
2462 f.close()
2463 except:
2464 pass
2465 try:
2466 import os
2467 os.unlink(TESTFN)
2468 except:
2469 pass
2470
Tim Peters808b94e2001-09-13 19:33:07 +00002471def keywords():
2472 if verbose:
2473 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002474 vereq(int(x=1), 1)
2475 vereq(float(x=2), 2.0)
2476 vereq(long(x=3), 3L)
2477 vereq(complex(imag=42, real=666), complex(666, 42))
2478 vereq(str(object=500), '500')
2479 vereq(unicode(string='abc', errors='strict'), u'abc')
2480 vereq(tuple(sequence=range(3)), (0, 1, 2))
2481 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002482 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002483
2484 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002485 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002486 try:
2487 constructor(bogus_keyword_arg=1)
2488 except TypeError:
2489 pass
2490 else:
2491 raise TestFailed("expected TypeError from bogus keyword "
2492 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002493
Tim Peters8fa45672001-09-13 21:01:29 +00002494def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002495 # XXX This test is disabled because rexec is not deemed safe
2496 return
Tim Peters8fa45672001-09-13 21:01:29 +00002497 import rexec
2498 if verbose:
2499 print "Testing interaction with restricted execution ..."
2500
2501 sandbox = rexec.RExec()
2502
2503 code1 = """f = open(%r, 'w')""" % TESTFN
2504 code2 = """f = file(%r, 'w')""" % TESTFN
2505 code3 = """\
2506f = open(%r)
2507t = type(f) # a sneaky way to get the file() constructor
2508f.close()
2509f = t(%r, 'w') # rexec can't catch this by itself
2510""" % (TESTFN, TESTFN)
2511
2512 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2513 f.close()
2514
2515 try:
2516 for code in code1, code2, code3:
2517 try:
2518 sandbox.r_exec(code)
2519 except IOError, msg:
2520 if str(msg).find("restricted") >= 0:
2521 outcome = "OK"
2522 else:
2523 outcome = "got an exception, but not an expected one"
2524 else:
2525 outcome = "expected a restricted-execution exception"
2526
2527 if outcome != "OK":
2528 raise TestFailed("%s, in %r" % (outcome, code))
2529
2530 finally:
2531 try:
2532 import os
2533 os.unlink(TESTFN)
2534 except:
2535 pass
2536
Tim Peters0ab085c2001-09-14 00:25:33 +00002537def str_subclass_as_dict_key():
2538 if verbose:
2539 print "Testing a str subclass used as dict key .."
2540
2541 class cistr(str):
2542 """Sublcass of str that computes __eq__ case-insensitively.
2543
2544 Also computes a hash code of the string in canonical form.
2545 """
2546
2547 def __init__(self, value):
2548 self.canonical = value.lower()
2549 self.hashcode = hash(self.canonical)
2550
2551 def __eq__(self, other):
2552 if not isinstance(other, cistr):
2553 other = cistr(other)
2554 return self.canonical == other.canonical
2555
2556 def __hash__(self):
2557 return self.hashcode
2558
Guido van Rossum45704552001-10-08 16:35:45 +00002559 vereq(cistr('ABC'), 'abc')
2560 vereq('aBc', cistr('ABC'))
2561 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002562
2563 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002564 vereq(d[cistr('one')], 1)
2565 vereq(d[cistr('tWo')], 2)
2566 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002567 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002568 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002569
Guido van Rossumab3b0342001-09-18 20:38:53 +00002570def classic_comparisons():
2571 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002572 class classic:
2573 pass
2574 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002575 if verbose: print " (base = %s)" % base
2576 class C(base):
2577 def __init__(self, value):
2578 self.value = int(value)
2579 def __cmp__(self, other):
2580 if isinstance(other, C):
2581 return cmp(self.value, other.value)
2582 if isinstance(other, int) or isinstance(other, long):
2583 return cmp(self.value, other)
2584 return NotImplemented
2585 c1 = C(1)
2586 c2 = C(2)
2587 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002588 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002589 c = {1: c1, 2: c2, 3: c3}
2590 for x in 1, 2, 3:
2591 for y in 1, 2, 3:
2592 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2593 for op in "<", "<=", "==", "!=", ">", ">=":
2594 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2595 "x=%d, y=%d" % (x, y))
2596 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2597 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2598
Guido van Rossum0639f592001-09-18 21:06:04 +00002599def rich_comparisons():
2600 if verbose:
2601 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002602 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002603 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002604 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002605 vereq(z, 1+0j)
2606 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002607 class ZZ(complex):
2608 def __eq__(self, other):
2609 try:
2610 return abs(self - other) <= 1e-6
2611 except:
2612 return NotImplemented
2613 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002614 vereq(zz, 1+0j)
2615 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002616
Guido van Rossum0639f592001-09-18 21:06:04 +00002617 class classic:
2618 pass
2619 for base in (classic, int, object, list):
2620 if verbose: print " (base = %s)" % base
2621 class C(base):
2622 def __init__(self, value):
2623 self.value = int(value)
2624 def __cmp__(self, other):
2625 raise TestFailed, "shouldn't call __cmp__"
2626 def __eq__(self, other):
2627 if isinstance(other, C):
2628 return self.value == other.value
2629 if isinstance(other, int) or isinstance(other, long):
2630 return self.value == other
2631 return NotImplemented
2632 def __ne__(self, other):
2633 if isinstance(other, C):
2634 return self.value != other.value
2635 if isinstance(other, int) or isinstance(other, long):
2636 return self.value != other
2637 return NotImplemented
2638 def __lt__(self, other):
2639 if isinstance(other, C):
2640 return self.value < other.value
2641 if isinstance(other, int) or isinstance(other, long):
2642 return self.value < other
2643 return NotImplemented
2644 def __le__(self, other):
2645 if isinstance(other, C):
2646 return self.value <= other.value
2647 if isinstance(other, int) or isinstance(other, long):
2648 return self.value <= other
2649 return NotImplemented
2650 def __gt__(self, other):
2651 if isinstance(other, C):
2652 return self.value > other.value
2653 if isinstance(other, int) or isinstance(other, long):
2654 return self.value > other
2655 return NotImplemented
2656 def __ge__(self, other):
2657 if isinstance(other, C):
2658 return self.value >= other.value
2659 if isinstance(other, int) or isinstance(other, long):
2660 return self.value >= other
2661 return NotImplemented
2662 c1 = C(1)
2663 c2 = C(2)
2664 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002665 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002666 c = {1: c1, 2: c2, 3: c3}
2667 for x in 1, 2, 3:
2668 for y in 1, 2, 3:
2669 for op in "<", "<=", "==", "!=", ">", ">=":
2670 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2671 "x=%d, y=%d" % (x, y))
2672 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2673 "x=%d, y=%d" % (x, y))
2674 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2675 "x=%d, y=%d" % (x, y))
2676
Guido van Rossum1952e382001-09-19 01:25:16 +00002677def coercions():
2678 if verbose: print "Testing coercions..."
2679 class I(int): pass
2680 coerce(I(0), 0)
2681 coerce(0, I(0))
2682 class L(long): pass
2683 coerce(L(0), 0)
2684 coerce(L(0), 0L)
2685 coerce(0, L(0))
2686 coerce(0L, L(0))
2687 class F(float): pass
2688 coerce(F(0), 0)
2689 coerce(F(0), 0L)
2690 coerce(F(0), 0.)
2691 coerce(0, F(0))
2692 coerce(0L, F(0))
2693 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002694 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002695 coerce(C(0), 0)
2696 coerce(C(0), 0L)
2697 coerce(C(0), 0.)
2698 coerce(C(0), 0j)
2699 coerce(0, C(0))
2700 coerce(0L, C(0))
2701 coerce(0., C(0))
2702 coerce(0j, C(0))
2703
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002704def descrdoc():
2705 if verbose: print "Testing descriptor doc strings..."
2706 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002707 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002708 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002709 check(file.name, "file name") # member descriptor
2710
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002711def setclass():
2712 if verbose: print "Testing __class__ assignment..."
2713 class C(object): pass
2714 class D(object): pass
2715 class E(object): pass
2716 class F(D, E): pass
2717 for cls in C, D, E, F:
2718 for cls2 in C, D, E, F:
2719 x = cls()
2720 x.__class__ = cls2
2721 verify(x.__class__ is cls2)
2722 x.__class__ = cls
2723 verify(x.__class__ is cls)
2724 def cant(x, C):
2725 try:
2726 x.__class__ = C
2727 except TypeError:
2728 pass
2729 else:
2730 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002731 try:
2732 delattr(x, "__class__")
2733 except TypeError:
2734 pass
2735 else:
2736 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002737 cant(C(), list)
2738 cant(list(), C)
2739 cant(C(), 1)
2740 cant(C(), object)
2741 cant(object(), list)
2742 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002743 class Int(int): __slots__ = []
2744 cant(2, Int)
2745 cant(Int(), int)
2746 cant(True, int)
2747 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002748 o = object()
2749 cant(o, type(1))
2750 cant(o, type(None))
2751 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002752
Guido van Rossum6661be32001-10-26 04:26:12 +00002753def setdict():
2754 if verbose: print "Testing __dict__ assignment..."
2755 class C(object): pass
2756 a = C()
2757 a.__dict__ = {'b': 1}
2758 vereq(a.b, 1)
2759 def cant(x, dict):
2760 try:
2761 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002762 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002763 pass
2764 else:
2765 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2766 cant(a, None)
2767 cant(a, [])
2768 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002769 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002770 # Classes don't allow __dict__ assignment
2771 cant(C, {})
2772
Guido van Rossum3926a632001-09-25 16:25:58 +00002773def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002774 if verbose:
2775 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002776 import pickle, cPickle
2777
2778 def sorteditems(d):
2779 L = d.items()
2780 L.sort()
2781 return L
2782
2783 global C
2784 class C(object):
2785 def __init__(self, a, b):
2786 super(C, self).__init__()
2787 self.a = a
2788 self.b = b
2789 def __repr__(self):
2790 return "C(%r, %r)" % (self.a, self.b)
2791
2792 global C1
2793 class C1(list):
2794 def __new__(cls, a, b):
2795 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002796 def __getnewargs__(self):
2797 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002798 def __init__(self, a, b):
2799 self.a = a
2800 self.b = b
2801 def __repr__(self):
2802 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2803
2804 global C2
2805 class C2(int):
2806 def __new__(cls, a, b, val=0):
2807 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002808 def __getnewargs__(self):
2809 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002810 def __init__(self, a, b, val=0):
2811 self.a = a
2812 self.b = b
2813 def __repr__(self):
2814 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2815
Guido van Rossum90c45142001-11-24 21:07:01 +00002816 global C3
2817 class C3(object):
2818 def __init__(self, foo):
2819 self.foo = foo
2820 def __getstate__(self):
2821 return self.foo
2822 def __setstate__(self, foo):
2823 self.foo = foo
2824
2825 global C4classic, C4
2826 class C4classic: # classic
2827 pass
2828 class C4(C4classic, object): # mixed inheritance
2829 pass
2830
Guido van Rossum3926a632001-09-25 16:25:58 +00002831 for p in pickle, cPickle:
2832 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002833 if verbose:
2834 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002835
2836 for cls in C, C1, C2:
2837 s = p.dumps(cls, bin)
2838 cls2 = p.loads(s)
2839 verify(cls2 is cls)
2840
2841 a = C1(1, 2); a.append(42); a.append(24)
2842 b = C2("hello", "world", 42)
2843 s = p.dumps((a, b), bin)
2844 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002845 vereq(x.__class__, a.__class__)
2846 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2847 vereq(y.__class__, b.__class__)
2848 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002849 vereq(repr(x), repr(a))
2850 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002851 if verbose:
2852 print "a = x =", a
2853 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002854 # Test for __getstate__ and __setstate__ on new style class
2855 u = C3(42)
2856 s = p.dumps(u, bin)
2857 v = p.loads(s)
2858 veris(u.__class__, v.__class__)
2859 vereq(u.foo, v.foo)
2860 # Test for picklability of hybrid class
2861 u = C4()
2862 u.foo = 42
2863 s = p.dumps(u, bin)
2864 v = p.loads(s)
2865 veris(u.__class__, v.__class__)
2866 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002867
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002868 # Testing copy.deepcopy()
2869 if verbose:
2870 print "deepcopy"
2871 import copy
2872 for cls in C, C1, C2:
2873 cls2 = copy.deepcopy(cls)
2874 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002875
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002876 a = C1(1, 2); a.append(42); a.append(24)
2877 b = C2("hello", "world", 42)
2878 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002879 vereq(x.__class__, a.__class__)
2880 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2881 vereq(y.__class__, b.__class__)
2882 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002883 vereq(repr(x), repr(a))
2884 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002885 if verbose:
2886 print "a = x =", a
2887 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002888
Guido van Rossum8c842552002-03-14 23:05:54 +00002889def pickleslots():
2890 if verbose: print "Testing pickling of classes with __slots__ ..."
2891 import pickle, cPickle
2892 # Pickling of classes with __slots__ but without __getstate__ should fail
2893 global B, C, D, E
2894 class B(object):
2895 pass
2896 for base in [object, B]:
2897 class C(base):
2898 __slots__ = ['a']
2899 class D(C):
2900 pass
2901 try:
2902 pickle.dumps(C())
2903 except TypeError:
2904 pass
2905 else:
2906 raise TestFailed, "should fail: pickle C instance - %s" % base
2907 try:
2908 cPickle.dumps(C())
2909 except TypeError:
2910 pass
2911 else:
2912 raise TestFailed, "should fail: cPickle C instance - %s" % base
2913 try:
2914 pickle.dumps(C())
2915 except TypeError:
2916 pass
2917 else:
2918 raise TestFailed, "should fail: pickle D instance - %s" % base
2919 try:
2920 cPickle.dumps(D())
2921 except TypeError:
2922 pass
2923 else:
2924 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002925 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002926 class C(base):
2927 __slots__ = ['a']
2928 def __getstate__(self):
2929 try:
2930 d = self.__dict__.copy()
2931 except AttributeError:
2932 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002933 for cls in self.__class__.__mro__:
2934 for sn in cls.__dict__.get('__slots__', ()):
2935 try:
2936 d[sn] = getattr(self, sn)
2937 except AttributeError:
2938 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002939 return d
2940 def __setstate__(self, d):
2941 for k, v in d.items():
2942 setattr(self, k, v)
2943 class D(C):
2944 pass
2945 # Now it should work
2946 x = C()
2947 y = pickle.loads(pickle.dumps(x))
2948 vereq(hasattr(y, 'a'), 0)
2949 y = cPickle.loads(cPickle.dumps(x))
2950 vereq(hasattr(y, 'a'), 0)
2951 x.a = 42
2952 y = pickle.loads(pickle.dumps(x))
2953 vereq(y.a, 42)
2954 y = cPickle.loads(cPickle.dumps(x))
2955 vereq(y.a, 42)
2956 x = D()
2957 x.a = 42
2958 x.b = 100
2959 y = pickle.loads(pickle.dumps(x))
2960 vereq(y.a + y.b, 142)
2961 y = cPickle.loads(cPickle.dumps(x))
2962 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002963 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00002964 class E(C):
2965 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002966 x = E()
2967 x.a = 42
2968 x.b = "foo"
2969 y = pickle.loads(pickle.dumps(x))
2970 vereq(y.a, x.a)
2971 vereq(y.b, x.b)
2972 y = cPickle.loads(cPickle.dumps(x))
2973 vereq(y.a, x.a)
2974 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00002975
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002976def copies():
2977 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2978 import copy
2979 class C(object):
2980 pass
2981
2982 a = C()
2983 a.foo = 12
2984 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002985 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002986
2987 a.bar = [1,2,3]
2988 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002989 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002990 verify(c.bar is a.bar)
2991
2992 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002993 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002994 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002995 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002996
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002997def binopoverride():
2998 if verbose: print "Testing overrides of binary operations..."
2999 class I(int):
3000 def __repr__(self):
3001 return "I(%r)" % int(self)
3002 def __add__(self, other):
3003 return I(int(self) + int(other))
3004 __radd__ = __add__
3005 def __pow__(self, other, mod=None):
3006 if mod is None:
3007 return I(pow(int(self), int(other)))
3008 else:
3009 return I(pow(int(self), int(other), int(mod)))
3010 def __rpow__(self, other, mod=None):
3011 if mod is None:
3012 return I(pow(int(other), int(self), mod))
3013 else:
3014 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003015
Walter Dörwald70a6b492004-02-12 17:35:32 +00003016 vereq(repr(I(1) + I(2)), "I(3)")
3017 vereq(repr(I(1) + 2), "I(3)")
3018 vereq(repr(1 + I(2)), "I(3)")
3019 vereq(repr(I(2) ** I(3)), "I(8)")
3020 vereq(repr(2 ** I(3)), "I(8)")
3021 vereq(repr(I(2) ** 3), "I(8)")
3022 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003023 class S(str):
3024 def __eq__(self, other):
3025 return self.lower() == other.lower()
3026
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003027def subclasspropagation():
3028 if verbose: print "Testing propagation of slot functions to subclasses..."
3029 class A(object):
3030 pass
3031 class B(A):
3032 pass
3033 class C(A):
3034 pass
3035 class D(B, C):
3036 pass
3037 d = D()
3038 vereq(hash(d), id(d))
3039 A.__hash__ = lambda self: 42
3040 vereq(hash(d), 42)
3041 C.__hash__ = lambda self: 314
3042 vereq(hash(d), 314)
3043 B.__hash__ = lambda self: 144
3044 vereq(hash(d), 144)
3045 D.__hash__ = lambda self: 100
3046 vereq(hash(d), 100)
3047 del D.__hash__
3048 vereq(hash(d), 144)
3049 del B.__hash__
3050 vereq(hash(d), 314)
3051 del C.__hash__
3052 vereq(hash(d), 42)
3053 del A.__hash__
3054 vereq(hash(d), id(d))
3055 d.foo = 42
3056 d.bar = 42
3057 vereq(d.foo, 42)
3058 vereq(d.bar, 42)
3059 def __getattribute__(self, name):
3060 if name == "foo":
3061 return 24
3062 return object.__getattribute__(self, name)
3063 A.__getattribute__ = __getattribute__
3064 vereq(d.foo, 24)
3065 vereq(d.bar, 42)
3066 def __getattr__(self, name):
3067 if name in ("spam", "foo", "bar"):
3068 return "hello"
3069 raise AttributeError, name
3070 B.__getattr__ = __getattr__
3071 vereq(d.spam, "hello")
3072 vereq(d.foo, 24)
3073 vereq(d.bar, 42)
3074 del A.__getattribute__
3075 vereq(d.foo, 42)
3076 del d.foo
3077 vereq(d.foo, "hello")
3078 vereq(d.bar, 42)
3079 del B.__getattr__
3080 try:
3081 d.foo
3082 except AttributeError:
3083 pass
3084 else:
3085 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003086
Guido van Rossume7f3e242002-06-14 02:35:45 +00003087 # Test a nasty bug in recurse_down_subclasses()
3088 import gc
3089 class A(object):
3090 pass
3091 class B(A):
3092 pass
3093 del B
3094 gc.collect()
3095 A.__setitem__ = lambda *a: None # crash
3096
Tim Petersfc57ccb2001-10-12 02:38:24 +00003097def buffer_inherit():
3098 import binascii
3099 # SF bug [#470040] ParseTuple t# vs subclasses.
3100 if verbose:
3101 print "Testing that buffer interface is inherited ..."
3102
3103 class MyStr(str):
3104 pass
3105 base = 'abc'
3106 m = MyStr(base)
3107 # b2a_hex uses the buffer interface to get its argument's value, via
3108 # PyArg_ParseTuple 't#' code.
3109 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3110
3111 # It's not clear that unicode will continue to support the character
3112 # buffer interface, and this test will fail if that's taken away.
3113 class MyUni(unicode):
3114 pass
3115 base = u'abc'
3116 m = MyUni(base)
3117 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3118
3119 class MyInt(int):
3120 pass
3121 m = MyInt(42)
3122 try:
3123 binascii.b2a_hex(m)
3124 raise TestFailed('subclass of int should not have a buffer interface')
3125 except TypeError:
3126 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003127
Tim Petersc9933152001-10-16 20:18:24 +00003128def str_of_str_subclass():
3129 import binascii
3130 import cStringIO
3131
3132 if verbose:
3133 print "Testing __str__ defined in subclass of str ..."
3134
3135 class octetstring(str):
3136 def __str__(self):
3137 return binascii.b2a_hex(self)
3138 def __repr__(self):
3139 return self + " repr"
3140
3141 o = octetstring('A')
3142 vereq(type(o), octetstring)
3143 vereq(type(str(o)), str)
3144 vereq(type(repr(o)), str)
3145 vereq(ord(o), 0x41)
3146 vereq(str(o), '41')
3147 vereq(repr(o), 'A repr')
3148 vereq(o.__str__(), '41')
3149 vereq(o.__repr__(), 'A repr')
3150
3151 capture = cStringIO.StringIO()
3152 # Calling str() or not exercises different internal paths.
3153 print >> capture, o
3154 print >> capture, str(o)
3155 vereq(capture.getvalue(), '41\n41\n')
3156 capture.close()
3157
Guido van Rossumc8e56452001-10-22 00:43:43 +00003158def kwdargs():
3159 if verbose: print "Testing keyword arguments to __init__, __call__..."
3160 def f(a): return a
3161 vereq(f.__call__(a=42), 42)
3162 a = []
3163 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003164 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003165
Guido van Rossumed87ad82001-10-30 02:33:02 +00003166def delhook():
3167 if verbose: print "Testing __del__ hook..."
3168 log = []
3169 class C(object):
3170 def __del__(self):
3171 log.append(1)
3172 c = C()
3173 vereq(log, [])
3174 del c
3175 vereq(log, [1])
3176
Guido van Rossum29d26062001-12-11 04:37:34 +00003177 class D(object): pass
3178 d = D()
3179 try: del d[0]
3180 except TypeError: pass
3181 else: raise TestFailed, "invalid del() didn't raise TypeError"
3182
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003183def hashinherit():
3184 if verbose: print "Testing hash of mutable subclasses..."
3185
3186 class mydict(dict):
3187 pass
3188 d = mydict()
3189 try:
3190 hash(d)
3191 except TypeError:
3192 pass
3193 else:
3194 raise TestFailed, "hash() of dict subclass should fail"
3195
3196 class mylist(list):
3197 pass
3198 d = mylist()
3199 try:
3200 hash(d)
3201 except TypeError:
3202 pass
3203 else:
3204 raise TestFailed, "hash() of list subclass should fail"
3205
Guido van Rossum29d26062001-12-11 04:37:34 +00003206def strops():
3207 try: 'a' + 5
3208 except TypeError: pass
3209 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3210
3211 try: ''.split('')
3212 except ValueError: pass
3213 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3214
3215 try: ''.join([0])
3216 except TypeError: pass
3217 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3218
3219 try: ''.rindex('5')
3220 except ValueError: pass
3221 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3222
Guido van Rossum29d26062001-12-11 04:37:34 +00003223 try: '%(n)s' % None
3224 except TypeError: pass
3225 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3226
3227 try: '%(n' % {}
3228 except ValueError: pass
3229 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3230
3231 try: '%*s' % ('abc')
3232 except TypeError: pass
3233 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3234
3235 try: '%*.*s' % ('abc', 5)
3236 except TypeError: pass
3237 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3238
3239 try: '%s' % (1, 2)
3240 except TypeError: pass
3241 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3242
3243 try: '%' % None
3244 except ValueError: pass
3245 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3246
3247 vereq('534253'.isdigit(), 1)
3248 vereq('534253x'.isdigit(), 0)
3249 vereq('%c' % 5, '\x05')
3250 vereq('%c' % '5', '5')
3251
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003252def deepcopyrecursive():
3253 if verbose: print "Testing deepcopy of recursive objects..."
3254 class Node:
3255 pass
3256 a = Node()
3257 b = Node()
3258 a.b = b
3259 b.a = a
3260 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003261
Guido van Rossumd7035672002-03-12 20:43:31 +00003262def modules():
3263 if verbose: print "Testing uninitialized module objects..."
3264 from types import ModuleType as M
3265 m = M.__new__(M)
3266 str(m)
3267 vereq(hasattr(m, "__name__"), 0)
3268 vereq(hasattr(m, "__file__"), 0)
3269 vereq(hasattr(m, "foo"), 0)
3270 vereq(m.__dict__, None)
3271 m.foo = 1
3272 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003273
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003274def dictproxyiterkeys():
3275 class C(object):
3276 def meth(self):
3277 pass
3278 if verbose: print "Testing dict-proxy iterkeys..."
3279 keys = [ key for key in C.__dict__.iterkeys() ]
3280 keys.sort()
3281 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3282
3283def dictproxyitervalues():
3284 class C(object):
3285 def meth(self):
3286 pass
3287 if verbose: print "Testing dict-proxy itervalues..."
3288 values = [ values for values in C.__dict__.itervalues() ]
3289 vereq(len(values), 5)
3290
3291def dictproxyiteritems():
3292 class C(object):
3293 def meth(self):
3294 pass
3295 if verbose: print "Testing dict-proxy iteritems..."
3296 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3297 keys.sort()
3298 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3299
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003300def funnynew():
3301 if verbose: print "Testing __new__ returning something unexpected..."
3302 class C(object):
3303 def __new__(cls, arg):
3304 if isinstance(arg, str): return [1, 2, 3]
3305 elif isinstance(arg, int): return object.__new__(D)
3306 else: return object.__new__(cls)
3307 class D(C):
3308 def __init__(self, arg):
3309 self.foo = arg
3310 vereq(C("1"), [1, 2, 3])
3311 vereq(D("1"), [1, 2, 3])
3312 d = D(None)
3313 veris(d.foo, None)
3314 d = C(1)
3315 vereq(isinstance(d, D), True)
3316 vereq(d.foo, 1)
3317 d = D(1)
3318 vereq(isinstance(d, D), True)
3319 vereq(d.foo, 1)
3320
Guido van Rossume8fc6402002-04-16 16:44:51 +00003321def imulbug():
3322 # SF bug 544647
3323 if verbose: print "Testing for __imul__ problems..."
3324 class C(object):
3325 def __imul__(self, other):
3326 return (self, other)
3327 x = C()
3328 y = x
3329 y *= 1.0
3330 vereq(y, (x, 1.0))
3331 y = x
3332 y *= 2
3333 vereq(y, (x, 2))
3334 y = x
3335 y *= 3L
3336 vereq(y, (x, 3L))
3337 y = x
3338 y *= 1L<<100
3339 vereq(y, (x, 1L<<100))
3340 y = x
3341 y *= None
3342 vereq(y, (x, None))
3343 y = x
3344 y *= "foo"
3345 vereq(y, (x, "foo"))
3346
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003347def docdescriptor():
3348 # SF bug 542984
3349 if verbose: print "Testing __doc__ descriptor..."
3350 class DocDescr(object):
3351 def __get__(self, object, otype):
3352 if object:
3353 object = object.__class__.__name__ + ' instance'
3354 if otype:
3355 otype = otype.__name__
3356 return 'object=%s; type=%s' % (object, otype)
3357 class OldClass:
3358 __doc__ = DocDescr()
3359 class NewClass(object):
3360 __doc__ = DocDescr()
3361 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3362 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3363 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3364 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3365
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003366def copy_setstate():
3367 if verbose:
3368 print "Testing that copy.*copy() correctly uses __setstate__..."
3369 import copy
3370 class C(object):
3371 def __init__(self, foo=None):
3372 self.foo = foo
3373 self.__foo = foo
3374 def setfoo(self, foo=None):
3375 self.foo = foo
3376 def getfoo(self):
3377 return self.__foo
3378 def __getstate__(self):
3379 return [self.foo]
3380 def __setstate__(self, lst):
3381 assert len(lst) == 1
3382 self.__foo = self.foo = lst[0]
3383 a = C(42)
3384 a.setfoo(24)
3385 vereq(a.foo, 24)
3386 vereq(a.getfoo(), 42)
3387 b = copy.copy(a)
3388 vereq(b.foo, 24)
3389 vereq(b.getfoo(), 24)
3390 b = copy.deepcopy(a)
3391 vereq(b.foo, 24)
3392 vereq(b.getfoo(), 24)
3393
Guido van Rossum09638c12002-06-13 19:17:46 +00003394def slices():
3395 if verbose:
3396 print "Testing cases with slices and overridden __getitem__ ..."
3397 # Strings
3398 vereq("hello"[:4], "hell")
3399 vereq("hello"[slice(4)], "hell")
3400 vereq(str.__getitem__("hello", slice(4)), "hell")
3401 class S(str):
3402 def __getitem__(self, x):
3403 return str.__getitem__(self, x)
3404 vereq(S("hello")[:4], "hell")
3405 vereq(S("hello")[slice(4)], "hell")
3406 vereq(S("hello").__getitem__(slice(4)), "hell")
3407 # Tuples
3408 vereq((1,2,3)[:2], (1,2))
3409 vereq((1,2,3)[slice(2)], (1,2))
3410 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3411 class T(tuple):
3412 def __getitem__(self, x):
3413 return tuple.__getitem__(self, x)
3414 vereq(T((1,2,3))[:2], (1,2))
3415 vereq(T((1,2,3))[slice(2)], (1,2))
3416 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3417 # Lists
3418 vereq([1,2,3][:2], [1,2])
3419 vereq([1,2,3][slice(2)], [1,2])
3420 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3421 class L(list):
3422 def __getitem__(self, x):
3423 return list.__getitem__(self, x)
3424 vereq(L([1,2,3])[:2], [1,2])
3425 vereq(L([1,2,3])[slice(2)], [1,2])
3426 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3427 # Now do lists and __setitem__
3428 a = L([1,2,3])
3429 a[slice(1, 3)] = [3,2]
3430 vereq(a, [1,3,2])
3431 a[slice(0, 2, 1)] = [3,1]
3432 vereq(a, [3,1,2])
3433 a.__setitem__(slice(1, 3), [2,1])
3434 vereq(a, [3,2,1])
3435 a.__setitem__(slice(0, 2, 1), [2,3])
3436 vereq(a, [2,3,1])
3437
Tim Peters2484aae2002-07-11 06:56:07 +00003438def subtype_resurrection():
3439 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003440 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003441
3442 class C(object):
3443 container = []
3444
3445 def __del__(self):
3446 # resurrect the instance
3447 C.container.append(self)
3448
3449 c = C()
3450 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003451 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003452 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003453 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003454
3455 # If that didn't blow up, it's also interesting to see whether clearing
3456 # the last container slot works: that will attempt to delete c again,
3457 # which will cause c to get appended back to the container again "during"
3458 # the del.
3459 del C.container[-1]
3460 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003461 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003462
Tim Peters14cb1e12002-07-11 18:26:21 +00003463 # Make c mortal again, so that the test framework with -l doesn't report
3464 # it as a leak.
3465 del C.__del__
3466
Guido van Rossum2d702462002-08-06 21:28:28 +00003467def slottrash():
3468 # Deallocating deeply nested slotted trash caused stack overflows
3469 if verbose:
3470 print "Testing slot trash..."
3471 class trash(object):
3472 __slots__ = ['x']
3473 def __init__(self, x):
3474 self.x = x
3475 o = None
3476 for i in xrange(50000):
3477 o = trash(o)
3478 del o
3479
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003480def slotmultipleinheritance():
3481 # SF bug 575229, multiple inheritance w/ slots dumps core
3482 class A(object):
3483 __slots__=()
3484 class B(object):
3485 pass
3486 class C(A,B) :
3487 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003488 vereq(C.__basicsize__, B.__basicsize__)
3489 verify(hasattr(C, '__dict__'))
3490 verify(hasattr(C, '__weakref__'))
3491 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003492
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003493def testrmul():
3494 # SF patch 592646
3495 if verbose:
3496 print "Testing correct invocation of __rmul__..."
3497 class C(object):
3498 def __mul__(self, other):
3499 return "mul"
3500 def __rmul__(self, other):
3501 return "rmul"
3502 a = C()
3503 vereq(a*2, "mul")
3504 vereq(a*2.2, "mul")
3505 vereq(2*a, "rmul")
3506 vereq(2.2*a, "rmul")
3507
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003508def testipow():
3509 # [SF bug 620179]
3510 if verbose:
3511 print "Testing correct invocation of __ipow__..."
3512 class C(object):
3513 def __ipow__(self, other):
3514 pass
3515 a = C()
3516 a **= 2
3517
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003518def do_this_first():
3519 if verbose:
3520 print "Testing SF bug 551412 ..."
3521 # This dumps core when SF bug 551412 isn't fixed --
3522 # but only when test_descr.py is run separately.
3523 # (That can't be helped -- as soon as PyType_Ready()
3524 # is called for PyLong_Type, the bug is gone.)
3525 class UserLong(object):
3526 def __pow__(self, *args):
3527 pass
3528 try:
3529 pow(0L, UserLong(), 0L)
3530 except:
3531 pass
3532
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003533 if verbose:
3534 print "Testing SF bug 570483..."
3535 # Another segfault only when run early
3536 # (before PyType_Ready(tuple) is called)
3537 type.mro(tuple)
3538
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003539def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003540 if verbose:
3541 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003542 # stuff that should work:
3543 class C(object):
3544 pass
3545 class C2(object):
3546 def __getattribute__(self, attr):
3547 if attr == 'a':
3548 return 2
3549 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003550 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003551 def meth(self):
3552 return 1
3553 class D(C):
3554 pass
3555 class E(D):
3556 pass
3557 d = D()
3558 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003559 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003560 D.__bases__ = (C2,)
3561 vereq(d.meth(), 1)
3562 vereq(e.meth(), 1)
3563 vereq(d.a, 2)
3564 vereq(e.a, 2)
3565 vereq(C2.__subclasses__(), [D])
3566
3567 # stuff that shouldn't:
3568 class L(list):
3569 pass
3570
3571 try:
3572 L.__bases__ = (dict,)
3573 except TypeError:
3574 pass
3575 else:
3576 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3577
3578 try:
3579 list.__bases__ = (dict,)
3580 except TypeError:
3581 pass
3582 else:
3583 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3584
3585 try:
3586 del D.__bases__
3587 except TypeError:
3588 pass
3589 else:
3590 raise TestFailed, "shouldn't be able to delete .__bases__"
3591
3592 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003593 D.__bases__ = ()
3594 except TypeError, msg:
3595 if str(msg) == "a new-style class can't have only classic bases":
3596 raise TestFailed, "wrong error message for .__bases__ = ()"
3597 else:
3598 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3599
3600 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003601 D.__bases__ = (D,)
3602 except TypeError:
3603 pass
3604 else:
3605 # actually, we'll have crashed by here...
3606 raise TestFailed, "shouldn't be able to create inheritance cycles"
3607
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003608 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003609 D.__bases__ = (C, C)
3610 except TypeError:
3611 pass
3612 else:
3613 raise TestFailed, "didn't detect repeated base classes"
3614
3615 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003616 D.__bases__ = (E,)
3617 except TypeError:
3618 pass
3619 else:
3620 raise TestFailed, "shouldn't be able to create inheritance cycles"
3621
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003622 # let's throw a classic class into the mix:
3623 class Classic:
3624 def meth2(self):
3625 return 3
3626
3627 D.__bases__ = (C, Classic)
3628
3629 vereq(d.meth2(), 3)
3630 vereq(e.meth2(), 3)
3631 try:
3632 d.a
3633 except AttributeError:
3634 pass
3635 else:
3636 raise TestFailed, "attribute should have vanished"
3637
3638 try:
3639 D.__bases__ = (Classic,)
3640 except TypeError:
3641 pass
3642 else:
3643 raise TestFailed, "new-style class must have a new-style base"
3644
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003645def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003646 if verbose:
3647 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003648 class WorkOnce(type):
3649 def __new__(self, name, bases, ns):
3650 self.flag = 0
3651 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3652 def mro(self):
3653 if self.flag > 0:
3654 raise RuntimeError, "bozo"
3655 else:
3656 self.flag += 1
3657 return type.mro(self)
3658
3659 class WorkAlways(type):
3660 def mro(self):
3661 # this is here to make sure that .mro()s aren't called
3662 # with an exception set (which was possible at one point).
3663 # An error message will be printed in a debug build.
3664 # What's a good way to test for this?
3665 return type.mro(self)
3666
3667 class C(object):
3668 pass
3669
3670 class C2(object):
3671 pass
3672
3673 class D(C):
3674 pass
3675
3676 class E(D):
3677 pass
3678
3679 class F(D):
3680 __metaclass__ = WorkOnce
3681
3682 class G(D):
3683 __metaclass__ = WorkAlways
3684
3685 # Immediate subclasses have their mro's adjusted in alphabetical
3686 # order, so E's will get adjusted before adjusting F's fails. We
3687 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003688
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003689 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003690 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003691
3692 try:
3693 D.__bases__ = (C2,)
3694 except RuntimeError:
3695 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003696 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003697 else:
3698 raise TestFailed, "exception not propagated"
3699
3700def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003701 if verbose:
3702 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003703 class A(object):
3704 pass
3705
3706 class B(object):
3707 pass
3708
3709 class C(A, B):
3710 pass
3711
3712 class D(A, B):
3713 pass
3714
3715 class E(C, D):
3716 pass
3717
3718 try:
3719 C.__bases__ = (B, A)
3720 except TypeError:
3721 pass
3722 else:
3723 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003724
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003725def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003726 if verbose:
3727 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003728 class C(object):
3729 pass
3730
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003731 # C.__module__ could be 'test_descr' or '__main__'
3732 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003733
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003734 C.__name__ = 'D'
3735 vereq((C.__module__, C.__name__), (mod, 'D'))
3736
3737 C.__name__ = 'D.E'
3738 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003739
Guido van Rossum613f24f2003-01-06 23:00:59 +00003740def subclass_right_op():
3741 if verbose:
3742 print "Testing correct dispatch of subclass overloading __r<op>__..."
3743
3744 # This code tests various cases where right-dispatch of a subclass
3745 # should be preferred over left-dispatch of a base class.
3746
3747 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3748
3749 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003750 def __floordiv__(self, other):
3751 return "B.__floordiv__"
3752 def __rfloordiv__(self, other):
3753 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003754
Guido van Rossumf389c772003-02-27 20:04:19 +00003755 vereq(B(1) // 1, "B.__floordiv__")
3756 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003757
3758 # Case 2: subclass of object; this is just the baseline for case 3
3759
3760 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003761 def __floordiv__(self, other):
3762 return "C.__floordiv__"
3763 def __rfloordiv__(self, other):
3764 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003765
Guido van Rossumf389c772003-02-27 20:04:19 +00003766 vereq(C() // 1, "C.__floordiv__")
3767 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003768
3769 # Case 3: subclass of new-style class; here it gets interesting
3770
3771 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003772 def __floordiv__(self, other):
3773 return "D.__floordiv__"
3774 def __rfloordiv__(self, other):
3775 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003776
Guido van Rossumf389c772003-02-27 20:04:19 +00003777 vereq(D() // C(), "D.__floordiv__")
3778 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003779
3780 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3781
3782 class E(C):
3783 pass
3784
Guido van Rossumf389c772003-02-27 20:04:19 +00003785 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003786
Guido van Rossumf389c772003-02-27 20:04:19 +00003787 vereq(E() // 1, "C.__floordiv__")
3788 vereq(1 // E(), "C.__rfloordiv__")
3789 vereq(E() // C(), "C.__floordiv__")
3790 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003791
Guido van Rossum373c7412003-01-07 13:41:37 +00003792def dict_type_with_metaclass():
3793 if verbose:
3794 print "Testing type of __dict__ when __metaclass__ set..."
3795
3796 class B(object):
3797 pass
3798 class M(type):
3799 pass
3800 class C:
3801 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3802 __metaclass__ = M
3803 veris(type(C.__dict__), type(B.__dict__))
3804
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003805def meth_class_get():
3806 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003807 if verbose:
3808 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003809 # Baseline
3810 arg = [1, 2, 3]
3811 res = {1: None, 2: None, 3: None}
3812 vereq(dict.fromkeys(arg), res)
3813 vereq({}.fromkeys(arg), res)
3814 # Now get the descriptor
3815 descr = dict.__dict__["fromkeys"]
3816 # More baseline using the descriptor directly
3817 vereq(descr.__get__(None, dict)(arg), res)
3818 vereq(descr.__get__({})(arg), res)
3819 # Now check various error cases
3820 try:
3821 descr.__get__(None, None)
3822 except TypeError:
3823 pass
3824 else:
3825 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3826 try:
3827 descr.__get__(42)
3828 except TypeError:
3829 pass
3830 else:
3831 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3832 try:
3833 descr.__get__(None, 42)
3834 except TypeError:
3835 pass
3836 else:
3837 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3838 try:
3839 descr.__get__(None, int)
3840 except TypeError:
3841 pass
3842 else:
3843 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3844
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003845def isinst_isclass():
3846 if verbose:
3847 print "Testing proxy isinstance() and isclass()..."
3848 class Proxy(object):
3849 def __init__(self, obj):
3850 self.__obj = obj
3851 def __getattribute__(self, name):
3852 if name.startswith("_Proxy__"):
3853 return object.__getattribute__(self, name)
3854 else:
3855 return getattr(self.__obj, name)
3856 # Test with a classic class
3857 class C:
3858 pass
3859 a = C()
3860 pa = Proxy(a)
3861 verify(isinstance(a, C)) # Baseline
3862 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003863 # Test with a classic subclass
3864 class D(C):
3865 pass
3866 a = D()
3867 pa = Proxy(a)
3868 verify(isinstance(a, C)) # Baseline
3869 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003870 # Test with a new-style class
3871 class C(object):
3872 pass
3873 a = C()
3874 pa = Proxy(a)
3875 verify(isinstance(a, C)) # Baseline
3876 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003877 # Test with a new-style subclass
3878 class D(C):
3879 pass
3880 a = D()
3881 pa = Proxy(a)
3882 verify(isinstance(a, C)) # Baseline
3883 verify(isinstance(pa, C)) # Test
3884
3885def proxysuper():
3886 if verbose:
3887 print "Testing super() for a proxy object..."
3888 class Proxy(object):
3889 def __init__(self, obj):
3890 self.__obj = obj
3891 def __getattribute__(self, name):
3892 if name.startswith("_Proxy__"):
3893 return object.__getattribute__(self, name)
3894 else:
3895 return getattr(self.__obj, name)
3896
3897 class B(object):
3898 def f(self):
3899 return "B.f"
3900
3901 class C(B):
3902 def f(self):
3903 return super(C, self).f() + "->C.f"
3904
3905 obj = C()
3906 p = Proxy(obj)
3907 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003908
Guido van Rossum52b27052003-04-15 20:05:10 +00003909def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003910 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00003911 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003912 try:
3913 object.__setattr__(str, "foo", 42)
3914 except TypeError:
3915 pass
3916 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003917 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003918 try:
3919 object.__delattr__(str, "lower")
3920 except TypeError:
3921 pass
3922 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003923 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003924
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003925def weakref_segfault():
3926 # SF 742911
3927 if verbose:
3928 print "Testing weakref segfault..."
3929
3930 import weakref
3931
3932 class Provoker:
3933 def __init__(self, referrent):
3934 self.ref = weakref.ref(referrent)
3935
3936 def __del__(self):
3937 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003938
3939 class Oops(object):
3940 pass
3941
3942 o = Oops()
3943 o.whatever = Provoker(o)
3944 del o
3945
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003946# Fix SF #762455, segfault when sys.stdout is changed in getattr
3947def filefault():
3948 if verbose:
3949 print "Testing sys.stdout is changed in getattr..."
3950 import sys
3951 class StdoutGuard:
3952 def __getattr__(self, attr):
3953 sys.stdout = sys.__stdout__
3954 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3955 sys.stdout = StdoutGuard()
3956 try:
3957 print "Oops!"
3958 except RuntimeError:
3959 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003960
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003961def vicious_descriptor_nonsense():
3962 # A potential segfault spotted by Thomas Wouters in mail to
3963 # python-dev 2003-04-17, turned into an example & fixed by Michael
3964 # Hudson just less than four months later...
3965 if verbose:
3966 print "Testing vicious_descriptor_nonsense..."
3967
3968 class Evil(object):
3969 def __hash__(self):
3970 return hash('attr')
3971 def __eq__(self, other):
3972 del C.attr
3973 return 0
3974
3975 class Descr(object):
3976 def __get__(self, ob, type=None):
3977 return 1
3978
3979 class C(object):
3980 attr = Descr()
3981
3982 c = C()
3983 c.__dict__[Evil()] = 0
3984
3985 vereq(c.attr, 1)
3986 # this makes a crash more likely:
3987 import gc; gc.collect()
3988 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00003989
Raymond Hettingerb67cc802005-03-03 16:45:19 +00003990def test_init():
3991 # SF 1155938
3992 class Foo(object):
3993 def __init__(self):
3994 return 10
3995 try:
3996 Foo()
3997 except TypeError:
3998 pass
3999 else:
4000 raise TestFailed, "did not test __init__() for None return"
4001
Armin Rigoc6686b72005-11-07 08:38:00 +00004002def methodwrapper():
4003 # <type 'method-wrapper'> did not support any reflection before 2.5
4004 if verbose:
4005 print "Testing method-wrapper objects..."
4006
4007 l = []
4008 vereq(l.__add__, l.__add__)
4009 verify(l.__add__ != [].__add__)
4010 verify(l.__add__.__name__ == '__add__')
4011 verify(l.__add__.__self__ is l)
4012 verify(l.__add__.__objclass__ is list)
4013 vereq(l.__add__.__doc__, list.__add__.__doc__)
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004014
Armin Rigofd163f92005-12-29 15:59:19 +00004015def notimplemented():
4016 # all binary methods should be able to return a NotImplemented
4017 if verbose:
4018 print "Testing NotImplemented..."
4019
4020 import sys
4021 import types
4022 import operator
4023
4024 def specialmethod(self, other):
4025 return NotImplemented
4026
4027 def check(expr, x, y):
4028 try:
4029 exec expr in {'x': x, 'y': y, 'operator': operator}
4030 except TypeError:
4031 pass
4032 else:
4033 raise TestFailed("no TypeError from %r" % (expr,))
4034
4035 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4036 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4037 # ValueErrors instead of TypeErrors
4038 for metaclass in [type, types.ClassType]:
4039 for name, expr, iexpr in [
4040 ('__add__', 'x + y', 'x += y'),
4041 ('__sub__', 'x - y', 'x -= y'),
4042 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004043 ('__truediv__', 'x / y', None),
4044 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00004045 ('__mod__', 'x % y', 'x %= y'),
4046 ('__divmod__', 'divmod(x, y)', None),
4047 ('__pow__', 'x ** y', 'x **= y'),
4048 ('__lshift__', 'x << y', 'x <<= y'),
4049 ('__rshift__', 'x >> y', 'x >>= y'),
4050 ('__and__', 'x & y', 'x &= y'),
4051 ('__or__', 'x | y', 'x |= y'),
4052 ('__xor__', 'x ^ y', 'x ^= y'),
4053 ('__coerce__', 'coerce(x, y)', None)]:
4054 if name == '__coerce__':
4055 rname = name
4056 else:
4057 rname = '__r' + name[2:]
4058 A = metaclass('A', (), {name: specialmethod})
4059 B = metaclass('B', (), {rname: specialmethod})
4060 a = A()
4061 b = B()
4062 check(expr, a, a)
4063 check(expr, a, b)
4064 check(expr, b, a)
4065 check(expr, b, b)
4066 check(expr, a, N1)
4067 check(expr, a, N2)
4068 check(expr, N1, b)
4069 check(expr, N2, b)
4070 if iexpr:
4071 check(iexpr, a, a)
4072 check(iexpr, a, b)
4073 check(iexpr, b, a)
4074 check(iexpr, b, b)
4075 check(iexpr, a, N1)
4076 check(iexpr, a, N2)
4077 iname = '__i' + name[2:]
4078 C = metaclass('C', (), {iname: specialmethod})
4079 c = C()
4080 check(iexpr, c, a)
4081 check(iexpr, c, b)
4082 check(iexpr, c, N1)
4083 check(iexpr, c, N2)
4084
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004085def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004086 weakref_segfault() # Must be first, somehow
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004087 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004088 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004089 lists()
4090 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004091 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004092 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004093 ints()
4094 longs()
4095 floats()
4096 complexes()
4097 spamlists()
4098 spamdicts()
4099 pydicts()
4100 pylists()
4101 metaclass()
4102 pymods()
4103 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004104 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004106 ex5()
4107 monotonicity()
4108 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004109 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004111 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004112 dynamics()
4113 errors()
4114 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004115 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004117 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118 classic()
4119 compattr()
4120 newslot()
4121 altmro()
4122 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004123 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004124 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004125 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004126 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004127 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004128 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004129 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004130 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004131 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004132 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004133 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004134 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004135 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004136 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004137 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004138 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004139 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004140 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004141 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004142 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004143 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004144 kwdargs()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004145 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004146 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004147 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004148 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004149 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004150 dictproxyiterkeys()
4151 dictproxyitervalues()
4152 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004153 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004154 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004155 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004156 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004157 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004158 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004159 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004160 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004161 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004162 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004163 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004164 test_mutable_bases()
4165 test_mutable_bases_with_failing_mro()
4166 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004167 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004168 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004169 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004170 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004171 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004172 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004173 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004174 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004175 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004176 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004177 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004178 notimplemented()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004179
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004180 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004182if __name__ == "__main__":
4183 test_main()