blob: 71f4ec43cd5ba8c834a5dfeecffaba49c21aea2e [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
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001229 # Test unicode slot names
1230 try:
1231 unichr
1232 except NameError:
1233 pass
1234 else:
1235 # _unicode_to_string used to modify slots in certain circumstances
1236 slots = (unicode("foo"), unicode("bar"))
1237 class C(object):
1238 __slots__ = slots
1239 x = C()
1240 x.foo = 5
1241 vereq(x.foo, 5)
1242 veris(type(slots[0]), unicode)
1243 # this used to leak references
1244 try:
1245 class C(object):
1246 __slots__ = [unichr(128)]
1247 except (TypeError, UnicodeEncodeError):
1248 pass
1249 else:
1250 raise TestFailed, "[unichr(128)] slots not caught"
1251
Guido van Rossum33bab012001-12-05 22:45:48 +00001252 # Test leaks
1253 class Counted(object):
1254 counter = 0 # counts the number of instances alive
1255 def __init__(self):
1256 Counted.counter += 1
1257 def __del__(self):
1258 Counted.counter -= 1
1259 class C(object):
1260 __slots__ = ['a', 'b', 'c']
1261 x = C()
1262 x.a = Counted()
1263 x.b = Counted()
1264 x.c = Counted()
1265 vereq(Counted.counter, 3)
1266 del x
1267 vereq(Counted.counter, 0)
1268 class D(C):
1269 pass
1270 x = D()
1271 x.a = Counted()
1272 x.z = Counted()
1273 vereq(Counted.counter, 2)
1274 del x
1275 vereq(Counted.counter, 0)
1276 class E(D):
1277 __slots__ = ['e']
1278 x = E()
1279 x.a = Counted()
1280 x.z = Counted()
1281 x.e = Counted()
1282 vereq(Counted.counter, 3)
1283 del x
1284 vereq(Counted.counter, 0)
1285
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001286 # Test cyclical leaks [SF bug 519621]
1287 class F(object):
1288 __slots__ = ['a', 'b']
1289 log = []
1290 s = F()
1291 s.a = [Counted(), s]
1292 vereq(Counted.counter, 1)
1293 s = None
1294 import gc
1295 gc.collect()
1296 vereq(Counted.counter, 0)
1297
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001298 # Test lookup leaks [SF bug 572567]
1299 import sys,gc
1300 class G(object):
1301 def __cmp__(self, other):
1302 return 0
1303 g = G()
1304 orig_objects = len(gc.get_objects())
1305 for i in xrange(10):
1306 g==g
1307 new_objects = len(gc.get_objects())
1308 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001309 class H(object):
1310 __slots__ = ['a', 'b']
1311 def __init__(self):
1312 self.a = 1
1313 self.b = 2
1314 def __del__(self):
1315 assert self.a == 1
1316 assert self.b == 2
1317
1318 save_stderr = sys.stderr
1319 sys.stderr = sys.stdout
1320 h = H()
1321 try:
1322 del h
1323 finally:
1324 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001325
Guido van Rossum8b056da2002-08-13 18:26:26 +00001326def slotspecials():
1327 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1328
1329 class D(object):
1330 __slots__ = ["__dict__"]
1331 a = D()
1332 verify(hasattr(a, "__dict__"))
1333 verify(not hasattr(a, "__weakref__"))
1334 a.foo = 42
1335 vereq(a.__dict__, {"foo": 42})
1336
1337 class W(object):
1338 __slots__ = ["__weakref__"]
1339 a = W()
1340 verify(hasattr(a, "__weakref__"))
1341 verify(not hasattr(a, "__dict__"))
1342 try:
1343 a.foo = 42
1344 except AttributeError:
1345 pass
1346 else:
1347 raise TestFailed, "shouldn't be allowed to set a.foo"
1348
1349 class C1(W, D):
1350 __slots__ = []
1351 a = C1()
1352 verify(hasattr(a, "__dict__"))
1353 verify(hasattr(a, "__weakref__"))
1354 a.foo = 42
1355 vereq(a.__dict__, {"foo": 42})
1356
1357 class C2(D, W):
1358 __slots__ = []
1359 a = C2()
1360 verify(hasattr(a, "__dict__"))
1361 verify(hasattr(a, "__weakref__"))
1362 a.foo = 42
1363 vereq(a.__dict__, {"foo": 42})
1364
Guido van Rossum9a818922002-11-14 19:50:14 +00001365# MRO order disagreement
1366#
1367# class C3(C1, C2):
1368# __slots__ = []
1369#
1370# class C4(C2, C1):
1371# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001372
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001374 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001377 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001379 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001382 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001384 vereq(E.foo, 1)
1385 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001386 # Test dynamic instances
1387 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001388 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001389 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001390 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001391 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001392 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001393 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001394 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001395 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001396 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001397 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001398 vereq(int(a), 100)
1399 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001400 verify(not hasattr(a, "spam"))
1401 def mygetattr(self, name):
1402 if name == "spam":
1403 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001404 raise AttributeError
1405 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001406 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001407 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001408 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001409 def mysetattr(self, name, value):
1410 if name == "spam":
1411 raise AttributeError
1412 return object.__setattr__(self, name, value)
1413 C.__setattr__ = mysetattr
1414 try:
1415 a.spam = "not spam"
1416 except AttributeError:
1417 pass
1418 else:
1419 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001420 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001421 class D(C):
1422 pass
1423 d = D()
1424 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001425 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426
Guido van Rossum7e35d572001-09-15 03:14:32 +00001427 # Test handling of int*seq and seq*int
1428 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001429 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001430 vereq("a"*I(2), "aa")
1431 vereq(I(2)*"a", "aa")
1432 vereq(2*I(3), 6)
1433 vereq(I(3)*2, 6)
1434 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001435
1436 # Test handling of long*seq and seq*long
1437 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001438 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001439 vereq("a"*L(2L), "aa")
1440 vereq(L(2L)*"a", "aa")
1441 vereq(2*L(3), 6)
1442 vereq(L(3)*2, 6)
1443 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001444
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001445 # Test comparison of classes with dynamic metaclasses
1446 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001447 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001448 class someclass:
1449 __metaclass__ = dynamicmetaclass
1450 verify(someclass != object)
1451
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452def errors():
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001453 """Test that type can't be placed after an instance of type in bases.
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001455 >>> class C(list, dict):
1456 ... pass
1457 Traceback (most recent call last):
1458 TypeError: Error when calling the metaclass bases
1459 multiple bases have instance lay-out conflict
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001461 >>> class C(object, None):
1462 ... pass
1463 Traceback (most recent call last):
1464 TypeError: Error when calling the metaclass bases
1465 bases must be types
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001467 >>> class C(type(len)):
1468 ... pass
1469 Traceback (most recent call last):
1470 TypeError: Error when calling the metaclass bases
1471 type 'builtin_function_or_method' is not an acceptable base type
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001473 >>> class Classic:
1474 ... def __init__(*args): pass
1475 >>> class C(object):
1476 ... __metaclass__ = Classic
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001478 >>> class C(object):
1479 ... __slots__ = 1
1480 Traceback (most recent call last):
1481 TypeError: Error when calling the metaclass bases
1482 'int' object is not iterable
1483
1484 >>> class C(object):
1485 ... __slots__ = [1]
1486 Traceback (most recent call last):
1487 TypeError: Error when calling the metaclass bases
1488 __slots__ items must be strings, not 'int'
1489
1490 >>> class A(object):
1491 ... pass
Tim Petersea5962f2007-03-12 18:07:52 +00001492
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001493 >>> class B(A, type):
1494 ... pass
1495 Traceback (most recent call last):
1496 TypeError: Error when calling the metaclass bases
1497 metaclass conflict: type must occur in bases before other non-classic base classes
1498
1499 Create two different metaclasses in order to setup an error where
1500 there is no inheritance relationship between the metaclass of a class
1501 and the metaclass of its bases.
1502
1503 >>> class M1(type):
1504 ... pass
1505 >>> class M2(type):
1506 ... pass
1507 >>> class A1(object):
1508 ... __metaclass__ = M1
1509 >>> class A2(object):
1510 ... __metaclass__ = M2
1511 >>> class B(A1, A2):
1512 ... pass
1513 Traceback (most recent call last):
1514 TypeError: Error when calling the metaclass bases
1515 metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1516 >>> class B(A1):
1517 ... pass
1518
1519 Also check that assignment to bases is safe.
Tim Petersea5962f2007-03-12 18:07:52 +00001520
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001521 >>> B.__bases__ = A1, A2
1522 Traceback (most recent call last):
1523 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1524 >>> B.__bases__ = A2,
1525 Traceback (most recent call last):
1526 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1527
1528 >>> class M3(M1):
1529 ... pass
1530 >>> class C(object):
1531 ... __metaclass__ = M3
1532 >>> B.__bases__ = C,
1533 Traceback (most recent call last):
1534 TypeError: assignment to __bases__ may not change metatype
1535 """
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536
1537def classmethods():
1538 if verbose: print "Testing class methods..."
1539 class C(object):
1540 def foo(*a): return a
1541 goo = classmethod(foo)
1542 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001543 vereq(C.goo(1), (C, 1))
1544 vereq(c.goo(1), (C, 1))
1545 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546 class D(C):
1547 pass
1548 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001549 vereq(D.goo(1), (D, 1))
1550 vereq(d.goo(1), (D, 1))
1551 vereq(d.foo(1), (d, 1))
1552 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001553 # Test for a specific crash (SF bug 528132)
1554 def f(cls, arg): return (cls, arg)
1555 ff = classmethod(f)
1556 vereq(ff.__get__(0, int)(42), (int, 42))
1557 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558
Guido van Rossum155db9a2002-04-02 17:53:47 +00001559 # Test super() with classmethods (SF bug 535444)
1560 veris(C.goo.im_self, C)
1561 veris(D.goo.im_self, D)
1562 veris(super(D,D).goo.im_self, D)
1563 veris(super(D,d).goo.im_self, D)
1564 vereq(super(D,D).goo(), (D,))
1565 vereq(super(D,d).goo(), (D,))
1566
Raymond Hettingerbe971532003-06-18 01:13:41 +00001567 # Verify that argument is checked for callability (SF bug 753451)
1568 try:
1569 classmethod(1).__get__(1)
1570 except TypeError:
1571 pass
1572 else:
1573 raise TestFailed, "classmethod should check for callability"
1574
Georg Brandl6a29c322006-02-21 22:17:46 +00001575 # Verify that classmethod() doesn't allow keyword args
1576 try:
1577 classmethod(f, kw=1)
1578 except TypeError:
1579 pass
1580 else:
1581 raise TestFailed, "classmethod shouldn't accept keyword args"
1582
Fred Drakef841aa62002-03-28 15:49:54 +00001583def classmethods_in_c():
1584 if verbose: print "Testing C-based class methods..."
1585 import xxsubtype as spam
1586 a = (1, 2, 3)
1587 d = {'abc': 123}
1588 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001589 veris(x, spam.spamlist)
1590 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001591 vereq(d, d1)
1592 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001593 veris(x, spam.spamlist)
1594 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001595 vereq(d, d1)
1596
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597def staticmethods():
1598 if verbose: print "Testing static methods..."
1599 class C(object):
1600 def foo(*a): return a
1601 goo = staticmethod(foo)
1602 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001603 vereq(C.goo(1), (1,))
1604 vereq(c.goo(1), (1,))
1605 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606 class D(C):
1607 pass
1608 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001609 vereq(D.goo(1), (1,))
1610 vereq(d.goo(1), (1,))
1611 vereq(d.foo(1), (d, 1))
1612 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613
Fred Drakef841aa62002-03-28 15:49:54 +00001614def staticmethods_in_c():
1615 if verbose: print "Testing C-based static methods..."
1616 import xxsubtype as spam
1617 a = (1, 2, 3)
1618 d = {"abc": 123}
1619 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1620 veris(x, None)
1621 vereq(a, a1)
1622 vereq(d, d1)
1623 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1624 veris(x, None)
1625 vereq(a, a1)
1626 vereq(d, d1)
1627
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628def classic():
1629 if verbose: print "Testing classic classes..."
1630 class C:
1631 def foo(*a): return a
1632 goo = classmethod(foo)
1633 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001634 vereq(C.goo(1), (C, 1))
1635 vereq(c.goo(1), (C, 1))
1636 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 class D(C):
1638 pass
1639 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001640 vereq(D.goo(1), (D, 1))
1641 vereq(d.goo(1), (D, 1))
1642 vereq(d.foo(1), (d, 1))
1643 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001644 class E: # *not* subclassing from C
1645 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001646 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001647 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648
1649def compattr():
1650 if verbose: print "Testing computed attributes..."
1651 class C(object):
1652 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001653 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 self.__get = get
1655 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001656 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 def __get__(self, obj, type=None):
1658 return self.__get(obj)
1659 def __set__(self, obj, value):
1660 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001661 def __delete__(self, obj):
1662 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 def __init__(self):
1664 self.__x = 0
1665 def __get_x(self):
1666 x = self.__x
1667 self.__x = x+1
1668 return x
1669 def __set_x(self, x):
1670 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001671 def __delete_x(self):
1672 del self.__x
1673 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001675 vereq(a.x, 0)
1676 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001678 vereq(a.x, 10)
1679 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001680 del a.x
1681 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682
1683def newslot():
1684 if verbose: print "Testing __new__ slot override..."
1685 class C(list):
1686 def __new__(cls):
1687 self = list.__new__(cls)
1688 self.foo = 1
1689 return self
1690 def __init__(self):
1691 self.foo = self.foo + 2
1692 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001693 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 verify(a.__class__ is C)
1695 class D(C):
1696 pass
1697 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001698 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 verify(b.__class__ is D)
1700
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701def altmro():
1702 if verbose: print "Testing mro() and overriding it..."
1703 class A(object):
1704 def f(self): return "A"
1705 class B(A):
1706 pass
1707 class C(A):
1708 def f(self): return "C"
1709 class D(B, C):
1710 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001711 vereq(D.mro(), [D, B, C, A, object])
1712 vereq(D.__mro__, (D, B, C, A, object))
1713 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001714
Guido van Rossumd3077402001-08-12 05:24:18 +00001715 class PerverseMetaType(type):
1716 def mro(cls):
1717 L = type.mro(cls)
1718 L.reverse()
1719 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001720 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001722 vereq(X.__mro__, (object, A, C, B, D, X))
1723 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724
Armin Rigo037d1e02005-12-29 17:07:39 +00001725 try:
1726 class X(object):
1727 class __metaclass__(type):
1728 def mro(self):
1729 return [self, dict, object]
1730 except TypeError:
1731 pass
1732 else:
1733 raise TestFailed, "devious mro() return not caught"
1734
1735 try:
1736 class X(object):
1737 class __metaclass__(type):
1738 def mro(self):
1739 return [1]
1740 except TypeError:
1741 pass
1742 else:
1743 raise TestFailed, "non-class mro() return not caught"
1744
1745 try:
1746 class X(object):
1747 class __metaclass__(type):
1748 def mro(self):
1749 return 1
1750 except TypeError:
1751 pass
1752 else:
1753 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001754
Armin Rigo037d1e02005-12-29 17:07:39 +00001755
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001757 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758
1759 class B(object):
1760 "Intermediate class because object doesn't have a __setattr__"
1761
1762 class C(B):
1763
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001764 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 if name == "foo":
1766 return ("getattr", name)
1767 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001768 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769 def __setattr__(self, name, value):
1770 if name == "foo":
1771 self.setattr = (name, value)
1772 else:
1773 return B.__setattr__(self, name, value)
1774 def __delattr__(self, name):
1775 if name == "foo":
1776 self.delattr = name
1777 else:
1778 return B.__delattr__(self, name)
1779
1780 def __getitem__(self, key):
1781 return ("getitem", key)
1782 def __setitem__(self, key, value):
1783 self.setitem = (key, value)
1784 def __delitem__(self, key):
1785 self.delitem = key
1786
1787 def __getslice__(self, i, j):
1788 return ("getslice", i, j)
1789 def __setslice__(self, i, j, value):
1790 self.setslice = (i, j, value)
1791 def __delslice__(self, i, j):
1792 self.delslice = (i, j)
1793
1794 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001795 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001797 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001799 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800
Guido van Rossum45704552001-10-08 16:35:45 +00001801 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001803 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001805 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806
Guido van Rossum45704552001-10-08 16:35:45 +00001807 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001809 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001811 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001813def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001814 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001815 class C(object):
1816 def __init__(self, x):
1817 self.x = x
1818 def foo(self):
1819 return self.x
1820 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001821 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001822 class D(C):
1823 boo = C.foo
1824 goo = c1.foo
1825 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001826 vereq(d2.foo(), 2)
1827 vereq(d2.boo(), 2)
1828 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001829 class E(object):
1830 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001831 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001832 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001833
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001834def specials():
1835 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001836 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001837 # Test the default behavior for static classes
1838 class C(object):
1839 def __getitem__(self, i):
1840 if 0 <= i < 10: return i
1841 raise IndexError
1842 c1 = C()
1843 c2 = C()
1844 verify(not not c1)
Tim Peters85b362f2006-04-11 01:21:00 +00001845 verify(id(c1) != id(c2))
1846 hash(c1)
1847 hash(c2)
Guido van Rossum45704552001-10-08 16:35:45 +00001848 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1849 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001850 verify(c1 != c2)
1851 verify(not c1 != c1)
1852 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001853 # Note that the module name appears in str/repr, and that varies
1854 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001855 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001856 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001857 verify(-1 not in c1)
1858 for i in range(10):
1859 verify(i in c1)
1860 verify(10 not in c1)
1861 # Test the default behavior for dynamic classes
1862 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001863 def __getitem__(self, i):
1864 if 0 <= i < 10: return i
1865 raise IndexError
1866 d1 = D()
1867 d2 = D()
1868 verify(not not d1)
Tim Peters85b362f2006-04-11 01:21:00 +00001869 verify(id(d1) != id(d2))
1870 hash(d1)
1871 hash(d2)
Guido van Rossum45704552001-10-08 16:35:45 +00001872 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1873 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001874 verify(d1 != d2)
1875 verify(not d1 != d1)
1876 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001877 # Note that the module name appears in str/repr, and that varies
1878 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001879 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001880 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001881 verify(-1 not in d1)
1882 for i in range(10):
1883 verify(i in d1)
1884 verify(10 not in d1)
1885 # Test overridden behavior for static classes
1886 class Proxy(object):
1887 def __init__(self, x):
1888 self.x = x
1889 def __nonzero__(self):
1890 return not not self.x
1891 def __hash__(self):
1892 return hash(self.x)
1893 def __eq__(self, other):
1894 return self.x == other
1895 def __ne__(self, other):
1896 return self.x != other
1897 def __cmp__(self, other):
1898 return cmp(self.x, other.x)
1899 def __str__(self):
1900 return "Proxy:%s" % self.x
1901 def __repr__(self):
1902 return "Proxy(%r)" % self.x
1903 def __contains__(self, value):
1904 return value in self.x
1905 p0 = Proxy(0)
1906 p1 = Proxy(1)
1907 p_1 = Proxy(-1)
1908 verify(not p0)
1909 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001910 vereq(hash(p0), hash(0))
1911 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001912 verify(p0 != p1)
1913 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001914 vereq(not p0, p1)
1915 vereq(cmp(p0, p1), -1)
1916 vereq(cmp(p0, p0), 0)
1917 vereq(cmp(p0, p_1), 1)
1918 vereq(str(p0), "Proxy:0")
1919 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001920 p10 = Proxy(range(10))
1921 verify(-1 not in p10)
1922 for i in range(10):
1923 verify(i in p10)
1924 verify(10 not in p10)
1925 # Test overridden behavior for dynamic classes
1926 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001927 def __init__(self, x):
1928 self.x = x
1929 def __nonzero__(self):
1930 return not not self.x
1931 def __hash__(self):
1932 return hash(self.x)
1933 def __eq__(self, other):
1934 return self.x == other
1935 def __ne__(self, other):
1936 return self.x != other
1937 def __cmp__(self, other):
1938 return cmp(self.x, other.x)
1939 def __str__(self):
1940 return "DProxy:%s" % self.x
1941 def __repr__(self):
1942 return "DProxy(%r)" % self.x
1943 def __contains__(self, value):
1944 return value in self.x
1945 p0 = DProxy(0)
1946 p1 = DProxy(1)
1947 p_1 = DProxy(-1)
1948 verify(not p0)
1949 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001950 vereq(hash(p0), hash(0))
1951 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001952 verify(p0 != p1)
1953 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001954 vereq(not p0, p1)
1955 vereq(cmp(p0, p1), -1)
1956 vereq(cmp(p0, p0), 0)
1957 vereq(cmp(p0, p_1), 1)
1958 vereq(str(p0), "DProxy:0")
1959 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001960 p10 = DProxy(range(10))
1961 verify(-1 not in p10)
1962 for i in range(10):
1963 verify(i in p10)
1964 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001965 # Safety test for __cmp__
1966 def unsafecmp(a, b):
1967 try:
1968 a.__class__.__cmp__(a, b)
1969 except TypeError:
1970 pass
1971 else:
1972 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1973 a.__class__, a, b)
1974 unsafecmp(u"123", "123")
1975 unsafecmp("123", u"123")
1976 unsafecmp(1, 1.0)
1977 unsafecmp(1.0, 1)
1978 unsafecmp(1, 1L)
1979 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001980
Neal Norwitz1a997502003-01-13 20:13:12 +00001981 class Letter(str):
1982 def __new__(cls, letter):
1983 if letter == 'EPS':
1984 return str.__new__(cls)
1985 return str.__new__(cls, letter)
1986 def __str__(self):
1987 if not self:
1988 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001989 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001990
1991 # sys.stdout needs to be the original to trigger the recursion bug
1992 import sys
1993 test_stdout = sys.stdout
1994 sys.stdout = get_original_stdout()
1995 try:
1996 # nothing should actually be printed, this should raise an exception
1997 print Letter('w')
1998 except RuntimeError:
1999 pass
2000 else:
2001 raise TestFailed, "expected a RuntimeError for print recursion"
2002 sys.stdout = test_stdout
2003
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002004def weakrefs():
2005 if verbose: print "Testing weak references..."
2006 import weakref
2007 class C(object):
2008 pass
2009 c = C()
2010 r = weakref.ref(c)
2011 verify(r() is c)
2012 del c
2013 verify(r() is None)
2014 del r
2015 class NoWeak(object):
2016 __slots__ = ['foo']
2017 no = NoWeak()
2018 try:
2019 weakref.ref(no)
2020 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00002021 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002022 else:
2023 verify(0, "weakref.ref(no) should be illegal")
2024 class Weak(object):
2025 __slots__ = ['foo', '__weakref__']
2026 yes = Weak()
2027 r = weakref.ref(yes)
2028 verify(r() is yes)
2029 del yes
2030 verify(r() is None)
2031 del r
2032
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002033def properties():
2034 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002035 class C(object):
2036 def getx(self):
2037 return self.__x
2038 def setx(self, value):
2039 self.__x = value
2040 def delx(self):
2041 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00002042 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002043 a = C()
2044 verify(not hasattr(a, "x"))
2045 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00002046 vereq(a._C__x, 42)
2047 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002048 del a.x
2049 verify(not hasattr(a, "x"))
2050 verify(not hasattr(a, "_C__x"))
2051 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00002052 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002053 C.x.__delete__(a)
2054 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002055
Tim Peters66c1a522001-09-24 21:17:50 +00002056 raw = C.__dict__['x']
2057 verify(isinstance(raw, property))
2058
2059 attrs = dir(raw)
2060 verify("__doc__" in attrs)
2061 verify("fget" in attrs)
2062 verify("fset" in attrs)
2063 verify("fdel" in attrs)
2064
Guido van Rossum45704552001-10-08 16:35:45 +00002065 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00002066 verify(raw.fget is C.__dict__['getx'])
2067 verify(raw.fset is C.__dict__['setx'])
2068 verify(raw.fdel is C.__dict__['delx'])
2069
2070 for attr in "__doc__", "fget", "fset", "fdel":
2071 try:
2072 setattr(raw, attr, 42)
2073 except TypeError, msg:
2074 if str(msg).find('readonly') < 0:
2075 raise TestFailed("when setting readonly attr %r on a "
2076 "property, got unexpected TypeError "
2077 "msg %r" % (attr, str(msg)))
2078 else:
2079 raise TestFailed("expected TypeError from trying to set "
2080 "readonly %r attr on a property" % attr)
2081
Neal Norwitz673cd822002-10-18 16:33:13 +00002082 class D(object):
2083 __getitem__ = property(lambda s: 1/0)
2084
2085 d = D()
2086 try:
2087 for i in d:
2088 str(i)
2089 except ZeroDivisionError:
2090 pass
2091 else:
2092 raise TestFailed, "expected ZeroDivisionError from bad property"
2093
Georg Brandl533ff6f2006-03-08 18:09:27 +00002094 class E(object):
2095 def getter(self):
2096 "getter method"
2097 return 0
2098 def setter(self, value):
2099 "setter method"
2100 pass
2101 prop = property(getter)
2102 vereq(prop.__doc__, "getter method")
2103 prop2 = property(fset=setter)
2104 vereq(prop2.__doc__, None)
2105
Georg Brandle9462c72006-08-04 18:03:37 +00002106 # this segfaulted in 2.5b2
2107 try:
2108 import _testcapi
2109 except ImportError:
2110 pass
2111 else:
2112 class X(object):
2113 p = property(_testcapi.test_with_docstring)
2114
2115
Guido van Rossumc4a18802001-08-24 16:55:27 +00002116def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002117 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002118
2119 class A(object):
2120 def meth(self, a):
2121 return "A(%r)" % a
2122
Guido van Rossum45704552001-10-08 16:35:45 +00002123 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002124
2125 class B(A):
2126 def __init__(self):
2127 self.__super = super(B, self)
2128 def meth(self, a):
2129 return "B(%r)" % a + self.__super.meth(a)
2130
Guido van Rossum45704552001-10-08 16:35:45 +00002131 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002132
2133 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002134 def meth(self, a):
2135 return "C(%r)" % a + self.__super.meth(a)
2136 C._C__super = super(C)
2137
Guido van Rossum45704552001-10-08 16:35:45 +00002138 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002139
2140 class D(C, B):
2141 def meth(self, a):
2142 return "D(%r)" % a + super(D, self).meth(a)
2143
Guido van Rossum5b443c62001-12-03 15:38:28 +00002144 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2145
2146 # Test for subclassing super
2147
2148 class mysuper(super):
2149 def __init__(self, *args):
2150 return super(mysuper, self).__init__(*args)
2151
2152 class E(D):
2153 def meth(self, a):
2154 return "E(%r)" % a + mysuper(E, self).meth(a)
2155
2156 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2157
2158 class F(E):
2159 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002160 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002161 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2162 F._F__super = mysuper(F)
2163
2164 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2165
2166 # Make sure certain errors are raised
2167
2168 try:
2169 super(D, 42)
2170 except TypeError:
2171 pass
2172 else:
2173 raise TestFailed, "shouldn't allow super(D, 42)"
2174
2175 try:
2176 super(D, C())
2177 except TypeError:
2178 pass
2179 else:
2180 raise TestFailed, "shouldn't allow super(D, C())"
2181
2182 try:
2183 super(D).__get__(12)
2184 except TypeError:
2185 pass
2186 else:
2187 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2188
2189 try:
2190 super(D).__get__(C())
2191 except TypeError:
2192 pass
2193 else:
2194 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002195
Guido van Rossuma4541a32003-04-16 20:02:22 +00002196 # Make sure data descriptors can be overridden and accessed via super
2197 # (new feature in Python 2.3)
2198
2199 class DDbase(object):
2200 def getx(self): return 42
2201 x = property(getx)
2202
2203 class DDsub(DDbase):
2204 def getx(self): return "hello"
2205 x = property(getx)
2206
2207 dd = DDsub()
2208 vereq(dd.x, "hello")
2209 vereq(super(DDsub, dd).x, 42)
2210
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002211 # Ensure that super() lookup of descriptor from classmethod
2212 # works (SF ID# 743627)
2213
2214 class Base(object):
2215 aProp = property(lambda self: "foo")
2216
2217 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002218 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002219 def test(klass):
2220 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002221
2222 veris(Sub.test(), Base.aProp)
2223
Georg Brandl5d59c092006-09-30 08:43:30 +00002224 # Verify that super() doesn't allow keyword args
2225 try:
2226 super(Base, kw=1)
2227 except TypeError:
2228 pass
2229 else:
2230 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002231
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002232def inherits():
2233 if verbose: print "Testing inheritance from basic types..."
2234
2235 class hexint(int):
2236 def __repr__(self):
2237 return hex(self)
2238 def __add__(self, other):
2239 return hexint(int.__add__(self, other))
2240 # (Note that overriding __radd__ doesn't work,
2241 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002242 vereq(repr(hexint(7) + 9), "0x10")
2243 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002244 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002245 vereq(a, 12345)
2246 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002247 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002248 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002249 verify((+a).__class__ is int)
2250 verify((a >> 0).__class__ is int)
2251 verify((a << 0).__class__ is int)
2252 verify((hexint(0) << 12).__class__ is int)
2253 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002254
2255 class octlong(long):
2256 __slots__ = []
2257 def __str__(self):
2258 s = oct(self)
2259 if s[-1] == 'L':
2260 s = s[:-1]
2261 return s
2262 def __add__(self, other):
2263 return self.__class__(super(octlong, self).__add__(other))
2264 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002265 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002266 # (Note that overriding __radd__ here only seems to work
2267 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002268 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002269 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002270 vereq(a, 12345L)
2271 vereq(long(a), 12345L)
2272 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002273 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002274 verify((+a).__class__ is long)
2275 verify((-a).__class__ is long)
2276 verify((-octlong(0)).__class__ is long)
2277 verify((a >> 0).__class__ is long)
2278 verify((a << 0).__class__ is long)
2279 verify((a - 0).__class__ is long)
2280 verify((a * 1).__class__ is long)
2281 verify((a ** 1).__class__ is long)
2282 verify((a // 1).__class__ is long)
2283 verify((1 * a).__class__ is long)
2284 verify((a | 0).__class__ is long)
2285 verify((a ^ 0).__class__ is long)
2286 verify((a & -1L).__class__ is long)
2287 verify((octlong(0) << 12).__class__ is long)
2288 verify((octlong(0) >> 12).__class__ is long)
2289 verify(abs(octlong(0)).__class__ is long)
2290
2291 # Because octlong overrides __add__, we can't check the absence of +0
2292 # optimizations using octlong.
2293 class longclone(long):
2294 pass
2295 a = longclone(1)
2296 verify((a + 0).__class__ is long)
2297 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002298
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002299 # Check that negative clones don't segfault
2300 a = longclone(-1)
2301 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002302 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002303
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002304 class precfloat(float):
2305 __slots__ = ['prec']
2306 def __init__(self, value=0.0, prec=12):
2307 self.prec = int(prec)
Armin Rigob8d6d732007-02-12 16:23:24 +00002308 float.__init__(self, value)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002309 def __repr__(self):
2310 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002312 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002313 vereq(a, 12345.0)
2314 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002315 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002316 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002317 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002318
Tim Peters2400fa42001-09-12 19:12:49 +00002319 class madcomplex(complex):
2320 def __repr__(self):
2321 return "%.17gj%+.17g" % (self.imag, self.real)
2322 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002323 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002324 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002325 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002326 vereq(a, base)
2327 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002328 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002329 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002330 vereq(repr(a), "4j-3")
2331 vereq(a, base)
2332 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002333 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002334 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002335 veris((+a).__class__, complex)
2336 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002337 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002338 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002339 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002340 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002341 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002342 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002343 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002344
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002345 class madtuple(tuple):
2346 _rev = None
2347 def rev(self):
2348 if self._rev is not None:
2349 return self._rev
2350 L = list(self)
2351 L.reverse()
2352 self._rev = self.__class__(L)
2353 return self._rev
2354 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002355 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2356 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2357 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002358 for i in range(512):
2359 t = madtuple(range(i))
2360 u = t.rev()
2361 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002362 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002363 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002364 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002365 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002366 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002367 verify(a[:].__class__ is tuple)
2368 verify((a * 1).__class__ is tuple)
2369 verify((a * 0).__class__ is tuple)
2370 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002371 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002372 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002373 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002374 verify((a + a).__class__ is tuple)
2375 verify((a * 0).__class__ is tuple)
2376 verify((a * 1).__class__ is tuple)
2377 verify((a * 2).__class__ is tuple)
2378 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002379
2380 class madstring(str):
2381 _rev = None
2382 def rev(self):
2383 if self._rev is not None:
2384 return self._rev
2385 L = list(self)
2386 L.reverse()
2387 self._rev = self.__class__("".join(L))
2388 return self._rev
2389 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002390 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2391 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2392 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002393 for i in range(256):
2394 s = madstring("".join(map(chr, range(i))))
2395 t = s.rev()
2396 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002397 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002398 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002399 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002400 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002401
Tim Peters8fa5dd02001-09-12 02:18:30 +00002402 base = "\x00" * 5
2403 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002404 vereq(s, base)
2405 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002406 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002407 vereq(hash(s), hash(base))
2408 vereq({s: 1}[base], 1)
2409 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002410 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002411 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002412 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002413 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002414 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002415 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002416 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002417 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002418 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002419 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002420 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002421 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002422 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002423 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002424 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002425 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002426 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002427 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002428 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002429 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002430 identitytab = ''.join([chr(i) for i in range(256)])
2431 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002432 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002433 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002434 vereq(s.translate(identitytab, "x"), base)
2435 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002436 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002437 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002438 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002439 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002440 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002441 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002442 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002443 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002444 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002445 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002446
Guido van Rossum91ee7982001-08-30 20:52:40 +00002447 class madunicode(unicode):
2448 _rev = None
2449 def rev(self):
2450 if self._rev is not None:
2451 return self._rev
2452 L = list(self)
2453 L.reverse()
2454 self._rev = self.__class__(u"".join(L))
2455 return self._rev
2456 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002457 vereq(u, u"ABCDEF")
2458 vereq(u.rev(), madunicode(u"FEDCBA"))
2459 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002460 base = u"12345"
2461 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002462 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002463 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002464 vereq(hash(u), hash(base))
2465 vereq({u: 1}[base], 1)
2466 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002467 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002468 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002469 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002470 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002471 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002472 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002473 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002474 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002475 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002476 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002477 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002478 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002479 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002480 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002481 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002482 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002483 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002484 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002485 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002486 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002487 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002488 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002489 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002490 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002491 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002492 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002493 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002494 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002495 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002496 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002497 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002498 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002499 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002500 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002501 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002502 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002503 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002504 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002505
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002506 class sublist(list):
2507 pass
2508 a = sublist(range(5))
2509 vereq(a, range(5))
2510 a.append("hello")
2511 vereq(a, range(5) + ["hello"])
2512 a[5] = 5
2513 vereq(a, range(6))
2514 a.extend(range(6, 20))
2515 vereq(a, range(20))
2516 a[-5:] = []
2517 vereq(a, range(15))
2518 del a[10:15]
2519 vereq(len(a), 10)
2520 vereq(a, range(10))
2521 vereq(list(a), range(10))
2522 vereq(a[0], 0)
2523 vereq(a[9], 9)
2524 vereq(a[-10], 0)
2525 vereq(a[-1], 9)
2526 vereq(a[:5], range(5))
2527
Tim Peters59c9a642001-09-13 05:38:56 +00002528 class CountedInput(file):
2529 """Counts lines read by self.readline().
2530
2531 self.lineno is the 0-based ordinal of the last line read, up to
2532 a maximum of one greater than the number of lines in the file.
2533
2534 self.ateof is true if and only if the final "" line has been read,
2535 at which point self.lineno stops incrementing, and further calls
2536 to readline() continue to return "".
2537 """
2538
2539 lineno = 0
2540 ateof = 0
2541 def readline(self):
2542 if self.ateof:
2543 return ""
2544 s = file.readline(self)
2545 # Next line works too.
2546 # s = super(CountedInput, self).readline()
2547 self.lineno += 1
2548 if s == "":
2549 self.ateof = 1
2550 return s
2551
Tim Peters561f8992001-09-13 19:36:36 +00002552 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002553 lines = ['a\n', 'b\n', 'c\n']
2554 try:
2555 f.writelines(lines)
2556 f.close()
2557 f = CountedInput(TESTFN)
2558 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2559 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002560 vereq(expected, got)
2561 vereq(f.lineno, i)
2562 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002563 f.close()
2564 finally:
2565 try:
2566 f.close()
2567 except:
2568 pass
2569 try:
2570 import os
2571 os.unlink(TESTFN)
2572 except:
2573 pass
2574
Tim Peters808b94e2001-09-13 19:33:07 +00002575def keywords():
2576 if verbose:
2577 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002578 vereq(int(x=1), 1)
2579 vereq(float(x=2), 2.0)
2580 vereq(long(x=3), 3L)
2581 vereq(complex(imag=42, real=666), complex(666, 42))
2582 vereq(str(object=500), '500')
2583 vereq(unicode(string='abc', errors='strict'), u'abc')
2584 vereq(tuple(sequence=range(3)), (0, 1, 2))
2585 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002586 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002587
2588 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002589 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002590 try:
2591 constructor(bogus_keyword_arg=1)
2592 except TypeError:
2593 pass
2594 else:
2595 raise TestFailed("expected TypeError from bogus keyword "
2596 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002597
Tim Peters8fa45672001-09-13 21:01:29 +00002598def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002599 # XXX This test is disabled because rexec is not deemed safe
2600 return
Tim Peters8fa45672001-09-13 21:01:29 +00002601 import rexec
2602 if verbose:
2603 print "Testing interaction with restricted execution ..."
2604
2605 sandbox = rexec.RExec()
2606
2607 code1 = """f = open(%r, 'w')""" % TESTFN
2608 code2 = """f = file(%r, 'w')""" % TESTFN
2609 code3 = """\
2610f = open(%r)
2611t = type(f) # a sneaky way to get the file() constructor
2612f.close()
2613f = t(%r, 'w') # rexec can't catch this by itself
2614""" % (TESTFN, TESTFN)
2615
2616 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2617 f.close()
2618
2619 try:
2620 for code in code1, code2, code3:
2621 try:
2622 sandbox.r_exec(code)
2623 except IOError, msg:
2624 if str(msg).find("restricted") >= 0:
2625 outcome = "OK"
2626 else:
2627 outcome = "got an exception, but not an expected one"
2628 else:
2629 outcome = "expected a restricted-execution exception"
2630
2631 if outcome != "OK":
2632 raise TestFailed("%s, in %r" % (outcome, code))
2633
2634 finally:
2635 try:
2636 import os
2637 os.unlink(TESTFN)
2638 except:
2639 pass
2640
Tim Peters0ab085c2001-09-14 00:25:33 +00002641def str_subclass_as_dict_key():
2642 if verbose:
2643 print "Testing a str subclass used as dict key .."
2644
2645 class cistr(str):
2646 """Sublcass of str that computes __eq__ case-insensitively.
2647
2648 Also computes a hash code of the string in canonical form.
2649 """
2650
2651 def __init__(self, value):
2652 self.canonical = value.lower()
2653 self.hashcode = hash(self.canonical)
2654
2655 def __eq__(self, other):
2656 if not isinstance(other, cistr):
2657 other = cistr(other)
2658 return self.canonical == other.canonical
2659
2660 def __hash__(self):
2661 return self.hashcode
2662
Guido van Rossum45704552001-10-08 16:35:45 +00002663 vereq(cistr('ABC'), 'abc')
2664 vereq('aBc', cistr('ABC'))
2665 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002666
2667 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002668 vereq(d[cistr('one')], 1)
2669 vereq(d[cistr('tWo')], 2)
2670 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002671 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002672 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002673
Guido van Rossumab3b0342001-09-18 20:38:53 +00002674def classic_comparisons():
2675 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002676 class classic:
2677 pass
2678 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002679 if verbose: print " (base = %s)" % base
2680 class C(base):
2681 def __init__(self, value):
2682 self.value = int(value)
2683 def __cmp__(self, other):
2684 if isinstance(other, C):
2685 return cmp(self.value, other.value)
2686 if isinstance(other, int) or isinstance(other, long):
2687 return cmp(self.value, other)
2688 return NotImplemented
2689 c1 = C(1)
2690 c2 = C(2)
2691 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002692 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002693 c = {1: c1, 2: c2, 3: c3}
2694 for x in 1, 2, 3:
2695 for y in 1, 2, 3:
2696 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2697 for op in "<", "<=", "==", "!=", ">", ">=":
2698 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2699 "x=%d, y=%d" % (x, y))
2700 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2701 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2702
Guido van Rossum0639f592001-09-18 21:06:04 +00002703def rich_comparisons():
2704 if verbose:
2705 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002706 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002707 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002708 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002709 vereq(z, 1+0j)
2710 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002711 class ZZ(complex):
2712 def __eq__(self, other):
2713 try:
2714 return abs(self - other) <= 1e-6
2715 except:
2716 return NotImplemented
2717 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002718 vereq(zz, 1+0j)
2719 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002720
Guido van Rossum0639f592001-09-18 21:06:04 +00002721 class classic:
2722 pass
2723 for base in (classic, int, object, list):
2724 if verbose: print " (base = %s)" % base
2725 class C(base):
2726 def __init__(self, value):
2727 self.value = int(value)
2728 def __cmp__(self, other):
2729 raise TestFailed, "shouldn't call __cmp__"
2730 def __eq__(self, other):
2731 if isinstance(other, C):
2732 return self.value == other.value
2733 if isinstance(other, int) or isinstance(other, long):
2734 return self.value == other
2735 return NotImplemented
2736 def __ne__(self, other):
2737 if isinstance(other, C):
2738 return self.value != other.value
2739 if isinstance(other, int) or isinstance(other, long):
2740 return self.value != other
2741 return NotImplemented
2742 def __lt__(self, other):
2743 if isinstance(other, C):
2744 return self.value < other.value
2745 if isinstance(other, int) or isinstance(other, long):
2746 return self.value < other
2747 return NotImplemented
2748 def __le__(self, other):
2749 if isinstance(other, C):
2750 return self.value <= other.value
2751 if isinstance(other, int) or isinstance(other, long):
2752 return self.value <= other
2753 return NotImplemented
2754 def __gt__(self, other):
2755 if isinstance(other, C):
2756 return self.value > other.value
2757 if isinstance(other, int) or isinstance(other, long):
2758 return self.value > other
2759 return NotImplemented
2760 def __ge__(self, other):
2761 if isinstance(other, C):
2762 return self.value >= other.value
2763 if isinstance(other, int) or isinstance(other, long):
2764 return self.value >= other
2765 return NotImplemented
2766 c1 = C(1)
2767 c2 = C(2)
2768 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002769 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002770 c = {1: c1, 2: c2, 3: c3}
2771 for x in 1, 2, 3:
2772 for y in 1, 2, 3:
2773 for op in "<", "<=", "==", "!=", ">", ">=":
2774 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2775 "x=%d, y=%d" % (x, y))
2776 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2777 "x=%d, y=%d" % (x, y))
2778 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2779 "x=%d, y=%d" % (x, y))
2780
Guido van Rossum1952e382001-09-19 01:25:16 +00002781def coercions():
2782 if verbose: print "Testing coercions..."
2783 class I(int): pass
2784 coerce(I(0), 0)
2785 coerce(0, I(0))
2786 class L(long): pass
2787 coerce(L(0), 0)
2788 coerce(L(0), 0L)
2789 coerce(0, L(0))
2790 coerce(0L, L(0))
2791 class F(float): pass
2792 coerce(F(0), 0)
2793 coerce(F(0), 0L)
2794 coerce(F(0), 0.)
2795 coerce(0, F(0))
2796 coerce(0L, F(0))
2797 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002798 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002799 coerce(C(0), 0)
2800 coerce(C(0), 0L)
2801 coerce(C(0), 0.)
2802 coerce(C(0), 0j)
2803 coerce(0, C(0))
2804 coerce(0L, C(0))
2805 coerce(0., C(0))
2806 coerce(0j, C(0))
2807
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002808def descrdoc():
2809 if verbose: print "Testing descriptor doc strings..."
2810 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002811 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002812 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002813 check(file.name, "file name") # member descriptor
2814
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002815def setclass():
2816 if verbose: print "Testing __class__ assignment..."
2817 class C(object): pass
2818 class D(object): pass
2819 class E(object): pass
2820 class F(D, E): pass
2821 for cls in C, D, E, F:
2822 for cls2 in C, D, E, F:
2823 x = cls()
2824 x.__class__ = cls2
2825 verify(x.__class__ is cls2)
2826 x.__class__ = cls
2827 verify(x.__class__ is cls)
2828 def cant(x, C):
2829 try:
2830 x.__class__ = C
2831 except TypeError:
2832 pass
2833 else:
2834 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002835 try:
2836 delattr(x, "__class__")
2837 except TypeError:
2838 pass
2839 else:
2840 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002841 cant(C(), list)
2842 cant(list(), C)
2843 cant(C(), 1)
2844 cant(C(), object)
2845 cant(object(), list)
2846 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002847 class Int(int): __slots__ = []
2848 cant(2, Int)
2849 cant(Int(), int)
2850 cant(True, int)
2851 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002852 o = object()
2853 cant(o, type(1))
2854 cant(o, type(None))
2855 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002856
Guido van Rossum6661be32001-10-26 04:26:12 +00002857def setdict():
2858 if verbose: print "Testing __dict__ assignment..."
2859 class C(object): pass
2860 a = C()
2861 a.__dict__ = {'b': 1}
2862 vereq(a.b, 1)
2863 def cant(x, dict):
2864 try:
2865 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002866 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002867 pass
2868 else:
2869 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2870 cant(a, None)
2871 cant(a, [])
2872 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002873 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002874 # Classes don't allow __dict__ assignment
2875 cant(C, {})
2876
Guido van Rossum3926a632001-09-25 16:25:58 +00002877def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002878 if verbose:
2879 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002880 import pickle, cPickle
2881
2882 def sorteditems(d):
2883 L = d.items()
2884 L.sort()
2885 return L
2886
2887 global C
2888 class C(object):
2889 def __init__(self, a, b):
2890 super(C, self).__init__()
2891 self.a = a
2892 self.b = b
2893 def __repr__(self):
2894 return "C(%r, %r)" % (self.a, self.b)
2895
2896 global C1
2897 class C1(list):
2898 def __new__(cls, a, b):
2899 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002900 def __getnewargs__(self):
2901 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002902 def __init__(self, a, b):
2903 self.a = a
2904 self.b = b
2905 def __repr__(self):
2906 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2907
2908 global C2
2909 class C2(int):
2910 def __new__(cls, a, b, val=0):
2911 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002912 def __getnewargs__(self):
2913 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002914 def __init__(self, a, b, val=0):
2915 self.a = a
2916 self.b = b
2917 def __repr__(self):
2918 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2919
Guido van Rossum90c45142001-11-24 21:07:01 +00002920 global C3
2921 class C3(object):
2922 def __init__(self, foo):
2923 self.foo = foo
2924 def __getstate__(self):
2925 return self.foo
2926 def __setstate__(self, foo):
2927 self.foo = foo
2928
2929 global C4classic, C4
2930 class C4classic: # classic
2931 pass
2932 class C4(C4classic, object): # mixed inheritance
2933 pass
2934
Guido van Rossum3926a632001-09-25 16:25:58 +00002935 for p in pickle, cPickle:
2936 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002937 if verbose:
2938 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002939
2940 for cls in C, C1, C2:
2941 s = p.dumps(cls, bin)
2942 cls2 = p.loads(s)
2943 verify(cls2 is cls)
2944
2945 a = C1(1, 2); a.append(42); a.append(24)
2946 b = C2("hello", "world", 42)
2947 s = p.dumps((a, b), bin)
2948 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002949 vereq(x.__class__, a.__class__)
2950 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2951 vereq(y.__class__, b.__class__)
2952 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002953 vereq(repr(x), repr(a))
2954 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002955 if verbose:
2956 print "a = x =", a
2957 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002958 # Test for __getstate__ and __setstate__ on new style class
2959 u = C3(42)
2960 s = p.dumps(u, bin)
2961 v = p.loads(s)
2962 veris(u.__class__, v.__class__)
2963 vereq(u.foo, v.foo)
2964 # Test for picklability of hybrid class
2965 u = C4()
2966 u.foo = 42
2967 s = p.dumps(u, bin)
2968 v = p.loads(s)
2969 veris(u.__class__, v.__class__)
2970 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002971
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002972 # Testing copy.deepcopy()
2973 if verbose:
2974 print "deepcopy"
2975 import copy
2976 for cls in C, C1, C2:
2977 cls2 = copy.deepcopy(cls)
2978 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002979
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002980 a = C1(1, 2); a.append(42); a.append(24)
2981 b = C2("hello", "world", 42)
2982 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002983 vereq(x.__class__, a.__class__)
2984 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2985 vereq(y.__class__, b.__class__)
2986 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002987 vereq(repr(x), repr(a))
2988 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002989 if verbose:
2990 print "a = x =", a
2991 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002992
Guido van Rossum8c842552002-03-14 23:05:54 +00002993def pickleslots():
2994 if verbose: print "Testing pickling of classes with __slots__ ..."
2995 import pickle, cPickle
2996 # Pickling of classes with __slots__ but without __getstate__ should fail
2997 global B, C, D, E
2998 class B(object):
2999 pass
3000 for base in [object, B]:
3001 class C(base):
3002 __slots__ = ['a']
3003 class D(C):
3004 pass
3005 try:
3006 pickle.dumps(C())
3007 except TypeError:
3008 pass
3009 else:
3010 raise TestFailed, "should fail: pickle C instance - %s" % base
3011 try:
3012 cPickle.dumps(C())
3013 except TypeError:
3014 pass
3015 else:
3016 raise TestFailed, "should fail: cPickle C instance - %s" % base
3017 try:
3018 pickle.dumps(C())
3019 except TypeError:
3020 pass
3021 else:
3022 raise TestFailed, "should fail: pickle D instance - %s" % base
3023 try:
3024 cPickle.dumps(D())
3025 except TypeError:
3026 pass
3027 else:
3028 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003029 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00003030 class C(base):
3031 __slots__ = ['a']
3032 def __getstate__(self):
3033 try:
3034 d = self.__dict__.copy()
3035 except AttributeError:
3036 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003037 for cls in self.__class__.__mro__:
3038 for sn in cls.__dict__.get('__slots__', ()):
3039 try:
3040 d[sn] = getattr(self, sn)
3041 except AttributeError:
3042 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00003043 return d
3044 def __setstate__(self, d):
3045 for k, v in d.items():
3046 setattr(self, k, v)
3047 class D(C):
3048 pass
3049 # Now it should work
3050 x = C()
3051 y = pickle.loads(pickle.dumps(x))
3052 vereq(hasattr(y, 'a'), 0)
3053 y = cPickle.loads(cPickle.dumps(x))
3054 vereq(hasattr(y, 'a'), 0)
3055 x.a = 42
3056 y = pickle.loads(pickle.dumps(x))
3057 vereq(y.a, 42)
3058 y = cPickle.loads(cPickle.dumps(x))
3059 vereq(y.a, 42)
3060 x = D()
3061 x.a = 42
3062 x.b = 100
3063 y = pickle.loads(pickle.dumps(x))
3064 vereq(y.a + y.b, 142)
3065 y = cPickle.loads(cPickle.dumps(x))
3066 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003067 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003068 class E(C):
3069 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003070 x = E()
3071 x.a = 42
3072 x.b = "foo"
3073 y = pickle.loads(pickle.dumps(x))
3074 vereq(y.a, x.a)
3075 vereq(y.b, x.b)
3076 y = cPickle.loads(cPickle.dumps(x))
3077 vereq(y.a, x.a)
3078 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003079
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003080def copies():
3081 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
3082 import copy
3083 class C(object):
3084 pass
3085
3086 a = C()
3087 a.foo = 12
3088 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003089 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003090
3091 a.bar = [1,2,3]
3092 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003093 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003094 verify(c.bar is a.bar)
3095
3096 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003097 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003098 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003099 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003100
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003101def binopoverride():
3102 if verbose: print "Testing overrides of binary operations..."
3103 class I(int):
3104 def __repr__(self):
3105 return "I(%r)" % int(self)
3106 def __add__(self, other):
3107 return I(int(self) + int(other))
3108 __radd__ = __add__
3109 def __pow__(self, other, mod=None):
3110 if mod is None:
3111 return I(pow(int(self), int(other)))
3112 else:
3113 return I(pow(int(self), int(other), int(mod)))
3114 def __rpow__(self, other, mod=None):
3115 if mod is None:
3116 return I(pow(int(other), int(self), mod))
3117 else:
3118 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003119
Walter Dörwald70a6b492004-02-12 17:35:32 +00003120 vereq(repr(I(1) + I(2)), "I(3)")
3121 vereq(repr(I(1) + 2), "I(3)")
3122 vereq(repr(1 + I(2)), "I(3)")
3123 vereq(repr(I(2) ** I(3)), "I(8)")
3124 vereq(repr(2 ** I(3)), "I(8)")
3125 vereq(repr(I(2) ** 3), "I(8)")
3126 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003127 class S(str):
3128 def __eq__(self, other):
3129 return self.lower() == other.lower()
3130
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003131def subclasspropagation():
3132 if verbose: print "Testing propagation of slot functions to subclasses..."
3133 class A(object):
3134 pass
3135 class B(A):
3136 pass
3137 class C(A):
3138 pass
3139 class D(B, C):
3140 pass
3141 d = D()
Tim Peters171b8682006-04-11 01:59:34 +00003142 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003143 A.__hash__ = lambda self: 42
3144 vereq(hash(d), 42)
3145 C.__hash__ = lambda self: 314
3146 vereq(hash(d), 314)
3147 B.__hash__ = lambda self: 144
3148 vereq(hash(d), 144)
3149 D.__hash__ = lambda self: 100
3150 vereq(hash(d), 100)
3151 del D.__hash__
3152 vereq(hash(d), 144)
3153 del B.__hash__
3154 vereq(hash(d), 314)
3155 del C.__hash__
3156 vereq(hash(d), 42)
3157 del A.__hash__
Tim Peters171b8682006-04-11 01:59:34 +00003158 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003159 d.foo = 42
3160 d.bar = 42
3161 vereq(d.foo, 42)
3162 vereq(d.bar, 42)
3163 def __getattribute__(self, name):
3164 if name == "foo":
3165 return 24
3166 return object.__getattribute__(self, name)
3167 A.__getattribute__ = __getattribute__
3168 vereq(d.foo, 24)
3169 vereq(d.bar, 42)
3170 def __getattr__(self, name):
3171 if name in ("spam", "foo", "bar"):
3172 return "hello"
3173 raise AttributeError, name
3174 B.__getattr__ = __getattr__
3175 vereq(d.spam, "hello")
3176 vereq(d.foo, 24)
3177 vereq(d.bar, 42)
3178 del A.__getattribute__
3179 vereq(d.foo, 42)
3180 del d.foo
3181 vereq(d.foo, "hello")
3182 vereq(d.bar, 42)
3183 del B.__getattr__
3184 try:
3185 d.foo
3186 except AttributeError:
3187 pass
3188 else:
3189 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003190
Guido van Rossume7f3e242002-06-14 02:35:45 +00003191 # Test a nasty bug in recurse_down_subclasses()
3192 import gc
3193 class A(object):
3194 pass
3195 class B(A):
3196 pass
3197 del B
3198 gc.collect()
3199 A.__setitem__ = lambda *a: None # crash
3200
Tim Petersfc57ccb2001-10-12 02:38:24 +00003201def buffer_inherit():
3202 import binascii
3203 # SF bug [#470040] ParseTuple t# vs subclasses.
3204 if verbose:
3205 print "Testing that buffer interface is inherited ..."
3206
3207 class MyStr(str):
3208 pass
3209 base = 'abc'
3210 m = MyStr(base)
3211 # b2a_hex uses the buffer interface to get its argument's value, via
3212 # PyArg_ParseTuple 't#' code.
3213 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3214
3215 # It's not clear that unicode will continue to support the character
3216 # buffer interface, and this test will fail if that's taken away.
3217 class MyUni(unicode):
3218 pass
3219 base = u'abc'
3220 m = MyUni(base)
3221 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3222
3223 class MyInt(int):
3224 pass
3225 m = MyInt(42)
3226 try:
3227 binascii.b2a_hex(m)
3228 raise TestFailed('subclass of int should not have a buffer interface')
3229 except TypeError:
3230 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003231
Tim Petersc9933152001-10-16 20:18:24 +00003232def str_of_str_subclass():
3233 import binascii
3234 import cStringIO
3235
3236 if verbose:
3237 print "Testing __str__ defined in subclass of str ..."
3238
3239 class octetstring(str):
3240 def __str__(self):
3241 return binascii.b2a_hex(self)
3242 def __repr__(self):
3243 return self + " repr"
3244
3245 o = octetstring('A')
3246 vereq(type(o), octetstring)
3247 vereq(type(str(o)), str)
3248 vereq(type(repr(o)), str)
3249 vereq(ord(o), 0x41)
3250 vereq(str(o), '41')
3251 vereq(repr(o), 'A repr')
3252 vereq(o.__str__(), '41')
3253 vereq(o.__repr__(), 'A repr')
3254
3255 capture = cStringIO.StringIO()
3256 # Calling str() or not exercises different internal paths.
3257 print >> capture, o
3258 print >> capture, str(o)
3259 vereq(capture.getvalue(), '41\n41\n')
3260 capture.close()
3261
Guido van Rossumc8e56452001-10-22 00:43:43 +00003262def kwdargs():
3263 if verbose: print "Testing keyword arguments to __init__, __call__..."
3264 def f(a): return a
3265 vereq(f.__call__(a=42), 42)
3266 a = []
3267 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003268 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003269
Brett Cannon22565aa2006-06-09 22:31:23 +00003270def recursive__call__():
3271 if verbose: print ("Testing recursive __call__() by setting to instance of "
3272 "class ...")
3273 class A(object):
3274 pass
3275
3276 A.__call__ = A()
3277 try:
3278 A()()
3279 except RuntimeError:
3280 pass
3281 else:
3282 raise TestFailed("Recursion limit should have been reached for "
3283 "__call__()")
3284
Guido van Rossumed87ad82001-10-30 02:33:02 +00003285def delhook():
3286 if verbose: print "Testing __del__ hook..."
3287 log = []
3288 class C(object):
3289 def __del__(self):
3290 log.append(1)
3291 c = C()
3292 vereq(log, [])
3293 del c
3294 vereq(log, [1])
3295
Guido van Rossum29d26062001-12-11 04:37:34 +00003296 class D(object): pass
3297 d = D()
3298 try: del d[0]
3299 except TypeError: pass
3300 else: raise TestFailed, "invalid del() didn't raise TypeError"
3301
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003302def hashinherit():
3303 if verbose: print "Testing hash of mutable subclasses..."
3304
3305 class mydict(dict):
3306 pass
3307 d = mydict()
3308 try:
3309 hash(d)
3310 except TypeError:
3311 pass
3312 else:
3313 raise TestFailed, "hash() of dict subclass should fail"
3314
3315 class mylist(list):
3316 pass
3317 d = mylist()
3318 try:
3319 hash(d)
3320 except TypeError:
3321 pass
3322 else:
3323 raise TestFailed, "hash() of list subclass should fail"
3324
Guido van Rossum29d26062001-12-11 04:37:34 +00003325def strops():
3326 try: 'a' + 5
3327 except TypeError: pass
3328 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3329
3330 try: ''.split('')
3331 except ValueError: pass
3332 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3333
3334 try: ''.join([0])
3335 except TypeError: pass
3336 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3337
3338 try: ''.rindex('5')
3339 except ValueError: pass
3340 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3341
Guido van Rossum29d26062001-12-11 04:37:34 +00003342 try: '%(n)s' % None
3343 except TypeError: pass
3344 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3345
3346 try: '%(n' % {}
3347 except ValueError: pass
3348 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3349
3350 try: '%*s' % ('abc')
3351 except TypeError: pass
3352 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3353
3354 try: '%*.*s' % ('abc', 5)
3355 except TypeError: pass
3356 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3357
3358 try: '%s' % (1, 2)
3359 except TypeError: pass
3360 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3361
3362 try: '%' % None
3363 except ValueError: pass
3364 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3365
3366 vereq('534253'.isdigit(), 1)
3367 vereq('534253x'.isdigit(), 0)
3368 vereq('%c' % 5, '\x05')
3369 vereq('%c' % '5', '5')
3370
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003371def deepcopyrecursive():
3372 if verbose: print "Testing deepcopy of recursive objects..."
3373 class Node:
3374 pass
3375 a = Node()
3376 b = Node()
3377 a.b = b
3378 b.a = a
3379 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003380
Guido van Rossumd7035672002-03-12 20:43:31 +00003381def modules():
3382 if verbose: print "Testing uninitialized module objects..."
3383 from types import ModuleType as M
3384 m = M.__new__(M)
3385 str(m)
3386 vereq(hasattr(m, "__name__"), 0)
3387 vereq(hasattr(m, "__file__"), 0)
3388 vereq(hasattr(m, "foo"), 0)
3389 vereq(m.__dict__, None)
3390 m.foo = 1
3391 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003392
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003393def dictproxyiterkeys():
3394 class C(object):
3395 def meth(self):
3396 pass
3397 if verbose: print "Testing dict-proxy iterkeys..."
3398 keys = [ key for key in C.__dict__.iterkeys() ]
3399 keys.sort()
3400 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3401
3402def dictproxyitervalues():
3403 class C(object):
3404 def meth(self):
3405 pass
3406 if verbose: print "Testing dict-proxy itervalues..."
3407 values = [ values for values in C.__dict__.itervalues() ]
3408 vereq(len(values), 5)
3409
3410def dictproxyiteritems():
3411 class C(object):
3412 def meth(self):
3413 pass
3414 if verbose: print "Testing dict-proxy iteritems..."
3415 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3416 keys.sort()
3417 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3418
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003419def funnynew():
3420 if verbose: print "Testing __new__ returning something unexpected..."
3421 class C(object):
3422 def __new__(cls, arg):
3423 if isinstance(arg, str): return [1, 2, 3]
3424 elif isinstance(arg, int): return object.__new__(D)
3425 else: return object.__new__(cls)
3426 class D(C):
3427 def __init__(self, arg):
3428 self.foo = arg
3429 vereq(C("1"), [1, 2, 3])
3430 vereq(D("1"), [1, 2, 3])
3431 d = D(None)
3432 veris(d.foo, None)
3433 d = C(1)
3434 vereq(isinstance(d, D), True)
3435 vereq(d.foo, 1)
3436 d = D(1)
3437 vereq(isinstance(d, D), True)
3438 vereq(d.foo, 1)
3439
Guido van Rossume8fc6402002-04-16 16:44:51 +00003440def imulbug():
3441 # SF bug 544647
3442 if verbose: print "Testing for __imul__ problems..."
3443 class C(object):
3444 def __imul__(self, other):
3445 return (self, other)
3446 x = C()
3447 y = x
3448 y *= 1.0
3449 vereq(y, (x, 1.0))
3450 y = x
3451 y *= 2
3452 vereq(y, (x, 2))
3453 y = x
3454 y *= 3L
3455 vereq(y, (x, 3L))
3456 y = x
3457 y *= 1L<<100
3458 vereq(y, (x, 1L<<100))
3459 y = x
3460 y *= None
3461 vereq(y, (x, None))
3462 y = x
3463 y *= "foo"
3464 vereq(y, (x, "foo"))
3465
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003466def docdescriptor():
3467 # SF bug 542984
3468 if verbose: print "Testing __doc__ descriptor..."
3469 class DocDescr(object):
3470 def __get__(self, object, otype):
3471 if object:
3472 object = object.__class__.__name__ + ' instance'
3473 if otype:
3474 otype = otype.__name__
3475 return 'object=%s; type=%s' % (object, otype)
3476 class OldClass:
3477 __doc__ = DocDescr()
3478 class NewClass(object):
3479 __doc__ = DocDescr()
3480 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3481 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3482 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3483 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3484
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003485def copy_setstate():
3486 if verbose:
3487 print "Testing that copy.*copy() correctly uses __setstate__..."
3488 import copy
3489 class C(object):
3490 def __init__(self, foo=None):
3491 self.foo = foo
3492 self.__foo = foo
3493 def setfoo(self, foo=None):
3494 self.foo = foo
3495 def getfoo(self):
3496 return self.__foo
3497 def __getstate__(self):
3498 return [self.foo]
3499 def __setstate__(self, lst):
3500 assert len(lst) == 1
3501 self.__foo = self.foo = lst[0]
3502 a = C(42)
3503 a.setfoo(24)
3504 vereq(a.foo, 24)
3505 vereq(a.getfoo(), 42)
3506 b = copy.copy(a)
3507 vereq(b.foo, 24)
3508 vereq(b.getfoo(), 24)
3509 b = copy.deepcopy(a)
3510 vereq(b.foo, 24)
3511 vereq(b.getfoo(), 24)
3512
Guido van Rossum09638c12002-06-13 19:17:46 +00003513def slices():
3514 if verbose:
3515 print "Testing cases with slices and overridden __getitem__ ..."
3516 # Strings
3517 vereq("hello"[:4], "hell")
3518 vereq("hello"[slice(4)], "hell")
3519 vereq(str.__getitem__("hello", slice(4)), "hell")
3520 class S(str):
3521 def __getitem__(self, x):
3522 return str.__getitem__(self, x)
3523 vereq(S("hello")[:4], "hell")
3524 vereq(S("hello")[slice(4)], "hell")
3525 vereq(S("hello").__getitem__(slice(4)), "hell")
3526 # Tuples
3527 vereq((1,2,3)[:2], (1,2))
3528 vereq((1,2,3)[slice(2)], (1,2))
3529 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3530 class T(tuple):
3531 def __getitem__(self, x):
3532 return tuple.__getitem__(self, x)
3533 vereq(T((1,2,3))[:2], (1,2))
3534 vereq(T((1,2,3))[slice(2)], (1,2))
3535 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3536 # Lists
3537 vereq([1,2,3][:2], [1,2])
3538 vereq([1,2,3][slice(2)], [1,2])
3539 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3540 class L(list):
3541 def __getitem__(self, x):
3542 return list.__getitem__(self, x)
3543 vereq(L([1,2,3])[:2], [1,2])
3544 vereq(L([1,2,3])[slice(2)], [1,2])
3545 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3546 # Now do lists and __setitem__
3547 a = L([1,2,3])
3548 a[slice(1, 3)] = [3,2]
3549 vereq(a, [1,3,2])
3550 a[slice(0, 2, 1)] = [3,1]
3551 vereq(a, [3,1,2])
3552 a.__setitem__(slice(1, 3), [2,1])
3553 vereq(a, [3,2,1])
3554 a.__setitem__(slice(0, 2, 1), [2,3])
3555 vereq(a, [2,3,1])
3556
Tim Peters2484aae2002-07-11 06:56:07 +00003557def subtype_resurrection():
3558 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003559 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003560
3561 class C(object):
3562 container = []
3563
3564 def __del__(self):
3565 # resurrect the instance
3566 C.container.append(self)
3567
3568 c = C()
3569 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003570 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003571 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003572 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003573
3574 # If that didn't blow up, it's also interesting to see whether clearing
3575 # the last container slot works: that will attempt to delete c again,
3576 # which will cause c to get appended back to the container again "during"
3577 # the del.
3578 del C.container[-1]
3579 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003580 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003581
Tim Peters14cb1e12002-07-11 18:26:21 +00003582 # Make c mortal again, so that the test framework with -l doesn't report
3583 # it as a leak.
3584 del C.__del__
3585
Guido van Rossum2d702462002-08-06 21:28:28 +00003586def slottrash():
3587 # Deallocating deeply nested slotted trash caused stack overflows
3588 if verbose:
3589 print "Testing slot trash..."
3590 class trash(object):
3591 __slots__ = ['x']
3592 def __init__(self, x):
3593 self.x = x
3594 o = None
3595 for i in xrange(50000):
3596 o = trash(o)
3597 del o
3598
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003599def slotmultipleinheritance():
3600 # SF bug 575229, multiple inheritance w/ slots dumps core
3601 class A(object):
3602 __slots__=()
3603 class B(object):
3604 pass
3605 class C(A,B) :
3606 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003607 vereq(C.__basicsize__, B.__basicsize__)
3608 verify(hasattr(C, '__dict__'))
3609 verify(hasattr(C, '__weakref__'))
3610 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003611
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003612def testrmul():
3613 # SF patch 592646
3614 if verbose:
3615 print "Testing correct invocation of __rmul__..."
3616 class C(object):
3617 def __mul__(self, other):
3618 return "mul"
3619 def __rmul__(self, other):
3620 return "rmul"
3621 a = C()
3622 vereq(a*2, "mul")
3623 vereq(a*2.2, "mul")
3624 vereq(2*a, "rmul")
3625 vereq(2.2*a, "rmul")
3626
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003627def testipow():
3628 # [SF bug 620179]
3629 if verbose:
3630 print "Testing correct invocation of __ipow__..."
3631 class C(object):
3632 def __ipow__(self, other):
3633 pass
3634 a = C()
3635 a **= 2
3636
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003637def do_this_first():
3638 if verbose:
3639 print "Testing SF bug 551412 ..."
3640 # This dumps core when SF bug 551412 isn't fixed --
3641 # but only when test_descr.py is run separately.
3642 # (That can't be helped -- as soon as PyType_Ready()
3643 # is called for PyLong_Type, the bug is gone.)
3644 class UserLong(object):
3645 def __pow__(self, *args):
3646 pass
3647 try:
3648 pow(0L, UserLong(), 0L)
3649 except:
3650 pass
3651
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003652 if verbose:
3653 print "Testing SF bug 570483..."
3654 # Another segfault only when run early
3655 # (before PyType_Ready(tuple) is called)
3656 type.mro(tuple)
3657
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003658def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003659 if verbose:
3660 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003661 # stuff that should work:
3662 class C(object):
3663 pass
3664 class C2(object):
3665 def __getattribute__(self, attr):
3666 if attr == 'a':
3667 return 2
3668 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003669 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003670 def meth(self):
3671 return 1
3672 class D(C):
3673 pass
3674 class E(D):
3675 pass
3676 d = D()
3677 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003678 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003679 D.__bases__ = (C2,)
3680 vereq(d.meth(), 1)
3681 vereq(e.meth(), 1)
3682 vereq(d.a, 2)
3683 vereq(e.a, 2)
3684 vereq(C2.__subclasses__(), [D])
3685
3686 # stuff that shouldn't:
3687 class L(list):
3688 pass
3689
3690 try:
3691 L.__bases__ = (dict,)
3692 except TypeError:
3693 pass
3694 else:
3695 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3696
3697 try:
3698 list.__bases__ = (dict,)
3699 except TypeError:
3700 pass
3701 else:
3702 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3703
3704 try:
Michael W. Hudsonf3904422006-11-23 13:54:04 +00003705 D.__bases__ = (C2, list)
3706 except TypeError:
3707 pass
3708 else:
3709 assert 0, "best_base calculation found wanting"
3710
3711 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003712 del D.__bases__
3713 except TypeError:
3714 pass
3715 else:
3716 raise TestFailed, "shouldn't be able to delete .__bases__"
3717
3718 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003719 D.__bases__ = ()
3720 except TypeError, msg:
3721 if str(msg) == "a new-style class can't have only classic bases":
3722 raise TestFailed, "wrong error message for .__bases__ = ()"
3723 else:
3724 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3725
3726 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003727 D.__bases__ = (D,)
3728 except TypeError:
3729 pass
3730 else:
3731 # actually, we'll have crashed by here...
3732 raise TestFailed, "shouldn't be able to create inheritance cycles"
3733
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003734 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003735 D.__bases__ = (C, C)
3736 except TypeError:
3737 pass
3738 else:
3739 raise TestFailed, "didn't detect repeated base classes"
3740
3741 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003742 D.__bases__ = (E,)
3743 except TypeError:
3744 pass
3745 else:
3746 raise TestFailed, "shouldn't be able to create inheritance cycles"
3747
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003748 # let's throw a classic class into the mix:
3749 class Classic:
3750 def meth2(self):
3751 return 3
3752
3753 D.__bases__ = (C, Classic)
3754
3755 vereq(d.meth2(), 3)
3756 vereq(e.meth2(), 3)
3757 try:
3758 d.a
3759 except AttributeError:
3760 pass
3761 else:
3762 raise TestFailed, "attribute should have vanished"
3763
3764 try:
3765 D.__bases__ = (Classic,)
3766 except TypeError:
3767 pass
3768 else:
3769 raise TestFailed, "new-style class must have a new-style base"
3770
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003771def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003772 if verbose:
3773 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003774 class WorkOnce(type):
3775 def __new__(self, name, bases, ns):
3776 self.flag = 0
3777 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3778 def mro(self):
3779 if self.flag > 0:
3780 raise RuntimeError, "bozo"
3781 else:
3782 self.flag += 1
3783 return type.mro(self)
3784
3785 class WorkAlways(type):
3786 def mro(self):
3787 # this is here to make sure that .mro()s aren't called
3788 # with an exception set (which was possible at one point).
3789 # An error message will be printed in a debug build.
3790 # What's a good way to test for this?
3791 return type.mro(self)
3792
3793 class C(object):
3794 pass
3795
3796 class C2(object):
3797 pass
3798
3799 class D(C):
3800 pass
3801
3802 class E(D):
3803 pass
3804
3805 class F(D):
3806 __metaclass__ = WorkOnce
3807
3808 class G(D):
3809 __metaclass__ = WorkAlways
3810
3811 # Immediate subclasses have their mro's adjusted in alphabetical
3812 # order, so E's will get adjusted before adjusting F's fails. We
3813 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003814
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003815 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003816 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003817
3818 try:
3819 D.__bases__ = (C2,)
3820 except RuntimeError:
3821 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003822 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003823 else:
3824 raise TestFailed, "exception not propagated"
3825
3826def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003827 if verbose:
3828 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003829 class A(object):
3830 pass
3831
3832 class B(object):
3833 pass
3834
3835 class C(A, B):
3836 pass
3837
3838 class D(A, B):
3839 pass
3840
3841 class E(C, D):
3842 pass
3843
3844 try:
3845 C.__bases__ = (B, A)
3846 except TypeError:
3847 pass
3848 else:
3849 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003850
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003851def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003852 if verbose:
3853 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003854 class C(object):
3855 pass
3856
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003857 # C.__module__ could be 'test_descr' or '__main__'
3858 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003859
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003860 C.__name__ = 'D'
3861 vereq((C.__module__, C.__name__), (mod, 'D'))
3862
3863 C.__name__ = 'D.E'
3864 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003865
Guido van Rossum613f24f2003-01-06 23:00:59 +00003866def subclass_right_op():
3867 if verbose:
3868 print "Testing correct dispatch of subclass overloading __r<op>__..."
3869
3870 # This code tests various cases where right-dispatch of a subclass
3871 # should be preferred over left-dispatch of a base class.
3872
3873 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3874
3875 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003876 def __floordiv__(self, other):
3877 return "B.__floordiv__"
3878 def __rfloordiv__(self, other):
3879 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003880
Guido van Rossumf389c772003-02-27 20:04:19 +00003881 vereq(B(1) // 1, "B.__floordiv__")
3882 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003883
3884 # Case 2: subclass of object; this is just the baseline for case 3
3885
3886 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003887 def __floordiv__(self, other):
3888 return "C.__floordiv__"
3889 def __rfloordiv__(self, other):
3890 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003891
Guido van Rossumf389c772003-02-27 20:04:19 +00003892 vereq(C() // 1, "C.__floordiv__")
3893 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003894
3895 # Case 3: subclass of new-style class; here it gets interesting
3896
3897 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003898 def __floordiv__(self, other):
3899 return "D.__floordiv__"
3900 def __rfloordiv__(self, other):
3901 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003902
Guido van Rossumf389c772003-02-27 20:04:19 +00003903 vereq(D() // C(), "D.__floordiv__")
3904 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003905
3906 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3907
3908 class E(C):
3909 pass
3910
Guido van Rossumf389c772003-02-27 20:04:19 +00003911 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003912
Guido van Rossumf389c772003-02-27 20:04:19 +00003913 vereq(E() // 1, "C.__floordiv__")
3914 vereq(1 // E(), "C.__rfloordiv__")
3915 vereq(E() // C(), "C.__floordiv__")
3916 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003917
Guido van Rossum373c7412003-01-07 13:41:37 +00003918def dict_type_with_metaclass():
3919 if verbose:
3920 print "Testing type of __dict__ when __metaclass__ set..."
3921
3922 class B(object):
3923 pass
3924 class M(type):
3925 pass
3926 class C:
3927 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3928 __metaclass__ = M
3929 veris(type(C.__dict__), type(B.__dict__))
3930
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003931def meth_class_get():
3932 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003933 if verbose:
3934 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003935 # Baseline
3936 arg = [1, 2, 3]
3937 res = {1: None, 2: None, 3: None}
3938 vereq(dict.fromkeys(arg), res)
3939 vereq({}.fromkeys(arg), res)
3940 # Now get the descriptor
3941 descr = dict.__dict__["fromkeys"]
3942 # More baseline using the descriptor directly
3943 vereq(descr.__get__(None, dict)(arg), res)
3944 vereq(descr.__get__({})(arg), res)
3945 # Now check various error cases
3946 try:
3947 descr.__get__(None, None)
3948 except TypeError:
3949 pass
3950 else:
3951 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3952 try:
3953 descr.__get__(42)
3954 except TypeError:
3955 pass
3956 else:
3957 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3958 try:
3959 descr.__get__(None, 42)
3960 except TypeError:
3961 pass
3962 else:
3963 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3964 try:
3965 descr.__get__(None, int)
3966 except TypeError:
3967 pass
3968 else:
3969 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3970
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003971def isinst_isclass():
3972 if verbose:
3973 print "Testing proxy isinstance() and isclass()..."
3974 class Proxy(object):
3975 def __init__(self, obj):
3976 self.__obj = obj
3977 def __getattribute__(self, name):
3978 if name.startswith("_Proxy__"):
3979 return object.__getattribute__(self, name)
3980 else:
3981 return getattr(self.__obj, name)
3982 # Test with a classic class
3983 class C:
3984 pass
3985 a = C()
3986 pa = Proxy(a)
3987 verify(isinstance(a, C)) # Baseline
3988 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003989 # Test with a classic subclass
3990 class D(C):
3991 pass
3992 a = D()
3993 pa = Proxy(a)
3994 verify(isinstance(a, C)) # Baseline
3995 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003996 # Test with a new-style class
3997 class C(object):
3998 pass
3999 a = C()
4000 pa = Proxy(a)
4001 verify(isinstance(a, C)) # Baseline
4002 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004003 # Test with a new-style subclass
4004 class D(C):
4005 pass
4006 a = D()
4007 pa = Proxy(a)
4008 verify(isinstance(a, C)) # Baseline
4009 verify(isinstance(pa, C)) # Test
4010
4011def proxysuper():
4012 if verbose:
4013 print "Testing super() for a proxy object..."
4014 class Proxy(object):
4015 def __init__(self, obj):
4016 self.__obj = obj
4017 def __getattribute__(self, name):
4018 if name.startswith("_Proxy__"):
4019 return object.__getattribute__(self, name)
4020 else:
4021 return getattr(self.__obj, name)
4022
4023 class B(object):
4024 def f(self):
4025 return "B.f"
4026
4027 class C(B):
4028 def f(self):
4029 return super(C, self).f() + "->C.f"
4030
4031 obj = C()
4032 p = Proxy(obj)
4033 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004034
Guido van Rossum52b27052003-04-15 20:05:10 +00004035def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004036 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00004037 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004038 try:
4039 object.__setattr__(str, "foo", 42)
4040 except TypeError:
4041 pass
4042 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004043 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004044 try:
4045 object.__delattr__(str, "lower")
4046 except TypeError:
4047 pass
4048 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004049 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004050
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004051def weakref_segfault():
4052 # SF 742911
4053 if verbose:
4054 print "Testing weakref segfault..."
4055
4056 import weakref
4057
4058 class Provoker:
4059 def __init__(self, referrent):
4060 self.ref = weakref.ref(referrent)
4061
4062 def __del__(self):
4063 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004064
4065 class Oops(object):
4066 pass
4067
4068 o = Oops()
4069 o.whatever = Provoker(o)
4070 del o
4071
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004072def wrapper_segfault():
4073 # SF 927248: deeply nested wrappers could cause stack overflow
4074 f = lambda:None
4075 for i in xrange(1000000):
4076 f = f.__call__
4077 f = None
4078
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004079# Fix SF #762455, segfault when sys.stdout is changed in getattr
4080def filefault():
4081 if verbose:
4082 print "Testing sys.stdout is changed in getattr..."
4083 import sys
4084 class StdoutGuard:
4085 def __getattr__(self, attr):
4086 sys.stdout = sys.__stdout__
4087 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4088 sys.stdout = StdoutGuard()
4089 try:
4090 print "Oops!"
4091 except RuntimeError:
4092 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004093
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004094def vicious_descriptor_nonsense():
4095 # A potential segfault spotted by Thomas Wouters in mail to
4096 # python-dev 2003-04-17, turned into an example & fixed by Michael
4097 # Hudson just less than four months later...
4098 if verbose:
4099 print "Testing vicious_descriptor_nonsense..."
4100
4101 class Evil(object):
4102 def __hash__(self):
4103 return hash('attr')
4104 def __eq__(self, other):
4105 del C.attr
4106 return 0
4107
4108 class Descr(object):
4109 def __get__(self, ob, type=None):
4110 return 1
4111
4112 class C(object):
4113 attr = Descr()
4114
4115 c = C()
4116 c.__dict__[Evil()] = 0
4117
4118 vereq(c.attr, 1)
4119 # this makes a crash more likely:
4120 import gc; gc.collect()
4121 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004122
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004123def test_init():
4124 # SF 1155938
4125 class Foo(object):
4126 def __init__(self):
4127 return 10
4128 try:
4129 Foo()
4130 except TypeError:
4131 pass
4132 else:
4133 raise TestFailed, "did not test __init__() for None return"
4134
Armin Rigoc6686b72005-11-07 08:38:00 +00004135def methodwrapper():
4136 # <type 'method-wrapper'> did not support any reflection before 2.5
4137 if verbose:
4138 print "Testing method-wrapper objects..."
4139
4140 l = []
4141 vereq(l.__add__, l.__add__)
Armin Rigofd01d792006-06-08 10:56:24 +00004142 vereq(l.__add__, [].__add__)
4143 verify(l.__add__ != [5].__add__)
4144 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004145 verify(l.__add__.__name__ == '__add__')
4146 verify(l.__add__.__self__ is l)
4147 verify(l.__add__.__objclass__ is list)
4148 vereq(l.__add__.__doc__, list.__add__.__doc__)
Armin Rigofd01d792006-06-08 10:56:24 +00004149 try:
4150 hash(l.__add__)
4151 except TypeError:
4152 pass
4153 else:
4154 raise TestFailed("no TypeError from hash([].__add__)")
4155
4156 t = ()
4157 t += (7,)
4158 vereq(t.__add__, (7,).__add__)
4159 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004160
Armin Rigofd163f92005-12-29 15:59:19 +00004161def notimplemented():
4162 # all binary methods should be able to return a NotImplemented
4163 if verbose:
4164 print "Testing NotImplemented..."
4165
4166 import sys
4167 import types
4168 import operator
4169
4170 def specialmethod(self, other):
4171 return NotImplemented
4172
4173 def check(expr, x, y):
4174 try:
4175 exec expr in {'x': x, 'y': y, 'operator': operator}
4176 except TypeError:
4177 pass
4178 else:
4179 raise TestFailed("no TypeError from %r" % (expr,))
4180
4181 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4182 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4183 # ValueErrors instead of TypeErrors
4184 for metaclass in [type, types.ClassType]:
4185 for name, expr, iexpr in [
4186 ('__add__', 'x + y', 'x += y'),
4187 ('__sub__', 'x - y', 'x -= y'),
4188 ('__mul__', 'x * y', 'x *= y'),
4189 ('__truediv__', 'operator.truediv(x, y)', None),
4190 ('__floordiv__', 'operator.floordiv(x, y)', None),
4191 ('__div__', 'x / y', 'x /= y'),
4192 ('__mod__', 'x % y', 'x %= y'),
4193 ('__divmod__', 'divmod(x, y)', None),
4194 ('__pow__', 'x ** y', 'x **= y'),
4195 ('__lshift__', 'x << y', 'x <<= y'),
4196 ('__rshift__', 'x >> y', 'x >>= y'),
4197 ('__and__', 'x & y', 'x &= y'),
4198 ('__or__', 'x | y', 'x |= y'),
4199 ('__xor__', 'x ^ y', 'x ^= y'),
4200 ('__coerce__', 'coerce(x, y)', None)]:
4201 if name == '__coerce__':
4202 rname = name
4203 else:
4204 rname = '__r' + name[2:]
4205 A = metaclass('A', (), {name: specialmethod})
4206 B = metaclass('B', (), {rname: specialmethod})
4207 a = A()
4208 b = B()
4209 check(expr, a, a)
4210 check(expr, a, b)
4211 check(expr, b, a)
4212 check(expr, b, b)
4213 check(expr, a, N1)
4214 check(expr, a, N2)
4215 check(expr, N1, b)
4216 check(expr, N2, b)
4217 if iexpr:
4218 check(iexpr, a, a)
4219 check(iexpr, a, b)
4220 check(iexpr, b, a)
4221 check(iexpr, b, b)
4222 check(iexpr, a, N1)
4223 check(iexpr, a, N2)
4224 iname = '__i' + name[2:]
4225 C = metaclass('C', (), {iname: specialmethod})
4226 c = C()
4227 check(iexpr, c, a)
4228 check(iexpr, c, b)
4229 check(iexpr, c, N1)
4230 check(iexpr, c, N2)
4231
Georg Brandl0fca97a2007-03-05 22:28:08 +00004232def test_assign_slice():
4233 # ceval.c's assign_slice used to check for
4234 # tp->tp_as_sequence->sq_slice instead of
4235 # tp->tp_as_sequence->sq_ass_slice
4236
4237 class C(object):
4238 def __setslice__(self, start, stop, value):
4239 self.value = value
4240
4241 c = C()
4242 c[1:2] = 3
4243 vereq(c.value, 3)
4244
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004245def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004246 weakref_segfault() # Must be first, somehow
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004247 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004248 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004249 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250 lists()
4251 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004252 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004253 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254 ints()
4255 longs()
4256 floats()
4257 complexes()
4258 spamlists()
4259 spamdicts()
4260 pydicts()
4261 pylists()
4262 metaclass()
4263 pymods()
4264 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004265 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004266 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004267 ex5()
4268 monotonicity()
4269 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004270 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004271 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004272 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273 dynamics()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004274 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004275 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004277 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278 classic()
4279 compattr()
4280 newslot()
4281 altmro()
4282 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004283 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004284 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004285 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004286 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004287 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004288 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004289 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004290 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004291 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004292 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004293 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004294 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004295 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004296 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004297 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004298 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004299 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004300 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004301 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004302 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004303 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004304 kwdargs()
Brett Cannon22565aa2006-06-09 22:31:23 +00004305 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004306 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004307 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004308 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004309 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004310 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004311 dictproxyiterkeys()
4312 dictproxyitervalues()
4313 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004314 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004315 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004316 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004317 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004318 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004319 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004320 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004321 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004322 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004323 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004324 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004325 test_mutable_bases()
4326 test_mutable_bases_with_failing_mro()
4327 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004328 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004329 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004330 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004331 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004332 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004333 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004334 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004335 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004336 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004337 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004338 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004339 notimplemented()
Georg Brandl0fca97a2007-03-05 22:28:08 +00004340 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004341
Jeremy Hyltonfa955692007-02-27 18:29:45 +00004342 from test import test_descr
4343 run_doctest(test_descr, verbosity=True)
4344
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004345 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004346
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004347if __name__ == "__main__":
4348 test_main()