blob: 1c0b366cc3c91962689be68ff8149a12e66a5510 [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
Jeremy Hyltonfa955692007-02-27 18:29:45 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, run_doctest
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
Jeremy Hyltonfa955692007-02-27 18:29:45 +0000823 # Testing code to find most derived baseclass
824 class A(type):
825 def __new__(*args, **kwargs):
826 return type.__new__(*args, **kwargs)
827
828 class B(object):
829 pass
830
831 class C(object):
832 __metaclass__ = A
833
834 # The most derived metaclass of D is A rather than type.
835 class D(B, C):
836 pass
837
838
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839def pymods():
840 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000842 import sys
843 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000845 def __init__(self, name):
846 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000847 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000848 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000849 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 def __setattr__(self, name, value):
851 log.append(("setattr", name, value))
852 MT.__setattr__(self, name, value)
853 def __delattr__(self, name):
854 log.append(("delattr", name))
855 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000856 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 a.foo = 12
858 x = a.foo
859 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000860 vereq(log, [("setattr", "foo", 12),
861 ("getattr", "foo"),
862 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863
864def multi():
865 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 class C(object):
867 def __init__(self):
868 self.__state = 0
869 def getstate(self):
870 return self.__state
871 def setstate(self, state):
872 self.__state = state
873 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000874 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000876 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000877 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878 def __init__(self):
879 type({}).__init__(self)
880 C.__init__(self)
881 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000882 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000884 vereq(d.items(), [("hello", "world")])
885 vereq(d["hello"], "world")
886 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000888 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000889 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000890
Guido van Rossume45763a2001-08-10 21:28:46 +0000891 # SF bug #442833
892 class Node(object):
893 def __int__(self):
894 return int(self.foo())
895 def foo(self):
896 return "23"
897 class Frag(Node, list):
898 def foo(self):
899 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000900 vereq(Node().__int__(), 23)
901 vereq(int(Node()), 23)
902 vereq(Frag().__int__(), 42)
903 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000904
Tim Petersa91e9642001-11-14 23:32:33 +0000905 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000906
907 class A:
908 x = 1
909
910 class B(A):
911 pass
912
913 class C(A):
914 x = 2
915
916 class D(B, C):
917 pass
918 vereq(D.x, 1)
919
920 # Classic MRO is preserved for a classic base class.
921 class E(D, object):
922 pass
923 vereq(E.__mro__, (E, D, B, A, C, object))
924 vereq(E.x, 1)
925
926 # But with a mix of classic bases, their MROs are combined using
927 # new-style MRO.
928 class F(B, C, object):
929 pass
930 vereq(F.__mro__, (F, B, C, A, object))
931 vereq(F.x, 2)
932
933 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000934 class C:
935 def cmethod(self):
936 return "C a"
937 def all_method(self):
938 return "C b"
939
940 class M1(C, object):
941 def m1method(self):
942 return "M1 a"
943 def all_method(self):
944 return "M1 b"
945
946 vereq(M1.__mro__, (M1, C, object))
947 m = M1()
948 vereq(m.cmethod(), "C a")
949 vereq(m.m1method(), "M1 a")
950 vereq(m.all_method(), "M1 b")
951
952 class D(C):
953 def dmethod(self):
954 return "D a"
955 def all_method(self):
956 return "D b"
957
Guido van Rossum9a818922002-11-14 19:50:14 +0000958 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000959 def m2method(self):
960 return "M2 a"
961 def all_method(self):
962 return "M2 b"
963
Guido van Rossum9a818922002-11-14 19:50:14 +0000964 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000965 m = M2()
966 vereq(m.cmethod(), "C a")
967 vereq(m.dmethod(), "D a")
968 vereq(m.m2method(), "M2 a")
969 vereq(m.all_method(), "M2 b")
970
Guido van Rossum9a818922002-11-14 19:50:14 +0000971 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000972 def m3method(self):
973 return "M3 a"
974 def all_method(self):
975 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000976 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000977 m = M3()
978 vereq(m.cmethod(), "C a")
979 vereq(m.dmethod(), "D a")
980 vereq(m.m1method(), "M1 a")
981 vereq(m.m2method(), "M2 a")
982 vereq(m.m3method(), "M3 a")
983 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000984
Guido van Rossume54616c2001-12-14 04:19:56 +0000985 class Classic:
986 pass
987 try:
988 class New(Classic):
989 __metaclass__ = type
990 except TypeError:
991 pass
992 else:
993 raise TestFailed, "new class with only classic bases - shouldn't be"
994
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995def diamond():
996 if verbose: print "Testing multiple inheritance special cases..."
997 class A(object):
998 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000999 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 class B(A):
1001 def boo(self): return "B"
1002 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +00001003 vereq(B().spam(), "B")
1004 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 class C(A):
1006 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +00001007 vereq(C().spam(), "A")
1008 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001010 vereq(D().spam(), "B")
1011 vereq(D().boo(), "B")
1012 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001014 vereq(E().spam(), "B")
1015 vereq(E().boo(), "C")
1016 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +00001017 # MRO order disagreement
1018 try:
1019 class F(D, E): pass
1020 except TypeError:
1021 pass
1022 else:
1023 raise TestFailed, "expected MRO order disagreement (F)"
1024 try:
1025 class G(E, D): pass
1026 except TypeError:
1027 pass
1028 else:
1029 raise TestFailed, "expected MRO order disagreement (G)"
1030
1031
1032# see thread python-dev/2002-October/029035.html
1033def ex5():
1034 if verbose: print "Testing ex5 from C3 switch discussion..."
1035 class A(object): pass
1036 class B(object): pass
1037 class C(object): pass
1038 class X(A): pass
1039 class Y(A): pass
1040 class Z(X,B,Y,C): pass
1041 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1042
1043# see "A Monotonic Superclass Linearization for Dylan",
1044# by Kim Barrett et al. (OOPSLA 1996)
1045def monotonicity():
1046 if verbose: print "Testing MRO monotonicity..."
1047 class Boat(object): pass
1048 class DayBoat(Boat): pass
1049 class WheelBoat(Boat): pass
1050 class EngineLess(DayBoat): pass
1051 class SmallMultihull(DayBoat): pass
1052 class PedalWheelBoat(EngineLess,WheelBoat): pass
1053 class SmallCatamaran(SmallMultihull): pass
1054 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1055
1056 vereq(PedalWheelBoat.__mro__,
1057 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1058 object))
1059 vereq(SmallCatamaran.__mro__,
1060 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1061
1062 vereq(Pedalo.__mro__,
1063 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1064 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1065
1066# see "A Monotonic Superclass Linearization for Dylan",
1067# by Kim Barrett et al. (OOPSLA 1996)
1068def consistency_with_epg():
1069 if verbose: print "Testing consistentcy with EPG..."
1070 class Pane(object): pass
1071 class ScrollingMixin(object): pass
1072 class EditingMixin(object): pass
1073 class ScrollablePane(Pane,ScrollingMixin): pass
1074 class EditablePane(Pane,EditingMixin): pass
1075 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1076
1077 vereq(EditableScrollablePane.__mro__,
1078 (EditableScrollablePane, ScrollablePane, EditablePane,
1079 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
Raymond Hettingerf394df42003-04-06 19:13:41 +00001081mro_err_msg = """Cannot create a consistent method resolution
1082order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +00001083
Guido van Rossumd32047f2002-11-25 21:38:52 +00001084def mro_disagreement():
1085 if verbose: print "Testing error messages for MRO disagreement..."
1086 def raises(exc, expected, callable, *args):
1087 try:
1088 callable(*args)
1089 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001090 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001091 raise TestFailed, "Message %r, expected %r" % (str(msg),
1092 expected)
1093 else:
1094 raise TestFailed, "Expected %s" % exc
1095 class A(object): pass
1096 class B(A): pass
1097 class C(object): pass
1098 # Test some very simple errors
1099 raises(TypeError, "duplicate base class A",
1100 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001101 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001102 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001103 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001104 type, "X", (A, C, B), {})
1105 # Test a slightly more complex error
1106 class GridLayout(object): pass
1107 class HorizontalGrid(GridLayout): pass
1108 class VerticalGrid(GridLayout): pass
1109 class HVGrid(HorizontalGrid, VerticalGrid): pass
1110 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +00001111 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001112 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1113
Guido van Rossum37202612001-08-09 19:45:21 +00001114def objects():
1115 if verbose: print "Testing object class..."
1116 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001117 vereq(a.__class__, object)
1118 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001119 b = object()
1120 verify(a is not b)
1121 verify(not hasattr(a, "foo"))
1122 try:
1123 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001124 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001125 pass
1126 else:
1127 verify(0, "object() should not allow setting a foo attribute")
1128 verify(not hasattr(object(), "__dict__"))
1129
1130 class Cdict(object):
1131 pass
1132 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001133 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001134 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001135 vereq(x.foo, 1)
1136 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001137
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138def slots():
1139 if verbose: print "Testing __slots__..."
1140 class C0(object):
1141 __slots__ = []
1142 x = C0()
1143 verify(not hasattr(x, "__dict__"))
1144 verify(not hasattr(x, "foo"))
1145
1146 class C1(object):
1147 __slots__ = ['a']
1148 x = C1()
1149 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001150 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001152 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001153 x.a = None
1154 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001156 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157
1158 class C3(object):
1159 __slots__ = ['a', 'b', 'c']
1160 x = C3()
1161 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001162 verify(not hasattr(x, 'a'))
1163 verify(not hasattr(x, 'b'))
1164 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 x.a = 1
1166 x.b = 2
1167 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001168 vereq(x.a, 1)
1169 vereq(x.b, 2)
1170 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001172 class C4(object):
1173 """Validate name mangling"""
1174 __slots__ = ['__a']
1175 def __init__(self, value):
1176 self.__a = value
1177 def get(self):
1178 return self.__a
1179 x = C4(5)
1180 verify(not hasattr(x, '__dict__'))
1181 verify(not hasattr(x, '__a'))
1182 vereq(x.get(), 5)
1183 try:
1184 x.__a = 6
1185 except AttributeError:
1186 pass
1187 else:
1188 raise TestFailed, "Double underscored names not mangled"
1189
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001190 # Make sure slot names are proper identifiers
1191 try:
1192 class C(object):
1193 __slots__ = [None]
1194 except TypeError:
1195 pass
1196 else:
1197 raise TestFailed, "[None] slots not caught"
1198 try:
1199 class C(object):
1200 __slots__ = ["foo bar"]
1201 except TypeError:
1202 pass
1203 else:
1204 raise TestFailed, "['foo bar'] slots not caught"
1205 try:
1206 class C(object):
1207 __slots__ = ["foo\0bar"]
1208 except TypeError:
1209 pass
1210 else:
1211 raise TestFailed, "['foo\\0bar'] slots not caught"
1212 try:
1213 class C(object):
1214 __slots__ = ["1"]
1215 except TypeError:
1216 pass
1217 else:
1218 raise TestFailed, "['1'] slots not caught"
1219 try:
1220 class C(object):
1221 __slots__ = [""]
1222 except TypeError:
1223 pass
1224 else:
1225 raise TestFailed, "[''] slots not caught"
1226 class C(object):
1227 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1228
Guido van Rossum33bab012001-12-05 22:45:48 +00001229 # Test leaks
1230 class Counted(object):
1231 counter = 0 # counts the number of instances alive
1232 def __init__(self):
1233 Counted.counter += 1
1234 def __del__(self):
1235 Counted.counter -= 1
1236 class C(object):
1237 __slots__ = ['a', 'b', 'c']
1238 x = C()
1239 x.a = Counted()
1240 x.b = Counted()
1241 x.c = Counted()
1242 vereq(Counted.counter, 3)
1243 del x
1244 vereq(Counted.counter, 0)
1245 class D(C):
1246 pass
1247 x = D()
1248 x.a = Counted()
1249 x.z = Counted()
1250 vereq(Counted.counter, 2)
1251 del x
1252 vereq(Counted.counter, 0)
1253 class E(D):
1254 __slots__ = ['e']
1255 x = E()
1256 x.a = Counted()
1257 x.z = Counted()
1258 x.e = Counted()
1259 vereq(Counted.counter, 3)
1260 del x
1261 vereq(Counted.counter, 0)
1262
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001263 # Test cyclical leaks [SF bug 519621]
1264 class F(object):
1265 __slots__ = ['a', 'b']
1266 log = []
1267 s = F()
1268 s.a = [Counted(), s]
1269 vereq(Counted.counter, 1)
1270 s = None
1271 import gc
1272 gc.collect()
1273 vereq(Counted.counter, 0)
1274
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001275 # Test lookup leaks [SF bug 572567]
1276 import sys,gc
1277 class G(object):
1278 def __cmp__(self, other):
1279 return 0
1280 g = G()
1281 orig_objects = len(gc.get_objects())
1282 for i in xrange(10):
1283 g==g
1284 new_objects = len(gc.get_objects())
1285 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001286 class H(object):
1287 __slots__ = ['a', 'b']
1288 def __init__(self):
1289 self.a = 1
1290 self.b = 2
1291 def __del__(self):
1292 assert self.a == 1
1293 assert self.b == 2
1294
1295 save_stderr = sys.stderr
1296 sys.stderr = sys.stdout
1297 h = H()
1298 try:
1299 del h
1300 finally:
1301 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001302
Guido van Rossum8b056da2002-08-13 18:26:26 +00001303def slotspecials():
1304 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1305
1306 class D(object):
1307 __slots__ = ["__dict__"]
1308 a = D()
1309 verify(hasattr(a, "__dict__"))
1310 verify(not hasattr(a, "__weakref__"))
1311 a.foo = 42
1312 vereq(a.__dict__, {"foo": 42})
1313
1314 class W(object):
1315 __slots__ = ["__weakref__"]
1316 a = W()
1317 verify(hasattr(a, "__weakref__"))
1318 verify(not hasattr(a, "__dict__"))
1319 try:
1320 a.foo = 42
1321 except AttributeError:
1322 pass
1323 else:
1324 raise TestFailed, "shouldn't be allowed to set a.foo"
1325
1326 class C1(W, D):
1327 __slots__ = []
1328 a = C1()
1329 verify(hasattr(a, "__dict__"))
1330 verify(hasattr(a, "__weakref__"))
1331 a.foo = 42
1332 vereq(a.__dict__, {"foo": 42})
1333
1334 class C2(D, W):
1335 __slots__ = []
1336 a = C2()
1337 verify(hasattr(a, "__dict__"))
1338 verify(hasattr(a, "__weakref__"))
1339 a.foo = 42
1340 vereq(a.__dict__, {"foo": 42})
1341
Guido van Rossum9a818922002-11-14 19:50:14 +00001342# MRO order disagreement
1343#
1344# class C3(C1, C2):
1345# __slots__ = []
1346#
1347# class C4(C2, C1):
1348# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001349
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001351 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001354 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001356 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001359 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001361 vereq(E.foo, 1)
1362 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001363 # Test dynamic instances
1364 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001365 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001366 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001367 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001368 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001369 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001370 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001371 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001372 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001373 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001374 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001375 vereq(int(a), 100)
1376 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001377 verify(not hasattr(a, "spam"))
1378 def mygetattr(self, name):
1379 if name == "spam":
1380 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001381 raise AttributeError
1382 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001383 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001384 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001385 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001386 def mysetattr(self, name, value):
1387 if name == "spam":
1388 raise AttributeError
1389 return object.__setattr__(self, name, value)
1390 C.__setattr__ = mysetattr
1391 try:
1392 a.spam = "not spam"
1393 except AttributeError:
1394 pass
1395 else:
1396 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001397 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001398 class D(C):
1399 pass
1400 d = D()
1401 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001402 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403
Guido van Rossum7e35d572001-09-15 03:14:32 +00001404 # Test handling of int*seq and seq*int
1405 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001406 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001407 vereq("a"*I(2), "aa")
1408 vereq(I(2)*"a", "aa")
1409 vereq(2*I(3), 6)
1410 vereq(I(3)*2, 6)
1411 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001412
1413 # Test handling of long*seq and seq*long
1414 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001415 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001416 vereq("a"*L(2L), "aa")
1417 vereq(L(2L)*"a", "aa")
1418 vereq(2*L(3), 6)
1419 vereq(L(3)*2, 6)
1420 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001421
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001422 # Test comparison of classes with dynamic metaclasses
1423 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001424 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001425 class someclass:
1426 __metaclass__ = dynamicmetaclass
1427 verify(someclass != object)
1428
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429def errors():
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001430 """Test that type can't be placed after an instance of type in bases.
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001432 >>> class C(list, dict):
1433 ... pass
1434 Traceback (most recent call last):
1435 TypeError: Error when calling the metaclass bases
1436 multiple bases have instance lay-out conflict
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001438 >>> class C(object, None):
1439 ... pass
1440 Traceback (most recent call last):
1441 TypeError: Error when calling the metaclass bases
1442 bases must be types
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001444 >>> class C(type(len)):
1445 ... pass
1446 Traceback (most recent call last):
1447 TypeError: Error when calling the metaclass bases
1448 type 'builtin_function_or_method' is not an acceptable base type
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001450 >>> class Classic:
1451 ... def __init__(*args): pass
1452 >>> class C(object):
1453 ... __metaclass__ = Classic
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001455 >>> class C(object):
1456 ... __slots__ = 1
1457 Traceback (most recent call last):
1458 TypeError: Error when calling the metaclass bases
1459 'int' object is not iterable
1460
1461 >>> class C(object):
1462 ... __slots__ = [1]
1463 Traceback (most recent call last):
1464 TypeError: Error when calling the metaclass bases
1465 __slots__ items must be strings, not 'int'
1466
1467 >>> class A(object):
1468 ... pass
1469
1470 >>> class B(A, type):
1471 ... pass
1472 Traceback (most recent call last):
1473 TypeError: Error when calling the metaclass bases
1474 metaclass conflict: type must occur in bases before other non-classic base classes
1475
1476 Create two different metaclasses in order to setup an error where
1477 there is no inheritance relationship between the metaclass of a class
1478 and the metaclass of its bases.
1479
1480 >>> class M1(type):
1481 ... pass
1482 >>> class M2(type):
1483 ... pass
1484 >>> class A1(object):
1485 ... __metaclass__ = M1
1486 >>> class A2(object):
1487 ... __metaclass__ = M2
1488 >>> class B(A1, A2):
1489 ... pass
1490 Traceback (most recent call last):
1491 TypeError: Error when calling the metaclass bases
1492 metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1493 >>> class B(A1):
1494 ... pass
1495
1496 Also check that assignment to bases is safe.
1497
1498 >>> B.__bases__ = A1, A2
1499 Traceback (most recent call last):
1500 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1501 >>> B.__bases__ = A2,
1502 Traceback (most recent call last):
1503 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1504
1505 >>> class M3(M1):
1506 ... pass
1507 >>> class C(object):
1508 ... __metaclass__ = M3
1509 >>> B.__bases__ = C,
1510 Traceback (most recent call last):
1511 TypeError: assignment to __bases__ may not change metatype
1512 """
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513
1514def classmethods():
1515 if verbose: print "Testing class methods..."
1516 class C(object):
1517 def foo(*a): return a
1518 goo = classmethod(foo)
1519 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001520 vereq(C.goo(1), (C, 1))
1521 vereq(c.goo(1), (C, 1))
1522 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 class D(C):
1524 pass
1525 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001526 vereq(D.goo(1), (D, 1))
1527 vereq(d.goo(1), (D, 1))
1528 vereq(d.foo(1), (d, 1))
1529 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001530 # Test for a specific crash (SF bug 528132)
1531 def f(cls, arg): return (cls, arg)
1532 ff = classmethod(f)
1533 vereq(ff.__get__(0, int)(42), (int, 42))
1534 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535
Guido van Rossum155db9a2002-04-02 17:53:47 +00001536 # Test super() with classmethods (SF bug 535444)
1537 veris(C.goo.im_self, C)
1538 veris(D.goo.im_self, D)
1539 veris(super(D,D).goo.im_self, D)
1540 veris(super(D,d).goo.im_self, D)
1541 vereq(super(D,D).goo(), (D,))
1542 vereq(super(D,d).goo(), (D,))
1543
Raymond Hettingerbe971532003-06-18 01:13:41 +00001544 # Verify that argument is checked for callability (SF bug 753451)
1545 try:
1546 classmethod(1).__get__(1)
1547 except TypeError:
1548 pass
1549 else:
1550 raise TestFailed, "classmethod should check for callability"
1551
Georg Brandl6a29c322006-02-21 22:17:46 +00001552 # Verify that classmethod() doesn't allow keyword args
1553 try:
1554 classmethod(f, kw=1)
1555 except TypeError:
1556 pass
1557 else:
1558 raise TestFailed, "classmethod shouldn't accept keyword args"
1559
Fred Drakef841aa62002-03-28 15:49:54 +00001560def classmethods_in_c():
1561 if verbose: print "Testing C-based class methods..."
1562 import xxsubtype as spam
1563 a = (1, 2, 3)
1564 d = {'abc': 123}
1565 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001566 veris(x, spam.spamlist)
1567 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001568 vereq(d, d1)
1569 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001570 veris(x, spam.spamlist)
1571 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001572 vereq(d, d1)
1573
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574def staticmethods():
1575 if verbose: print "Testing static methods..."
1576 class C(object):
1577 def foo(*a): return a
1578 goo = staticmethod(foo)
1579 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001580 vereq(C.goo(1), (1,))
1581 vereq(c.goo(1), (1,))
1582 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 class D(C):
1584 pass
1585 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001586 vereq(D.goo(1), (1,))
1587 vereq(d.goo(1), (1,))
1588 vereq(d.foo(1), (d, 1))
1589 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590
Fred Drakef841aa62002-03-28 15:49:54 +00001591def staticmethods_in_c():
1592 if verbose: print "Testing C-based static methods..."
1593 import xxsubtype as spam
1594 a = (1, 2, 3)
1595 d = {"abc": 123}
1596 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1597 veris(x, None)
1598 vereq(a, a1)
1599 vereq(d, d1)
1600 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1601 veris(x, None)
1602 vereq(a, a1)
1603 vereq(d, d1)
1604
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605def classic():
1606 if verbose: print "Testing classic classes..."
1607 class C:
1608 def foo(*a): return a
1609 goo = classmethod(foo)
1610 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001611 vereq(C.goo(1), (C, 1))
1612 vereq(c.goo(1), (C, 1))
1613 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001614 class D(C):
1615 pass
1616 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001617 vereq(D.goo(1), (D, 1))
1618 vereq(d.goo(1), (D, 1))
1619 vereq(d.foo(1), (d, 1))
1620 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001621 class E: # *not* subclassing from C
1622 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001623 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001624 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625
1626def compattr():
1627 if verbose: print "Testing computed attributes..."
1628 class C(object):
1629 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001630 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 self.__get = get
1632 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001633 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634 def __get__(self, obj, type=None):
1635 return self.__get(obj)
1636 def __set__(self, obj, value):
1637 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001638 def __delete__(self, obj):
1639 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 def __init__(self):
1641 self.__x = 0
1642 def __get_x(self):
1643 x = self.__x
1644 self.__x = x+1
1645 return x
1646 def __set_x(self, x):
1647 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001648 def __delete_x(self):
1649 del self.__x
1650 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001652 vereq(a.x, 0)
1653 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001655 vereq(a.x, 10)
1656 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001657 del a.x
1658 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659
1660def newslot():
1661 if verbose: print "Testing __new__ slot override..."
1662 class C(list):
1663 def __new__(cls):
1664 self = list.__new__(cls)
1665 self.foo = 1
1666 return self
1667 def __init__(self):
1668 self.foo = self.foo + 2
1669 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001670 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 verify(a.__class__ is C)
1672 class D(C):
1673 pass
1674 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001675 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676 verify(b.__class__ is D)
1677
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678def altmro():
1679 if verbose: print "Testing mro() and overriding it..."
1680 class A(object):
1681 def f(self): return "A"
1682 class B(A):
1683 pass
1684 class C(A):
1685 def f(self): return "C"
1686 class D(B, C):
1687 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001688 vereq(D.mro(), [D, B, C, A, object])
1689 vereq(D.__mro__, (D, B, C, A, object))
1690 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001691
Guido van Rossumd3077402001-08-12 05:24:18 +00001692 class PerverseMetaType(type):
1693 def mro(cls):
1694 L = type.mro(cls)
1695 L.reverse()
1696 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001697 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001699 vereq(X.__mro__, (object, A, C, B, D, X))
1700 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701
Armin Rigo037d1e02005-12-29 17:07:39 +00001702 try:
1703 class X(object):
1704 class __metaclass__(type):
1705 def mro(self):
1706 return [self, dict, object]
1707 except TypeError:
1708 pass
1709 else:
1710 raise TestFailed, "devious mro() return not caught"
1711
1712 try:
1713 class X(object):
1714 class __metaclass__(type):
1715 def mro(self):
1716 return [1]
1717 except TypeError:
1718 pass
1719 else:
1720 raise TestFailed, "non-class mro() return not caught"
1721
1722 try:
1723 class X(object):
1724 class __metaclass__(type):
1725 def mro(self):
1726 return 1
1727 except TypeError:
1728 pass
1729 else:
1730 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001731
Armin Rigo037d1e02005-12-29 17:07:39 +00001732
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001734 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735
1736 class B(object):
1737 "Intermediate class because object doesn't have a __setattr__"
1738
1739 class C(B):
1740
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001741 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742 if name == "foo":
1743 return ("getattr", name)
1744 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001745 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746 def __setattr__(self, name, value):
1747 if name == "foo":
1748 self.setattr = (name, value)
1749 else:
1750 return B.__setattr__(self, name, value)
1751 def __delattr__(self, name):
1752 if name == "foo":
1753 self.delattr = name
1754 else:
1755 return B.__delattr__(self, name)
1756
1757 def __getitem__(self, key):
1758 return ("getitem", key)
1759 def __setitem__(self, key, value):
1760 self.setitem = (key, value)
1761 def __delitem__(self, key):
1762 self.delitem = key
1763
1764 def __getslice__(self, i, j):
1765 return ("getslice", i, j)
1766 def __setslice__(self, i, j, value):
1767 self.setslice = (i, j, value)
1768 def __delslice__(self, i, j):
1769 self.delslice = (i, j)
1770
1771 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001772 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001774 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001776 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
Guido van Rossum45704552001-10-08 16:35:45 +00001778 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001780 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001782 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783
Guido van Rossum45704552001-10-08 16:35:45 +00001784 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001786 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001788 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001790def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001791 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001792 class C(object):
1793 def __init__(self, x):
1794 self.x = x
1795 def foo(self):
1796 return self.x
1797 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001798 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001799 class D(C):
1800 boo = C.foo
1801 goo = c1.foo
1802 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001803 vereq(d2.foo(), 2)
1804 vereq(d2.boo(), 2)
1805 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001806 class E(object):
1807 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001808 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001809 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001810
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001811def specials():
1812 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001813 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001814 # Test the default behavior for static classes
1815 class C(object):
1816 def __getitem__(self, i):
1817 if 0 <= i < 10: return i
1818 raise IndexError
1819 c1 = C()
1820 c2 = C()
1821 verify(not not c1)
Tim Peters85b362f2006-04-11 01:21:00 +00001822 verify(id(c1) != id(c2))
1823 hash(c1)
1824 hash(c2)
Guido van Rossum45704552001-10-08 16:35:45 +00001825 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1826 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001827 verify(c1 != c2)
1828 verify(not c1 != c1)
1829 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001830 # Note that the module name appears in str/repr, and that varies
1831 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001832 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001833 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001834 verify(-1 not in c1)
1835 for i in range(10):
1836 verify(i in c1)
1837 verify(10 not in c1)
1838 # Test the default behavior for dynamic classes
1839 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001840 def __getitem__(self, i):
1841 if 0 <= i < 10: return i
1842 raise IndexError
1843 d1 = D()
1844 d2 = D()
1845 verify(not not d1)
Tim Peters85b362f2006-04-11 01:21:00 +00001846 verify(id(d1) != id(d2))
1847 hash(d1)
1848 hash(d2)
Guido van Rossum45704552001-10-08 16:35:45 +00001849 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1850 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001851 verify(d1 != d2)
1852 verify(not d1 != d1)
1853 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001854 # Note that the module name appears in str/repr, and that varies
1855 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001856 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001857 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001858 verify(-1 not in d1)
1859 for i in range(10):
1860 verify(i in d1)
1861 verify(10 not in d1)
1862 # Test overridden behavior for static classes
1863 class Proxy(object):
1864 def __init__(self, x):
1865 self.x = x
1866 def __nonzero__(self):
1867 return not not self.x
1868 def __hash__(self):
1869 return hash(self.x)
1870 def __eq__(self, other):
1871 return self.x == other
1872 def __ne__(self, other):
1873 return self.x != other
1874 def __cmp__(self, other):
1875 return cmp(self.x, other.x)
1876 def __str__(self):
1877 return "Proxy:%s" % self.x
1878 def __repr__(self):
1879 return "Proxy(%r)" % self.x
1880 def __contains__(self, value):
1881 return value in self.x
1882 p0 = Proxy(0)
1883 p1 = Proxy(1)
1884 p_1 = Proxy(-1)
1885 verify(not p0)
1886 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001887 vereq(hash(p0), hash(0))
1888 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001889 verify(p0 != p1)
1890 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001891 vereq(not p0, p1)
1892 vereq(cmp(p0, p1), -1)
1893 vereq(cmp(p0, p0), 0)
1894 vereq(cmp(p0, p_1), 1)
1895 vereq(str(p0), "Proxy:0")
1896 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001897 p10 = Proxy(range(10))
1898 verify(-1 not in p10)
1899 for i in range(10):
1900 verify(i in p10)
1901 verify(10 not in p10)
1902 # Test overridden behavior for dynamic classes
1903 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001904 def __init__(self, x):
1905 self.x = x
1906 def __nonzero__(self):
1907 return not not self.x
1908 def __hash__(self):
1909 return hash(self.x)
1910 def __eq__(self, other):
1911 return self.x == other
1912 def __ne__(self, other):
1913 return self.x != other
1914 def __cmp__(self, other):
1915 return cmp(self.x, other.x)
1916 def __str__(self):
1917 return "DProxy:%s" % self.x
1918 def __repr__(self):
1919 return "DProxy(%r)" % self.x
1920 def __contains__(self, value):
1921 return value in self.x
1922 p0 = DProxy(0)
1923 p1 = DProxy(1)
1924 p_1 = DProxy(-1)
1925 verify(not p0)
1926 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001927 vereq(hash(p0), hash(0))
1928 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001929 verify(p0 != p1)
1930 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001931 vereq(not p0, p1)
1932 vereq(cmp(p0, p1), -1)
1933 vereq(cmp(p0, p0), 0)
1934 vereq(cmp(p0, p_1), 1)
1935 vereq(str(p0), "DProxy:0")
1936 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001937 p10 = DProxy(range(10))
1938 verify(-1 not in p10)
1939 for i in range(10):
1940 verify(i in p10)
1941 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001942 # Safety test for __cmp__
1943 def unsafecmp(a, b):
1944 try:
1945 a.__class__.__cmp__(a, b)
1946 except TypeError:
1947 pass
1948 else:
1949 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1950 a.__class__, a, b)
1951 unsafecmp(u"123", "123")
1952 unsafecmp("123", u"123")
1953 unsafecmp(1, 1.0)
1954 unsafecmp(1.0, 1)
1955 unsafecmp(1, 1L)
1956 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001957
Neal Norwitz1a997502003-01-13 20:13:12 +00001958 class Letter(str):
1959 def __new__(cls, letter):
1960 if letter == 'EPS':
1961 return str.__new__(cls)
1962 return str.__new__(cls, letter)
1963 def __str__(self):
1964 if not self:
1965 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001966 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001967
1968 # sys.stdout needs to be the original to trigger the recursion bug
1969 import sys
1970 test_stdout = sys.stdout
1971 sys.stdout = get_original_stdout()
1972 try:
1973 # nothing should actually be printed, this should raise an exception
1974 print Letter('w')
1975 except RuntimeError:
1976 pass
1977 else:
1978 raise TestFailed, "expected a RuntimeError for print recursion"
1979 sys.stdout = test_stdout
1980
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001981def weakrefs():
1982 if verbose: print "Testing weak references..."
1983 import weakref
1984 class C(object):
1985 pass
1986 c = C()
1987 r = weakref.ref(c)
1988 verify(r() is c)
1989 del c
1990 verify(r() is None)
1991 del r
1992 class NoWeak(object):
1993 __slots__ = ['foo']
1994 no = NoWeak()
1995 try:
1996 weakref.ref(no)
1997 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001998 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001999 else:
2000 verify(0, "weakref.ref(no) should be illegal")
2001 class Weak(object):
2002 __slots__ = ['foo', '__weakref__']
2003 yes = Weak()
2004 r = weakref.ref(yes)
2005 verify(r() is yes)
2006 del yes
2007 verify(r() is None)
2008 del r
2009
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002010def properties():
2011 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002012 class C(object):
2013 def getx(self):
2014 return self.__x
2015 def setx(self, value):
2016 self.__x = value
2017 def delx(self):
2018 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00002019 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002020 a = C()
2021 verify(not hasattr(a, "x"))
2022 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00002023 vereq(a._C__x, 42)
2024 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002025 del a.x
2026 verify(not hasattr(a, "x"))
2027 verify(not hasattr(a, "_C__x"))
2028 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00002029 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002030 C.x.__delete__(a)
2031 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002032
Tim Peters66c1a522001-09-24 21:17:50 +00002033 raw = C.__dict__['x']
2034 verify(isinstance(raw, property))
2035
2036 attrs = dir(raw)
2037 verify("__doc__" in attrs)
2038 verify("fget" in attrs)
2039 verify("fset" in attrs)
2040 verify("fdel" in attrs)
2041
Guido van Rossum45704552001-10-08 16:35:45 +00002042 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00002043 verify(raw.fget is C.__dict__['getx'])
2044 verify(raw.fset is C.__dict__['setx'])
2045 verify(raw.fdel is C.__dict__['delx'])
2046
2047 for attr in "__doc__", "fget", "fset", "fdel":
2048 try:
2049 setattr(raw, attr, 42)
2050 except TypeError, msg:
2051 if str(msg).find('readonly') < 0:
2052 raise TestFailed("when setting readonly attr %r on a "
2053 "property, got unexpected TypeError "
2054 "msg %r" % (attr, str(msg)))
2055 else:
2056 raise TestFailed("expected TypeError from trying to set "
2057 "readonly %r attr on a property" % attr)
2058
Neal Norwitz673cd822002-10-18 16:33:13 +00002059 class D(object):
2060 __getitem__ = property(lambda s: 1/0)
2061
2062 d = D()
2063 try:
2064 for i in d:
2065 str(i)
2066 except ZeroDivisionError:
2067 pass
2068 else:
2069 raise TestFailed, "expected ZeroDivisionError from bad property"
2070
Georg Brandl533ff6f2006-03-08 18:09:27 +00002071 class E(object):
2072 def getter(self):
2073 "getter method"
2074 return 0
2075 def setter(self, value):
2076 "setter method"
2077 pass
2078 prop = property(getter)
2079 vereq(prop.__doc__, "getter method")
2080 prop2 = property(fset=setter)
2081 vereq(prop2.__doc__, None)
2082
Georg Brandle9462c72006-08-04 18:03:37 +00002083 # this segfaulted in 2.5b2
2084 try:
2085 import _testcapi
2086 except ImportError:
2087 pass
2088 else:
2089 class X(object):
2090 p = property(_testcapi.test_with_docstring)
2091
2092
Guido van Rossumc4a18802001-08-24 16:55:27 +00002093def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002094 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002095
2096 class A(object):
2097 def meth(self, a):
2098 return "A(%r)" % a
2099
Guido van Rossum45704552001-10-08 16:35:45 +00002100 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002101
2102 class B(A):
2103 def __init__(self):
2104 self.__super = super(B, self)
2105 def meth(self, a):
2106 return "B(%r)" % a + self.__super.meth(a)
2107
Guido van Rossum45704552001-10-08 16:35:45 +00002108 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002109
2110 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002111 def meth(self, a):
2112 return "C(%r)" % a + self.__super.meth(a)
2113 C._C__super = super(C)
2114
Guido van Rossum45704552001-10-08 16:35:45 +00002115 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002116
2117 class D(C, B):
2118 def meth(self, a):
2119 return "D(%r)" % a + super(D, self).meth(a)
2120
Guido van Rossum5b443c62001-12-03 15:38:28 +00002121 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2122
2123 # Test for subclassing super
2124
2125 class mysuper(super):
2126 def __init__(self, *args):
2127 return super(mysuper, self).__init__(*args)
2128
2129 class E(D):
2130 def meth(self, a):
2131 return "E(%r)" % a + mysuper(E, self).meth(a)
2132
2133 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2134
2135 class F(E):
2136 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002137 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002138 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2139 F._F__super = mysuper(F)
2140
2141 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2142
2143 # Make sure certain errors are raised
2144
2145 try:
2146 super(D, 42)
2147 except TypeError:
2148 pass
2149 else:
2150 raise TestFailed, "shouldn't allow super(D, 42)"
2151
2152 try:
2153 super(D, C())
2154 except TypeError:
2155 pass
2156 else:
2157 raise TestFailed, "shouldn't allow super(D, C())"
2158
2159 try:
2160 super(D).__get__(12)
2161 except TypeError:
2162 pass
2163 else:
2164 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2165
2166 try:
2167 super(D).__get__(C())
2168 except TypeError:
2169 pass
2170 else:
2171 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002172
Guido van Rossuma4541a32003-04-16 20:02:22 +00002173 # Make sure data descriptors can be overridden and accessed via super
2174 # (new feature in Python 2.3)
2175
2176 class DDbase(object):
2177 def getx(self): return 42
2178 x = property(getx)
2179
2180 class DDsub(DDbase):
2181 def getx(self): return "hello"
2182 x = property(getx)
2183
2184 dd = DDsub()
2185 vereq(dd.x, "hello")
2186 vereq(super(DDsub, dd).x, 42)
2187
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002188 # Ensure that super() lookup of descriptor from classmethod
2189 # works (SF ID# 743627)
2190
2191 class Base(object):
2192 aProp = property(lambda self: "foo")
2193
2194 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002195 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002196 def test(klass):
2197 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002198
2199 veris(Sub.test(), Base.aProp)
2200
Georg Brandl5d59c092006-09-30 08:43:30 +00002201 # Verify that super() doesn't allow keyword args
2202 try:
2203 super(Base, kw=1)
2204 except TypeError:
2205 pass
2206 else:
2207 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002208
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002209def inherits():
2210 if verbose: print "Testing inheritance from basic types..."
2211
2212 class hexint(int):
2213 def __repr__(self):
2214 return hex(self)
2215 def __add__(self, other):
2216 return hexint(int.__add__(self, other))
2217 # (Note that overriding __radd__ doesn't work,
2218 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002219 vereq(repr(hexint(7) + 9), "0x10")
2220 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002221 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002222 vereq(a, 12345)
2223 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002224 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002225 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002226 verify((+a).__class__ is int)
2227 verify((a >> 0).__class__ is int)
2228 verify((a << 0).__class__ is int)
2229 verify((hexint(0) << 12).__class__ is int)
2230 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002231
2232 class octlong(long):
2233 __slots__ = []
2234 def __str__(self):
2235 s = oct(self)
2236 if s[-1] == 'L':
2237 s = s[:-1]
2238 return s
2239 def __add__(self, other):
2240 return self.__class__(super(octlong, self).__add__(other))
2241 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002242 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002243 # (Note that overriding __radd__ here only seems to work
2244 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002245 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002246 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002247 vereq(a, 12345L)
2248 vereq(long(a), 12345L)
2249 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002250 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002251 verify((+a).__class__ is long)
2252 verify((-a).__class__ is long)
2253 verify((-octlong(0)).__class__ is long)
2254 verify((a >> 0).__class__ is long)
2255 verify((a << 0).__class__ is long)
2256 verify((a - 0).__class__ is long)
2257 verify((a * 1).__class__ is long)
2258 verify((a ** 1).__class__ is long)
2259 verify((a // 1).__class__ is long)
2260 verify((1 * a).__class__ is long)
2261 verify((a | 0).__class__ is long)
2262 verify((a ^ 0).__class__ is long)
2263 verify((a & -1L).__class__ is long)
2264 verify((octlong(0) << 12).__class__ is long)
2265 verify((octlong(0) >> 12).__class__ is long)
2266 verify(abs(octlong(0)).__class__ is long)
2267
2268 # Because octlong overrides __add__, we can't check the absence of +0
2269 # optimizations using octlong.
2270 class longclone(long):
2271 pass
2272 a = longclone(1)
2273 verify((a + 0).__class__ is long)
2274 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002275
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002276 # Check that negative clones don't segfault
2277 a = longclone(-1)
2278 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002279 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002280
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002281 class precfloat(float):
2282 __slots__ = ['prec']
2283 def __init__(self, value=0.0, prec=12):
2284 self.prec = int(prec)
Armin Rigob8d6d732007-02-12 16:23:24 +00002285 float.__init__(self, value)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002286 def __repr__(self):
2287 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002288 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002289 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002290 vereq(a, 12345.0)
2291 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002292 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002293 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002294 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002295
Tim Peters2400fa42001-09-12 19:12:49 +00002296 class madcomplex(complex):
2297 def __repr__(self):
2298 return "%.17gj%+.17g" % (self.imag, self.real)
2299 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002300 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002301 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002302 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002303 vereq(a, base)
2304 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002305 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002306 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(repr(a), "4j-3")
2308 vereq(a, base)
2309 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002310 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002312 veris((+a).__class__, complex)
2313 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002314 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002315 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002316 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002317 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002318 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002319 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002320 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002321
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002322 class madtuple(tuple):
2323 _rev = None
2324 def rev(self):
2325 if self._rev is not None:
2326 return self._rev
2327 L = list(self)
2328 L.reverse()
2329 self._rev = self.__class__(L)
2330 return self._rev
2331 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002332 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2333 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2334 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002335 for i in range(512):
2336 t = madtuple(range(i))
2337 u = t.rev()
2338 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002339 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002340 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002341 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002342 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002343 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002344 verify(a[:].__class__ is tuple)
2345 verify((a * 1).__class__ is tuple)
2346 verify((a * 0).__class__ is tuple)
2347 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002348 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002349 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002350 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002351 verify((a + a).__class__ is tuple)
2352 verify((a * 0).__class__ is tuple)
2353 verify((a * 1).__class__ is tuple)
2354 verify((a * 2).__class__ is tuple)
2355 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002356
2357 class madstring(str):
2358 _rev = None
2359 def rev(self):
2360 if self._rev is not None:
2361 return self._rev
2362 L = list(self)
2363 L.reverse()
2364 self._rev = self.__class__("".join(L))
2365 return self._rev
2366 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002367 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2368 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2369 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002370 for i in range(256):
2371 s = madstring("".join(map(chr, range(i))))
2372 t = s.rev()
2373 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002374 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002375 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002376 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002377 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002378
Tim Peters8fa5dd02001-09-12 02:18:30 +00002379 base = "\x00" * 5
2380 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002381 vereq(s, base)
2382 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002383 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002384 vereq(hash(s), hash(base))
2385 vereq({s: 1}[base], 1)
2386 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002387 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002388 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002389 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002390 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002391 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002392 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002393 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002394 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002395 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002396 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002397 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002398 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002399 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002400 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002401 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002402 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002403 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002404 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002405 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002406 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002407 identitytab = ''.join([chr(i) for i in range(256)])
2408 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002409 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002410 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002411 vereq(s.translate(identitytab, "x"), base)
2412 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002413 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002414 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002415 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002416 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002417 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002418 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002419 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002420 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002421 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002422 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002423
Guido van Rossum91ee7982001-08-30 20:52:40 +00002424 class madunicode(unicode):
2425 _rev = None
2426 def rev(self):
2427 if self._rev is not None:
2428 return self._rev
2429 L = list(self)
2430 L.reverse()
2431 self._rev = self.__class__(u"".join(L))
2432 return self._rev
2433 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002434 vereq(u, u"ABCDEF")
2435 vereq(u.rev(), madunicode(u"FEDCBA"))
2436 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002437 base = u"12345"
2438 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002439 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002440 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002441 vereq(hash(u), hash(base))
2442 vereq({u: 1}[base], 1)
2443 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002444 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002445 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002446 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002447 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002448 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002449 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002450 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002451 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002452 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002453 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002454 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002455 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002456 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002457 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002458 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002459 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002460 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002461 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002462 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002463 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002464 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002465 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002466 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002467 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002468 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002469 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002470 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002471 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002472 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002473 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002474 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002475 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002476 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002477 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002478 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002479 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002480 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002481 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002482
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002483 class sublist(list):
2484 pass
2485 a = sublist(range(5))
2486 vereq(a, range(5))
2487 a.append("hello")
2488 vereq(a, range(5) + ["hello"])
2489 a[5] = 5
2490 vereq(a, range(6))
2491 a.extend(range(6, 20))
2492 vereq(a, range(20))
2493 a[-5:] = []
2494 vereq(a, range(15))
2495 del a[10:15]
2496 vereq(len(a), 10)
2497 vereq(a, range(10))
2498 vereq(list(a), range(10))
2499 vereq(a[0], 0)
2500 vereq(a[9], 9)
2501 vereq(a[-10], 0)
2502 vereq(a[-1], 9)
2503 vereq(a[:5], range(5))
2504
Tim Peters59c9a642001-09-13 05:38:56 +00002505 class CountedInput(file):
2506 """Counts lines read by self.readline().
2507
2508 self.lineno is the 0-based ordinal of the last line read, up to
2509 a maximum of one greater than the number of lines in the file.
2510
2511 self.ateof is true if and only if the final "" line has been read,
2512 at which point self.lineno stops incrementing, and further calls
2513 to readline() continue to return "".
2514 """
2515
2516 lineno = 0
2517 ateof = 0
2518 def readline(self):
2519 if self.ateof:
2520 return ""
2521 s = file.readline(self)
2522 # Next line works too.
2523 # s = super(CountedInput, self).readline()
2524 self.lineno += 1
2525 if s == "":
2526 self.ateof = 1
2527 return s
2528
Tim Peters561f8992001-09-13 19:36:36 +00002529 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002530 lines = ['a\n', 'b\n', 'c\n']
2531 try:
2532 f.writelines(lines)
2533 f.close()
2534 f = CountedInput(TESTFN)
2535 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2536 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002537 vereq(expected, got)
2538 vereq(f.lineno, i)
2539 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002540 f.close()
2541 finally:
2542 try:
2543 f.close()
2544 except:
2545 pass
2546 try:
2547 import os
2548 os.unlink(TESTFN)
2549 except:
2550 pass
2551
Tim Peters808b94e2001-09-13 19:33:07 +00002552def keywords():
2553 if verbose:
2554 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002555 vereq(int(x=1), 1)
2556 vereq(float(x=2), 2.0)
2557 vereq(long(x=3), 3L)
2558 vereq(complex(imag=42, real=666), complex(666, 42))
2559 vereq(str(object=500), '500')
2560 vereq(unicode(string='abc', errors='strict'), u'abc')
2561 vereq(tuple(sequence=range(3)), (0, 1, 2))
2562 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002563 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002564
2565 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002566 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002567 try:
2568 constructor(bogus_keyword_arg=1)
2569 except TypeError:
2570 pass
2571 else:
2572 raise TestFailed("expected TypeError from bogus keyword "
2573 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002574
Tim Peters8fa45672001-09-13 21:01:29 +00002575def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002576 # XXX This test is disabled because rexec is not deemed safe
2577 return
Tim Peters8fa45672001-09-13 21:01:29 +00002578 import rexec
2579 if verbose:
2580 print "Testing interaction with restricted execution ..."
2581
2582 sandbox = rexec.RExec()
2583
2584 code1 = """f = open(%r, 'w')""" % TESTFN
2585 code2 = """f = file(%r, 'w')""" % TESTFN
2586 code3 = """\
2587f = open(%r)
2588t = type(f) # a sneaky way to get the file() constructor
2589f.close()
2590f = t(%r, 'w') # rexec can't catch this by itself
2591""" % (TESTFN, TESTFN)
2592
2593 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2594 f.close()
2595
2596 try:
2597 for code in code1, code2, code3:
2598 try:
2599 sandbox.r_exec(code)
2600 except IOError, msg:
2601 if str(msg).find("restricted") >= 0:
2602 outcome = "OK"
2603 else:
2604 outcome = "got an exception, but not an expected one"
2605 else:
2606 outcome = "expected a restricted-execution exception"
2607
2608 if outcome != "OK":
2609 raise TestFailed("%s, in %r" % (outcome, code))
2610
2611 finally:
2612 try:
2613 import os
2614 os.unlink(TESTFN)
2615 except:
2616 pass
2617
Tim Peters0ab085c2001-09-14 00:25:33 +00002618def str_subclass_as_dict_key():
2619 if verbose:
2620 print "Testing a str subclass used as dict key .."
2621
2622 class cistr(str):
2623 """Sublcass of str that computes __eq__ case-insensitively.
2624
2625 Also computes a hash code of the string in canonical form.
2626 """
2627
2628 def __init__(self, value):
2629 self.canonical = value.lower()
2630 self.hashcode = hash(self.canonical)
2631
2632 def __eq__(self, other):
2633 if not isinstance(other, cistr):
2634 other = cistr(other)
2635 return self.canonical == other.canonical
2636
2637 def __hash__(self):
2638 return self.hashcode
2639
Guido van Rossum45704552001-10-08 16:35:45 +00002640 vereq(cistr('ABC'), 'abc')
2641 vereq('aBc', cistr('ABC'))
2642 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002643
2644 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002645 vereq(d[cistr('one')], 1)
2646 vereq(d[cistr('tWo')], 2)
2647 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002648 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002649 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002650
Guido van Rossumab3b0342001-09-18 20:38:53 +00002651def classic_comparisons():
2652 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002653 class classic:
2654 pass
2655 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002656 if verbose: print " (base = %s)" % base
2657 class C(base):
2658 def __init__(self, value):
2659 self.value = int(value)
2660 def __cmp__(self, other):
2661 if isinstance(other, C):
2662 return cmp(self.value, other.value)
2663 if isinstance(other, int) or isinstance(other, long):
2664 return cmp(self.value, other)
2665 return NotImplemented
2666 c1 = C(1)
2667 c2 = C(2)
2668 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002669 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002670 c = {1: c1, 2: c2, 3: c3}
2671 for x in 1, 2, 3:
2672 for y in 1, 2, 3:
2673 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2674 for op in "<", "<=", "==", "!=", ">", ">=":
2675 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2676 "x=%d, y=%d" % (x, y))
2677 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2678 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2679
Guido van Rossum0639f592001-09-18 21:06:04 +00002680def rich_comparisons():
2681 if verbose:
2682 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002683 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002684 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002685 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002686 vereq(z, 1+0j)
2687 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002688 class ZZ(complex):
2689 def __eq__(self, other):
2690 try:
2691 return abs(self - other) <= 1e-6
2692 except:
2693 return NotImplemented
2694 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002695 vereq(zz, 1+0j)
2696 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002697
Guido van Rossum0639f592001-09-18 21:06:04 +00002698 class classic:
2699 pass
2700 for base in (classic, int, object, list):
2701 if verbose: print " (base = %s)" % base
2702 class C(base):
2703 def __init__(self, value):
2704 self.value = int(value)
2705 def __cmp__(self, other):
2706 raise TestFailed, "shouldn't call __cmp__"
2707 def __eq__(self, other):
2708 if isinstance(other, C):
2709 return self.value == other.value
2710 if isinstance(other, int) or isinstance(other, long):
2711 return self.value == other
2712 return NotImplemented
2713 def __ne__(self, other):
2714 if isinstance(other, C):
2715 return self.value != other.value
2716 if isinstance(other, int) or isinstance(other, long):
2717 return self.value != other
2718 return NotImplemented
2719 def __lt__(self, other):
2720 if isinstance(other, C):
2721 return self.value < other.value
2722 if isinstance(other, int) or isinstance(other, long):
2723 return self.value < other
2724 return NotImplemented
2725 def __le__(self, other):
2726 if isinstance(other, C):
2727 return self.value <= other.value
2728 if isinstance(other, int) or isinstance(other, long):
2729 return self.value <= other
2730 return NotImplemented
2731 def __gt__(self, other):
2732 if isinstance(other, C):
2733 return self.value > other.value
2734 if isinstance(other, int) or isinstance(other, long):
2735 return self.value > other
2736 return NotImplemented
2737 def __ge__(self, other):
2738 if isinstance(other, C):
2739 return self.value >= other.value
2740 if isinstance(other, int) or isinstance(other, long):
2741 return self.value >= other
2742 return NotImplemented
2743 c1 = C(1)
2744 c2 = C(2)
2745 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002746 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002747 c = {1: c1, 2: c2, 3: c3}
2748 for x in 1, 2, 3:
2749 for y in 1, 2, 3:
2750 for op in "<", "<=", "==", "!=", ">", ">=":
2751 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2752 "x=%d, y=%d" % (x, y))
2753 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2754 "x=%d, y=%d" % (x, y))
2755 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2756 "x=%d, y=%d" % (x, y))
2757
Guido van Rossum1952e382001-09-19 01:25:16 +00002758def coercions():
2759 if verbose: print "Testing coercions..."
2760 class I(int): pass
2761 coerce(I(0), 0)
2762 coerce(0, I(0))
2763 class L(long): pass
2764 coerce(L(0), 0)
2765 coerce(L(0), 0L)
2766 coerce(0, L(0))
2767 coerce(0L, L(0))
2768 class F(float): pass
2769 coerce(F(0), 0)
2770 coerce(F(0), 0L)
2771 coerce(F(0), 0.)
2772 coerce(0, F(0))
2773 coerce(0L, F(0))
2774 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002775 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002776 coerce(C(0), 0)
2777 coerce(C(0), 0L)
2778 coerce(C(0), 0.)
2779 coerce(C(0), 0j)
2780 coerce(0, C(0))
2781 coerce(0L, C(0))
2782 coerce(0., C(0))
2783 coerce(0j, C(0))
2784
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002785def descrdoc():
2786 if verbose: print "Testing descriptor doc strings..."
2787 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002788 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002789 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002790 check(file.name, "file name") # member descriptor
2791
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002792def setclass():
2793 if verbose: print "Testing __class__ assignment..."
2794 class C(object): pass
2795 class D(object): pass
2796 class E(object): pass
2797 class F(D, E): pass
2798 for cls in C, D, E, F:
2799 for cls2 in C, D, E, F:
2800 x = cls()
2801 x.__class__ = cls2
2802 verify(x.__class__ is cls2)
2803 x.__class__ = cls
2804 verify(x.__class__ is cls)
2805 def cant(x, C):
2806 try:
2807 x.__class__ = C
2808 except TypeError:
2809 pass
2810 else:
2811 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002812 try:
2813 delattr(x, "__class__")
2814 except TypeError:
2815 pass
2816 else:
2817 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002818 cant(C(), list)
2819 cant(list(), C)
2820 cant(C(), 1)
2821 cant(C(), object)
2822 cant(object(), list)
2823 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002824 class Int(int): __slots__ = []
2825 cant(2, Int)
2826 cant(Int(), int)
2827 cant(True, int)
2828 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002829 o = object()
2830 cant(o, type(1))
2831 cant(o, type(None))
2832 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002833
Guido van Rossum6661be32001-10-26 04:26:12 +00002834def setdict():
2835 if verbose: print "Testing __dict__ assignment..."
2836 class C(object): pass
2837 a = C()
2838 a.__dict__ = {'b': 1}
2839 vereq(a.b, 1)
2840 def cant(x, dict):
2841 try:
2842 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002843 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002844 pass
2845 else:
2846 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2847 cant(a, None)
2848 cant(a, [])
2849 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002850 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002851 # Classes don't allow __dict__ assignment
2852 cant(C, {})
2853
Guido van Rossum3926a632001-09-25 16:25:58 +00002854def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002855 if verbose:
2856 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002857 import pickle, cPickle
2858
2859 def sorteditems(d):
2860 L = d.items()
2861 L.sort()
2862 return L
2863
2864 global C
2865 class C(object):
2866 def __init__(self, a, b):
2867 super(C, self).__init__()
2868 self.a = a
2869 self.b = b
2870 def __repr__(self):
2871 return "C(%r, %r)" % (self.a, self.b)
2872
2873 global C1
2874 class C1(list):
2875 def __new__(cls, a, b):
2876 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002877 def __getnewargs__(self):
2878 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002879 def __init__(self, a, b):
2880 self.a = a
2881 self.b = b
2882 def __repr__(self):
2883 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2884
2885 global C2
2886 class C2(int):
2887 def __new__(cls, a, b, val=0):
2888 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002889 def __getnewargs__(self):
2890 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002891 def __init__(self, a, b, val=0):
2892 self.a = a
2893 self.b = b
2894 def __repr__(self):
2895 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2896
Guido van Rossum90c45142001-11-24 21:07:01 +00002897 global C3
2898 class C3(object):
2899 def __init__(self, foo):
2900 self.foo = foo
2901 def __getstate__(self):
2902 return self.foo
2903 def __setstate__(self, foo):
2904 self.foo = foo
2905
2906 global C4classic, C4
2907 class C4classic: # classic
2908 pass
2909 class C4(C4classic, object): # mixed inheritance
2910 pass
2911
Guido van Rossum3926a632001-09-25 16:25:58 +00002912 for p in pickle, cPickle:
2913 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002914 if verbose:
2915 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002916
2917 for cls in C, C1, C2:
2918 s = p.dumps(cls, bin)
2919 cls2 = p.loads(s)
2920 verify(cls2 is cls)
2921
2922 a = C1(1, 2); a.append(42); a.append(24)
2923 b = C2("hello", "world", 42)
2924 s = p.dumps((a, b), bin)
2925 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002926 vereq(x.__class__, a.__class__)
2927 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2928 vereq(y.__class__, b.__class__)
2929 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002930 vereq(repr(x), repr(a))
2931 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002932 if verbose:
2933 print "a = x =", a
2934 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002935 # Test for __getstate__ and __setstate__ on new style class
2936 u = C3(42)
2937 s = p.dumps(u, bin)
2938 v = p.loads(s)
2939 veris(u.__class__, v.__class__)
2940 vereq(u.foo, v.foo)
2941 # Test for picklability of hybrid class
2942 u = C4()
2943 u.foo = 42
2944 s = p.dumps(u, bin)
2945 v = p.loads(s)
2946 veris(u.__class__, v.__class__)
2947 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002948
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002949 # Testing copy.deepcopy()
2950 if verbose:
2951 print "deepcopy"
2952 import copy
2953 for cls in C, C1, C2:
2954 cls2 = copy.deepcopy(cls)
2955 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002956
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002957 a = C1(1, 2); a.append(42); a.append(24)
2958 b = C2("hello", "world", 42)
2959 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002960 vereq(x.__class__, a.__class__)
2961 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2962 vereq(y.__class__, b.__class__)
2963 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002964 vereq(repr(x), repr(a))
2965 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002966 if verbose:
2967 print "a = x =", a
2968 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002969
Guido van Rossum8c842552002-03-14 23:05:54 +00002970def pickleslots():
2971 if verbose: print "Testing pickling of classes with __slots__ ..."
2972 import pickle, cPickle
2973 # Pickling of classes with __slots__ but without __getstate__ should fail
2974 global B, C, D, E
2975 class B(object):
2976 pass
2977 for base in [object, B]:
2978 class C(base):
2979 __slots__ = ['a']
2980 class D(C):
2981 pass
2982 try:
2983 pickle.dumps(C())
2984 except TypeError:
2985 pass
2986 else:
2987 raise TestFailed, "should fail: pickle C instance - %s" % base
2988 try:
2989 cPickle.dumps(C())
2990 except TypeError:
2991 pass
2992 else:
2993 raise TestFailed, "should fail: cPickle C instance - %s" % base
2994 try:
2995 pickle.dumps(C())
2996 except TypeError:
2997 pass
2998 else:
2999 raise TestFailed, "should fail: pickle D instance - %s" % base
3000 try:
3001 cPickle.dumps(D())
3002 except TypeError:
3003 pass
3004 else:
3005 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003006 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00003007 class C(base):
3008 __slots__ = ['a']
3009 def __getstate__(self):
3010 try:
3011 d = self.__dict__.copy()
3012 except AttributeError:
3013 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003014 for cls in self.__class__.__mro__:
3015 for sn in cls.__dict__.get('__slots__', ()):
3016 try:
3017 d[sn] = getattr(self, sn)
3018 except AttributeError:
3019 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00003020 return d
3021 def __setstate__(self, d):
3022 for k, v in d.items():
3023 setattr(self, k, v)
3024 class D(C):
3025 pass
3026 # Now it should work
3027 x = C()
3028 y = pickle.loads(pickle.dumps(x))
3029 vereq(hasattr(y, 'a'), 0)
3030 y = cPickle.loads(cPickle.dumps(x))
3031 vereq(hasattr(y, 'a'), 0)
3032 x.a = 42
3033 y = pickle.loads(pickle.dumps(x))
3034 vereq(y.a, 42)
3035 y = cPickle.loads(cPickle.dumps(x))
3036 vereq(y.a, 42)
3037 x = D()
3038 x.a = 42
3039 x.b = 100
3040 y = pickle.loads(pickle.dumps(x))
3041 vereq(y.a + y.b, 142)
3042 y = cPickle.loads(cPickle.dumps(x))
3043 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003044 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003045 class E(C):
3046 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003047 x = E()
3048 x.a = 42
3049 x.b = "foo"
3050 y = pickle.loads(pickle.dumps(x))
3051 vereq(y.a, x.a)
3052 vereq(y.b, x.b)
3053 y = cPickle.loads(cPickle.dumps(x))
3054 vereq(y.a, x.a)
3055 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003056
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003057def copies():
3058 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
3059 import copy
3060 class C(object):
3061 pass
3062
3063 a = C()
3064 a.foo = 12
3065 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003066 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003067
3068 a.bar = [1,2,3]
3069 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003070 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003071 verify(c.bar is a.bar)
3072
3073 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003074 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003075 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003076 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003077
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003078def binopoverride():
3079 if verbose: print "Testing overrides of binary operations..."
3080 class I(int):
3081 def __repr__(self):
3082 return "I(%r)" % int(self)
3083 def __add__(self, other):
3084 return I(int(self) + int(other))
3085 __radd__ = __add__
3086 def __pow__(self, other, mod=None):
3087 if mod is None:
3088 return I(pow(int(self), int(other)))
3089 else:
3090 return I(pow(int(self), int(other), int(mod)))
3091 def __rpow__(self, other, mod=None):
3092 if mod is None:
3093 return I(pow(int(other), int(self), mod))
3094 else:
3095 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003096
Walter Dörwald70a6b492004-02-12 17:35:32 +00003097 vereq(repr(I(1) + I(2)), "I(3)")
3098 vereq(repr(I(1) + 2), "I(3)")
3099 vereq(repr(1 + I(2)), "I(3)")
3100 vereq(repr(I(2) ** I(3)), "I(8)")
3101 vereq(repr(2 ** I(3)), "I(8)")
3102 vereq(repr(I(2) ** 3), "I(8)")
3103 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003104 class S(str):
3105 def __eq__(self, other):
3106 return self.lower() == other.lower()
3107
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003108def subclasspropagation():
3109 if verbose: print "Testing propagation of slot functions to subclasses..."
3110 class A(object):
3111 pass
3112 class B(A):
3113 pass
3114 class C(A):
3115 pass
3116 class D(B, C):
3117 pass
3118 d = D()
Tim Peters171b8682006-04-11 01:59:34 +00003119 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003120 A.__hash__ = lambda self: 42
3121 vereq(hash(d), 42)
3122 C.__hash__ = lambda self: 314
3123 vereq(hash(d), 314)
3124 B.__hash__ = lambda self: 144
3125 vereq(hash(d), 144)
3126 D.__hash__ = lambda self: 100
3127 vereq(hash(d), 100)
3128 del D.__hash__
3129 vereq(hash(d), 144)
3130 del B.__hash__
3131 vereq(hash(d), 314)
3132 del C.__hash__
3133 vereq(hash(d), 42)
3134 del A.__hash__
Tim Peters171b8682006-04-11 01:59:34 +00003135 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003136 d.foo = 42
3137 d.bar = 42
3138 vereq(d.foo, 42)
3139 vereq(d.bar, 42)
3140 def __getattribute__(self, name):
3141 if name == "foo":
3142 return 24
3143 return object.__getattribute__(self, name)
3144 A.__getattribute__ = __getattribute__
3145 vereq(d.foo, 24)
3146 vereq(d.bar, 42)
3147 def __getattr__(self, name):
3148 if name in ("spam", "foo", "bar"):
3149 return "hello"
3150 raise AttributeError, name
3151 B.__getattr__ = __getattr__
3152 vereq(d.spam, "hello")
3153 vereq(d.foo, 24)
3154 vereq(d.bar, 42)
3155 del A.__getattribute__
3156 vereq(d.foo, 42)
3157 del d.foo
3158 vereq(d.foo, "hello")
3159 vereq(d.bar, 42)
3160 del B.__getattr__
3161 try:
3162 d.foo
3163 except AttributeError:
3164 pass
3165 else:
3166 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003167
Guido van Rossume7f3e242002-06-14 02:35:45 +00003168 # Test a nasty bug in recurse_down_subclasses()
3169 import gc
3170 class A(object):
3171 pass
3172 class B(A):
3173 pass
3174 del B
3175 gc.collect()
3176 A.__setitem__ = lambda *a: None # crash
3177
Tim Petersfc57ccb2001-10-12 02:38:24 +00003178def buffer_inherit():
3179 import binascii
3180 # SF bug [#470040] ParseTuple t# vs subclasses.
3181 if verbose:
3182 print "Testing that buffer interface is inherited ..."
3183
3184 class MyStr(str):
3185 pass
3186 base = 'abc'
3187 m = MyStr(base)
3188 # b2a_hex uses the buffer interface to get its argument's value, via
3189 # PyArg_ParseTuple 't#' code.
3190 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3191
3192 # It's not clear that unicode will continue to support the character
3193 # buffer interface, and this test will fail if that's taken away.
3194 class MyUni(unicode):
3195 pass
3196 base = u'abc'
3197 m = MyUni(base)
3198 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3199
3200 class MyInt(int):
3201 pass
3202 m = MyInt(42)
3203 try:
3204 binascii.b2a_hex(m)
3205 raise TestFailed('subclass of int should not have a buffer interface')
3206 except TypeError:
3207 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003208
Tim Petersc9933152001-10-16 20:18:24 +00003209def str_of_str_subclass():
3210 import binascii
3211 import cStringIO
3212
3213 if verbose:
3214 print "Testing __str__ defined in subclass of str ..."
3215
3216 class octetstring(str):
3217 def __str__(self):
3218 return binascii.b2a_hex(self)
3219 def __repr__(self):
3220 return self + " repr"
3221
3222 o = octetstring('A')
3223 vereq(type(o), octetstring)
3224 vereq(type(str(o)), str)
3225 vereq(type(repr(o)), str)
3226 vereq(ord(o), 0x41)
3227 vereq(str(o), '41')
3228 vereq(repr(o), 'A repr')
3229 vereq(o.__str__(), '41')
3230 vereq(o.__repr__(), 'A repr')
3231
3232 capture = cStringIO.StringIO()
3233 # Calling str() or not exercises different internal paths.
3234 print >> capture, o
3235 print >> capture, str(o)
3236 vereq(capture.getvalue(), '41\n41\n')
3237 capture.close()
3238
Guido van Rossumc8e56452001-10-22 00:43:43 +00003239def kwdargs():
3240 if verbose: print "Testing keyword arguments to __init__, __call__..."
3241 def f(a): return a
3242 vereq(f.__call__(a=42), 42)
3243 a = []
3244 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003245 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003246
Brett Cannon22565aa2006-06-09 22:31:23 +00003247def recursive__call__():
3248 if verbose: print ("Testing recursive __call__() by setting to instance of "
3249 "class ...")
3250 class A(object):
3251 pass
3252
3253 A.__call__ = A()
3254 try:
3255 A()()
3256 except RuntimeError:
3257 pass
3258 else:
3259 raise TestFailed("Recursion limit should have been reached for "
3260 "__call__()")
3261
Guido van Rossumed87ad82001-10-30 02:33:02 +00003262def delhook():
3263 if verbose: print "Testing __del__ hook..."
3264 log = []
3265 class C(object):
3266 def __del__(self):
3267 log.append(1)
3268 c = C()
3269 vereq(log, [])
3270 del c
3271 vereq(log, [1])
3272
Guido van Rossum29d26062001-12-11 04:37:34 +00003273 class D(object): pass
3274 d = D()
3275 try: del d[0]
3276 except TypeError: pass
3277 else: raise TestFailed, "invalid del() didn't raise TypeError"
3278
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003279def hashinherit():
3280 if verbose: print "Testing hash of mutable subclasses..."
3281
3282 class mydict(dict):
3283 pass
3284 d = mydict()
3285 try:
3286 hash(d)
3287 except TypeError:
3288 pass
3289 else:
3290 raise TestFailed, "hash() of dict subclass should fail"
3291
3292 class mylist(list):
3293 pass
3294 d = mylist()
3295 try:
3296 hash(d)
3297 except TypeError:
3298 pass
3299 else:
3300 raise TestFailed, "hash() of list subclass should fail"
3301
Guido van Rossum29d26062001-12-11 04:37:34 +00003302def strops():
3303 try: 'a' + 5
3304 except TypeError: pass
3305 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3306
3307 try: ''.split('')
3308 except ValueError: pass
3309 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3310
3311 try: ''.join([0])
3312 except TypeError: pass
3313 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3314
3315 try: ''.rindex('5')
3316 except ValueError: pass
3317 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3318
Guido van Rossum29d26062001-12-11 04:37:34 +00003319 try: '%(n)s' % None
3320 except TypeError: pass
3321 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3322
3323 try: '%(n' % {}
3324 except ValueError: pass
3325 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3326
3327 try: '%*s' % ('abc')
3328 except TypeError: pass
3329 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3330
3331 try: '%*.*s' % ('abc', 5)
3332 except TypeError: pass
3333 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3334
3335 try: '%s' % (1, 2)
3336 except TypeError: pass
3337 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3338
3339 try: '%' % None
3340 except ValueError: pass
3341 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3342
3343 vereq('534253'.isdigit(), 1)
3344 vereq('534253x'.isdigit(), 0)
3345 vereq('%c' % 5, '\x05')
3346 vereq('%c' % '5', '5')
3347
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003348def deepcopyrecursive():
3349 if verbose: print "Testing deepcopy of recursive objects..."
3350 class Node:
3351 pass
3352 a = Node()
3353 b = Node()
3354 a.b = b
3355 b.a = a
3356 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003357
Guido van Rossumd7035672002-03-12 20:43:31 +00003358def modules():
3359 if verbose: print "Testing uninitialized module objects..."
3360 from types import ModuleType as M
3361 m = M.__new__(M)
3362 str(m)
3363 vereq(hasattr(m, "__name__"), 0)
3364 vereq(hasattr(m, "__file__"), 0)
3365 vereq(hasattr(m, "foo"), 0)
3366 vereq(m.__dict__, None)
3367 m.foo = 1
3368 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003369
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003370def dictproxyiterkeys():
3371 class C(object):
3372 def meth(self):
3373 pass
3374 if verbose: print "Testing dict-proxy iterkeys..."
3375 keys = [ key for key in C.__dict__.iterkeys() ]
3376 keys.sort()
3377 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3378
3379def dictproxyitervalues():
3380 class C(object):
3381 def meth(self):
3382 pass
3383 if verbose: print "Testing dict-proxy itervalues..."
3384 values = [ values for values in C.__dict__.itervalues() ]
3385 vereq(len(values), 5)
3386
3387def dictproxyiteritems():
3388 class C(object):
3389 def meth(self):
3390 pass
3391 if verbose: print "Testing dict-proxy iteritems..."
3392 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3393 keys.sort()
3394 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3395
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003396def funnynew():
3397 if verbose: print "Testing __new__ returning something unexpected..."
3398 class C(object):
3399 def __new__(cls, arg):
3400 if isinstance(arg, str): return [1, 2, 3]
3401 elif isinstance(arg, int): return object.__new__(D)
3402 else: return object.__new__(cls)
3403 class D(C):
3404 def __init__(self, arg):
3405 self.foo = arg
3406 vereq(C("1"), [1, 2, 3])
3407 vereq(D("1"), [1, 2, 3])
3408 d = D(None)
3409 veris(d.foo, None)
3410 d = C(1)
3411 vereq(isinstance(d, D), True)
3412 vereq(d.foo, 1)
3413 d = D(1)
3414 vereq(isinstance(d, D), True)
3415 vereq(d.foo, 1)
3416
Guido van Rossume8fc6402002-04-16 16:44:51 +00003417def imulbug():
3418 # SF bug 544647
3419 if verbose: print "Testing for __imul__ problems..."
3420 class C(object):
3421 def __imul__(self, other):
3422 return (self, other)
3423 x = C()
3424 y = x
3425 y *= 1.0
3426 vereq(y, (x, 1.0))
3427 y = x
3428 y *= 2
3429 vereq(y, (x, 2))
3430 y = x
3431 y *= 3L
3432 vereq(y, (x, 3L))
3433 y = x
3434 y *= 1L<<100
3435 vereq(y, (x, 1L<<100))
3436 y = x
3437 y *= None
3438 vereq(y, (x, None))
3439 y = x
3440 y *= "foo"
3441 vereq(y, (x, "foo"))
3442
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003443def docdescriptor():
3444 # SF bug 542984
3445 if verbose: print "Testing __doc__ descriptor..."
3446 class DocDescr(object):
3447 def __get__(self, object, otype):
3448 if object:
3449 object = object.__class__.__name__ + ' instance'
3450 if otype:
3451 otype = otype.__name__
3452 return 'object=%s; type=%s' % (object, otype)
3453 class OldClass:
3454 __doc__ = DocDescr()
3455 class NewClass(object):
3456 __doc__ = DocDescr()
3457 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3458 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3459 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3460 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3461
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003462def copy_setstate():
3463 if verbose:
3464 print "Testing that copy.*copy() correctly uses __setstate__..."
3465 import copy
3466 class C(object):
3467 def __init__(self, foo=None):
3468 self.foo = foo
3469 self.__foo = foo
3470 def setfoo(self, foo=None):
3471 self.foo = foo
3472 def getfoo(self):
3473 return self.__foo
3474 def __getstate__(self):
3475 return [self.foo]
3476 def __setstate__(self, lst):
3477 assert len(lst) == 1
3478 self.__foo = self.foo = lst[0]
3479 a = C(42)
3480 a.setfoo(24)
3481 vereq(a.foo, 24)
3482 vereq(a.getfoo(), 42)
3483 b = copy.copy(a)
3484 vereq(b.foo, 24)
3485 vereq(b.getfoo(), 24)
3486 b = copy.deepcopy(a)
3487 vereq(b.foo, 24)
3488 vereq(b.getfoo(), 24)
3489
Guido van Rossum09638c12002-06-13 19:17:46 +00003490def slices():
3491 if verbose:
3492 print "Testing cases with slices and overridden __getitem__ ..."
3493 # Strings
3494 vereq("hello"[:4], "hell")
3495 vereq("hello"[slice(4)], "hell")
3496 vereq(str.__getitem__("hello", slice(4)), "hell")
3497 class S(str):
3498 def __getitem__(self, x):
3499 return str.__getitem__(self, x)
3500 vereq(S("hello")[:4], "hell")
3501 vereq(S("hello")[slice(4)], "hell")
3502 vereq(S("hello").__getitem__(slice(4)), "hell")
3503 # Tuples
3504 vereq((1,2,3)[:2], (1,2))
3505 vereq((1,2,3)[slice(2)], (1,2))
3506 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3507 class T(tuple):
3508 def __getitem__(self, x):
3509 return tuple.__getitem__(self, x)
3510 vereq(T((1,2,3))[:2], (1,2))
3511 vereq(T((1,2,3))[slice(2)], (1,2))
3512 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3513 # Lists
3514 vereq([1,2,3][:2], [1,2])
3515 vereq([1,2,3][slice(2)], [1,2])
3516 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3517 class L(list):
3518 def __getitem__(self, x):
3519 return list.__getitem__(self, x)
3520 vereq(L([1,2,3])[:2], [1,2])
3521 vereq(L([1,2,3])[slice(2)], [1,2])
3522 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3523 # Now do lists and __setitem__
3524 a = L([1,2,3])
3525 a[slice(1, 3)] = [3,2]
3526 vereq(a, [1,3,2])
3527 a[slice(0, 2, 1)] = [3,1]
3528 vereq(a, [3,1,2])
3529 a.__setitem__(slice(1, 3), [2,1])
3530 vereq(a, [3,2,1])
3531 a.__setitem__(slice(0, 2, 1), [2,3])
3532 vereq(a, [2,3,1])
3533
Tim Peters2484aae2002-07-11 06:56:07 +00003534def subtype_resurrection():
3535 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003536 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003537
3538 class C(object):
3539 container = []
3540
3541 def __del__(self):
3542 # resurrect the instance
3543 C.container.append(self)
3544
3545 c = C()
3546 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003547 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003548 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003549 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003550
3551 # If that didn't blow up, it's also interesting to see whether clearing
3552 # the last container slot works: that will attempt to delete c again,
3553 # which will cause c to get appended back to the container again "during"
3554 # the del.
3555 del C.container[-1]
3556 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003557 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003558
Tim Peters14cb1e12002-07-11 18:26:21 +00003559 # Make c mortal again, so that the test framework with -l doesn't report
3560 # it as a leak.
3561 del C.__del__
3562
Guido van Rossum2d702462002-08-06 21:28:28 +00003563def slottrash():
3564 # Deallocating deeply nested slotted trash caused stack overflows
3565 if verbose:
3566 print "Testing slot trash..."
3567 class trash(object):
3568 __slots__ = ['x']
3569 def __init__(self, x):
3570 self.x = x
3571 o = None
3572 for i in xrange(50000):
3573 o = trash(o)
3574 del o
3575
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003576def slotmultipleinheritance():
3577 # SF bug 575229, multiple inheritance w/ slots dumps core
3578 class A(object):
3579 __slots__=()
3580 class B(object):
3581 pass
3582 class C(A,B) :
3583 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003584 vereq(C.__basicsize__, B.__basicsize__)
3585 verify(hasattr(C, '__dict__'))
3586 verify(hasattr(C, '__weakref__'))
3587 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003588
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003589def testrmul():
3590 # SF patch 592646
3591 if verbose:
3592 print "Testing correct invocation of __rmul__..."
3593 class C(object):
3594 def __mul__(self, other):
3595 return "mul"
3596 def __rmul__(self, other):
3597 return "rmul"
3598 a = C()
3599 vereq(a*2, "mul")
3600 vereq(a*2.2, "mul")
3601 vereq(2*a, "rmul")
3602 vereq(2.2*a, "rmul")
3603
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003604def testipow():
3605 # [SF bug 620179]
3606 if verbose:
3607 print "Testing correct invocation of __ipow__..."
3608 class C(object):
3609 def __ipow__(self, other):
3610 pass
3611 a = C()
3612 a **= 2
3613
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003614def do_this_first():
3615 if verbose:
3616 print "Testing SF bug 551412 ..."
3617 # This dumps core when SF bug 551412 isn't fixed --
3618 # but only when test_descr.py is run separately.
3619 # (That can't be helped -- as soon as PyType_Ready()
3620 # is called for PyLong_Type, the bug is gone.)
3621 class UserLong(object):
3622 def __pow__(self, *args):
3623 pass
3624 try:
3625 pow(0L, UserLong(), 0L)
3626 except:
3627 pass
3628
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003629 if verbose:
3630 print "Testing SF bug 570483..."
3631 # Another segfault only when run early
3632 # (before PyType_Ready(tuple) is called)
3633 type.mro(tuple)
3634
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003635def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003636 if verbose:
3637 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003638 # stuff that should work:
3639 class C(object):
3640 pass
3641 class C2(object):
3642 def __getattribute__(self, attr):
3643 if attr == 'a':
3644 return 2
3645 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003646 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003647 def meth(self):
3648 return 1
3649 class D(C):
3650 pass
3651 class E(D):
3652 pass
3653 d = D()
3654 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003655 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003656 D.__bases__ = (C2,)
3657 vereq(d.meth(), 1)
3658 vereq(e.meth(), 1)
3659 vereq(d.a, 2)
3660 vereq(e.a, 2)
3661 vereq(C2.__subclasses__(), [D])
3662
3663 # stuff that shouldn't:
3664 class L(list):
3665 pass
3666
3667 try:
3668 L.__bases__ = (dict,)
3669 except TypeError:
3670 pass
3671 else:
3672 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3673
3674 try:
3675 list.__bases__ = (dict,)
3676 except TypeError:
3677 pass
3678 else:
3679 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3680
3681 try:
Michael W. Hudsonf3904422006-11-23 13:54:04 +00003682 D.__bases__ = (C2, list)
3683 except TypeError:
3684 pass
3685 else:
3686 assert 0, "best_base calculation found wanting"
3687
3688 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003689 del D.__bases__
3690 except TypeError:
3691 pass
3692 else:
3693 raise TestFailed, "shouldn't be able to delete .__bases__"
3694
3695 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003696 D.__bases__ = ()
3697 except TypeError, msg:
3698 if str(msg) == "a new-style class can't have only classic bases":
3699 raise TestFailed, "wrong error message for .__bases__ = ()"
3700 else:
3701 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3702
3703 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003704 D.__bases__ = (D,)
3705 except TypeError:
3706 pass
3707 else:
3708 # actually, we'll have crashed by here...
3709 raise TestFailed, "shouldn't be able to create inheritance cycles"
3710
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003711 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003712 D.__bases__ = (C, C)
3713 except TypeError:
3714 pass
3715 else:
3716 raise TestFailed, "didn't detect repeated base classes"
3717
3718 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003719 D.__bases__ = (E,)
3720 except TypeError:
3721 pass
3722 else:
3723 raise TestFailed, "shouldn't be able to create inheritance cycles"
3724
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003725 # let's throw a classic class into the mix:
3726 class Classic:
3727 def meth2(self):
3728 return 3
3729
3730 D.__bases__ = (C, Classic)
3731
3732 vereq(d.meth2(), 3)
3733 vereq(e.meth2(), 3)
3734 try:
3735 d.a
3736 except AttributeError:
3737 pass
3738 else:
3739 raise TestFailed, "attribute should have vanished"
3740
3741 try:
3742 D.__bases__ = (Classic,)
3743 except TypeError:
3744 pass
3745 else:
3746 raise TestFailed, "new-style class must have a new-style base"
3747
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003748def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003749 if verbose:
3750 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003751 class WorkOnce(type):
3752 def __new__(self, name, bases, ns):
3753 self.flag = 0
3754 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3755 def mro(self):
3756 if self.flag > 0:
3757 raise RuntimeError, "bozo"
3758 else:
3759 self.flag += 1
3760 return type.mro(self)
3761
3762 class WorkAlways(type):
3763 def mro(self):
3764 # this is here to make sure that .mro()s aren't called
3765 # with an exception set (which was possible at one point).
3766 # An error message will be printed in a debug build.
3767 # What's a good way to test for this?
3768 return type.mro(self)
3769
3770 class C(object):
3771 pass
3772
3773 class C2(object):
3774 pass
3775
3776 class D(C):
3777 pass
3778
3779 class E(D):
3780 pass
3781
3782 class F(D):
3783 __metaclass__ = WorkOnce
3784
3785 class G(D):
3786 __metaclass__ = WorkAlways
3787
3788 # Immediate subclasses have their mro's adjusted in alphabetical
3789 # order, so E's will get adjusted before adjusting F's fails. We
3790 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003791
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003792 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003793 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003794
3795 try:
3796 D.__bases__ = (C2,)
3797 except RuntimeError:
3798 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003799 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003800 else:
3801 raise TestFailed, "exception not propagated"
3802
3803def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003804 if verbose:
3805 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003806 class A(object):
3807 pass
3808
3809 class B(object):
3810 pass
3811
3812 class C(A, B):
3813 pass
3814
3815 class D(A, B):
3816 pass
3817
3818 class E(C, D):
3819 pass
3820
3821 try:
3822 C.__bases__ = (B, A)
3823 except TypeError:
3824 pass
3825 else:
3826 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003827
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003828def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003829 if verbose:
3830 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003831 class C(object):
3832 pass
3833
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003834 # C.__module__ could be 'test_descr' or '__main__'
3835 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003836
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003837 C.__name__ = 'D'
3838 vereq((C.__module__, C.__name__), (mod, 'D'))
3839
3840 C.__name__ = 'D.E'
3841 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003842
Guido van Rossum613f24f2003-01-06 23:00:59 +00003843def subclass_right_op():
3844 if verbose:
3845 print "Testing correct dispatch of subclass overloading __r<op>__..."
3846
3847 # This code tests various cases where right-dispatch of a subclass
3848 # should be preferred over left-dispatch of a base class.
3849
3850 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3851
3852 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003853 def __floordiv__(self, other):
3854 return "B.__floordiv__"
3855 def __rfloordiv__(self, other):
3856 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003857
Guido van Rossumf389c772003-02-27 20:04:19 +00003858 vereq(B(1) // 1, "B.__floordiv__")
3859 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003860
3861 # Case 2: subclass of object; this is just the baseline for case 3
3862
3863 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003864 def __floordiv__(self, other):
3865 return "C.__floordiv__"
3866 def __rfloordiv__(self, other):
3867 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003868
Guido van Rossumf389c772003-02-27 20:04:19 +00003869 vereq(C() // 1, "C.__floordiv__")
3870 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003871
3872 # Case 3: subclass of new-style class; here it gets interesting
3873
3874 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003875 def __floordiv__(self, other):
3876 return "D.__floordiv__"
3877 def __rfloordiv__(self, other):
3878 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003879
Guido van Rossumf389c772003-02-27 20:04:19 +00003880 vereq(D() // C(), "D.__floordiv__")
3881 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003882
3883 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3884
3885 class E(C):
3886 pass
3887
Guido van Rossumf389c772003-02-27 20:04:19 +00003888 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003889
Guido van Rossumf389c772003-02-27 20:04:19 +00003890 vereq(E() // 1, "C.__floordiv__")
3891 vereq(1 // E(), "C.__rfloordiv__")
3892 vereq(E() // C(), "C.__floordiv__")
3893 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003894
Guido van Rossum373c7412003-01-07 13:41:37 +00003895def dict_type_with_metaclass():
3896 if verbose:
3897 print "Testing type of __dict__ when __metaclass__ set..."
3898
3899 class B(object):
3900 pass
3901 class M(type):
3902 pass
3903 class C:
3904 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3905 __metaclass__ = M
3906 veris(type(C.__dict__), type(B.__dict__))
3907
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003908def meth_class_get():
3909 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003910 if verbose:
3911 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003912 # Baseline
3913 arg = [1, 2, 3]
3914 res = {1: None, 2: None, 3: None}
3915 vereq(dict.fromkeys(arg), res)
3916 vereq({}.fromkeys(arg), res)
3917 # Now get the descriptor
3918 descr = dict.__dict__["fromkeys"]
3919 # More baseline using the descriptor directly
3920 vereq(descr.__get__(None, dict)(arg), res)
3921 vereq(descr.__get__({})(arg), res)
3922 # Now check various error cases
3923 try:
3924 descr.__get__(None, None)
3925 except TypeError:
3926 pass
3927 else:
3928 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3929 try:
3930 descr.__get__(42)
3931 except TypeError:
3932 pass
3933 else:
3934 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3935 try:
3936 descr.__get__(None, 42)
3937 except TypeError:
3938 pass
3939 else:
3940 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3941 try:
3942 descr.__get__(None, int)
3943 except TypeError:
3944 pass
3945 else:
3946 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3947
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003948def isinst_isclass():
3949 if verbose:
3950 print "Testing proxy isinstance() and isclass()..."
3951 class Proxy(object):
3952 def __init__(self, obj):
3953 self.__obj = obj
3954 def __getattribute__(self, name):
3955 if name.startswith("_Proxy__"):
3956 return object.__getattribute__(self, name)
3957 else:
3958 return getattr(self.__obj, name)
3959 # Test with a classic class
3960 class C:
3961 pass
3962 a = C()
3963 pa = Proxy(a)
3964 verify(isinstance(a, C)) # Baseline
3965 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003966 # Test with a classic subclass
3967 class D(C):
3968 pass
3969 a = D()
3970 pa = Proxy(a)
3971 verify(isinstance(a, C)) # Baseline
3972 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003973 # Test with a new-style class
3974 class C(object):
3975 pass
3976 a = C()
3977 pa = Proxy(a)
3978 verify(isinstance(a, C)) # Baseline
3979 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003980 # Test with a new-style subclass
3981 class D(C):
3982 pass
3983 a = D()
3984 pa = Proxy(a)
3985 verify(isinstance(a, C)) # Baseline
3986 verify(isinstance(pa, C)) # Test
3987
3988def proxysuper():
3989 if verbose:
3990 print "Testing super() for a proxy object..."
3991 class Proxy(object):
3992 def __init__(self, obj):
3993 self.__obj = obj
3994 def __getattribute__(self, name):
3995 if name.startswith("_Proxy__"):
3996 return object.__getattribute__(self, name)
3997 else:
3998 return getattr(self.__obj, name)
3999
4000 class B(object):
4001 def f(self):
4002 return "B.f"
4003
4004 class C(B):
4005 def f(self):
4006 return super(C, self).f() + "->C.f"
4007
4008 obj = C()
4009 p = Proxy(obj)
4010 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004011
Guido van Rossum52b27052003-04-15 20:05:10 +00004012def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004013 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00004014 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004015 try:
4016 object.__setattr__(str, "foo", 42)
4017 except TypeError:
4018 pass
4019 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004020 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004021 try:
4022 object.__delattr__(str, "lower")
4023 except TypeError:
4024 pass
4025 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004026 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004027
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004028def weakref_segfault():
4029 # SF 742911
4030 if verbose:
4031 print "Testing weakref segfault..."
4032
4033 import weakref
4034
4035 class Provoker:
4036 def __init__(self, referrent):
4037 self.ref = weakref.ref(referrent)
4038
4039 def __del__(self):
4040 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004041
4042 class Oops(object):
4043 pass
4044
4045 o = Oops()
4046 o.whatever = Provoker(o)
4047 del o
4048
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004049def wrapper_segfault():
4050 # SF 927248: deeply nested wrappers could cause stack overflow
4051 f = lambda:None
4052 for i in xrange(1000000):
4053 f = f.__call__
4054 f = None
4055
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004056# Fix SF #762455, segfault when sys.stdout is changed in getattr
4057def filefault():
4058 if verbose:
4059 print "Testing sys.stdout is changed in getattr..."
4060 import sys
4061 class StdoutGuard:
4062 def __getattr__(self, attr):
4063 sys.stdout = sys.__stdout__
4064 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4065 sys.stdout = StdoutGuard()
4066 try:
4067 print "Oops!"
4068 except RuntimeError:
4069 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004070
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004071def vicious_descriptor_nonsense():
4072 # A potential segfault spotted by Thomas Wouters in mail to
4073 # python-dev 2003-04-17, turned into an example & fixed by Michael
4074 # Hudson just less than four months later...
4075 if verbose:
4076 print "Testing vicious_descriptor_nonsense..."
4077
4078 class Evil(object):
4079 def __hash__(self):
4080 return hash('attr')
4081 def __eq__(self, other):
4082 del C.attr
4083 return 0
4084
4085 class Descr(object):
4086 def __get__(self, ob, type=None):
4087 return 1
4088
4089 class C(object):
4090 attr = Descr()
4091
4092 c = C()
4093 c.__dict__[Evil()] = 0
4094
4095 vereq(c.attr, 1)
4096 # this makes a crash more likely:
4097 import gc; gc.collect()
4098 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004099
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004100def test_init():
4101 # SF 1155938
4102 class Foo(object):
4103 def __init__(self):
4104 return 10
4105 try:
4106 Foo()
4107 except TypeError:
4108 pass
4109 else:
4110 raise TestFailed, "did not test __init__() for None return"
4111
Armin Rigoc6686b72005-11-07 08:38:00 +00004112def methodwrapper():
4113 # <type 'method-wrapper'> did not support any reflection before 2.5
4114 if verbose:
4115 print "Testing method-wrapper objects..."
4116
4117 l = []
4118 vereq(l.__add__, l.__add__)
Armin Rigofd01d792006-06-08 10:56:24 +00004119 vereq(l.__add__, [].__add__)
4120 verify(l.__add__ != [5].__add__)
4121 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004122 verify(l.__add__.__name__ == '__add__')
4123 verify(l.__add__.__self__ is l)
4124 verify(l.__add__.__objclass__ is list)
4125 vereq(l.__add__.__doc__, list.__add__.__doc__)
Armin Rigofd01d792006-06-08 10:56:24 +00004126 try:
4127 hash(l.__add__)
4128 except TypeError:
4129 pass
4130 else:
4131 raise TestFailed("no TypeError from hash([].__add__)")
4132
4133 t = ()
4134 t += (7,)
4135 vereq(t.__add__, (7,).__add__)
4136 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004137
Armin Rigofd163f92005-12-29 15:59:19 +00004138def notimplemented():
4139 # all binary methods should be able to return a NotImplemented
4140 if verbose:
4141 print "Testing NotImplemented..."
4142
4143 import sys
4144 import types
4145 import operator
4146
4147 def specialmethod(self, other):
4148 return NotImplemented
4149
4150 def check(expr, x, y):
4151 try:
4152 exec expr in {'x': x, 'y': y, 'operator': operator}
4153 except TypeError:
4154 pass
4155 else:
4156 raise TestFailed("no TypeError from %r" % (expr,))
4157
4158 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4159 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4160 # ValueErrors instead of TypeErrors
4161 for metaclass in [type, types.ClassType]:
4162 for name, expr, iexpr in [
4163 ('__add__', 'x + y', 'x += y'),
4164 ('__sub__', 'x - y', 'x -= y'),
4165 ('__mul__', 'x * y', 'x *= y'),
4166 ('__truediv__', 'operator.truediv(x, y)', None),
4167 ('__floordiv__', 'operator.floordiv(x, y)', None),
4168 ('__div__', 'x / y', 'x /= y'),
4169 ('__mod__', 'x % y', 'x %= y'),
4170 ('__divmod__', 'divmod(x, y)', None),
4171 ('__pow__', 'x ** y', 'x **= y'),
4172 ('__lshift__', 'x << y', 'x <<= y'),
4173 ('__rshift__', 'x >> y', 'x >>= y'),
4174 ('__and__', 'x & y', 'x &= y'),
4175 ('__or__', 'x | y', 'x |= y'),
4176 ('__xor__', 'x ^ y', 'x ^= y'),
4177 ('__coerce__', 'coerce(x, y)', None)]:
4178 if name == '__coerce__':
4179 rname = name
4180 else:
4181 rname = '__r' + name[2:]
4182 A = metaclass('A', (), {name: specialmethod})
4183 B = metaclass('B', (), {rname: specialmethod})
4184 a = A()
4185 b = B()
4186 check(expr, a, a)
4187 check(expr, a, b)
4188 check(expr, b, a)
4189 check(expr, b, b)
4190 check(expr, a, N1)
4191 check(expr, a, N2)
4192 check(expr, N1, b)
4193 check(expr, N2, b)
4194 if iexpr:
4195 check(iexpr, a, a)
4196 check(iexpr, a, b)
4197 check(iexpr, b, a)
4198 check(iexpr, b, b)
4199 check(iexpr, a, N1)
4200 check(iexpr, a, N2)
4201 iname = '__i' + name[2:]
4202 C = metaclass('C', (), {iname: specialmethod})
4203 c = C()
4204 check(iexpr, c, a)
4205 check(iexpr, c, b)
4206 check(iexpr, c, N1)
4207 check(iexpr, c, N2)
4208
Georg Brandl0fca97a2007-03-05 22:28:08 +00004209def test_assign_slice():
4210 # ceval.c's assign_slice used to check for
4211 # tp->tp_as_sequence->sq_slice instead of
4212 # tp->tp_as_sequence->sq_ass_slice
4213
4214 class C(object):
4215 def __setslice__(self, start, stop, value):
4216 self.value = value
4217
4218 c = C()
4219 c[1:2] = 3
4220 vereq(c.value, 3)
4221
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004222def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004223 weakref_segfault() # Must be first, somehow
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004224 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004225 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004226 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227 lists()
4228 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004229 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004230 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231 ints()
4232 longs()
4233 floats()
4234 complexes()
4235 spamlists()
4236 spamdicts()
4237 pydicts()
4238 pylists()
4239 metaclass()
4240 pymods()
4241 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004242 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004244 ex5()
4245 monotonicity()
4246 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004247 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004249 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250 dynamics()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004252 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004254 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004255 classic()
4256 compattr()
4257 newslot()
4258 altmro()
4259 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004260 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004261 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004262 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004263 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004264 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004265 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004266 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004267 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004268 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004269 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004270 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004271 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004272 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004273 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004274 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004275 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004276 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004277 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004278 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004279 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004280 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004281 kwdargs()
Brett Cannon22565aa2006-06-09 22:31:23 +00004282 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004283 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004284 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004285 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004286 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004287 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004288 dictproxyiterkeys()
4289 dictproxyitervalues()
4290 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004291 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004292 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004293 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004294 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004295 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004296 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004297 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004298 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004299 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004300 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004301 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004302 test_mutable_bases()
4303 test_mutable_bases_with_failing_mro()
4304 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004305 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004306 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004307 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004308 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004309 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004310 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004311 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004312 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004313 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004314 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004315 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004316 notimplemented()
Georg Brandl0fca97a2007-03-05 22:28:08 +00004317 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004318
Jeremy Hyltonfa955692007-02-27 18:29:45 +00004319 from test import test_descr
4320 run_doctest(test_descr, verbosity=True)
4321
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004322 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004323
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004324if __name__ == "__main__":
4325 test_main()