blob: 2f12e96bf41e7096f22740b4fca47fa760ce5b02 [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
32 # XXX Hack so this passes before 2.3 when -Qnew is specified.
33 if meth == "__div__" and 1/2 == 0.5:
34 meth = "__truediv__"
35
Guido van Rossum45704552001-10-08 16:35:45 +000036 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000037 t = type(a)
38 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000039 while meth not in t.__dict__:
40 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000041 vereq(m, t.__dict__[meth])
42 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000043 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000044 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000045
46def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
47 if verbose: print "checking", expr
48 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000049 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000050 t = type(a)
51 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000052 while meth not in t.__dict__:
53 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000054 vereq(m, t.__dict__[meth])
55 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000056 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000057 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000058
59def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
60 if verbose: print "checking", stmt
61 dict = {'a': deepcopy(a), 'b': b}
62 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000063 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000064 t = type(a)
65 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000066 while meth not in t.__dict__:
67 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000068 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000069 dict['a'] = deepcopy(a)
70 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000071 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000072 dict['a'] = deepcopy(a)
73 bm = getattr(dict['a'], meth)
74 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000075 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076
77def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
78 if verbose: print "checking", stmt
79 dict = {'a': deepcopy(a), 'b': b, 'c': c}
80 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000081 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000082 t = type(a)
83 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000084 while meth not in t.__dict__:
85 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000086 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 dict['a'] = deepcopy(a)
88 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000089 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000090 dict['a'] = deepcopy(a)
91 bm = getattr(dict['a'], meth)
92 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000093 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000094
95def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
96 if verbose: print "checking", stmt
97 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
98 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000099 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000101 while meth not in t.__dict__:
102 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +0000103 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000104 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000105 dict['a'] = deepcopy(a)
106 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000107 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108 dict['a'] = deepcopy(a)
109 bm = getattr(dict['a'], meth)
110 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000111 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000112
Tim Peters2f93e282001-10-04 05:27:00 +0000113def class_docstrings():
114 class Classic:
115 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000116 vereq(Classic.__doc__, "A classic docstring.")
117 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000118
119 class Classic2:
120 pass
121 verify(Classic2.__doc__ is None)
122
Tim Peters4fb1fe82001-10-04 05:48:13 +0000123 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000124 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000125 vereq(NewStatic.__doc__, "Another docstring.")
126 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000127
Tim Peters4fb1fe82001-10-04 05:48:13 +0000128 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000129 pass
130 verify(NewStatic2.__doc__ is None)
131
Tim Peters4fb1fe82001-10-04 05:48:13 +0000132 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000133 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000134 vereq(NewDynamic.__doc__, "Another docstring.")
135 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000136
Tim Peters4fb1fe82001-10-04 05:48:13 +0000137 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000138 pass
139 verify(NewDynamic2.__doc__ is None)
140
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141def lists():
142 if verbose: print "Testing list operations..."
143 testbinop([1], [2], [1,2], "a+b", "__add__")
144 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
145 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
146 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
147 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
148 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
149 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
150 testunop([1,2,3], 3, "len(a)", "__len__")
151 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
152 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
153 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
154 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
155
156def dicts():
157 if verbose: print "Testing dict operations..."
158 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
159 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
160 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
161 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
162 d = {1:2,3:4}
163 l1 = []
164 for i in d.keys(): l1.append(i)
165 l = []
166 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000167 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000168 l = []
169 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000170 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000172 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000173 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 d = {1:2, 3:4}
175 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000176 vereq(eval(repr(d), {}), d)
177 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
179
Tim Peters25786c02001-09-02 08:22:48 +0000180def dict_constructor():
181 if verbose:
Tim Petersa427a2b2001-10-29 22:25:45 +0000182 print "Testing dict constructor ..."
183 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000184 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000185 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000186 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000187 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000188 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000189 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000190 vereq(d, dict(d.iteritems()))
191 d = dict({'one':1, 'two':2})
192 vereq(d, dict(one=1, two=2))
193 vereq(d, dict(**d))
194 vereq(d, dict({"one": 1}, two=2))
195 vereq(d, dict([("two", 2)], one=1))
196 vereq(d, dict([("one", 100), ("two", 200)], **d))
197 verify(d is not dict(**d))
Tim Peters25786c02001-09-02 08:22:48 +0000198 for badarg in 0, 0L, 0j, "0", [0], (0,):
199 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000200 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000201 except TypeError:
202 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000203 except ValueError:
204 if badarg == "0":
205 # It's a sequence, and its elements are also sequences (gotta
206 # love strings <wink>), but they aren't of length 2, so this
207 # one seemed better as a ValueError than a TypeError.
208 pass
209 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000210 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000211 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000212 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000213
214 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000215 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000216 except TypeError:
217 pass
218 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000219 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000220
221 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000222 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000223 dict = {1:2, 3:4, 'a':1j}
224
Tim Peters25786c02001-09-02 08:22:48 +0000225 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000226 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000227 except TypeError:
228 pass
229 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000230 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000231
232 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000233 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000234 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000235 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000236
Tim Peters1fc240e2001-10-26 05:06:50 +0000237 # Init from sequence of iterable objects, each producing a 2-sequence.
238 class AddressBookEntry:
239 def __init__(self, first, last):
240 self.first = first
241 self.last = last
242 def __iter__(self):
243 return iter([self.first, self.last])
244
Tim Petersa427a2b2001-10-29 22:25:45 +0000245 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000246 AddressBookEntry('Barry', 'Peters'),
247 AddressBookEntry('Tim', 'Peters'),
248 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000249 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
250
Tim Petersa427a2b2001-10-29 22:25:45 +0000251 d = dict(zip(range(4), range(1, 5)))
252 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000253
254 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000255 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000256 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000257 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000258 except ValueError:
259 pass
260 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000261 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000262
Tim Peters5d2b77c2001-09-03 05:47:38 +0000263def test_dir():
264 if verbose:
265 print "Testing dir() ..."
266 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000267 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000268 del junk
269
270 # Just make sure these don't blow up!
271 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
272 dir(arg)
273
Tim Peters37a309d2001-09-04 01:20:04 +0000274 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275 class C:
276 Cdata = 1
277 def Cmethod(self): pass
278
279 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
Guido van Rossum45704552001-10-08 16:35:45 +0000280 vereq(dir(C), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000281 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000282
283 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
Guido van Rossum45704552001-10-08 16:35:45 +0000284 vereq(dir(c), cstuff)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000285
286 c.cdata = 2
287 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000288 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000289 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000290
291 class A(C):
292 Adata = 1
293 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000294
Tim Peters37a309d2001-09-04 01:20:04 +0000295 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000296 vereq(dir(A), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000297 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000298 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000299 vereq(dir(a), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000300 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000301 a.adata = 42
302 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000303 vereq(dir(a), astuff + ['adata', 'amethod'])
Tim Peters37a309d2001-09-04 01:20:04 +0000304
305 # The same, but with new-style classes. Since these have object as a
306 # base class, a lot more gets sucked in.
307 def interesting(strings):
308 return [s for s in strings if not s.startswith('_')]
309
Tim Peters5d2b77c2001-09-03 05:47:38 +0000310 class C(object):
311 Cdata = 1
312 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000313
314 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000315 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000316
317 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000318 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000319 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000320
321 c.cdata = 2
322 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000323 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000324 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000325
Tim Peters5d2b77c2001-09-03 05:47:38 +0000326 class A(C):
327 Adata = 1
328 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000329
330 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000331 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000332 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000333 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000334 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000335 a.adata = 42
336 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000337 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000338 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000339
Tim Peterscaaff8d2001-09-10 23:12:14 +0000340 # Try a module subclass.
341 import sys
342 class M(type(sys)):
343 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000344 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000345 minstance.b = 2
346 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000347 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
348 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000349
350 class M2(M):
351 def getdict(self):
352 return "Not a dict!"
353 __dict__ = property(getdict)
354
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000355 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000356 m2instance.b = 2
357 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000358 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000359 try:
360 dir(m2instance)
361 except TypeError:
362 pass
363
Tim Peters9e6a3992001-10-30 05:45:26 +0000364 # Two essentially featureless objects, just inheriting stuff from
365 # object.
366 vereq(dir(None), dir(Ellipsis))
367
Guido van Rossum44022412002-05-13 18:29:46 +0000368 # Nasty test case for proxied objects
369 class Wrapper(object):
370 def __init__(self, obj):
371 self.__obj = obj
372 def __repr__(self):
373 return "Wrapper(%s)" % repr(self.__obj)
374 def __getitem__(self, key):
375 return Wrapper(self.__obj[key])
376 def __len__(self):
377 return len(self.__obj)
378 def __getattr__(self, name):
379 return Wrapper(getattr(self.__obj, name))
380
381 class C(object):
382 def __getclass(self):
383 return Wrapper(type(self))
384 __class__ = property(__getclass)
385
386 dir(C()) # This used to segfault
387
Tim Peters6d6c1a32001-08-02 04:15:00 +0000388binops = {
389 'add': '+',
390 'sub': '-',
391 'mul': '*',
392 'div': '/',
393 'mod': '%',
394 'divmod': 'divmod',
395 'pow': '**',
396 'lshift': '<<',
397 'rshift': '>>',
398 'and': '&',
399 'xor': '^',
400 'or': '|',
401 'cmp': 'cmp',
402 'lt': '<',
403 'le': '<=',
404 'eq': '==',
405 'ne': '!=',
406 'gt': '>',
407 'ge': '>=',
408 }
409
410for name, expr in binops.items():
411 if expr.islower():
412 expr = expr + "(a, b)"
413 else:
414 expr = 'a %s b' % expr
415 binops[name] = expr
416
417unops = {
418 'pos': '+',
419 'neg': '-',
420 'abs': 'abs',
421 'invert': '~',
422 'int': 'int',
423 'long': 'long',
424 'float': 'float',
425 'oct': 'oct',
426 'hex': 'hex',
427 }
428
429for name, expr in unops.items():
430 if expr.islower():
431 expr = expr + "(a)"
432 else:
433 expr = '%s a' % expr
434 unops[name] = expr
435
436def numops(a, b, skip=[]):
437 dict = {'a': a, 'b': b}
438 for name, expr in binops.items():
439 if name not in skip:
440 name = "__%s__" % name
441 if hasattr(a, name):
442 res = eval(expr, dict)
443 testbinop(a, b, res, expr, name)
444 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000445 if name not in skip:
446 name = "__%s__" % name
447 if hasattr(a, name):
448 res = eval(expr, dict)
449 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450
451def ints():
452 if verbose: print "Testing int operations..."
453 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000454 # The following crashes in Python 2.2
455 vereq((1).__nonzero__(), 1)
456 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000457 # This returns 'NotImplemented' in Python 2.2
458 class C(int):
459 def __add__(self, other):
460 return NotImplemented
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000461 vereq(C(5L), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000462 try:
463 C() + ""
464 except TypeError:
465 pass
466 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000467 raise TestFailed, "NotImplemented should have caused TypeError"
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000468 import sys
469 try:
470 C(sys.maxint+1)
471 except OverflowError:
472 pass
473 else:
474 raise TestFailed, "should have raised OverflowError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000475
476def longs():
477 if verbose: print "Testing long operations..."
478 numops(100L, 3L)
479
480def floats():
481 if verbose: print "Testing float operations..."
482 numops(100.0, 3.0)
483
484def complexes():
485 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000486 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000487 class Number(complex):
488 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000489 def __new__(cls, *args, **kwds):
490 result = complex.__new__(cls, *args)
491 result.prec = kwds.get('prec', 12)
492 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 def __repr__(self):
494 prec = self.prec
495 if self.imag == 0.0:
496 return "%.*g" % (prec, self.real)
497 if self.real == 0.0:
498 return "%.*gj" % (prec, self.imag)
499 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
500 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000501
Tim Peters6d6c1a32001-08-02 04:15:00 +0000502 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000503 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000504 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000505
Tim Peters3f996e72001-09-13 19:18:27 +0000506 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000507 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000508 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000509
510 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000511 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000512 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000513
Tim Peters6d6c1a32001-08-02 04:15:00 +0000514def spamlists():
515 if verbose: print "Testing spamlist operations..."
516 import copy, xxsubtype as spam
517 def spamlist(l, memo=None):
518 import xxsubtype as spam
519 return spam.spamlist(l)
520 # This is an ugly hack:
521 copy._deepcopy_dispatch[spam.spamlist] = spamlist
522
523 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
524 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
525 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
526 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
527 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
528 "a[b:c]", "__getslice__")
529 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
530 "a+=b", "__iadd__")
531 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
532 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
533 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
535 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
536 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
537 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
538 # Test subclassing
539 class C(spam.spamlist):
540 def foo(self): return 1
541 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000542 vereq(a, [])
543 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000544 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000545 vereq(a, [100])
546 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000548 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000549
550def spamdicts():
551 if verbose: print "Testing spamdict operations..."
552 import copy, xxsubtype as spam
553 def spamdict(d, memo=None):
554 import xxsubtype as spam
555 sd = spam.spamdict()
556 for k, v in d.items(): sd[k] = v
557 return sd
558 # This is an ugly hack:
559 copy._deepcopy_dispatch[spam.spamdict] = spamdict
560
561 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
562 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
563 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
564 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
565 d = spamdict({1:2,3:4})
566 l1 = []
567 for i in d.keys(): l1.append(i)
568 l = []
569 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000570 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000571 l = []
572 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000573 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000574 l = []
575 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000576 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577 straightd = {1:2, 3:4}
578 spamd = spamdict(straightd)
579 testunop(spamd, 2, "len(a)", "__len__")
580 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
581 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
582 "a[b]=c", "__setitem__")
583 # Test subclassing
584 class C(spam.spamdict):
585 def foo(self): return 1
586 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000587 vereq(a.items(), [])
588 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000590 vereq(a.items(), [('foo', 'bar')])
591 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000593 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
595def pydicts():
596 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000597 verify(issubclass(dict, dict))
598 verify(isinstance({}, dict))
599 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000600 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000601 verify(d.__class__ is dict)
602 verify(isinstance(d, dict))
603 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604 state = -1
605 def __init__(self, *a, **kw):
606 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000607 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000608 self.state = a[0]
609 if kw:
610 for k, v in kw.items(): self[v] = k
611 def __getitem__(self, key):
612 return self.get(key, 0)
613 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000614 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000615 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616 def setstate(self, state):
617 self.state = state
618 def getstate(self):
619 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000620 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000622 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000624 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000626 vereq(a.state, -1)
627 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000629 vereq(a.state, 0)
630 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000632 vereq(a.state, 10)
633 vereq(a.getstate(), 10)
634 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000636 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000637 if verbose: print "pydict stress test ..."
638 N = 50
639 for i in range(N):
640 a[i] = C()
641 for j in range(N):
642 a[i][j] = i*j
643 for i in range(N):
644 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000645 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646
647def pylists():
648 if verbose: print "Testing Python subclass of list..."
649 class C(list):
650 def __getitem__(self, i):
651 return list.__getitem__(self, i) + 100
652 def __getslice__(self, i, j):
653 return (i, j)
654 a = C()
655 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000656 vereq(a[0], 100)
657 vereq(a[1], 101)
658 vereq(a[2], 102)
659 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660
661def metaclass():
662 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 class C:
664 __metaclass__ = type
665 def __init__(self):
666 self.__state = 0
667 def getstate(self):
668 return self.__state
669 def setstate(self, state):
670 self.__state = state
671 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000672 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000674 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675 class D:
676 class __metaclass__(type):
677 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000678 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000679 d = D()
680 verify(d.__class__ is D)
681 class M1(type):
682 def __new__(cls, name, bases, dict):
683 dict['__spam__'] = 1
684 return type.__new__(cls, name, bases, dict)
685 class C:
686 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000687 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000688 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000689 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000690
Guido van Rossum309b5662001-08-17 11:43:17 +0000691 class _instance(object):
692 pass
693 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000694 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000695 def __new__(cls, name, bases, dict):
696 self = object.__new__(cls)
697 self.name = name
698 self.bases = bases
699 self.dict = dict
700 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000701 def __call__(self):
702 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000703 # Early binding of methods
704 for key in self.dict:
705 if key.startswith("__"):
706 continue
707 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000708 return it
709 class C:
710 __metaclass__ = M2
711 def spam(self):
712 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000713 vereq(C.name, 'C')
714 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000715 verify('spam' in C.dict)
716 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000717 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
Guido van Rossum91ee7982001-08-30 20:52:40 +0000719 # More metaclass examples
720
721 class autosuper(type):
722 # Automatically add __super to the class
723 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000724 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000725 cls = super(autosuper, metaclass).__new__(metaclass,
726 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000727 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000728 while name[:1] == "_":
729 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000730 if name:
731 name = "_%s__super" % name
732 else:
733 name = "__super"
734 setattr(cls, name, super(cls))
735 return cls
736 class A:
737 __metaclass__ = autosuper
738 def meth(self):
739 return "A"
740 class B(A):
741 def meth(self):
742 return "B" + self.__super.meth()
743 class C(A):
744 def meth(self):
745 return "C" + self.__super.meth()
746 class D(C, B):
747 def meth(self):
748 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000749 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000750 class E(B, C):
751 def meth(self):
752 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000753 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000754
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000755 class autoproperty(type):
756 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000757 # named _get_x and/or _set_x are found
758 def __new__(metaclass, name, bases, dict):
759 hits = {}
760 for key, val in dict.iteritems():
761 if key.startswith("_get_"):
762 key = key[5:]
763 get, set = hits.get(key, (None, None))
764 get = val
765 hits[key] = get, set
766 elif key.startswith("_set_"):
767 key = key[5:]
768 get, set = hits.get(key, (None, None))
769 set = val
770 hits[key] = get, set
771 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000772 dict[key] = property(get, set)
773 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000774 name, bases, dict)
775 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000776 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000777 def _get_x(self):
778 return -self.__x
779 def _set_x(self, x):
780 self.__x = -x
781 a = A()
782 verify(not hasattr(a, "x"))
783 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000784 vereq(a.x, 12)
785 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000786
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000787 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000788 # Merge of multiple cooperating metaclasses
789 pass
790 class A:
791 __metaclass__ = multimetaclass
792 def _get_x(self):
793 return "A"
794 class B(A):
795 def _get_x(self):
796 return "B" + self.__super._get_x()
797 class C(A):
798 def _get_x(self):
799 return "C" + self.__super._get_x()
800 class D(C, B):
801 def _get_x(self):
802 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000803 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000804
Guido van Rossumf76de622001-10-18 15:49:21 +0000805 # Make sure type(x) doesn't call x.__class__.__init__
806 class T(type):
807 counter = 0
808 def __init__(self, *args):
809 T.counter += 1
810 class C:
811 __metaclass__ = T
812 vereq(T.counter, 1)
813 a = C()
814 vereq(type(a), C)
815 vereq(T.counter, 1)
816
Guido van Rossum29d26062001-12-11 04:37:34 +0000817 class C(object): pass
818 c = C()
819 try: c()
820 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000821 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000822
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823def pymods():
824 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000826 import sys
827 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000829 def __init__(self, name):
830 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000831 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000833 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 def __setattr__(self, name, value):
835 log.append(("setattr", name, value))
836 MT.__setattr__(self, name, value)
837 def __delattr__(self, name):
838 log.append(("delattr", name))
839 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000840 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 a.foo = 12
842 x = a.foo
843 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000844 vereq(log, [("setattr", "foo", 12),
845 ("getattr", "foo"),
846 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847
848def multi():
849 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 class C(object):
851 def __init__(self):
852 self.__state = 0
853 def getstate(self):
854 return self.__state
855 def setstate(self, state):
856 self.__state = state
857 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000858 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000860 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000861 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862 def __init__(self):
863 type({}).__init__(self)
864 C.__init__(self)
865 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000866 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000868 vereq(d.items(), [("hello", "world")])
869 vereq(d["hello"], "world")
870 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000872 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000873 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874
Guido van Rossume45763a2001-08-10 21:28:46 +0000875 # SF bug #442833
876 class Node(object):
877 def __int__(self):
878 return int(self.foo())
879 def foo(self):
880 return "23"
881 class Frag(Node, list):
882 def foo(self):
883 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000884 vereq(Node().__int__(), 23)
885 vereq(int(Node()), 23)
886 vereq(Frag().__int__(), 42)
887 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000888
Tim Petersa91e9642001-11-14 23:32:33 +0000889 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000890
891 class A:
892 x = 1
893
894 class B(A):
895 pass
896
897 class C(A):
898 x = 2
899
900 class D(B, C):
901 pass
902 vereq(D.x, 1)
903
904 # Classic MRO is preserved for a classic base class.
905 class E(D, object):
906 pass
907 vereq(E.__mro__, (E, D, B, A, C, object))
908 vereq(E.x, 1)
909
910 # But with a mix of classic bases, their MROs are combined using
911 # new-style MRO.
912 class F(B, C, object):
913 pass
914 vereq(F.__mro__, (F, B, C, A, object))
915 vereq(F.x, 2)
916
917 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000918 class C:
919 def cmethod(self):
920 return "C a"
921 def all_method(self):
922 return "C b"
923
924 class M1(C, object):
925 def m1method(self):
926 return "M1 a"
927 def all_method(self):
928 return "M1 b"
929
930 vereq(M1.__mro__, (M1, C, object))
931 m = M1()
932 vereq(m.cmethod(), "C a")
933 vereq(m.m1method(), "M1 a")
934 vereq(m.all_method(), "M1 b")
935
936 class D(C):
937 def dmethod(self):
938 return "D a"
939 def all_method(self):
940 return "D b"
941
Guido van Rossum9a818922002-11-14 19:50:14 +0000942 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000943 def m2method(self):
944 return "M2 a"
945 def all_method(self):
946 return "M2 b"
947
Guido van Rossum9a818922002-11-14 19:50:14 +0000948 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000949 m = M2()
950 vereq(m.cmethod(), "C a")
951 vereq(m.dmethod(), "D a")
952 vereq(m.m2method(), "M2 a")
953 vereq(m.all_method(), "M2 b")
954
Guido van Rossum9a818922002-11-14 19:50:14 +0000955 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000956 def m3method(self):
957 return "M3 a"
958 def all_method(self):
959 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000960 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000961 m = M3()
962 vereq(m.cmethod(), "C a")
963 vereq(m.dmethod(), "D a")
964 vereq(m.m1method(), "M1 a")
965 vereq(m.m2method(), "M2 a")
966 vereq(m.m3method(), "M3 a")
967 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000968
Guido van Rossume54616c2001-12-14 04:19:56 +0000969 class Classic:
970 pass
971 try:
972 class New(Classic):
973 __metaclass__ = type
974 except TypeError:
975 pass
976 else:
977 raise TestFailed, "new class with only classic bases - shouldn't be"
978
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979def diamond():
980 if verbose: print "Testing multiple inheritance special cases..."
981 class A(object):
982 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000983 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984 class B(A):
985 def boo(self): return "B"
986 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000987 vereq(B().spam(), "B")
988 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 class C(A):
990 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000991 vereq(C().spam(), "A")
992 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000994 vereq(D().spam(), "B")
995 vereq(D().boo(), "B")
996 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000998 vereq(E().spam(), "B")
999 vereq(E().boo(), "C")
1000 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +00001001 # MRO order disagreement
1002 try:
1003 class F(D, E): pass
1004 except TypeError:
1005 pass
1006 else:
1007 raise TestFailed, "expected MRO order disagreement (F)"
1008 try:
1009 class G(E, D): pass
1010 except TypeError:
1011 pass
1012 else:
1013 raise TestFailed, "expected MRO order disagreement (G)"
1014
1015
1016# see thread python-dev/2002-October/029035.html
1017def ex5():
1018 if verbose: print "Testing ex5 from C3 switch discussion..."
1019 class A(object): pass
1020 class B(object): pass
1021 class C(object): pass
1022 class X(A): pass
1023 class Y(A): pass
1024 class Z(X,B,Y,C): pass
1025 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1026
1027# see "A Monotonic Superclass Linearization for Dylan",
1028# by Kim Barrett et al. (OOPSLA 1996)
1029def monotonicity():
1030 if verbose: print "Testing MRO monotonicity..."
1031 class Boat(object): pass
1032 class DayBoat(Boat): pass
1033 class WheelBoat(Boat): pass
1034 class EngineLess(DayBoat): pass
1035 class SmallMultihull(DayBoat): pass
1036 class PedalWheelBoat(EngineLess,WheelBoat): pass
1037 class SmallCatamaran(SmallMultihull): pass
1038 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1039
1040 vereq(PedalWheelBoat.__mro__,
1041 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1042 object))
1043 vereq(SmallCatamaran.__mro__,
1044 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1045
1046 vereq(Pedalo.__mro__,
1047 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1048 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1049
1050# see "A Monotonic Superclass Linearization for Dylan",
1051# by Kim Barrett et al. (OOPSLA 1996)
1052def consistency_with_epg():
1053 if verbose: print "Testing consistentcy with EPG..."
1054 class Pane(object): pass
1055 class ScrollingMixin(object): pass
1056 class EditingMixin(object): pass
1057 class ScrollablePane(Pane,ScrollingMixin): pass
1058 class EditablePane(Pane,EditingMixin): pass
1059 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1060
1061 vereq(EditableScrollablePane.__mro__,
1062 (EditableScrollablePane, ScrollablePane, EditablePane,
1063 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064
Raymond Hettingerf394df42003-04-06 19:13:41 +00001065mro_err_msg = """Cannot create a consistent method resolution
1066order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +00001067
Guido van Rossumd32047f2002-11-25 21:38:52 +00001068def mro_disagreement():
1069 if verbose: print "Testing error messages for MRO disagreement..."
1070 def raises(exc, expected, callable, *args):
1071 try:
1072 callable(*args)
1073 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001074 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001075 raise TestFailed, "Message %r, expected %r" % (str(msg),
1076 expected)
1077 else:
1078 raise TestFailed, "Expected %s" % exc
1079 class A(object): pass
1080 class B(A): pass
1081 class C(object): pass
1082 # Test some very simple errors
1083 raises(TypeError, "duplicate base class A",
1084 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001085 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001086 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001087 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001088 type, "X", (A, C, B), {})
1089 # Test a slightly more complex error
1090 class GridLayout(object): pass
1091 class HorizontalGrid(GridLayout): pass
1092 class VerticalGrid(GridLayout): pass
1093 class HVGrid(HorizontalGrid, VerticalGrid): pass
1094 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +00001095 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001096 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1097
Guido van Rossum37202612001-08-09 19:45:21 +00001098def objects():
1099 if verbose: print "Testing object class..."
1100 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001101 vereq(a.__class__, object)
1102 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001103 b = object()
1104 verify(a is not b)
1105 verify(not hasattr(a, "foo"))
1106 try:
1107 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001108 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001109 pass
1110 else:
1111 verify(0, "object() should not allow setting a foo attribute")
1112 verify(not hasattr(object(), "__dict__"))
1113
1114 class Cdict(object):
1115 pass
1116 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001117 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001118 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001119 vereq(x.foo, 1)
1120 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001121
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122def slots():
1123 if verbose: print "Testing __slots__..."
1124 class C0(object):
1125 __slots__ = []
1126 x = C0()
1127 verify(not hasattr(x, "__dict__"))
1128 verify(not hasattr(x, "foo"))
1129
1130 class C1(object):
1131 __slots__ = ['a']
1132 x = C1()
1133 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001134 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001136 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001137 x.a = None
1138 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001140 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141
1142 class C3(object):
1143 __slots__ = ['a', 'b', 'c']
1144 x = C3()
1145 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001146 verify(not hasattr(x, 'a'))
1147 verify(not hasattr(x, 'b'))
1148 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 x.a = 1
1150 x.b = 2
1151 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001152 vereq(x.a, 1)
1153 vereq(x.b, 2)
1154 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001156 class C4(object):
1157 """Validate name mangling"""
1158 __slots__ = ['__a']
1159 def __init__(self, value):
1160 self.__a = value
1161 def get(self):
1162 return self.__a
1163 x = C4(5)
1164 verify(not hasattr(x, '__dict__'))
1165 verify(not hasattr(x, '__a'))
1166 vereq(x.get(), 5)
1167 try:
1168 x.__a = 6
1169 except AttributeError:
1170 pass
1171 else:
1172 raise TestFailed, "Double underscored names not mangled"
1173
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001174 # Make sure slot names are proper identifiers
1175 try:
1176 class C(object):
1177 __slots__ = [None]
1178 except TypeError:
1179 pass
1180 else:
1181 raise TestFailed, "[None] slots not caught"
1182 try:
1183 class C(object):
1184 __slots__ = ["foo bar"]
1185 except TypeError:
1186 pass
1187 else:
1188 raise TestFailed, "['foo bar'] slots not caught"
1189 try:
1190 class C(object):
1191 __slots__ = ["foo\0bar"]
1192 except TypeError:
1193 pass
1194 else:
1195 raise TestFailed, "['foo\\0bar'] slots not caught"
1196 try:
1197 class C(object):
1198 __slots__ = ["1"]
1199 except TypeError:
1200 pass
1201 else:
1202 raise TestFailed, "['1'] slots not caught"
1203 try:
1204 class C(object):
1205 __slots__ = [""]
1206 except TypeError:
1207 pass
1208 else:
1209 raise TestFailed, "[''] slots not caught"
1210 class C(object):
1211 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1212
Guido van Rossum33bab012001-12-05 22:45:48 +00001213 # Test leaks
1214 class Counted(object):
1215 counter = 0 # counts the number of instances alive
1216 def __init__(self):
1217 Counted.counter += 1
1218 def __del__(self):
1219 Counted.counter -= 1
1220 class C(object):
1221 __slots__ = ['a', 'b', 'c']
1222 x = C()
1223 x.a = Counted()
1224 x.b = Counted()
1225 x.c = Counted()
1226 vereq(Counted.counter, 3)
1227 del x
1228 vereq(Counted.counter, 0)
1229 class D(C):
1230 pass
1231 x = D()
1232 x.a = Counted()
1233 x.z = Counted()
1234 vereq(Counted.counter, 2)
1235 del x
1236 vereq(Counted.counter, 0)
1237 class E(D):
1238 __slots__ = ['e']
1239 x = E()
1240 x.a = Counted()
1241 x.z = Counted()
1242 x.e = Counted()
1243 vereq(Counted.counter, 3)
1244 del x
1245 vereq(Counted.counter, 0)
1246
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001247 # Test cyclical leaks [SF bug 519621]
1248 class F(object):
1249 __slots__ = ['a', 'b']
1250 log = []
1251 s = F()
1252 s.a = [Counted(), s]
1253 vereq(Counted.counter, 1)
1254 s = None
1255 import gc
1256 gc.collect()
1257 vereq(Counted.counter, 0)
1258
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001259 # Test lookup leaks [SF bug 572567]
1260 import sys,gc
1261 class G(object):
1262 def __cmp__(self, other):
1263 return 0
1264 g = G()
1265 orig_objects = len(gc.get_objects())
1266 for i in xrange(10):
1267 g==g
1268 new_objects = len(gc.get_objects())
1269 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001270 class H(object):
1271 __slots__ = ['a', 'b']
1272 def __init__(self):
1273 self.a = 1
1274 self.b = 2
1275 def __del__(self):
1276 assert self.a == 1
1277 assert self.b == 2
1278
1279 save_stderr = sys.stderr
1280 sys.stderr = sys.stdout
1281 h = H()
1282 try:
1283 del h
1284 finally:
1285 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001286
Guido van Rossum8b056da2002-08-13 18:26:26 +00001287def slotspecials():
1288 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1289
1290 class D(object):
1291 __slots__ = ["__dict__"]
1292 a = D()
1293 verify(hasattr(a, "__dict__"))
1294 verify(not hasattr(a, "__weakref__"))
1295 a.foo = 42
1296 vereq(a.__dict__, {"foo": 42})
1297
1298 class W(object):
1299 __slots__ = ["__weakref__"]
1300 a = W()
1301 verify(hasattr(a, "__weakref__"))
1302 verify(not hasattr(a, "__dict__"))
1303 try:
1304 a.foo = 42
1305 except AttributeError:
1306 pass
1307 else:
1308 raise TestFailed, "shouldn't be allowed to set a.foo"
1309
1310 class C1(W, D):
1311 __slots__ = []
1312 a = C1()
1313 verify(hasattr(a, "__dict__"))
1314 verify(hasattr(a, "__weakref__"))
1315 a.foo = 42
1316 vereq(a.__dict__, {"foo": 42})
1317
1318 class C2(D, W):
1319 __slots__ = []
1320 a = C2()
1321 verify(hasattr(a, "__dict__"))
1322 verify(hasattr(a, "__weakref__"))
1323 a.foo = 42
1324 vereq(a.__dict__, {"foo": 42})
1325
Guido van Rossum9a818922002-11-14 19:50:14 +00001326# MRO order disagreement
1327#
1328# class C3(C1, C2):
1329# __slots__ = []
1330#
1331# class C4(C2, C1):
1332# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001333
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001335 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001338 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001340 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001343 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001345 vereq(E.foo, 1)
1346 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001347 # Test dynamic instances
1348 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001349 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001350 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001351 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001352 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001353 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001354 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001355 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001356 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001357 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001358 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001359 vereq(int(a), 100)
1360 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001361 verify(not hasattr(a, "spam"))
1362 def mygetattr(self, name):
1363 if name == "spam":
1364 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001365 raise AttributeError
1366 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001367 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001368 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001369 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001370 def mysetattr(self, name, value):
1371 if name == "spam":
1372 raise AttributeError
1373 return object.__setattr__(self, name, value)
1374 C.__setattr__ = mysetattr
1375 try:
1376 a.spam = "not spam"
1377 except AttributeError:
1378 pass
1379 else:
1380 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001381 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001382 class D(C):
1383 pass
1384 d = D()
1385 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001386 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001387
Guido van Rossum7e35d572001-09-15 03:14:32 +00001388 # Test handling of int*seq and seq*int
1389 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001390 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001391 vereq("a"*I(2), "aa")
1392 vereq(I(2)*"a", "aa")
1393 vereq(2*I(3), 6)
1394 vereq(I(3)*2, 6)
1395 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001396
1397 # Test handling of long*seq and seq*long
1398 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001399 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001400 vereq("a"*L(2L), "aa")
1401 vereq(L(2L)*"a", "aa")
1402 vereq(2*L(3), 6)
1403 vereq(L(3)*2, 6)
1404 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001405
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001406 # Test comparison of classes with dynamic metaclasses
1407 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001408 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001409 class someclass:
1410 __metaclass__ = dynamicmetaclass
1411 verify(someclass != object)
1412
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413def errors():
1414 if verbose: print "Testing errors..."
1415
1416 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001417 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 pass
1419 except TypeError:
1420 pass
1421 else:
1422 verify(0, "inheritance from both list and dict should be illegal")
1423
1424 try:
1425 class C(object, None):
1426 pass
1427 except TypeError:
1428 pass
1429 else:
1430 verify(0, "inheritance from non-type should be illegal")
1431 class Classic:
1432 pass
1433
1434 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001435 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436 pass
1437 except TypeError:
1438 pass
1439 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001440 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441
1442 try:
1443 class C(object):
1444 __slots__ = 1
1445 except TypeError:
1446 pass
1447 else:
1448 verify(0, "__slots__ = 1 should be illegal")
1449
1450 try:
1451 class C(object):
1452 __slots__ = [1]
1453 except TypeError:
1454 pass
1455 else:
1456 verify(0, "__slots__ = [1] should be illegal")
1457
1458def classmethods():
1459 if verbose: print "Testing class methods..."
1460 class C(object):
1461 def foo(*a): return a
1462 goo = classmethod(foo)
1463 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001464 vereq(C.goo(1), (C, 1))
1465 vereq(c.goo(1), (C, 1))
1466 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 class D(C):
1468 pass
1469 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001470 vereq(D.goo(1), (D, 1))
1471 vereq(d.goo(1), (D, 1))
1472 vereq(d.foo(1), (d, 1))
1473 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001474 # Test for a specific crash (SF bug 528132)
1475 def f(cls, arg): return (cls, arg)
1476 ff = classmethod(f)
1477 vereq(ff.__get__(0, int)(42), (int, 42))
1478 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479
Guido van Rossum155db9a2002-04-02 17:53:47 +00001480 # Test super() with classmethods (SF bug 535444)
1481 veris(C.goo.im_self, C)
1482 veris(D.goo.im_self, D)
1483 veris(super(D,D).goo.im_self, D)
1484 veris(super(D,d).goo.im_self, D)
1485 vereq(super(D,D).goo(), (D,))
1486 vereq(super(D,d).goo(), (D,))
1487
Raymond Hettingerbe971532003-06-18 01:13:41 +00001488 # Verify that argument is checked for callability (SF bug 753451)
1489 try:
1490 classmethod(1).__get__(1)
1491 except TypeError:
1492 pass
1493 else:
1494 raise TestFailed, "classmethod should check for callability"
1495
Georg Brandl6a29c322006-02-21 22:17:46 +00001496 # Verify that classmethod() doesn't allow keyword args
1497 try:
1498 classmethod(f, kw=1)
1499 except TypeError:
1500 pass
1501 else:
1502 raise TestFailed, "classmethod shouldn't accept keyword args"
1503
Fred Drakef841aa62002-03-28 15:49:54 +00001504def classmethods_in_c():
1505 if verbose: print "Testing C-based class methods..."
1506 import xxsubtype as spam
1507 a = (1, 2, 3)
1508 d = {'abc': 123}
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 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001514 veris(x, spam.spamlist)
1515 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001516 vereq(d, d1)
1517
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518def staticmethods():
1519 if verbose: print "Testing static methods..."
1520 class C(object):
1521 def foo(*a): return a
1522 goo = staticmethod(foo)
1523 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001524 vereq(C.goo(1), (1,))
1525 vereq(c.goo(1), (1,))
1526 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 class D(C):
1528 pass
1529 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001530 vereq(D.goo(1), (1,))
1531 vereq(d.goo(1), (1,))
1532 vereq(d.foo(1), (d, 1))
1533 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
Fred Drakef841aa62002-03-28 15:49:54 +00001535def staticmethods_in_c():
1536 if verbose: print "Testing C-based static methods..."
1537 import xxsubtype as spam
1538 a = (1, 2, 3)
1539 d = {"abc": 123}
1540 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1541 veris(x, None)
1542 vereq(a, a1)
1543 vereq(d, d1)
1544 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1545 veris(x, None)
1546 vereq(a, a1)
1547 vereq(d, d1)
1548
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549def classic():
1550 if verbose: print "Testing classic classes..."
1551 class C:
1552 def foo(*a): return a
1553 goo = classmethod(foo)
1554 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001555 vereq(C.goo(1), (C, 1))
1556 vereq(c.goo(1), (C, 1))
1557 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 class D(C):
1559 pass
1560 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001561 vereq(D.goo(1), (D, 1))
1562 vereq(d.goo(1), (D, 1))
1563 vereq(d.foo(1), (d, 1))
1564 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001565 class E: # *not* subclassing from C
1566 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001567 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001568 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569
1570def compattr():
1571 if verbose: print "Testing computed attributes..."
1572 class C(object):
1573 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001574 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 self.__get = get
1576 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001577 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 def __get__(self, obj, type=None):
1579 return self.__get(obj)
1580 def __set__(self, obj, value):
1581 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001582 def __delete__(self, obj):
1583 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584 def __init__(self):
1585 self.__x = 0
1586 def __get_x(self):
1587 x = self.__x
1588 self.__x = x+1
1589 return x
1590 def __set_x(self, x):
1591 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001592 def __delete_x(self):
1593 del self.__x
1594 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001596 vereq(a.x, 0)
1597 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001599 vereq(a.x, 10)
1600 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001601 del a.x
1602 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603
1604def newslot():
1605 if verbose: print "Testing __new__ slot override..."
1606 class C(list):
1607 def __new__(cls):
1608 self = list.__new__(cls)
1609 self.foo = 1
1610 return self
1611 def __init__(self):
1612 self.foo = self.foo + 2
1613 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001614 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615 verify(a.__class__ is C)
1616 class D(C):
1617 pass
1618 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001619 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001620 verify(b.__class__ is D)
1621
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622def altmro():
1623 if verbose: print "Testing mro() and overriding it..."
1624 class A(object):
1625 def f(self): return "A"
1626 class B(A):
1627 pass
1628 class C(A):
1629 def f(self): return "C"
1630 class D(B, C):
1631 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001632 vereq(D.mro(), [D, B, C, A, object])
1633 vereq(D.__mro__, (D, B, C, A, object))
1634 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001635
Guido van Rossumd3077402001-08-12 05:24:18 +00001636 class PerverseMetaType(type):
1637 def mro(cls):
1638 L = type.mro(cls)
1639 L.reverse()
1640 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001641 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001642 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001643 vereq(X.__mro__, (object, A, C, B, D, X))
1644 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645
Armin Rigo037d1e02005-12-29 17:07:39 +00001646 try:
1647 class X(object):
1648 class __metaclass__(type):
1649 def mro(self):
1650 return [self, dict, object]
1651 except TypeError:
1652 pass
1653 else:
1654 raise TestFailed, "devious mro() return not caught"
1655
1656 try:
1657 class X(object):
1658 class __metaclass__(type):
1659 def mro(self):
1660 return [1]
1661 except TypeError:
1662 pass
1663 else:
1664 raise TestFailed, "non-class mro() return not caught"
1665
1666 try:
1667 class X(object):
1668 class __metaclass__(type):
1669 def mro(self):
1670 return 1
1671 except TypeError:
1672 pass
1673 else:
1674 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001675
Armin Rigo037d1e02005-12-29 17:07:39 +00001676
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001678 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679
1680 class B(object):
1681 "Intermediate class because object doesn't have a __setattr__"
1682
1683 class C(B):
1684
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001685 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 if name == "foo":
1687 return ("getattr", name)
1688 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001689 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 def __setattr__(self, name, value):
1691 if name == "foo":
1692 self.setattr = (name, value)
1693 else:
1694 return B.__setattr__(self, name, value)
1695 def __delattr__(self, name):
1696 if name == "foo":
1697 self.delattr = name
1698 else:
1699 return B.__delattr__(self, name)
1700
1701 def __getitem__(self, key):
1702 return ("getitem", key)
1703 def __setitem__(self, key, value):
1704 self.setitem = (key, value)
1705 def __delitem__(self, key):
1706 self.delitem = key
1707
1708 def __getslice__(self, i, j):
1709 return ("getslice", i, j)
1710 def __setslice__(self, i, j, value):
1711 self.setslice = (i, j, value)
1712 def __delslice__(self, i, j):
1713 self.delslice = (i, j)
1714
1715 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001716 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001718 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001720 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721
Guido van Rossum45704552001-10-08 16:35:45 +00001722 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001724 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001725 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001726 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727
Guido van Rossum45704552001-10-08 16:35:45 +00001728 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001730 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001732 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001734def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001735 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001736 class C(object):
1737 def __init__(self, x):
1738 self.x = x
1739 def foo(self):
1740 return self.x
1741 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001742 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001743 class D(C):
1744 boo = C.foo
1745 goo = c1.foo
1746 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001747 vereq(d2.foo(), 2)
1748 vereq(d2.boo(), 2)
1749 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001750 class E(object):
1751 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001752 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001753 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001754
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001755def specials():
1756 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001757 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001758 # Test the default behavior for static classes
1759 class C(object):
1760 def __getitem__(self, i):
1761 if 0 <= i < 10: return i
1762 raise IndexError
1763 c1 = C()
1764 c2 = C()
1765 verify(not not c1)
Guido van Rossum45704552001-10-08 16:35:45 +00001766 vereq(hash(c1), id(c1))
1767 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1768 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001769 verify(c1 != c2)
1770 verify(not c1 != c1)
1771 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001772 # Note that the module name appears in str/repr, and that varies
1773 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001774 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001775 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001776 verify(-1 not in c1)
1777 for i in range(10):
1778 verify(i in c1)
1779 verify(10 not in c1)
1780 # Test the default behavior for dynamic classes
1781 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001782 def __getitem__(self, i):
1783 if 0 <= i < 10: return i
1784 raise IndexError
1785 d1 = D()
1786 d2 = D()
1787 verify(not not d1)
Guido van Rossum45704552001-10-08 16:35:45 +00001788 vereq(hash(d1), id(d1))
1789 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1790 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001791 verify(d1 != d2)
1792 verify(not d1 != d1)
1793 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001794 # Note that the module name appears in str/repr, and that varies
1795 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001796 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001797 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001798 verify(-1 not in d1)
1799 for i in range(10):
1800 verify(i in d1)
1801 verify(10 not in d1)
1802 # Test overridden behavior for static classes
1803 class Proxy(object):
1804 def __init__(self, x):
1805 self.x = x
1806 def __nonzero__(self):
1807 return not not self.x
1808 def __hash__(self):
1809 return hash(self.x)
1810 def __eq__(self, other):
1811 return self.x == other
1812 def __ne__(self, other):
1813 return self.x != other
1814 def __cmp__(self, other):
1815 return cmp(self.x, other.x)
1816 def __str__(self):
1817 return "Proxy:%s" % self.x
1818 def __repr__(self):
1819 return "Proxy(%r)" % self.x
1820 def __contains__(self, value):
1821 return value in self.x
1822 p0 = Proxy(0)
1823 p1 = Proxy(1)
1824 p_1 = Proxy(-1)
1825 verify(not p0)
1826 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001827 vereq(hash(p0), hash(0))
1828 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001829 verify(p0 != p1)
1830 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001831 vereq(not p0, p1)
1832 vereq(cmp(p0, p1), -1)
1833 vereq(cmp(p0, p0), 0)
1834 vereq(cmp(p0, p_1), 1)
1835 vereq(str(p0), "Proxy:0")
1836 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001837 p10 = Proxy(range(10))
1838 verify(-1 not in p10)
1839 for i in range(10):
1840 verify(i in p10)
1841 verify(10 not in p10)
1842 # Test overridden behavior for dynamic classes
1843 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001844 def __init__(self, x):
1845 self.x = x
1846 def __nonzero__(self):
1847 return not not self.x
1848 def __hash__(self):
1849 return hash(self.x)
1850 def __eq__(self, other):
1851 return self.x == other
1852 def __ne__(self, other):
1853 return self.x != other
1854 def __cmp__(self, other):
1855 return cmp(self.x, other.x)
1856 def __str__(self):
1857 return "DProxy:%s" % self.x
1858 def __repr__(self):
1859 return "DProxy(%r)" % self.x
1860 def __contains__(self, value):
1861 return value in self.x
1862 p0 = DProxy(0)
1863 p1 = DProxy(1)
1864 p_1 = DProxy(-1)
1865 verify(not p0)
1866 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001867 vereq(hash(p0), hash(0))
1868 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001869 verify(p0 != p1)
1870 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001871 vereq(not p0, p1)
1872 vereq(cmp(p0, p1), -1)
1873 vereq(cmp(p0, p0), 0)
1874 vereq(cmp(p0, p_1), 1)
1875 vereq(str(p0), "DProxy:0")
1876 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001877 p10 = DProxy(range(10))
1878 verify(-1 not in p10)
1879 for i in range(10):
1880 verify(i in p10)
1881 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001882 # Safety test for __cmp__
1883 def unsafecmp(a, b):
1884 try:
1885 a.__class__.__cmp__(a, b)
1886 except TypeError:
1887 pass
1888 else:
1889 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1890 a.__class__, a, b)
1891 unsafecmp(u"123", "123")
1892 unsafecmp("123", u"123")
1893 unsafecmp(1, 1.0)
1894 unsafecmp(1.0, 1)
1895 unsafecmp(1, 1L)
1896 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001897
Neal Norwitz1a997502003-01-13 20:13:12 +00001898 class Letter(str):
1899 def __new__(cls, letter):
1900 if letter == 'EPS':
1901 return str.__new__(cls)
1902 return str.__new__(cls, letter)
1903 def __str__(self):
1904 if not self:
1905 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001906 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001907
1908 # sys.stdout needs to be the original to trigger the recursion bug
1909 import sys
1910 test_stdout = sys.stdout
1911 sys.stdout = get_original_stdout()
1912 try:
1913 # nothing should actually be printed, this should raise an exception
1914 print Letter('w')
1915 except RuntimeError:
1916 pass
1917 else:
1918 raise TestFailed, "expected a RuntimeError for print recursion"
1919 sys.stdout = test_stdout
1920
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001921def weakrefs():
1922 if verbose: print "Testing weak references..."
1923 import weakref
1924 class C(object):
1925 pass
1926 c = C()
1927 r = weakref.ref(c)
1928 verify(r() is c)
1929 del c
1930 verify(r() is None)
1931 del r
1932 class NoWeak(object):
1933 __slots__ = ['foo']
1934 no = NoWeak()
1935 try:
1936 weakref.ref(no)
1937 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001938 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001939 else:
1940 verify(0, "weakref.ref(no) should be illegal")
1941 class Weak(object):
1942 __slots__ = ['foo', '__weakref__']
1943 yes = Weak()
1944 r = weakref.ref(yes)
1945 verify(r() is yes)
1946 del yes
1947 verify(r() is None)
1948 del r
1949
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001950def properties():
1951 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001952 class C(object):
1953 def getx(self):
1954 return self.__x
1955 def setx(self, value):
1956 self.__x = value
1957 def delx(self):
1958 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001959 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001960 a = C()
1961 verify(not hasattr(a, "x"))
1962 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001963 vereq(a._C__x, 42)
1964 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001965 del a.x
1966 verify(not hasattr(a, "x"))
1967 verify(not hasattr(a, "_C__x"))
1968 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001969 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001970 C.x.__delete__(a)
1971 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001972
Tim Peters66c1a522001-09-24 21:17:50 +00001973 raw = C.__dict__['x']
1974 verify(isinstance(raw, property))
1975
1976 attrs = dir(raw)
1977 verify("__doc__" in attrs)
1978 verify("fget" in attrs)
1979 verify("fset" in attrs)
1980 verify("fdel" in attrs)
1981
Guido van Rossum45704552001-10-08 16:35:45 +00001982 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001983 verify(raw.fget is C.__dict__['getx'])
1984 verify(raw.fset is C.__dict__['setx'])
1985 verify(raw.fdel is C.__dict__['delx'])
1986
1987 for attr in "__doc__", "fget", "fset", "fdel":
1988 try:
1989 setattr(raw, attr, 42)
1990 except TypeError, msg:
1991 if str(msg).find('readonly') < 0:
1992 raise TestFailed("when setting readonly attr %r on a "
1993 "property, got unexpected TypeError "
1994 "msg %r" % (attr, str(msg)))
1995 else:
1996 raise TestFailed("expected TypeError from trying to set "
1997 "readonly %r attr on a property" % attr)
1998
Neal Norwitz673cd822002-10-18 16:33:13 +00001999 class D(object):
2000 __getitem__ = property(lambda s: 1/0)
2001
2002 d = D()
2003 try:
2004 for i in d:
2005 str(i)
2006 except ZeroDivisionError:
2007 pass
2008 else:
2009 raise TestFailed, "expected ZeroDivisionError from bad property"
2010
Guido van Rossumc4a18802001-08-24 16:55:27 +00002011def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002012 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002013
2014 class A(object):
2015 def meth(self, a):
2016 return "A(%r)" % a
2017
Guido van Rossum45704552001-10-08 16:35:45 +00002018 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002019
2020 class B(A):
2021 def __init__(self):
2022 self.__super = super(B, self)
2023 def meth(self, a):
2024 return "B(%r)" % a + self.__super.meth(a)
2025
Guido van Rossum45704552001-10-08 16:35:45 +00002026 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002027
2028 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002029 def meth(self, a):
2030 return "C(%r)" % a + self.__super.meth(a)
2031 C._C__super = super(C)
2032
Guido van Rossum45704552001-10-08 16:35:45 +00002033 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002034
2035 class D(C, B):
2036 def meth(self, a):
2037 return "D(%r)" % a + super(D, self).meth(a)
2038
Guido van Rossum5b443c62001-12-03 15:38:28 +00002039 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2040
2041 # Test for subclassing super
2042
2043 class mysuper(super):
2044 def __init__(self, *args):
2045 return super(mysuper, self).__init__(*args)
2046
2047 class E(D):
2048 def meth(self, a):
2049 return "E(%r)" % a + mysuper(E, self).meth(a)
2050
2051 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2052
2053 class F(E):
2054 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002055 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002056 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2057 F._F__super = mysuper(F)
2058
2059 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2060
2061 # Make sure certain errors are raised
2062
2063 try:
2064 super(D, 42)
2065 except TypeError:
2066 pass
2067 else:
2068 raise TestFailed, "shouldn't allow super(D, 42)"
2069
2070 try:
2071 super(D, C())
2072 except TypeError:
2073 pass
2074 else:
2075 raise TestFailed, "shouldn't allow super(D, C())"
2076
2077 try:
2078 super(D).__get__(12)
2079 except TypeError:
2080 pass
2081 else:
2082 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2083
2084 try:
2085 super(D).__get__(C())
2086 except TypeError:
2087 pass
2088 else:
2089 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002090
Guido van Rossuma4541a32003-04-16 20:02:22 +00002091 # Make sure data descriptors can be overridden and accessed via super
2092 # (new feature in Python 2.3)
2093
2094 class DDbase(object):
2095 def getx(self): return 42
2096 x = property(getx)
2097
2098 class DDsub(DDbase):
2099 def getx(self): return "hello"
2100 x = property(getx)
2101
2102 dd = DDsub()
2103 vereq(dd.x, "hello")
2104 vereq(super(DDsub, dd).x, 42)
2105
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002106 # Ensure that super() lookup of descriptor from classmethod
2107 # works (SF ID# 743627)
2108
2109 class Base(object):
2110 aProp = property(lambda self: "foo")
2111
2112 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002113 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002114 def test(klass):
2115 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002116
2117 veris(Sub.test(), Base.aProp)
2118
2119
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002120def inherits():
2121 if verbose: print "Testing inheritance from basic types..."
2122
2123 class hexint(int):
2124 def __repr__(self):
2125 return hex(self)
2126 def __add__(self, other):
2127 return hexint(int.__add__(self, other))
2128 # (Note that overriding __radd__ doesn't work,
2129 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002130 vereq(repr(hexint(7) + 9), "0x10")
2131 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002132 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002133 vereq(a, 12345)
2134 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002135 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002136 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002137 verify((+a).__class__ is int)
2138 verify((a >> 0).__class__ is int)
2139 verify((a << 0).__class__ is int)
2140 verify((hexint(0) << 12).__class__ is int)
2141 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002142
2143 class octlong(long):
2144 __slots__ = []
2145 def __str__(self):
2146 s = oct(self)
2147 if s[-1] == 'L':
2148 s = s[:-1]
2149 return s
2150 def __add__(self, other):
2151 return self.__class__(super(octlong, self).__add__(other))
2152 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002153 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002154 # (Note that overriding __radd__ here only seems to work
2155 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002156 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002157 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002158 vereq(a, 12345L)
2159 vereq(long(a), 12345L)
2160 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002161 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002162 verify((+a).__class__ is long)
2163 verify((-a).__class__ is long)
2164 verify((-octlong(0)).__class__ is long)
2165 verify((a >> 0).__class__ is long)
2166 verify((a << 0).__class__ is long)
2167 verify((a - 0).__class__ is long)
2168 verify((a * 1).__class__ is long)
2169 verify((a ** 1).__class__ is long)
2170 verify((a // 1).__class__ is long)
2171 verify((1 * a).__class__ is long)
2172 verify((a | 0).__class__ is long)
2173 verify((a ^ 0).__class__ is long)
2174 verify((a & -1L).__class__ is long)
2175 verify((octlong(0) << 12).__class__ is long)
2176 verify((octlong(0) >> 12).__class__ is long)
2177 verify(abs(octlong(0)).__class__ is long)
2178
2179 # Because octlong overrides __add__, we can't check the absence of +0
2180 # optimizations using octlong.
2181 class longclone(long):
2182 pass
2183 a = longclone(1)
2184 verify((a + 0).__class__ is long)
2185 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002186
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002187 # Check that negative clones don't segfault
2188 a = longclone(-1)
2189 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002190 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002191
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002192 class precfloat(float):
2193 __slots__ = ['prec']
2194 def __init__(self, value=0.0, prec=12):
2195 self.prec = int(prec)
2196 float.__init__(value)
2197 def __repr__(self):
2198 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002199 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002200 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002201 vereq(a, 12345.0)
2202 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002203 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002204 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002205 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002206
Tim Peters2400fa42001-09-12 19:12:49 +00002207 class madcomplex(complex):
2208 def __repr__(self):
2209 return "%.17gj%+.17g" % (self.imag, self.real)
2210 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002211 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002212 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002213 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002214 vereq(a, base)
2215 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002216 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002217 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002218 vereq(repr(a), "4j-3")
2219 vereq(a, base)
2220 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002221 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002222 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002223 veris((+a).__class__, complex)
2224 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002225 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002226 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002227 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002228 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002229 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002230 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002231 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002232
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002233 class madtuple(tuple):
2234 _rev = None
2235 def rev(self):
2236 if self._rev is not None:
2237 return self._rev
2238 L = list(self)
2239 L.reverse()
2240 self._rev = self.__class__(L)
2241 return self._rev
2242 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002243 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2244 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2245 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002246 for i in range(512):
2247 t = madtuple(range(i))
2248 u = t.rev()
2249 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002250 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002251 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002252 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002253 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002254 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002255 verify(a[:].__class__ is tuple)
2256 verify((a * 1).__class__ is tuple)
2257 verify((a * 0).__class__ is tuple)
2258 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002259 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002260 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002261 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002262 verify((a + a).__class__ is tuple)
2263 verify((a * 0).__class__ is tuple)
2264 verify((a * 1).__class__ is tuple)
2265 verify((a * 2).__class__ is tuple)
2266 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002267
2268 class madstring(str):
2269 _rev = None
2270 def rev(self):
2271 if self._rev is not None:
2272 return self._rev
2273 L = list(self)
2274 L.reverse()
2275 self._rev = self.__class__("".join(L))
2276 return self._rev
2277 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002278 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2279 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2280 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002281 for i in range(256):
2282 s = madstring("".join(map(chr, range(i))))
2283 t = s.rev()
2284 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002285 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002286 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002287 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002288 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002289
Tim Peters8fa5dd02001-09-12 02:18:30 +00002290 base = "\x00" * 5
2291 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002292 vereq(s, base)
2293 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002294 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002295 vereq(hash(s), hash(base))
2296 vereq({s: 1}[base], 1)
2297 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002298 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002299 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002300 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002301 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002302 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002303 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002304 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002305 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002306 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(s * 2, base + 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:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002312 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002313 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002314 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002315 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002316 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002317 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002318 identitytab = ''.join([chr(i) for i in range(256)])
2319 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002320 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002321 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002322 vereq(s.translate(identitytab, "x"), base)
2323 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002324 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002325 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002326 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002327 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002328 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002329 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002330 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002331 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002332 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002333 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002334
Guido van Rossum91ee7982001-08-30 20:52:40 +00002335 class madunicode(unicode):
2336 _rev = None
2337 def rev(self):
2338 if self._rev is not None:
2339 return self._rev
2340 L = list(self)
2341 L.reverse()
2342 self._rev = self.__class__(u"".join(L))
2343 return self._rev
2344 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002345 vereq(u, u"ABCDEF")
2346 vereq(u.rev(), madunicode(u"FEDCBA"))
2347 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002348 base = u"12345"
2349 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002350 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002351 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002352 vereq(hash(u), hash(base))
2353 vereq({u: 1}[base], 1)
2354 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002355 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002356 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002357 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002358 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002359 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002360 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002361 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002362 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002363 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002364 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002365 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002366 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002367 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002368 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002369 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002370 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002371 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002372 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002373 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002374 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002375 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002376 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002377 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002378 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002379 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002380 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002381 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002382 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002383 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002384 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002385 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002386 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002387 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002388 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002389 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002390 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002391 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002392 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002393
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002394 class sublist(list):
2395 pass
2396 a = sublist(range(5))
2397 vereq(a, range(5))
2398 a.append("hello")
2399 vereq(a, range(5) + ["hello"])
2400 a[5] = 5
2401 vereq(a, range(6))
2402 a.extend(range(6, 20))
2403 vereq(a, range(20))
2404 a[-5:] = []
2405 vereq(a, range(15))
2406 del a[10:15]
2407 vereq(len(a), 10)
2408 vereq(a, range(10))
2409 vereq(list(a), range(10))
2410 vereq(a[0], 0)
2411 vereq(a[9], 9)
2412 vereq(a[-10], 0)
2413 vereq(a[-1], 9)
2414 vereq(a[:5], range(5))
2415
Tim Peters59c9a642001-09-13 05:38:56 +00002416 class CountedInput(file):
2417 """Counts lines read by self.readline().
2418
2419 self.lineno is the 0-based ordinal of the last line read, up to
2420 a maximum of one greater than the number of lines in the file.
2421
2422 self.ateof is true if and only if the final "" line has been read,
2423 at which point self.lineno stops incrementing, and further calls
2424 to readline() continue to return "".
2425 """
2426
2427 lineno = 0
2428 ateof = 0
2429 def readline(self):
2430 if self.ateof:
2431 return ""
2432 s = file.readline(self)
2433 # Next line works too.
2434 # s = super(CountedInput, self).readline()
2435 self.lineno += 1
2436 if s == "":
2437 self.ateof = 1
2438 return s
2439
Tim Peters561f8992001-09-13 19:36:36 +00002440 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002441 lines = ['a\n', 'b\n', 'c\n']
2442 try:
2443 f.writelines(lines)
2444 f.close()
2445 f = CountedInput(TESTFN)
2446 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2447 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002448 vereq(expected, got)
2449 vereq(f.lineno, i)
2450 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002451 f.close()
2452 finally:
2453 try:
2454 f.close()
2455 except:
2456 pass
2457 try:
2458 import os
2459 os.unlink(TESTFN)
2460 except:
2461 pass
2462
Tim Peters808b94e2001-09-13 19:33:07 +00002463def keywords():
2464 if verbose:
2465 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002466 vereq(int(x=1), 1)
2467 vereq(float(x=2), 2.0)
2468 vereq(long(x=3), 3L)
2469 vereq(complex(imag=42, real=666), complex(666, 42))
2470 vereq(str(object=500), '500')
2471 vereq(unicode(string='abc', errors='strict'), u'abc')
2472 vereq(tuple(sequence=range(3)), (0, 1, 2))
2473 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002474 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002475
2476 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002477 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002478 try:
2479 constructor(bogus_keyword_arg=1)
2480 except TypeError:
2481 pass
2482 else:
2483 raise TestFailed("expected TypeError from bogus keyword "
2484 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002485
Tim Peters8fa45672001-09-13 21:01:29 +00002486def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002487 # XXX This test is disabled because rexec is not deemed safe
2488 return
Tim Peters8fa45672001-09-13 21:01:29 +00002489 import rexec
2490 if verbose:
2491 print "Testing interaction with restricted execution ..."
2492
2493 sandbox = rexec.RExec()
2494
2495 code1 = """f = open(%r, 'w')""" % TESTFN
2496 code2 = """f = file(%r, 'w')""" % TESTFN
2497 code3 = """\
2498f = open(%r)
2499t = type(f) # a sneaky way to get the file() constructor
2500f.close()
2501f = t(%r, 'w') # rexec can't catch this by itself
2502""" % (TESTFN, TESTFN)
2503
2504 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2505 f.close()
2506
2507 try:
2508 for code in code1, code2, code3:
2509 try:
2510 sandbox.r_exec(code)
2511 except IOError, msg:
2512 if str(msg).find("restricted") >= 0:
2513 outcome = "OK"
2514 else:
2515 outcome = "got an exception, but not an expected one"
2516 else:
2517 outcome = "expected a restricted-execution exception"
2518
2519 if outcome != "OK":
2520 raise TestFailed("%s, in %r" % (outcome, code))
2521
2522 finally:
2523 try:
2524 import os
2525 os.unlink(TESTFN)
2526 except:
2527 pass
2528
Tim Peters0ab085c2001-09-14 00:25:33 +00002529def str_subclass_as_dict_key():
2530 if verbose:
2531 print "Testing a str subclass used as dict key .."
2532
2533 class cistr(str):
2534 """Sublcass of str that computes __eq__ case-insensitively.
2535
2536 Also computes a hash code of the string in canonical form.
2537 """
2538
2539 def __init__(self, value):
2540 self.canonical = value.lower()
2541 self.hashcode = hash(self.canonical)
2542
2543 def __eq__(self, other):
2544 if not isinstance(other, cistr):
2545 other = cistr(other)
2546 return self.canonical == other.canonical
2547
2548 def __hash__(self):
2549 return self.hashcode
2550
Guido van Rossum45704552001-10-08 16:35:45 +00002551 vereq(cistr('ABC'), 'abc')
2552 vereq('aBc', cistr('ABC'))
2553 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002554
2555 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002556 vereq(d[cistr('one')], 1)
2557 vereq(d[cistr('tWo')], 2)
2558 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002559 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002560 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002561
Guido van Rossumab3b0342001-09-18 20:38:53 +00002562def classic_comparisons():
2563 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002564 class classic:
2565 pass
2566 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002567 if verbose: print " (base = %s)" % base
2568 class C(base):
2569 def __init__(self, value):
2570 self.value = int(value)
2571 def __cmp__(self, other):
2572 if isinstance(other, C):
2573 return cmp(self.value, other.value)
2574 if isinstance(other, int) or isinstance(other, long):
2575 return cmp(self.value, other)
2576 return NotImplemented
2577 c1 = C(1)
2578 c2 = C(2)
2579 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002580 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002581 c = {1: c1, 2: c2, 3: c3}
2582 for x in 1, 2, 3:
2583 for y in 1, 2, 3:
2584 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2585 for op in "<", "<=", "==", "!=", ">", ">=":
2586 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2587 "x=%d, y=%d" % (x, y))
2588 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2589 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2590
Guido van Rossum0639f592001-09-18 21:06:04 +00002591def rich_comparisons():
2592 if verbose:
2593 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002594 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002595 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002596 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002597 vereq(z, 1+0j)
2598 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002599 class ZZ(complex):
2600 def __eq__(self, other):
2601 try:
2602 return abs(self - other) <= 1e-6
2603 except:
2604 return NotImplemented
2605 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002606 vereq(zz, 1+0j)
2607 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002608
Guido van Rossum0639f592001-09-18 21:06:04 +00002609 class classic:
2610 pass
2611 for base in (classic, int, object, list):
2612 if verbose: print " (base = %s)" % base
2613 class C(base):
2614 def __init__(self, value):
2615 self.value = int(value)
2616 def __cmp__(self, other):
2617 raise TestFailed, "shouldn't call __cmp__"
2618 def __eq__(self, other):
2619 if isinstance(other, C):
2620 return self.value == other.value
2621 if isinstance(other, int) or isinstance(other, long):
2622 return self.value == other
2623 return NotImplemented
2624 def __ne__(self, other):
2625 if isinstance(other, C):
2626 return self.value != other.value
2627 if isinstance(other, int) or isinstance(other, long):
2628 return self.value != other
2629 return NotImplemented
2630 def __lt__(self, other):
2631 if isinstance(other, C):
2632 return self.value < other.value
2633 if isinstance(other, int) or isinstance(other, long):
2634 return self.value < other
2635 return NotImplemented
2636 def __le__(self, other):
2637 if isinstance(other, C):
2638 return self.value <= other.value
2639 if isinstance(other, int) or isinstance(other, long):
2640 return self.value <= other
2641 return NotImplemented
2642 def __gt__(self, other):
2643 if isinstance(other, C):
2644 return self.value > other.value
2645 if isinstance(other, int) or isinstance(other, long):
2646 return self.value > other
2647 return NotImplemented
2648 def __ge__(self, other):
2649 if isinstance(other, C):
2650 return self.value >= other.value
2651 if isinstance(other, int) or isinstance(other, long):
2652 return self.value >= other
2653 return NotImplemented
2654 c1 = C(1)
2655 c2 = C(2)
2656 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002657 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002658 c = {1: c1, 2: c2, 3: c3}
2659 for x in 1, 2, 3:
2660 for y in 1, 2, 3:
2661 for op in "<", "<=", "==", "!=", ">", ">=":
2662 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2663 "x=%d, y=%d" % (x, y))
2664 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2665 "x=%d, y=%d" % (x, y))
2666 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2667 "x=%d, y=%d" % (x, y))
2668
Guido van Rossum1952e382001-09-19 01:25:16 +00002669def coercions():
2670 if verbose: print "Testing coercions..."
2671 class I(int): pass
2672 coerce(I(0), 0)
2673 coerce(0, I(0))
2674 class L(long): pass
2675 coerce(L(0), 0)
2676 coerce(L(0), 0L)
2677 coerce(0, L(0))
2678 coerce(0L, L(0))
2679 class F(float): pass
2680 coerce(F(0), 0)
2681 coerce(F(0), 0L)
2682 coerce(F(0), 0.)
2683 coerce(0, F(0))
2684 coerce(0L, F(0))
2685 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002686 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002687 coerce(C(0), 0)
2688 coerce(C(0), 0L)
2689 coerce(C(0), 0.)
2690 coerce(C(0), 0j)
2691 coerce(0, C(0))
2692 coerce(0L, C(0))
2693 coerce(0., C(0))
2694 coerce(0j, C(0))
2695
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002696def descrdoc():
2697 if verbose: print "Testing descriptor doc strings..."
2698 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002699 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002700 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002701 check(file.name, "file name") # member descriptor
2702
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002703def setclass():
2704 if verbose: print "Testing __class__ assignment..."
2705 class C(object): pass
2706 class D(object): pass
2707 class E(object): pass
2708 class F(D, E): pass
2709 for cls in C, D, E, F:
2710 for cls2 in C, D, E, F:
2711 x = cls()
2712 x.__class__ = cls2
2713 verify(x.__class__ is cls2)
2714 x.__class__ = cls
2715 verify(x.__class__ is cls)
2716 def cant(x, C):
2717 try:
2718 x.__class__ = C
2719 except TypeError:
2720 pass
2721 else:
2722 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002723 try:
2724 delattr(x, "__class__")
2725 except TypeError:
2726 pass
2727 else:
2728 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002729 cant(C(), list)
2730 cant(list(), C)
2731 cant(C(), 1)
2732 cant(C(), object)
2733 cant(object(), list)
2734 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002735 class Int(int): __slots__ = []
2736 cant(2, Int)
2737 cant(Int(), int)
2738 cant(True, int)
2739 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002740 o = object()
2741 cant(o, type(1))
2742 cant(o, type(None))
2743 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002744
Guido van Rossum6661be32001-10-26 04:26:12 +00002745def setdict():
2746 if verbose: print "Testing __dict__ assignment..."
2747 class C(object): pass
2748 a = C()
2749 a.__dict__ = {'b': 1}
2750 vereq(a.b, 1)
2751 def cant(x, dict):
2752 try:
2753 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002754 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002755 pass
2756 else:
2757 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2758 cant(a, None)
2759 cant(a, [])
2760 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002761 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002762 # Classes don't allow __dict__ assignment
2763 cant(C, {})
2764
Guido van Rossum3926a632001-09-25 16:25:58 +00002765def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002766 if verbose:
2767 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002768 import pickle, cPickle
2769
2770 def sorteditems(d):
2771 L = d.items()
2772 L.sort()
2773 return L
2774
2775 global C
2776 class C(object):
2777 def __init__(self, a, b):
2778 super(C, self).__init__()
2779 self.a = a
2780 self.b = b
2781 def __repr__(self):
2782 return "C(%r, %r)" % (self.a, self.b)
2783
2784 global C1
2785 class C1(list):
2786 def __new__(cls, a, b):
2787 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002788 def __getnewargs__(self):
2789 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002790 def __init__(self, a, b):
2791 self.a = a
2792 self.b = b
2793 def __repr__(self):
2794 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2795
2796 global C2
2797 class C2(int):
2798 def __new__(cls, a, b, val=0):
2799 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002800 def __getnewargs__(self):
2801 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002802 def __init__(self, a, b, val=0):
2803 self.a = a
2804 self.b = b
2805 def __repr__(self):
2806 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2807
Guido van Rossum90c45142001-11-24 21:07:01 +00002808 global C3
2809 class C3(object):
2810 def __init__(self, foo):
2811 self.foo = foo
2812 def __getstate__(self):
2813 return self.foo
2814 def __setstate__(self, foo):
2815 self.foo = foo
2816
2817 global C4classic, C4
2818 class C4classic: # classic
2819 pass
2820 class C4(C4classic, object): # mixed inheritance
2821 pass
2822
Guido van Rossum3926a632001-09-25 16:25:58 +00002823 for p in pickle, cPickle:
2824 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002825 if verbose:
2826 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002827
2828 for cls in C, C1, C2:
2829 s = p.dumps(cls, bin)
2830 cls2 = p.loads(s)
2831 verify(cls2 is cls)
2832
2833 a = C1(1, 2); a.append(42); a.append(24)
2834 b = C2("hello", "world", 42)
2835 s = p.dumps((a, b), bin)
2836 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002837 vereq(x.__class__, a.__class__)
2838 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2839 vereq(y.__class__, b.__class__)
2840 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002841 vereq(repr(x), repr(a))
2842 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002843 if verbose:
2844 print "a = x =", a
2845 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002846 # Test for __getstate__ and __setstate__ on new style class
2847 u = C3(42)
2848 s = p.dumps(u, bin)
2849 v = p.loads(s)
2850 veris(u.__class__, v.__class__)
2851 vereq(u.foo, v.foo)
2852 # Test for picklability of hybrid class
2853 u = C4()
2854 u.foo = 42
2855 s = p.dumps(u, bin)
2856 v = p.loads(s)
2857 veris(u.__class__, v.__class__)
2858 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002859
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002860 # Testing copy.deepcopy()
2861 if verbose:
2862 print "deepcopy"
2863 import copy
2864 for cls in C, C1, C2:
2865 cls2 = copy.deepcopy(cls)
2866 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002867
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002868 a = C1(1, 2); a.append(42); a.append(24)
2869 b = C2("hello", "world", 42)
2870 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002871 vereq(x.__class__, a.__class__)
2872 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2873 vereq(y.__class__, b.__class__)
2874 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002875 vereq(repr(x), repr(a))
2876 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002877 if verbose:
2878 print "a = x =", a
2879 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002880
Guido van Rossum8c842552002-03-14 23:05:54 +00002881def pickleslots():
2882 if verbose: print "Testing pickling of classes with __slots__ ..."
2883 import pickle, cPickle
2884 # Pickling of classes with __slots__ but without __getstate__ should fail
2885 global B, C, D, E
2886 class B(object):
2887 pass
2888 for base in [object, B]:
2889 class C(base):
2890 __slots__ = ['a']
2891 class D(C):
2892 pass
2893 try:
2894 pickle.dumps(C())
2895 except TypeError:
2896 pass
2897 else:
2898 raise TestFailed, "should fail: pickle C instance - %s" % base
2899 try:
2900 cPickle.dumps(C())
2901 except TypeError:
2902 pass
2903 else:
2904 raise TestFailed, "should fail: cPickle C instance - %s" % base
2905 try:
2906 pickle.dumps(C())
2907 except TypeError:
2908 pass
2909 else:
2910 raise TestFailed, "should fail: pickle D instance - %s" % base
2911 try:
2912 cPickle.dumps(D())
2913 except TypeError:
2914 pass
2915 else:
2916 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002917 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002918 class C(base):
2919 __slots__ = ['a']
2920 def __getstate__(self):
2921 try:
2922 d = self.__dict__.copy()
2923 except AttributeError:
2924 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002925 for cls in self.__class__.__mro__:
2926 for sn in cls.__dict__.get('__slots__', ()):
2927 try:
2928 d[sn] = getattr(self, sn)
2929 except AttributeError:
2930 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002931 return d
2932 def __setstate__(self, d):
2933 for k, v in d.items():
2934 setattr(self, k, v)
2935 class D(C):
2936 pass
2937 # Now it should work
2938 x = C()
2939 y = pickle.loads(pickle.dumps(x))
2940 vereq(hasattr(y, 'a'), 0)
2941 y = cPickle.loads(cPickle.dumps(x))
2942 vereq(hasattr(y, 'a'), 0)
2943 x.a = 42
2944 y = pickle.loads(pickle.dumps(x))
2945 vereq(y.a, 42)
2946 y = cPickle.loads(cPickle.dumps(x))
2947 vereq(y.a, 42)
2948 x = D()
2949 x.a = 42
2950 x.b = 100
2951 y = pickle.loads(pickle.dumps(x))
2952 vereq(y.a + y.b, 142)
2953 y = cPickle.loads(cPickle.dumps(x))
2954 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002955 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00002956 class E(C):
2957 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002958 x = E()
2959 x.a = 42
2960 x.b = "foo"
2961 y = pickle.loads(pickle.dumps(x))
2962 vereq(y.a, x.a)
2963 vereq(y.b, x.b)
2964 y = cPickle.loads(cPickle.dumps(x))
2965 vereq(y.a, x.a)
2966 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00002967
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002968def copies():
2969 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2970 import copy
2971 class C(object):
2972 pass
2973
2974 a = C()
2975 a.foo = 12
2976 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002977 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002978
2979 a.bar = [1,2,3]
2980 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002981 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002982 verify(c.bar is a.bar)
2983
2984 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002985 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002986 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002987 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002988
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002989def binopoverride():
2990 if verbose: print "Testing overrides of binary operations..."
2991 class I(int):
2992 def __repr__(self):
2993 return "I(%r)" % int(self)
2994 def __add__(self, other):
2995 return I(int(self) + int(other))
2996 __radd__ = __add__
2997 def __pow__(self, other, mod=None):
2998 if mod is None:
2999 return I(pow(int(self), int(other)))
3000 else:
3001 return I(pow(int(self), int(other), int(mod)))
3002 def __rpow__(self, other, mod=None):
3003 if mod is None:
3004 return I(pow(int(other), int(self), mod))
3005 else:
3006 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003007
Walter Dörwald70a6b492004-02-12 17:35:32 +00003008 vereq(repr(I(1) + I(2)), "I(3)")
3009 vereq(repr(I(1) + 2), "I(3)")
3010 vereq(repr(1 + I(2)), "I(3)")
3011 vereq(repr(I(2) ** I(3)), "I(8)")
3012 vereq(repr(2 ** I(3)), "I(8)")
3013 vereq(repr(I(2) ** 3), "I(8)")
3014 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003015 class S(str):
3016 def __eq__(self, other):
3017 return self.lower() == other.lower()
3018
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003019def subclasspropagation():
3020 if verbose: print "Testing propagation of slot functions to subclasses..."
3021 class A(object):
3022 pass
3023 class B(A):
3024 pass
3025 class C(A):
3026 pass
3027 class D(B, C):
3028 pass
3029 d = D()
3030 vereq(hash(d), id(d))
3031 A.__hash__ = lambda self: 42
3032 vereq(hash(d), 42)
3033 C.__hash__ = lambda self: 314
3034 vereq(hash(d), 314)
3035 B.__hash__ = lambda self: 144
3036 vereq(hash(d), 144)
3037 D.__hash__ = lambda self: 100
3038 vereq(hash(d), 100)
3039 del D.__hash__
3040 vereq(hash(d), 144)
3041 del B.__hash__
3042 vereq(hash(d), 314)
3043 del C.__hash__
3044 vereq(hash(d), 42)
3045 del A.__hash__
3046 vereq(hash(d), id(d))
3047 d.foo = 42
3048 d.bar = 42
3049 vereq(d.foo, 42)
3050 vereq(d.bar, 42)
3051 def __getattribute__(self, name):
3052 if name == "foo":
3053 return 24
3054 return object.__getattribute__(self, name)
3055 A.__getattribute__ = __getattribute__
3056 vereq(d.foo, 24)
3057 vereq(d.bar, 42)
3058 def __getattr__(self, name):
3059 if name in ("spam", "foo", "bar"):
3060 return "hello"
3061 raise AttributeError, name
3062 B.__getattr__ = __getattr__
3063 vereq(d.spam, "hello")
3064 vereq(d.foo, 24)
3065 vereq(d.bar, 42)
3066 del A.__getattribute__
3067 vereq(d.foo, 42)
3068 del d.foo
3069 vereq(d.foo, "hello")
3070 vereq(d.bar, 42)
3071 del B.__getattr__
3072 try:
3073 d.foo
3074 except AttributeError:
3075 pass
3076 else:
3077 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003078
Guido van Rossume7f3e242002-06-14 02:35:45 +00003079 # Test a nasty bug in recurse_down_subclasses()
3080 import gc
3081 class A(object):
3082 pass
3083 class B(A):
3084 pass
3085 del B
3086 gc.collect()
3087 A.__setitem__ = lambda *a: None # crash
3088
Tim Petersfc57ccb2001-10-12 02:38:24 +00003089def buffer_inherit():
3090 import binascii
3091 # SF bug [#470040] ParseTuple t# vs subclasses.
3092 if verbose:
3093 print "Testing that buffer interface is inherited ..."
3094
3095 class MyStr(str):
3096 pass
3097 base = 'abc'
3098 m = MyStr(base)
3099 # b2a_hex uses the buffer interface to get its argument's value, via
3100 # PyArg_ParseTuple 't#' code.
3101 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3102
3103 # It's not clear that unicode will continue to support the character
3104 # buffer interface, and this test will fail if that's taken away.
3105 class MyUni(unicode):
3106 pass
3107 base = u'abc'
3108 m = MyUni(base)
3109 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3110
3111 class MyInt(int):
3112 pass
3113 m = MyInt(42)
3114 try:
3115 binascii.b2a_hex(m)
3116 raise TestFailed('subclass of int should not have a buffer interface')
3117 except TypeError:
3118 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003119
Tim Petersc9933152001-10-16 20:18:24 +00003120def str_of_str_subclass():
3121 import binascii
3122 import cStringIO
3123
3124 if verbose:
3125 print "Testing __str__ defined in subclass of str ..."
3126
3127 class octetstring(str):
3128 def __str__(self):
3129 return binascii.b2a_hex(self)
3130 def __repr__(self):
3131 return self + " repr"
3132
3133 o = octetstring('A')
3134 vereq(type(o), octetstring)
3135 vereq(type(str(o)), str)
3136 vereq(type(repr(o)), str)
3137 vereq(ord(o), 0x41)
3138 vereq(str(o), '41')
3139 vereq(repr(o), 'A repr')
3140 vereq(o.__str__(), '41')
3141 vereq(o.__repr__(), 'A repr')
3142
3143 capture = cStringIO.StringIO()
3144 # Calling str() or not exercises different internal paths.
3145 print >> capture, o
3146 print >> capture, str(o)
3147 vereq(capture.getvalue(), '41\n41\n')
3148 capture.close()
3149
Guido van Rossumc8e56452001-10-22 00:43:43 +00003150def kwdargs():
3151 if verbose: print "Testing keyword arguments to __init__, __call__..."
3152 def f(a): return a
3153 vereq(f.__call__(a=42), 42)
3154 a = []
3155 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003156 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003157
Guido van Rossumed87ad82001-10-30 02:33:02 +00003158def delhook():
3159 if verbose: print "Testing __del__ hook..."
3160 log = []
3161 class C(object):
3162 def __del__(self):
3163 log.append(1)
3164 c = C()
3165 vereq(log, [])
3166 del c
3167 vereq(log, [1])
3168
Guido van Rossum29d26062001-12-11 04:37:34 +00003169 class D(object): pass
3170 d = D()
3171 try: del d[0]
3172 except TypeError: pass
3173 else: raise TestFailed, "invalid del() didn't raise TypeError"
3174
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003175def hashinherit():
3176 if verbose: print "Testing hash of mutable subclasses..."
3177
3178 class mydict(dict):
3179 pass
3180 d = mydict()
3181 try:
3182 hash(d)
3183 except TypeError:
3184 pass
3185 else:
3186 raise TestFailed, "hash() of dict subclass should fail"
3187
3188 class mylist(list):
3189 pass
3190 d = mylist()
3191 try:
3192 hash(d)
3193 except TypeError:
3194 pass
3195 else:
3196 raise TestFailed, "hash() of list subclass should fail"
3197
Guido van Rossum29d26062001-12-11 04:37:34 +00003198def strops():
3199 try: 'a' + 5
3200 except TypeError: pass
3201 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3202
3203 try: ''.split('')
3204 except ValueError: pass
3205 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3206
3207 try: ''.join([0])
3208 except TypeError: pass
3209 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3210
3211 try: ''.rindex('5')
3212 except ValueError: pass
3213 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3214
Guido van Rossum29d26062001-12-11 04:37:34 +00003215 try: '%(n)s' % None
3216 except TypeError: pass
3217 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3218
3219 try: '%(n' % {}
3220 except ValueError: pass
3221 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3222
3223 try: '%*s' % ('abc')
3224 except TypeError: pass
3225 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3226
3227 try: '%*.*s' % ('abc', 5)
3228 except TypeError: pass
3229 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3230
3231 try: '%s' % (1, 2)
3232 except TypeError: pass
3233 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3234
3235 try: '%' % None
3236 except ValueError: pass
3237 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3238
3239 vereq('534253'.isdigit(), 1)
3240 vereq('534253x'.isdigit(), 0)
3241 vereq('%c' % 5, '\x05')
3242 vereq('%c' % '5', '5')
3243
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003244def deepcopyrecursive():
3245 if verbose: print "Testing deepcopy of recursive objects..."
3246 class Node:
3247 pass
3248 a = Node()
3249 b = Node()
3250 a.b = b
3251 b.a = a
3252 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003253
Guido van Rossumd7035672002-03-12 20:43:31 +00003254def modules():
3255 if verbose: print "Testing uninitialized module objects..."
3256 from types import ModuleType as M
3257 m = M.__new__(M)
3258 str(m)
3259 vereq(hasattr(m, "__name__"), 0)
3260 vereq(hasattr(m, "__file__"), 0)
3261 vereq(hasattr(m, "foo"), 0)
3262 vereq(m.__dict__, None)
3263 m.foo = 1
3264 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003265
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003266def dictproxyiterkeys():
3267 class C(object):
3268 def meth(self):
3269 pass
3270 if verbose: print "Testing dict-proxy iterkeys..."
3271 keys = [ key for key in C.__dict__.iterkeys() ]
3272 keys.sort()
3273 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3274
3275def dictproxyitervalues():
3276 class C(object):
3277 def meth(self):
3278 pass
3279 if verbose: print "Testing dict-proxy itervalues..."
3280 values = [ values for values in C.__dict__.itervalues() ]
3281 vereq(len(values), 5)
3282
3283def dictproxyiteritems():
3284 class C(object):
3285 def meth(self):
3286 pass
3287 if verbose: print "Testing dict-proxy iteritems..."
3288 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3289 keys.sort()
3290 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3291
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003292def funnynew():
3293 if verbose: print "Testing __new__ returning something unexpected..."
3294 class C(object):
3295 def __new__(cls, arg):
3296 if isinstance(arg, str): return [1, 2, 3]
3297 elif isinstance(arg, int): return object.__new__(D)
3298 else: return object.__new__(cls)
3299 class D(C):
3300 def __init__(self, arg):
3301 self.foo = arg
3302 vereq(C("1"), [1, 2, 3])
3303 vereq(D("1"), [1, 2, 3])
3304 d = D(None)
3305 veris(d.foo, None)
3306 d = C(1)
3307 vereq(isinstance(d, D), True)
3308 vereq(d.foo, 1)
3309 d = D(1)
3310 vereq(isinstance(d, D), True)
3311 vereq(d.foo, 1)
3312
Guido van Rossume8fc6402002-04-16 16:44:51 +00003313def imulbug():
3314 # SF bug 544647
3315 if verbose: print "Testing for __imul__ problems..."
3316 class C(object):
3317 def __imul__(self, other):
3318 return (self, other)
3319 x = C()
3320 y = x
3321 y *= 1.0
3322 vereq(y, (x, 1.0))
3323 y = x
3324 y *= 2
3325 vereq(y, (x, 2))
3326 y = x
3327 y *= 3L
3328 vereq(y, (x, 3L))
3329 y = x
3330 y *= 1L<<100
3331 vereq(y, (x, 1L<<100))
3332 y = x
3333 y *= None
3334 vereq(y, (x, None))
3335 y = x
3336 y *= "foo"
3337 vereq(y, (x, "foo"))
3338
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003339def docdescriptor():
3340 # SF bug 542984
3341 if verbose: print "Testing __doc__ descriptor..."
3342 class DocDescr(object):
3343 def __get__(self, object, otype):
3344 if object:
3345 object = object.__class__.__name__ + ' instance'
3346 if otype:
3347 otype = otype.__name__
3348 return 'object=%s; type=%s' % (object, otype)
3349 class OldClass:
3350 __doc__ = DocDescr()
3351 class NewClass(object):
3352 __doc__ = DocDescr()
3353 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3354 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3355 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3356 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3357
Tim Petersafb2c802002-04-18 18:06:20 +00003358def string_exceptions():
3359 if verbose:
3360 print "Testing string exceptions ..."
3361
3362 # Ensure builtin strings work OK as exceptions.
3363 astring = "An exception string."
3364 try:
3365 raise astring
3366 except astring:
3367 pass
3368 else:
3369 raise TestFailed, "builtin string not usable as exception"
3370
3371 # Ensure string subclass instances do not.
3372 class MyStr(str):
3373 pass
3374
3375 newstring = MyStr("oops -- shouldn't work")
3376 try:
3377 raise newstring
3378 except TypeError:
3379 pass
3380 except:
3381 raise TestFailed, "string subclass allowed as exception"
3382
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003383def copy_setstate():
3384 if verbose:
3385 print "Testing that copy.*copy() correctly uses __setstate__..."
3386 import copy
3387 class C(object):
3388 def __init__(self, foo=None):
3389 self.foo = foo
3390 self.__foo = foo
3391 def setfoo(self, foo=None):
3392 self.foo = foo
3393 def getfoo(self):
3394 return self.__foo
3395 def __getstate__(self):
3396 return [self.foo]
3397 def __setstate__(self, lst):
3398 assert len(lst) == 1
3399 self.__foo = self.foo = lst[0]
3400 a = C(42)
3401 a.setfoo(24)
3402 vereq(a.foo, 24)
3403 vereq(a.getfoo(), 42)
3404 b = copy.copy(a)
3405 vereq(b.foo, 24)
3406 vereq(b.getfoo(), 24)
3407 b = copy.deepcopy(a)
3408 vereq(b.foo, 24)
3409 vereq(b.getfoo(), 24)
3410
Guido van Rossum09638c12002-06-13 19:17:46 +00003411def slices():
3412 if verbose:
3413 print "Testing cases with slices and overridden __getitem__ ..."
3414 # Strings
3415 vereq("hello"[:4], "hell")
3416 vereq("hello"[slice(4)], "hell")
3417 vereq(str.__getitem__("hello", slice(4)), "hell")
3418 class S(str):
3419 def __getitem__(self, x):
3420 return str.__getitem__(self, x)
3421 vereq(S("hello")[:4], "hell")
3422 vereq(S("hello")[slice(4)], "hell")
3423 vereq(S("hello").__getitem__(slice(4)), "hell")
3424 # Tuples
3425 vereq((1,2,3)[:2], (1,2))
3426 vereq((1,2,3)[slice(2)], (1,2))
3427 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3428 class T(tuple):
3429 def __getitem__(self, x):
3430 return tuple.__getitem__(self, x)
3431 vereq(T((1,2,3))[:2], (1,2))
3432 vereq(T((1,2,3))[slice(2)], (1,2))
3433 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3434 # Lists
3435 vereq([1,2,3][:2], [1,2])
3436 vereq([1,2,3][slice(2)], [1,2])
3437 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3438 class L(list):
3439 def __getitem__(self, x):
3440 return list.__getitem__(self, x)
3441 vereq(L([1,2,3])[:2], [1,2])
3442 vereq(L([1,2,3])[slice(2)], [1,2])
3443 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3444 # Now do lists and __setitem__
3445 a = L([1,2,3])
3446 a[slice(1, 3)] = [3,2]
3447 vereq(a, [1,3,2])
3448 a[slice(0, 2, 1)] = [3,1]
3449 vereq(a, [3,1,2])
3450 a.__setitem__(slice(1, 3), [2,1])
3451 vereq(a, [3,2,1])
3452 a.__setitem__(slice(0, 2, 1), [2,3])
3453 vereq(a, [2,3,1])
3454
Tim Peters2484aae2002-07-11 06:56:07 +00003455def subtype_resurrection():
3456 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003457 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003458
3459 class C(object):
3460 container = []
3461
3462 def __del__(self):
3463 # resurrect the instance
3464 C.container.append(self)
3465
3466 c = C()
3467 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003468 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003469 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003470 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003471
3472 # If that didn't blow up, it's also interesting to see whether clearing
3473 # the last container slot works: that will attempt to delete c again,
3474 # which will cause c to get appended back to the container again "during"
3475 # the del.
3476 del C.container[-1]
3477 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003478 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003479
Tim Peters14cb1e12002-07-11 18:26:21 +00003480 # Make c mortal again, so that the test framework with -l doesn't report
3481 # it as a leak.
3482 del C.__del__
3483
Guido van Rossum2d702462002-08-06 21:28:28 +00003484def slottrash():
3485 # Deallocating deeply nested slotted trash caused stack overflows
3486 if verbose:
3487 print "Testing slot trash..."
3488 class trash(object):
3489 __slots__ = ['x']
3490 def __init__(self, x):
3491 self.x = x
3492 o = None
3493 for i in xrange(50000):
3494 o = trash(o)
3495 del o
3496
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003497def slotmultipleinheritance():
3498 # SF bug 575229, multiple inheritance w/ slots dumps core
3499 class A(object):
3500 __slots__=()
3501 class B(object):
3502 pass
3503 class C(A,B) :
3504 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003505 vereq(C.__basicsize__, B.__basicsize__)
3506 verify(hasattr(C, '__dict__'))
3507 verify(hasattr(C, '__weakref__'))
3508 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003509
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003510def testrmul():
3511 # SF patch 592646
3512 if verbose:
3513 print "Testing correct invocation of __rmul__..."
3514 class C(object):
3515 def __mul__(self, other):
3516 return "mul"
3517 def __rmul__(self, other):
3518 return "rmul"
3519 a = C()
3520 vereq(a*2, "mul")
3521 vereq(a*2.2, "mul")
3522 vereq(2*a, "rmul")
3523 vereq(2.2*a, "rmul")
3524
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003525def testipow():
3526 # [SF bug 620179]
3527 if verbose:
3528 print "Testing correct invocation of __ipow__..."
3529 class C(object):
3530 def __ipow__(self, other):
3531 pass
3532 a = C()
3533 a **= 2
3534
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003535def do_this_first():
3536 if verbose:
3537 print "Testing SF bug 551412 ..."
3538 # This dumps core when SF bug 551412 isn't fixed --
3539 # but only when test_descr.py is run separately.
3540 # (That can't be helped -- as soon as PyType_Ready()
3541 # is called for PyLong_Type, the bug is gone.)
3542 class UserLong(object):
3543 def __pow__(self, *args):
3544 pass
3545 try:
3546 pow(0L, UserLong(), 0L)
3547 except:
3548 pass
3549
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003550 if verbose:
3551 print "Testing SF bug 570483..."
3552 # Another segfault only when run early
3553 # (before PyType_Ready(tuple) is called)
3554 type.mro(tuple)
3555
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003556def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003557 if verbose:
3558 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003559 # stuff that should work:
3560 class C(object):
3561 pass
3562 class C2(object):
3563 def __getattribute__(self, attr):
3564 if attr == 'a':
3565 return 2
3566 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003567 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003568 def meth(self):
3569 return 1
3570 class D(C):
3571 pass
3572 class E(D):
3573 pass
3574 d = D()
3575 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003576 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003577 D.__bases__ = (C2,)
3578 vereq(d.meth(), 1)
3579 vereq(e.meth(), 1)
3580 vereq(d.a, 2)
3581 vereq(e.a, 2)
3582 vereq(C2.__subclasses__(), [D])
3583
3584 # stuff that shouldn't:
3585 class L(list):
3586 pass
3587
3588 try:
3589 L.__bases__ = (dict,)
3590 except TypeError:
3591 pass
3592 else:
3593 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3594
3595 try:
3596 list.__bases__ = (dict,)
3597 except TypeError:
3598 pass
3599 else:
3600 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3601
3602 try:
3603 del D.__bases__
3604 except TypeError:
3605 pass
3606 else:
3607 raise TestFailed, "shouldn't be able to delete .__bases__"
3608
3609 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003610 D.__bases__ = ()
3611 except TypeError, msg:
3612 if str(msg) == "a new-style class can't have only classic bases":
3613 raise TestFailed, "wrong error message for .__bases__ = ()"
3614 else:
3615 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3616
3617 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003618 D.__bases__ = (D,)
3619 except TypeError:
3620 pass
3621 else:
3622 # actually, we'll have crashed by here...
3623 raise TestFailed, "shouldn't be able to create inheritance cycles"
3624
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003625 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003626 D.__bases__ = (C, C)
3627 except TypeError:
3628 pass
3629 else:
3630 raise TestFailed, "didn't detect repeated base classes"
3631
3632 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003633 D.__bases__ = (E,)
3634 except TypeError:
3635 pass
3636 else:
3637 raise TestFailed, "shouldn't be able to create inheritance cycles"
3638
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003639 # let's throw a classic class into the mix:
3640 class Classic:
3641 def meth2(self):
3642 return 3
3643
3644 D.__bases__ = (C, Classic)
3645
3646 vereq(d.meth2(), 3)
3647 vereq(e.meth2(), 3)
3648 try:
3649 d.a
3650 except AttributeError:
3651 pass
3652 else:
3653 raise TestFailed, "attribute should have vanished"
3654
3655 try:
3656 D.__bases__ = (Classic,)
3657 except TypeError:
3658 pass
3659 else:
3660 raise TestFailed, "new-style class must have a new-style base"
3661
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003662def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003663 if verbose:
3664 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003665 class WorkOnce(type):
3666 def __new__(self, name, bases, ns):
3667 self.flag = 0
3668 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3669 def mro(self):
3670 if self.flag > 0:
3671 raise RuntimeError, "bozo"
3672 else:
3673 self.flag += 1
3674 return type.mro(self)
3675
3676 class WorkAlways(type):
3677 def mro(self):
3678 # this is here to make sure that .mro()s aren't called
3679 # with an exception set (which was possible at one point).
3680 # An error message will be printed in a debug build.
3681 # What's a good way to test for this?
3682 return type.mro(self)
3683
3684 class C(object):
3685 pass
3686
3687 class C2(object):
3688 pass
3689
3690 class D(C):
3691 pass
3692
3693 class E(D):
3694 pass
3695
3696 class F(D):
3697 __metaclass__ = WorkOnce
3698
3699 class G(D):
3700 __metaclass__ = WorkAlways
3701
3702 # Immediate subclasses have their mro's adjusted in alphabetical
3703 # order, so E's will get adjusted before adjusting F's fails. We
3704 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003705
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003706 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003707 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003708
3709 try:
3710 D.__bases__ = (C2,)
3711 except RuntimeError:
3712 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003713 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003714 else:
3715 raise TestFailed, "exception not propagated"
3716
3717def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003718 if verbose:
3719 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003720 class A(object):
3721 pass
3722
3723 class B(object):
3724 pass
3725
3726 class C(A, B):
3727 pass
3728
3729 class D(A, B):
3730 pass
3731
3732 class E(C, D):
3733 pass
3734
3735 try:
3736 C.__bases__ = (B, A)
3737 except TypeError:
3738 pass
3739 else:
3740 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003741
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003742def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003743 if verbose:
3744 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003745 class C(object):
3746 pass
3747
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003748 # C.__module__ could be 'test_descr' or '__main__'
3749 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003750
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003751 C.__name__ = 'D'
3752 vereq((C.__module__, C.__name__), (mod, 'D'))
3753
3754 C.__name__ = 'D.E'
3755 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003756
Guido van Rossum613f24f2003-01-06 23:00:59 +00003757def subclass_right_op():
3758 if verbose:
3759 print "Testing correct dispatch of subclass overloading __r<op>__..."
3760
3761 # This code tests various cases where right-dispatch of a subclass
3762 # should be preferred over left-dispatch of a base class.
3763
3764 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3765
3766 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003767 def __floordiv__(self, other):
3768 return "B.__floordiv__"
3769 def __rfloordiv__(self, other):
3770 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003771
Guido van Rossumf389c772003-02-27 20:04:19 +00003772 vereq(B(1) // 1, "B.__floordiv__")
3773 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003774
3775 # Case 2: subclass of object; this is just the baseline for case 3
3776
3777 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003778 def __floordiv__(self, other):
3779 return "C.__floordiv__"
3780 def __rfloordiv__(self, other):
3781 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003782
Guido van Rossumf389c772003-02-27 20:04:19 +00003783 vereq(C() // 1, "C.__floordiv__")
3784 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003785
3786 # Case 3: subclass of new-style class; here it gets interesting
3787
3788 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003789 def __floordiv__(self, other):
3790 return "D.__floordiv__"
3791 def __rfloordiv__(self, other):
3792 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003793
Guido van Rossumf389c772003-02-27 20:04:19 +00003794 vereq(D() // C(), "D.__floordiv__")
3795 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003796
3797 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3798
3799 class E(C):
3800 pass
3801
Guido van Rossumf389c772003-02-27 20:04:19 +00003802 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003803
Guido van Rossumf389c772003-02-27 20:04:19 +00003804 vereq(E() // 1, "C.__floordiv__")
3805 vereq(1 // E(), "C.__rfloordiv__")
3806 vereq(E() // C(), "C.__floordiv__")
3807 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003808
Guido van Rossum373c7412003-01-07 13:41:37 +00003809def dict_type_with_metaclass():
3810 if verbose:
3811 print "Testing type of __dict__ when __metaclass__ set..."
3812
3813 class B(object):
3814 pass
3815 class M(type):
3816 pass
3817 class C:
3818 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3819 __metaclass__ = M
3820 veris(type(C.__dict__), type(B.__dict__))
3821
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003822def meth_class_get():
3823 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003824 if verbose:
3825 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003826 # Baseline
3827 arg = [1, 2, 3]
3828 res = {1: None, 2: None, 3: None}
3829 vereq(dict.fromkeys(arg), res)
3830 vereq({}.fromkeys(arg), res)
3831 # Now get the descriptor
3832 descr = dict.__dict__["fromkeys"]
3833 # More baseline using the descriptor directly
3834 vereq(descr.__get__(None, dict)(arg), res)
3835 vereq(descr.__get__({})(arg), res)
3836 # Now check various error cases
3837 try:
3838 descr.__get__(None, None)
3839 except TypeError:
3840 pass
3841 else:
3842 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3843 try:
3844 descr.__get__(42)
3845 except TypeError:
3846 pass
3847 else:
3848 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3849 try:
3850 descr.__get__(None, 42)
3851 except TypeError:
3852 pass
3853 else:
3854 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3855 try:
3856 descr.__get__(None, int)
3857 except TypeError:
3858 pass
3859 else:
3860 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3861
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003862def isinst_isclass():
3863 if verbose:
3864 print "Testing proxy isinstance() and isclass()..."
3865 class Proxy(object):
3866 def __init__(self, obj):
3867 self.__obj = obj
3868 def __getattribute__(self, name):
3869 if name.startswith("_Proxy__"):
3870 return object.__getattribute__(self, name)
3871 else:
3872 return getattr(self.__obj, name)
3873 # Test with a classic class
3874 class C:
3875 pass
3876 a = C()
3877 pa = Proxy(a)
3878 verify(isinstance(a, C)) # Baseline
3879 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003880 # Test with a classic subclass
3881 class D(C):
3882 pass
3883 a = D()
3884 pa = Proxy(a)
3885 verify(isinstance(a, C)) # Baseline
3886 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003887 # Test with a new-style class
3888 class C(object):
3889 pass
3890 a = C()
3891 pa = Proxy(a)
3892 verify(isinstance(a, C)) # Baseline
3893 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003894 # Test with a new-style subclass
3895 class D(C):
3896 pass
3897 a = D()
3898 pa = Proxy(a)
3899 verify(isinstance(a, C)) # Baseline
3900 verify(isinstance(pa, C)) # Test
3901
3902def proxysuper():
3903 if verbose:
3904 print "Testing super() for a proxy object..."
3905 class Proxy(object):
3906 def __init__(self, obj):
3907 self.__obj = obj
3908 def __getattribute__(self, name):
3909 if name.startswith("_Proxy__"):
3910 return object.__getattribute__(self, name)
3911 else:
3912 return getattr(self.__obj, name)
3913
3914 class B(object):
3915 def f(self):
3916 return "B.f"
3917
3918 class C(B):
3919 def f(self):
3920 return super(C, self).f() + "->C.f"
3921
3922 obj = C()
3923 p = Proxy(obj)
3924 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003925
Guido van Rossum52b27052003-04-15 20:05:10 +00003926def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003927 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00003928 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003929 try:
3930 object.__setattr__(str, "foo", 42)
3931 except TypeError:
3932 pass
3933 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003934 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003935 try:
3936 object.__delattr__(str, "lower")
3937 except TypeError:
3938 pass
3939 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003940 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003941
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003942def weakref_segfault():
3943 # SF 742911
3944 if verbose:
3945 print "Testing weakref segfault..."
3946
3947 import weakref
3948
3949 class Provoker:
3950 def __init__(self, referrent):
3951 self.ref = weakref.ref(referrent)
3952
3953 def __del__(self):
3954 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003955
3956 class Oops(object):
3957 pass
3958
3959 o = Oops()
3960 o.whatever = Provoker(o)
3961 del o
3962
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003963# Fix SF #762455, segfault when sys.stdout is changed in getattr
3964def filefault():
3965 if verbose:
3966 print "Testing sys.stdout is changed in getattr..."
3967 import sys
3968 class StdoutGuard:
3969 def __getattr__(self, attr):
3970 sys.stdout = sys.__stdout__
3971 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3972 sys.stdout = StdoutGuard()
3973 try:
3974 print "Oops!"
3975 except RuntimeError:
3976 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003977
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003978def vicious_descriptor_nonsense():
3979 # A potential segfault spotted by Thomas Wouters in mail to
3980 # python-dev 2003-04-17, turned into an example & fixed by Michael
3981 # Hudson just less than four months later...
3982 if verbose:
3983 print "Testing vicious_descriptor_nonsense..."
3984
3985 class Evil(object):
3986 def __hash__(self):
3987 return hash('attr')
3988 def __eq__(self, other):
3989 del C.attr
3990 return 0
3991
3992 class Descr(object):
3993 def __get__(self, ob, type=None):
3994 return 1
3995
3996 class C(object):
3997 attr = Descr()
3998
3999 c = C()
4000 c.__dict__[Evil()] = 0
4001
4002 vereq(c.attr, 1)
4003 # this makes a crash more likely:
4004 import gc; gc.collect()
4005 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004006
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004007def test_init():
4008 # SF 1155938
4009 class Foo(object):
4010 def __init__(self):
4011 return 10
4012 try:
4013 Foo()
4014 except TypeError:
4015 pass
4016 else:
4017 raise TestFailed, "did not test __init__() for None return"
4018
Armin Rigoc6686b72005-11-07 08:38:00 +00004019def methodwrapper():
4020 # <type 'method-wrapper'> did not support any reflection before 2.5
4021 if verbose:
4022 print "Testing method-wrapper objects..."
4023
4024 l = []
4025 vereq(l.__add__, l.__add__)
4026 verify(l.__add__ != [].__add__)
4027 verify(l.__add__.__name__ == '__add__')
4028 verify(l.__add__.__self__ is l)
4029 verify(l.__add__.__objclass__ is list)
4030 vereq(l.__add__.__doc__, list.__add__.__doc__)
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004031
Armin Rigofd163f92005-12-29 15:59:19 +00004032def notimplemented():
4033 # all binary methods should be able to return a NotImplemented
4034 if verbose:
4035 print "Testing NotImplemented..."
4036
4037 import sys
4038 import types
4039 import operator
4040
4041 def specialmethod(self, other):
4042 return NotImplemented
4043
4044 def check(expr, x, y):
4045 try:
4046 exec expr in {'x': x, 'y': y, 'operator': operator}
4047 except TypeError:
4048 pass
4049 else:
4050 raise TestFailed("no TypeError from %r" % (expr,))
4051
4052 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4053 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4054 # ValueErrors instead of TypeErrors
4055 for metaclass in [type, types.ClassType]:
4056 for name, expr, iexpr in [
4057 ('__add__', 'x + y', 'x += y'),
4058 ('__sub__', 'x - y', 'x -= y'),
4059 ('__mul__', 'x * y', 'x *= y'),
4060 ('__truediv__', 'operator.truediv(x, y)', None),
4061 ('__floordiv__', 'operator.floordiv(x, y)', None),
4062 ('__div__', 'x / y', 'x /= y'),
4063 ('__mod__', 'x % y', 'x %= y'),
4064 ('__divmod__', 'divmod(x, y)', None),
4065 ('__pow__', 'x ** y', 'x **= y'),
4066 ('__lshift__', 'x << y', 'x <<= y'),
4067 ('__rshift__', 'x >> y', 'x >>= y'),
4068 ('__and__', 'x & y', 'x &= y'),
4069 ('__or__', 'x | y', 'x |= y'),
4070 ('__xor__', 'x ^ y', 'x ^= y'),
4071 ('__coerce__', 'coerce(x, y)', None)]:
4072 if name == '__coerce__':
4073 rname = name
4074 else:
4075 rname = '__r' + name[2:]
4076 A = metaclass('A', (), {name: specialmethod})
4077 B = metaclass('B', (), {rname: specialmethod})
4078 a = A()
4079 b = B()
4080 check(expr, a, a)
4081 check(expr, a, b)
4082 check(expr, b, a)
4083 check(expr, b, b)
4084 check(expr, a, N1)
4085 check(expr, a, N2)
4086 check(expr, N1, b)
4087 check(expr, N2, b)
4088 if iexpr:
4089 check(iexpr, a, a)
4090 check(iexpr, a, b)
4091 check(iexpr, b, a)
4092 check(iexpr, b, b)
4093 check(iexpr, a, N1)
4094 check(iexpr, a, N2)
4095 iname = '__i' + name[2:]
4096 C = metaclass('C', (), {iname: specialmethod})
4097 c = C()
4098 check(iexpr, c, a)
4099 check(iexpr, c, b)
4100 check(iexpr, c, N1)
4101 check(iexpr, c, N2)
4102
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004103def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004104 weakref_segfault() # Must be first, somehow
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004105 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004106 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107 lists()
4108 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004109 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004110 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111 ints()
4112 longs()
4113 floats()
4114 complexes()
4115 spamlists()
4116 spamdicts()
4117 pydicts()
4118 pylists()
4119 metaclass()
4120 pymods()
4121 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004122 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004124 ex5()
4125 monotonicity()
4126 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004127 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004129 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130 dynamics()
4131 errors()
4132 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004133 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004135 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136 classic()
4137 compattr()
4138 newslot()
4139 altmro()
4140 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004141 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004142 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004143 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004144 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004145 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004146 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004147 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004148 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004149 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004150 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004151 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004152 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004153 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004154 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004155 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004156 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004157 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004158 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004159 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004160 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004161 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004162 kwdargs()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004163 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004164 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004165 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004166 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004167 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004168 dictproxyiterkeys()
4169 dictproxyitervalues()
4170 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004171 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004172 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004173 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004174 docdescriptor()
Tim Petersafb2c802002-04-18 18:06:20 +00004175 string_exceptions()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004176 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004177 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004178 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004179 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004180 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004181 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004182 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004183 test_mutable_bases()
4184 test_mutable_bases_with_failing_mro()
4185 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004186 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004187 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004188 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004189 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004190 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004191 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004192 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004193 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004194 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004195 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004196 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004197 notimplemented()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004198
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004199 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004201if __name__ == "__main__":
4202 test_main()