blob: 974fd25cd70158a42c57168907dec469e2e6de17 [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
Barry Warsaw04f357c2002-07-23 19:04:11 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN
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
461 try:
462 C() + ""
463 except TypeError:
464 pass
465 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000466 raise TestFailed, "NotImplemented should have caused TypeError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467
468def longs():
469 if verbose: print "Testing long operations..."
470 numops(100L, 3L)
471
472def floats():
473 if verbose: print "Testing float operations..."
474 numops(100.0, 3.0)
475
476def complexes():
477 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000478 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000479 class Number(complex):
480 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000481 def __new__(cls, *args, **kwds):
482 result = complex.__new__(cls, *args)
483 result.prec = kwds.get('prec', 12)
484 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000485 def __repr__(self):
486 prec = self.prec
487 if self.imag == 0.0:
488 return "%.*g" % (prec, self.real)
489 if self.real == 0.0:
490 return "%.*gj" % (prec, self.imag)
491 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
492 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000493
Tim Peters6d6c1a32001-08-02 04:15:00 +0000494 a = Number(3.14, prec=6)
Guido van Rossum45704552001-10-08 16:35:45 +0000495 vereq(`a`, "3.14")
496 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000497
Tim Peters3f996e72001-09-13 19:18:27 +0000498 a = Number(a, prec=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000499 vereq(`a`, "3.1")
500 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000501
502 a = Number(234.5)
Guido van Rossum45704552001-10-08 16:35:45 +0000503 vereq(`a`, "234.5")
504 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000505
Tim Peters6d6c1a32001-08-02 04:15:00 +0000506def spamlists():
507 if verbose: print "Testing spamlist operations..."
508 import copy, xxsubtype as spam
509 def spamlist(l, memo=None):
510 import xxsubtype as spam
511 return spam.spamlist(l)
512 # This is an ugly hack:
513 copy._deepcopy_dispatch[spam.spamlist] = spamlist
514
515 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
516 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
517 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
518 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
519 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
520 "a[b:c]", "__getslice__")
521 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
522 "a+=b", "__iadd__")
523 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
524 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
525 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
526 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
527 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
528 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
529 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
530 # Test subclassing
531 class C(spam.spamlist):
532 def foo(self): return 1
533 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000534 vereq(a, [])
535 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000536 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000537 vereq(a, [100])
538 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000539 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000540 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000541
542def spamdicts():
543 if verbose: print "Testing spamdict operations..."
544 import copy, xxsubtype as spam
545 def spamdict(d, memo=None):
546 import xxsubtype as spam
547 sd = spam.spamdict()
548 for k, v in d.items(): sd[k] = v
549 return sd
550 # This is an ugly hack:
551 copy._deepcopy_dispatch[spam.spamdict] = spamdict
552
553 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
554 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
555 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
556 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
557 d = spamdict({1:2,3:4})
558 l1 = []
559 for i in d.keys(): l1.append(i)
560 l = []
561 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000562 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000563 l = []
564 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000565 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000566 l = []
567 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000568 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000569 straightd = {1:2, 3:4}
570 spamd = spamdict(straightd)
571 testunop(spamd, 2, "len(a)", "__len__")
572 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
573 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
574 "a[b]=c", "__setitem__")
575 # Test subclassing
576 class C(spam.spamdict):
577 def foo(self): return 1
578 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000579 vereq(a.items(), [])
580 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000582 vereq(a.items(), [('foo', 'bar')])
583 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000584 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000585 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586
587def pydicts():
588 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000589 verify(issubclass(dict, dict))
590 verify(isinstance({}, dict))
591 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000592 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000593 verify(d.__class__ is dict)
594 verify(isinstance(d, dict))
595 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 state = -1
597 def __init__(self, *a, **kw):
598 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000599 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000600 self.state = a[0]
601 if kw:
602 for k, v in kw.items(): self[v] = k
603 def __getitem__(self, key):
604 return self.get(key, 0)
605 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000606 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000607 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000608 def setstate(self, state):
609 self.state = state
610 def getstate(self):
611 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000612 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000613 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000614 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000616 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000617 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000618 vereq(a.state, -1)
619 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000620 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000621 vereq(a.state, 0)
622 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000624 vereq(a.state, 10)
625 vereq(a.getstate(), 10)
626 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000628 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000629 if verbose: print "pydict stress test ..."
630 N = 50
631 for i in range(N):
632 a[i] = C()
633 for j in range(N):
634 a[i][j] = i*j
635 for i in range(N):
636 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000637 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638
639def pylists():
640 if verbose: print "Testing Python subclass of list..."
641 class C(list):
642 def __getitem__(self, i):
643 return list.__getitem__(self, i) + 100
644 def __getslice__(self, i, j):
645 return (i, j)
646 a = C()
647 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000648 vereq(a[0], 100)
649 vereq(a[1], 101)
650 vereq(a[2], 102)
651 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652
653def metaclass():
654 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655 class C:
656 __metaclass__ = type
657 def __init__(self):
658 self.__state = 0
659 def getstate(self):
660 return self.__state
661 def setstate(self, state):
662 self.__state = state
663 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000664 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000666 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 class D:
668 class __metaclass__(type):
669 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000670 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000671 d = D()
672 verify(d.__class__ is D)
673 class M1(type):
674 def __new__(cls, name, bases, dict):
675 dict['__spam__'] = 1
676 return type.__new__(cls, name, bases, dict)
677 class C:
678 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000679 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000680 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000681 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000682
Guido van Rossum309b5662001-08-17 11:43:17 +0000683 class _instance(object):
684 pass
685 class M2(object):
686 def __new__(cls, name, bases, dict):
687 self = object.__new__(cls)
688 self.name = name
689 self.bases = bases
690 self.dict = dict
691 return self
692 __new__ = staticmethod(__new__)
693 def __call__(self):
694 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000695 # Early binding of methods
696 for key in self.dict:
697 if key.startswith("__"):
698 continue
699 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000700 return it
701 class C:
702 __metaclass__ = M2
703 def spam(self):
704 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000705 vereq(C.name, 'C')
706 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000707 verify('spam' in C.dict)
708 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000709 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000710
Guido van Rossum91ee7982001-08-30 20:52:40 +0000711 # More metaclass examples
712
713 class autosuper(type):
714 # Automatically add __super to the class
715 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000716 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000717 cls = super(autosuper, metaclass).__new__(metaclass,
718 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000719 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000720 while name[:1] == "_":
721 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000722 if name:
723 name = "_%s__super" % name
724 else:
725 name = "__super"
726 setattr(cls, name, super(cls))
727 return cls
728 class A:
729 __metaclass__ = autosuper
730 def meth(self):
731 return "A"
732 class B(A):
733 def meth(self):
734 return "B" + self.__super.meth()
735 class C(A):
736 def meth(self):
737 return "C" + self.__super.meth()
738 class D(C, B):
739 def meth(self):
740 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000741 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000742 class E(B, C):
743 def meth(self):
744 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000745 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000746
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000747 class autoproperty(type):
748 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000749 # named _get_x and/or _set_x are found
750 def __new__(metaclass, name, bases, dict):
751 hits = {}
752 for key, val in dict.iteritems():
753 if key.startswith("_get_"):
754 key = key[5:]
755 get, set = hits.get(key, (None, None))
756 get = val
757 hits[key] = get, set
758 elif key.startswith("_set_"):
759 key = key[5:]
760 get, set = hits.get(key, (None, None))
761 set = val
762 hits[key] = get, set
763 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000764 dict[key] = property(get, set)
765 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000766 name, bases, dict)
767 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000768 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000769 def _get_x(self):
770 return -self.__x
771 def _set_x(self, x):
772 self.__x = -x
773 a = A()
774 verify(not hasattr(a, "x"))
775 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000776 vereq(a.x, 12)
777 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000778
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000779 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000780 # Merge of multiple cooperating metaclasses
781 pass
782 class A:
783 __metaclass__ = multimetaclass
784 def _get_x(self):
785 return "A"
786 class B(A):
787 def _get_x(self):
788 return "B" + self.__super._get_x()
789 class C(A):
790 def _get_x(self):
791 return "C" + self.__super._get_x()
792 class D(C, B):
793 def _get_x(self):
794 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000795 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000796
Guido van Rossumf76de622001-10-18 15:49:21 +0000797 # Make sure type(x) doesn't call x.__class__.__init__
798 class T(type):
799 counter = 0
800 def __init__(self, *args):
801 T.counter += 1
802 class C:
803 __metaclass__ = T
804 vereq(T.counter, 1)
805 a = C()
806 vereq(type(a), C)
807 vereq(T.counter, 1)
808
Guido van Rossum29d26062001-12-11 04:37:34 +0000809 class C(object): pass
810 c = C()
811 try: c()
812 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000813 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000814
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815def pymods():
816 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000818 import sys
819 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000821 def __init__(self, name):
822 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000823 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000825 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826 def __setattr__(self, name, value):
827 log.append(("setattr", name, value))
828 MT.__setattr__(self, name, value)
829 def __delattr__(self, name):
830 log.append(("delattr", name))
831 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000832 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833 a.foo = 12
834 x = a.foo
835 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000836 vereq(log, [("setattr", "foo", 12),
837 ("getattr", "foo"),
838 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839
840def multi():
841 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 class C(object):
843 def __init__(self):
844 self.__state = 0
845 def getstate(self):
846 return self.__state
847 def setstate(self, state):
848 self.__state = state
849 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000850 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000852 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000853 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 def __init__(self):
855 type({}).__init__(self)
856 C.__init__(self)
857 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000858 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000860 vereq(d.items(), [("hello", "world")])
861 vereq(d["hello"], "world")
862 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000864 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000865 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866
Guido van Rossume45763a2001-08-10 21:28:46 +0000867 # SF bug #442833
868 class Node(object):
869 def __int__(self):
870 return int(self.foo())
871 def foo(self):
872 return "23"
873 class Frag(Node, list):
874 def foo(self):
875 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000876 vereq(Node().__int__(), 23)
877 vereq(int(Node()), 23)
878 vereq(Frag().__int__(), 42)
879 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000880
Tim Petersa91e9642001-11-14 23:32:33 +0000881 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000882
883 class A:
884 x = 1
885
886 class B(A):
887 pass
888
889 class C(A):
890 x = 2
891
892 class D(B, C):
893 pass
894 vereq(D.x, 1)
895
896 # Classic MRO is preserved for a classic base class.
897 class E(D, object):
898 pass
899 vereq(E.__mro__, (E, D, B, A, C, object))
900 vereq(E.x, 1)
901
902 # But with a mix of classic bases, their MROs are combined using
903 # new-style MRO.
904 class F(B, C, object):
905 pass
906 vereq(F.__mro__, (F, B, C, A, object))
907 vereq(F.x, 2)
908
909 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000910 class C:
911 def cmethod(self):
912 return "C a"
913 def all_method(self):
914 return "C b"
915
916 class M1(C, object):
917 def m1method(self):
918 return "M1 a"
919 def all_method(self):
920 return "M1 b"
921
922 vereq(M1.__mro__, (M1, C, object))
923 m = M1()
924 vereq(m.cmethod(), "C a")
925 vereq(m.m1method(), "M1 a")
926 vereq(m.all_method(), "M1 b")
927
928 class D(C):
929 def dmethod(self):
930 return "D a"
931 def all_method(self):
932 return "D b"
933
Guido van Rossum9a818922002-11-14 19:50:14 +0000934 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000935 def m2method(self):
936 return "M2 a"
937 def all_method(self):
938 return "M2 b"
939
Guido van Rossum9a818922002-11-14 19:50:14 +0000940 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000941 m = M2()
942 vereq(m.cmethod(), "C a")
943 vereq(m.dmethod(), "D a")
944 vereq(m.m2method(), "M2 a")
945 vereq(m.all_method(), "M2 b")
946
Guido van Rossum9a818922002-11-14 19:50:14 +0000947 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000948 def m3method(self):
949 return "M3 a"
950 def all_method(self):
951 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000952 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000953 m = M3()
954 vereq(m.cmethod(), "C a")
955 vereq(m.dmethod(), "D a")
956 vereq(m.m1method(), "M1 a")
957 vereq(m.m2method(), "M2 a")
958 vereq(m.m3method(), "M3 a")
959 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000960
Guido van Rossume54616c2001-12-14 04:19:56 +0000961 class Classic:
962 pass
963 try:
964 class New(Classic):
965 __metaclass__ = type
966 except TypeError:
967 pass
968 else:
969 raise TestFailed, "new class with only classic bases - shouldn't be"
970
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971def diamond():
972 if verbose: print "Testing multiple inheritance special cases..."
973 class A(object):
974 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000975 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000976 class B(A):
977 def boo(self): return "B"
978 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000979 vereq(B().spam(), "B")
980 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 class C(A):
982 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000983 vereq(C().spam(), "A")
984 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000986 vereq(D().spam(), "B")
987 vereq(D().boo(), "B")
988 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000990 vereq(E().spam(), "B")
991 vereq(E().boo(), "C")
992 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000993 # MRO order disagreement
994 try:
995 class F(D, E): pass
996 except TypeError:
997 pass
998 else:
999 raise TestFailed, "expected MRO order disagreement (F)"
1000 try:
1001 class G(E, D): pass
1002 except TypeError:
1003 pass
1004 else:
1005 raise TestFailed, "expected MRO order disagreement (G)"
1006
1007
1008# see thread python-dev/2002-October/029035.html
1009def ex5():
1010 if verbose: print "Testing ex5 from C3 switch discussion..."
1011 class A(object): pass
1012 class B(object): pass
1013 class C(object): pass
1014 class X(A): pass
1015 class Y(A): pass
1016 class Z(X,B,Y,C): pass
1017 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1018
1019# see "A Monotonic Superclass Linearization for Dylan",
1020# by Kim Barrett et al. (OOPSLA 1996)
1021def monotonicity():
1022 if verbose: print "Testing MRO monotonicity..."
1023 class Boat(object): pass
1024 class DayBoat(Boat): pass
1025 class WheelBoat(Boat): pass
1026 class EngineLess(DayBoat): pass
1027 class SmallMultihull(DayBoat): pass
1028 class PedalWheelBoat(EngineLess,WheelBoat): pass
1029 class SmallCatamaran(SmallMultihull): pass
1030 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1031
1032 vereq(PedalWheelBoat.__mro__,
1033 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1034 object))
1035 vereq(SmallCatamaran.__mro__,
1036 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1037
1038 vereq(Pedalo.__mro__,
1039 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1040 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1041
1042# see "A Monotonic Superclass Linearization for Dylan",
1043# by Kim Barrett et al. (OOPSLA 1996)
1044def consistency_with_epg():
1045 if verbose: print "Testing consistentcy with EPG..."
1046 class Pane(object): pass
1047 class ScrollingMixin(object): pass
1048 class EditingMixin(object): pass
1049 class ScrollablePane(Pane,ScrollingMixin): pass
1050 class EditablePane(Pane,EditingMixin): pass
1051 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1052
1053 vereq(EditableScrollablePane.__mro__,
1054 (EditableScrollablePane, ScrollablePane, EditablePane,
1055 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056
Guido van Rossumd32047f2002-11-25 21:38:52 +00001057def mro_disagreement():
1058 if verbose: print "Testing error messages for MRO disagreement..."
1059 def raises(exc, expected, callable, *args):
1060 try:
1061 callable(*args)
1062 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001063 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001064 raise TestFailed, "Message %r, expected %r" % (str(msg),
1065 expected)
1066 else:
1067 raise TestFailed, "Expected %s" % exc
1068 class A(object): pass
1069 class B(A): pass
1070 class C(object): pass
1071 # Test some very simple errors
1072 raises(TypeError, "duplicate base class A",
1073 type, "X", (A, A), {})
Guido van Rossuma01fa262002-11-27 04:00:59 +00001074 raises(TypeError, "MRO conflict among bases ",
Guido van Rossumd32047f2002-11-25 21:38:52 +00001075 type, "X", (A, B), {})
Guido van Rossuma01fa262002-11-27 04:00:59 +00001076 raises(TypeError, "MRO conflict among bases ",
Guido van Rossumd32047f2002-11-25 21:38:52 +00001077 type, "X", (A, C, B), {})
1078 # Test a slightly more complex error
1079 class GridLayout(object): pass
1080 class HorizontalGrid(GridLayout): pass
1081 class VerticalGrid(GridLayout): pass
1082 class HVGrid(HorizontalGrid, VerticalGrid): pass
1083 class VHGrid(VerticalGrid, HorizontalGrid): pass
Guido van Rossuma01fa262002-11-27 04:00:59 +00001084 raises(TypeError, "MRO conflict among bases ",
Guido van Rossumd32047f2002-11-25 21:38:52 +00001085 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1086
Guido van Rossum37202612001-08-09 19:45:21 +00001087def objects():
1088 if verbose: print "Testing object class..."
1089 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001090 vereq(a.__class__, object)
1091 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001092 b = object()
1093 verify(a is not b)
1094 verify(not hasattr(a, "foo"))
1095 try:
1096 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001097 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001098 pass
1099 else:
1100 verify(0, "object() should not allow setting a foo attribute")
1101 verify(not hasattr(object(), "__dict__"))
1102
1103 class Cdict(object):
1104 pass
1105 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001106 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001107 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001108 vereq(x.foo, 1)
1109 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001110
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111def slots():
1112 if verbose: print "Testing __slots__..."
1113 class C0(object):
1114 __slots__ = []
1115 x = C0()
1116 verify(not hasattr(x, "__dict__"))
1117 verify(not hasattr(x, "foo"))
1118
1119 class C1(object):
1120 __slots__ = ['a']
1121 x = C1()
1122 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001123 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001125 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001126 x.a = None
1127 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001129 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130
1131 class C3(object):
1132 __slots__ = ['a', 'b', 'c']
1133 x = C3()
1134 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001135 verify(not hasattr(x, 'a'))
1136 verify(not hasattr(x, 'b'))
1137 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 x.a = 1
1139 x.b = 2
1140 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001141 vereq(x.a, 1)
1142 vereq(x.b, 2)
1143 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001145 class C4(object):
1146 """Validate name mangling"""
1147 __slots__ = ['__a']
1148 def __init__(self, value):
1149 self.__a = value
1150 def get(self):
1151 return self.__a
1152 x = C4(5)
1153 verify(not hasattr(x, '__dict__'))
1154 verify(not hasattr(x, '__a'))
1155 vereq(x.get(), 5)
1156 try:
1157 x.__a = 6
1158 except AttributeError:
1159 pass
1160 else:
1161 raise TestFailed, "Double underscored names not mangled"
1162
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001163 # Make sure slot names are proper identifiers
1164 try:
1165 class C(object):
1166 __slots__ = [None]
1167 except TypeError:
1168 pass
1169 else:
1170 raise TestFailed, "[None] slots not caught"
1171 try:
1172 class C(object):
1173 __slots__ = ["foo bar"]
1174 except TypeError:
1175 pass
1176 else:
1177 raise TestFailed, "['foo bar'] slots not caught"
1178 try:
1179 class C(object):
1180 __slots__ = ["foo\0bar"]
1181 except TypeError:
1182 pass
1183 else:
1184 raise TestFailed, "['foo\\0bar'] slots not caught"
1185 try:
1186 class C(object):
1187 __slots__ = ["1"]
1188 except TypeError:
1189 pass
1190 else:
1191 raise TestFailed, "['1'] slots not caught"
1192 try:
1193 class C(object):
1194 __slots__ = [""]
1195 except TypeError:
1196 pass
1197 else:
1198 raise TestFailed, "[''] slots not caught"
1199 class C(object):
1200 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1201
Guido van Rossum33bab012001-12-05 22:45:48 +00001202 # Test leaks
1203 class Counted(object):
1204 counter = 0 # counts the number of instances alive
1205 def __init__(self):
1206 Counted.counter += 1
1207 def __del__(self):
1208 Counted.counter -= 1
1209 class C(object):
1210 __slots__ = ['a', 'b', 'c']
1211 x = C()
1212 x.a = Counted()
1213 x.b = Counted()
1214 x.c = Counted()
1215 vereq(Counted.counter, 3)
1216 del x
1217 vereq(Counted.counter, 0)
1218 class D(C):
1219 pass
1220 x = D()
1221 x.a = Counted()
1222 x.z = Counted()
1223 vereq(Counted.counter, 2)
1224 del x
1225 vereq(Counted.counter, 0)
1226 class E(D):
1227 __slots__ = ['e']
1228 x = E()
1229 x.a = Counted()
1230 x.z = Counted()
1231 x.e = Counted()
1232 vereq(Counted.counter, 3)
1233 del x
1234 vereq(Counted.counter, 0)
1235
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001236 # Test cyclical leaks [SF bug 519621]
1237 class F(object):
1238 __slots__ = ['a', 'b']
1239 log = []
1240 s = F()
1241 s.a = [Counted(), s]
1242 vereq(Counted.counter, 1)
1243 s = None
1244 import gc
1245 gc.collect()
1246 vereq(Counted.counter, 0)
1247
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001248 # Test lookup leaks [SF bug 572567]
1249 import sys,gc
1250 class G(object):
1251 def __cmp__(self, other):
1252 return 0
1253 g = G()
1254 orig_objects = len(gc.get_objects())
1255 for i in xrange(10):
1256 g==g
1257 new_objects = len(gc.get_objects())
1258 vereq(orig_objects, new_objects)
1259
Guido van Rossum8b056da2002-08-13 18:26:26 +00001260def slotspecials():
1261 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1262
1263 class D(object):
1264 __slots__ = ["__dict__"]
1265 a = D()
1266 verify(hasattr(a, "__dict__"))
1267 verify(not hasattr(a, "__weakref__"))
1268 a.foo = 42
1269 vereq(a.__dict__, {"foo": 42})
1270
1271 class W(object):
1272 __slots__ = ["__weakref__"]
1273 a = W()
1274 verify(hasattr(a, "__weakref__"))
1275 verify(not hasattr(a, "__dict__"))
1276 try:
1277 a.foo = 42
1278 except AttributeError:
1279 pass
1280 else:
1281 raise TestFailed, "shouldn't be allowed to set a.foo"
1282
1283 class C1(W, D):
1284 __slots__ = []
1285 a = C1()
1286 verify(hasattr(a, "__dict__"))
1287 verify(hasattr(a, "__weakref__"))
1288 a.foo = 42
1289 vereq(a.__dict__, {"foo": 42})
1290
1291 class C2(D, W):
1292 __slots__ = []
1293 a = C2()
1294 verify(hasattr(a, "__dict__"))
1295 verify(hasattr(a, "__weakref__"))
1296 a.foo = 42
1297 vereq(a.__dict__, {"foo": 42})
1298
Guido van Rossum9a818922002-11-14 19:50:14 +00001299# MRO order disagreement
1300#
1301# class C3(C1, C2):
1302# __slots__ = []
1303#
1304# class C4(C2, C1):
1305# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001306
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001308 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001311 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001313 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001316 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001318 vereq(E.foo, 1)
1319 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001320 # Test dynamic instances
1321 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001322 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001323 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001324 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001325 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001326 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001327 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001328 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001329 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001330 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001331 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001332 vereq(int(a), 100)
1333 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001334 verify(not hasattr(a, "spam"))
1335 def mygetattr(self, name):
1336 if name == "spam":
1337 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001338 raise AttributeError
1339 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001340 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001341 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001342 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001343 def mysetattr(self, name, value):
1344 if name == "spam":
1345 raise AttributeError
1346 return object.__setattr__(self, name, value)
1347 C.__setattr__ = mysetattr
1348 try:
1349 a.spam = "not spam"
1350 except AttributeError:
1351 pass
1352 else:
1353 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001354 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001355 class D(C):
1356 pass
1357 d = D()
1358 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001359 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360
Guido van Rossum7e35d572001-09-15 03:14:32 +00001361 # Test handling of int*seq and seq*int
1362 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001363 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001364 vereq("a"*I(2), "aa")
1365 vereq(I(2)*"a", "aa")
1366 vereq(2*I(3), 6)
1367 vereq(I(3)*2, 6)
1368 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001369
1370 # Test handling of long*seq and seq*long
1371 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001372 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001373 vereq("a"*L(2L), "aa")
1374 vereq(L(2L)*"a", "aa")
1375 vereq(2*L(3), 6)
1376 vereq(L(3)*2, 6)
1377 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001378
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001379 # Test comparison of classes with dynamic metaclasses
1380 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001381 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001382 class someclass:
1383 __metaclass__ = dynamicmetaclass
1384 verify(someclass != object)
1385
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386def errors():
1387 if verbose: print "Testing errors..."
1388
1389 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001390 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 pass
1392 except TypeError:
1393 pass
1394 else:
1395 verify(0, "inheritance from both list and dict should be illegal")
1396
1397 try:
1398 class C(object, None):
1399 pass
1400 except TypeError:
1401 pass
1402 else:
1403 verify(0, "inheritance from non-type should be illegal")
1404 class Classic:
1405 pass
1406
1407 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001408 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 pass
1410 except TypeError:
1411 pass
1412 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001413 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414
1415 try:
1416 class C(object):
1417 __slots__ = 1
1418 except TypeError:
1419 pass
1420 else:
1421 verify(0, "__slots__ = 1 should be illegal")
1422
1423 try:
1424 class C(object):
1425 __slots__ = [1]
1426 except TypeError:
1427 pass
1428 else:
1429 verify(0, "__slots__ = [1] should be illegal")
1430
1431def classmethods():
1432 if verbose: print "Testing class methods..."
1433 class C(object):
1434 def foo(*a): return a
1435 goo = classmethod(foo)
1436 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001437 vereq(C.goo(1), (C, 1))
1438 vereq(c.goo(1), (C, 1))
1439 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 class D(C):
1441 pass
1442 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001443 vereq(D.goo(1), (D, 1))
1444 vereq(d.goo(1), (D, 1))
1445 vereq(d.foo(1), (d, 1))
1446 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001447 # Test for a specific crash (SF bug 528132)
1448 def f(cls, arg): return (cls, arg)
1449 ff = classmethod(f)
1450 vereq(ff.__get__(0, int)(42), (int, 42))
1451 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452
Guido van Rossum155db9a2002-04-02 17:53:47 +00001453 # Test super() with classmethods (SF bug 535444)
1454 veris(C.goo.im_self, C)
1455 veris(D.goo.im_self, D)
1456 veris(super(D,D).goo.im_self, D)
1457 veris(super(D,d).goo.im_self, D)
1458 vereq(super(D,D).goo(), (D,))
1459 vereq(super(D,d).goo(), (D,))
1460
Fred Drakef841aa62002-03-28 15:49:54 +00001461def classmethods_in_c():
1462 if verbose: print "Testing C-based class methods..."
1463 import xxsubtype as spam
1464 a = (1, 2, 3)
1465 d = {'abc': 123}
1466 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001467 veris(x, spam.spamlist)
1468 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001469 vereq(d, d1)
1470 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001471 veris(x, spam.spamlist)
1472 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001473 vereq(d, d1)
1474
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475def staticmethods():
1476 if verbose: print "Testing static methods..."
1477 class C(object):
1478 def foo(*a): return a
1479 goo = staticmethod(foo)
1480 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001481 vereq(C.goo(1), (1,))
1482 vereq(c.goo(1), (1,))
1483 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 class D(C):
1485 pass
1486 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001487 vereq(D.goo(1), (1,))
1488 vereq(d.goo(1), (1,))
1489 vereq(d.foo(1), (d, 1))
1490 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491
Fred Drakef841aa62002-03-28 15:49:54 +00001492def staticmethods_in_c():
1493 if verbose: print "Testing C-based static methods..."
1494 import xxsubtype as spam
1495 a = (1, 2, 3)
1496 d = {"abc": 123}
1497 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1498 veris(x, None)
1499 vereq(a, a1)
1500 vereq(d, d1)
1501 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1502 veris(x, None)
1503 vereq(a, a1)
1504 vereq(d, d1)
1505
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506def classic():
1507 if verbose: print "Testing classic classes..."
1508 class C:
1509 def foo(*a): return a
1510 goo = classmethod(foo)
1511 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001512 vereq(C.goo(1), (C, 1))
1513 vereq(c.goo(1), (C, 1))
1514 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515 class D(C):
1516 pass
1517 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001518 vereq(D.goo(1), (D, 1))
1519 vereq(d.goo(1), (D, 1))
1520 vereq(d.foo(1), (d, 1))
1521 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001522 class E: # *not* subclassing from C
1523 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001524 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001525 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526
1527def compattr():
1528 if verbose: print "Testing computed attributes..."
1529 class C(object):
1530 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001531 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532 self.__get = get
1533 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001534 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 def __get__(self, obj, type=None):
1536 return self.__get(obj)
1537 def __set__(self, obj, value):
1538 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001539 def __delete__(self, obj):
1540 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 def __init__(self):
1542 self.__x = 0
1543 def __get_x(self):
1544 x = self.__x
1545 self.__x = x+1
1546 return x
1547 def __set_x(self, x):
1548 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001549 def __delete_x(self):
1550 del self.__x
1551 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001553 vereq(a.x, 0)
1554 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001556 vereq(a.x, 10)
1557 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001558 del a.x
1559 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560
1561def newslot():
1562 if verbose: print "Testing __new__ slot override..."
1563 class C(list):
1564 def __new__(cls):
1565 self = list.__new__(cls)
1566 self.foo = 1
1567 return self
1568 def __init__(self):
1569 self.foo = self.foo + 2
1570 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001571 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572 verify(a.__class__ is C)
1573 class D(C):
1574 pass
1575 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001576 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 verify(b.__class__ is D)
1578
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579def altmro():
1580 if verbose: print "Testing mro() and overriding it..."
1581 class A(object):
1582 def f(self): return "A"
1583 class B(A):
1584 pass
1585 class C(A):
1586 def f(self): return "C"
1587 class D(B, C):
1588 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001589 vereq(D.mro(), [D, B, C, A, object])
1590 vereq(D.__mro__, (D, B, C, A, object))
1591 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001592
Guido van Rossumd3077402001-08-12 05:24:18 +00001593 class PerverseMetaType(type):
1594 def mro(cls):
1595 L = type.mro(cls)
1596 L.reverse()
1597 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001598 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001600 vereq(X.__mro__, (object, A, C, B, D, X))
1601 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602
1603def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001604 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605
1606 class B(object):
1607 "Intermediate class because object doesn't have a __setattr__"
1608
1609 class C(B):
1610
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001611 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612 if name == "foo":
1613 return ("getattr", name)
1614 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001615 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616 def __setattr__(self, name, value):
1617 if name == "foo":
1618 self.setattr = (name, value)
1619 else:
1620 return B.__setattr__(self, name, value)
1621 def __delattr__(self, name):
1622 if name == "foo":
1623 self.delattr = name
1624 else:
1625 return B.__delattr__(self, name)
1626
1627 def __getitem__(self, key):
1628 return ("getitem", key)
1629 def __setitem__(self, key, value):
1630 self.setitem = (key, value)
1631 def __delitem__(self, key):
1632 self.delitem = key
1633
1634 def __getslice__(self, i, j):
1635 return ("getslice", i, j)
1636 def __setslice__(self, i, j, value):
1637 self.setslice = (i, j, value)
1638 def __delslice__(self, i, j):
1639 self.delslice = (i, j)
1640
1641 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001642 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001643 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001644 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001646 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647
Guido van Rossum45704552001-10-08 16:35:45 +00001648 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001650 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001652 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653
Guido van Rossum45704552001-10-08 16:35:45 +00001654 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001656 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001658 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001660def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001661 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001662 class C(object):
1663 def __init__(self, x):
1664 self.x = x
1665 def foo(self):
1666 return self.x
1667 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001668 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001669 class D(C):
1670 boo = C.foo
1671 goo = c1.foo
1672 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001673 vereq(d2.foo(), 2)
1674 vereq(d2.boo(), 2)
1675 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001676 class E(object):
1677 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001678 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001679 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001680
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001681def specials():
1682 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001683 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001684 # Test the default behavior for static classes
1685 class C(object):
1686 def __getitem__(self, i):
1687 if 0 <= i < 10: return i
1688 raise IndexError
1689 c1 = C()
1690 c2 = C()
1691 verify(not not c1)
Guido van Rossum45704552001-10-08 16:35:45 +00001692 vereq(hash(c1), id(c1))
1693 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1694 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001695 verify(c1 != c2)
1696 verify(not c1 != c1)
1697 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001698 # Note that the module name appears in str/repr, and that varies
1699 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001700 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001701 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001702 verify(-1 not in c1)
1703 for i in range(10):
1704 verify(i in c1)
1705 verify(10 not in c1)
1706 # Test the default behavior for dynamic classes
1707 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001708 def __getitem__(self, i):
1709 if 0 <= i < 10: return i
1710 raise IndexError
1711 d1 = D()
1712 d2 = D()
1713 verify(not not d1)
Guido van Rossum45704552001-10-08 16:35:45 +00001714 vereq(hash(d1), id(d1))
1715 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1716 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001717 verify(d1 != d2)
1718 verify(not d1 != d1)
1719 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001720 # Note that the module name appears in str/repr, and that varies
1721 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001722 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001723 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001724 verify(-1 not in d1)
1725 for i in range(10):
1726 verify(i in d1)
1727 verify(10 not in d1)
1728 # Test overridden behavior for static classes
1729 class Proxy(object):
1730 def __init__(self, x):
1731 self.x = x
1732 def __nonzero__(self):
1733 return not not self.x
1734 def __hash__(self):
1735 return hash(self.x)
1736 def __eq__(self, other):
1737 return self.x == other
1738 def __ne__(self, other):
1739 return self.x != other
1740 def __cmp__(self, other):
1741 return cmp(self.x, other.x)
1742 def __str__(self):
1743 return "Proxy:%s" % self.x
1744 def __repr__(self):
1745 return "Proxy(%r)" % self.x
1746 def __contains__(self, value):
1747 return value in self.x
1748 p0 = Proxy(0)
1749 p1 = Proxy(1)
1750 p_1 = Proxy(-1)
1751 verify(not p0)
1752 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001753 vereq(hash(p0), hash(0))
1754 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001755 verify(p0 != p1)
1756 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001757 vereq(not p0, p1)
1758 vereq(cmp(p0, p1), -1)
1759 vereq(cmp(p0, p0), 0)
1760 vereq(cmp(p0, p_1), 1)
1761 vereq(str(p0), "Proxy:0")
1762 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001763 p10 = Proxy(range(10))
1764 verify(-1 not in p10)
1765 for i in range(10):
1766 verify(i in p10)
1767 verify(10 not in p10)
1768 # Test overridden behavior for dynamic classes
1769 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001770 def __init__(self, x):
1771 self.x = x
1772 def __nonzero__(self):
1773 return not not self.x
1774 def __hash__(self):
1775 return hash(self.x)
1776 def __eq__(self, other):
1777 return self.x == other
1778 def __ne__(self, other):
1779 return self.x != other
1780 def __cmp__(self, other):
1781 return cmp(self.x, other.x)
1782 def __str__(self):
1783 return "DProxy:%s" % self.x
1784 def __repr__(self):
1785 return "DProxy(%r)" % self.x
1786 def __contains__(self, value):
1787 return value in self.x
1788 p0 = DProxy(0)
1789 p1 = DProxy(1)
1790 p_1 = DProxy(-1)
1791 verify(not p0)
1792 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001793 vereq(hash(p0), hash(0))
1794 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001795 verify(p0 != p1)
1796 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001797 vereq(not p0, p1)
1798 vereq(cmp(p0, p1), -1)
1799 vereq(cmp(p0, p0), 0)
1800 vereq(cmp(p0, p_1), 1)
1801 vereq(str(p0), "DProxy:0")
1802 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001803 p10 = DProxy(range(10))
1804 verify(-1 not in p10)
1805 for i in range(10):
1806 verify(i in p10)
1807 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001808 # Safety test for __cmp__
1809 def unsafecmp(a, b):
1810 try:
1811 a.__class__.__cmp__(a, b)
1812 except TypeError:
1813 pass
1814 else:
1815 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1816 a.__class__, a, b)
1817 unsafecmp(u"123", "123")
1818 unsafecmp("123", u"123")
1819 unsafecmp(1, 1.0)
1820 unsafecmp(1.0, 1)
1821 unsafecmp(1, 1L)
1822 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001823
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001824def weakrefs():
1825 if verbose: print "Testing weak references..."
1826 import weakref
1827 class C(object):
1828 pass
1829 c = C()
1830 r = weakref.ref(c)
1831 verify(r() is c)
1832 del c
1833 verify(r() is None)
1834 del r
1835 class NoWeak(object):
1836 __slots__ = ['foo']
1837 no = NoWeak()
1838 try:
1839 weakref.ref(no)
1840 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001841 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001842 else:
1843 verify(0, "weakref.ref(no) should be illegal")
1844 class Weak(object):
1845 __slots__ = ['foo', '__weakref__']
1846 yes = Weak()
1847 r = weakref.ref(yes)
1848 verify(r() is yes)
1849 del yes
1850 verify(r() is None)
1851 del r
1852
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001853def properties():
1854 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001855 class C(object):
1856 def getx(self):
1857 return self.__x
1858 def setx(self, value):
1859 self.__x = value
1860 def delx(self):
1861 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001862 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001863 a = C()
1864 verify(not hasattr(a, "x"))
1865 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001866 vereq(a._C__x, 42)
1867 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001868 del a.x
1869 verify(not hasattr(a, "x"))
1870 verify(not hasattr(a, "_C__x"))
1871 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001872 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001873 C.x.__delete__(a)
1874 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001875
Tim Peters66c1a522001-09-24 21:17:50 +00001876 raw = C.__dict__['x']
1877 verify(isinstance(raw, property))
1878
1879 attrs = dir(raw)
1880 verify("__doc__" in attrs)
1881 verify("fget" in attrs)
1882 verify("fset" in attrs)
1883 verify("fdel" in attrs)
1884
Guido van Rossum45704552001-10-08 16:35:45 +00001885 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001886 verify(raw.fget is C.__dict__['getx'])
1887 verify(raw.fset is C.__dict__['setx'])
1888 verify(raw.fdel is C.__dict__['delx'])
1889
1890 for attr in "__doc__", "fget", "fset", "fdel":
1891 try:
1892 setattr(raw, attr, 42)
1893 except TypeError, msg:
1894 if str(msg).find('readonly') < 0:
1895 raise TestFailed("when setting readonly attr %r on a "
1896 "property, got unexpected TypeError "
1897 "msg %r" % (attr, str(msg)))
1898 else:
1899 raise TestFailed("expected TypeError from trying to set "
1900 "readonly %r attr on a property" % attr)
1901
Neal Norwitz673cd822002-10-18 16:33:13 +00001902 class D(object):
1903 __getitem__ = property(lambda s: 1/0)
1904
1905 d = D()
1906 try:
1907 for i in d:
1908 str(i)
1909 except ZeroDivisionError:
1910 pass
1911 else:
1912 raise TestFailed, "expected ZeroDivisionError from bad property"
1913
Guido van Rossumc4a18802001-08-24 16:55:27 +00001914def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001915 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001916
1917 class A(object):
1918 def meth(self, a):
1919 return "A(%r)" % a
1920
Guido van Rossum45704552001-10-08 16:35:45 +00001921 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001922
1923 class B(A):
1924 def __init__(self):
1925 self.__super = super(B, self)
1926 def meth(self, a):
1927 return "B(%r)" % a + self.__super.meth(a)
1928
Guido van Rossum45704552001-10-08 16:35:45 +00001929 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001930
1931 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00001932 def meth(self, a):
1933 return "C(%r)" % a + self.__super.meth(a)
1934 C._C__super = super(C)
1935
Guido van Rossum45704552001-10-08 16:35:45 +00001936 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001937
1938 class D(C, B):
1939 def meth(self, a):
1940 return "D(%r)" % a + super(D, self).meth(a)
1941
Guido van Rossum5b443c62001-12-03 15:38:28 +00001942 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1943
1944 # Test for subclassing super
1945
1946 class mysuper(super):
1947 def __init__(self, *args):
1948 return super(mysuper, self).__init__(*args)
1949
1950 class E(D):
1951 def meth(self, a):
1952 return "E(%r)" % a + mysuper(E, self).meth(a)
1953
1954 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1955
1956 class F(E):
1957 def meth(self, a):
1958 s = self.__super
1959 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1960 F._F__super = mysuper(F)
1961
1962 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1963
1964 # Make sure certain errors are raised
1965
1966 try:
1967 super(D, 42)
1968 except TypeError:
1969 pass
1970 else:
1971 raise TestFailed, "shouldn't allow super(D, 42)"
1972
1973 try:
1974 super(D, C())
1975 except TypeError:
1976 pass
1977 else:
1978 raise TestFailed, "shouldn't allow super(D, C())"
1979
1980 try:
1981 super(D).__get__(12)
1982 except TypeError:
1983 pass
1984 else:
1985 raise TestFailed, "shouldn't allow super(D).__get__(12)"
1986
1987 try:
1988 super(D).__get__(C())
1989 except TypeError:
1990 pass
1991 else:
1992 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00001993
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001994def inherits():
1995 if verbose: print "Testing inheritance from basic types..."
1996
1997 class hexint(int):
1998 def __repr__(self):
1999 return hex(self)
2000 def __add__(self, other):
2001 return hexint(int.__add__(self, other))
2002 # (Note that overriding __radd__ doesn't work,
2003 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002004 vereq(repr(hexint(7) + 9), "0x10")
2005 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002006 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002007 vereq(a, 12345)
2008 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002009 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002010 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002011 verify((+a).__class__ is int)
2012 verify((a >> 0).__class__ is int)
2013 verify((a << 0).__class__ is int)
2014 verify((hexint(0) << 12).__class__ is int)
2015 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002016
2017 class octlong(long):
2018 __slots__ = []
2019 def __str__(self):
2020 s = oct(self)
2021 if s[-1] == 'L':
2022 s = s[:-1]
2023 return s
2024 def __add__(self, other):
2025 return self.__class__(super(octlong, self).__add__(other))
2026 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002027 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002028 # (Note that overriding __radd__ here only seems to work
2029 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002030 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002031 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002032 vereq(a, 12345L)
2033 vereq(long(a), 12345L)
2034 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002035 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002036 verify((+a).__class__ is long)
2037 verify((-a).__class__ is long)
2038 verify((-octlong(0)).__class__ is long)
2039 verify((a >> 0).__class__ is long)
2040 verify((a << 0).__class__ is long)
2041 verify((a - 0).__class__ is long)
2042 verify((a * 1).__class__ is long)
2043 verify((a ** 1).__class__ is long)
2044 verify((a // 1).__class__ is long)
2045 verify((1 * a).__class__ is long)
2046 verify((a | 0).__class__ is long)
2047 verify((a ^ 0).__class__ is long)
2048 verify((a & -1L).__class__ is long)
2049 verify((octlong(0) << 12).__class__ is long)
2050 verify((octlong(0) >> 12).__class__ is long)
2051 verify(abs(octlong(0)).__class__ is long)
2052
2053 # Because octlong overrides __add__, we can't check the absence of +0
2054 # optimizations using octlong.
2055 class longclone(long):
2056 pass
2057 a = longclone(1)
2058 verify((a + 0).__class__ is long)
2059 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002060
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002061 # Check that negative clones don't segfault
2062 a = longclone(-1)
2063 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002064 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002065
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002066 class precfloat(float):
2067 __slots__ = ['prec']
2068 def __init__(self, value=0.0, prec=12):
2069 self.prec = int(prec)
2070 float.__init__(value)
2071 def __repr__(self):
2072 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002073 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002074 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002075 vereq(a, 12345.0)
2076 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002077 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002078 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002079 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002080
Tim Peters2400fa42001-09-12 19:12:49 +00002081 class madcomplex(complex):
2082 def __repr__(self):
2083 return "%.17gj%+.17g" % (self.imag, self.real)
2084 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002085 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002086 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002087 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002088 vereq(a, base)
2089 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002090 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002091 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002092 vereq(repr(a), "4j-3")
2093 vereq(a, base)
2094 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002095 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002096 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002097 veris((+a).__class__, complex)
2098 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002099 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002100 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002101 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002102 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002103 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002104 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002105 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002106
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002107 class madtuple(tuple):
2108 _rev = None
2109 def rev(self):
2110 if self._rev is not None:
2111 return self._rev
2112 L = list(self)
2113 L.reverse()
2114 self._rev = self.__class__(L)
2115 return self._rev
2116 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002117 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2118 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2119 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002120 for i in range(512):
2121 t = madtuple(range(i))
2122 u = t.rev()
2123 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002124 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002125 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002126 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002127 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002128 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002129 verify(a[:].__class__ is tuple)
2130 verify((a * 1).__class__ is tuple)
2131 verify((a * 0).__class__ is tuple)
2132 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002133 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002134 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002135 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002136 verify((a + a).__class__ is tuple)
2137 verify((a * 0).__class__ is tuple)
2138 verify((a * 1).__class__ is tuple)
2139 verify((a * 2).__class__ is tuple)
2140 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002141
2142 class madstring(str):
2143 _rev = None
2144 def rev(self):
2145 if self._rev is not None:
2146 return self._rev
2147 L = list(self)
2148 L.reverse()
2149 self._rev = self.__class__("".join(L))
2150 return self._rev
2151 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002152 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2153 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2154 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002155 for i in range(256):
2156 s = madstring("".join(map(chr, range(i))))
2157 t = s.rev()
2158 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002159 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002160 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002161 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002162 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002163
Tim Peters8fa5dd02001-09-12 02:18:30 +00002164 base = "\x00" * 5
2165 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002166 vereq(s, base)
2167 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002168 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002169 vereq(hash(s), hash(base))
2170 vereq({s: 1}[base], 1)
2171 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002172 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002173 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002174 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002175 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002176 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002177 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002178 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002179 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002180 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002181 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002182 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002183 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002184 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002185 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002186 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002187 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002188 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002189 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002190 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002191 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002192 identitytab = ''.join([chr(i) for i in range(256)])
2193 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002194 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002195 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002196 vereq(s.translate(identitytab, "x"), base)
2197 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002198 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002199 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002200 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002201 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002202 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002203 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002204 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002205 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002206 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002207 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002208
Tim Peters111f6092001-09-12 07:54:51 +00002209 s = madstring("x y")
Guido van Rossum45704552001-10-08 16:35:45 +00002210 vereq(s, "x y")
Tim Peters111f6092001-09-12 07:54:51 +00002211 verify(intern(s).__class__ is str)
2212 verify(intern(s) is intern("x y"))
Guido van Rossum45704552001-10-08 16:35:45 +00002213 vereq(intern(s), "x y")
Tim Peters111f6092001-09-12 07:54:51 +00002214
2215 i = intern("y x")
2216 s = madstring("y x")
Guido van Rossum45704552001-10-08 16:35:45 +00002217 vereq(s, i)
Tim Peters111f6092001-09-12 07:54:51 +00002218 verify(intern(s).__class__ is str)
2219 verify(intern(s) is i)
2220
2221 s = madstring(i)
2222 verify(intern(s).__class__ is str)
2223 verify(intern(s) is i)
2224
Guido van Rossum91ee7982001-08-30 20:52:40 +00002225 class madunicode(unicode):
2226 _rev = None
2227 def rev(self):
2228 if self._rev is not None:
2229 return self._rev
2230 L = list(self)
2231 L.reverse()
2232 self._rev = self.__class__(u"".join(L))
2233 return self._rev
2234 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002235 vereq(u, u"ABCDEF")
2236 vereq(u.rev(), madunicode(u"FEDCBA"))
2237 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002238 base = u"12345"
2239 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002240 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002241 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002242 vereq(hash(u), hash(base))
2243 vereq({u: 1}[base], 1)
2244 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002245 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002246 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002247 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002248 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002249 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002250 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002251 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002252 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002253 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002254 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002255 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002256 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002257 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002258 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002259 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002260 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002261 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002262 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002263 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002264 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002265 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002266 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002267 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002268 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002269 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002270 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002271 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002272 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002273 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002274 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002275 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002276 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002277 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002278 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002279 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002280 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002281 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002282 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002283
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002284 class sublist(list):
2285 pass
2286 a = sublist(range(5))
2287 vereq(a, range(5))
2288 a.append("hello")
2289 vereq(a, range(5) + ["hello"])
2290 a[5] = 5
2291 vereq(a, range(6))
2292 a.extend(range(6, 20))
2293 vereq(a, range(20))
2294 a[-5:] = []
2295 vereq(a, range(15))
2296 del a[10:15]
2297 vereq(len(a), 10)
2298 vereq(a, range(10))
2299 vereq(list(a), range(10))
2300 vereq(a[0], 0)
2301 vereq(a[9], 9)
2302 vereq(a[-10], 0)
2303 vereq(a[-1], 9)
2304 vereq(a[:5], range(5))
2305
Tim Peters59c9a642001-09-13 05:38:56 +00002306 class CountedInput(file):
2307 """Counts lines read by self.readline().
2308
2309 self.lineno is the 0-based ordinal of the last line read, up to
2310 a maximum of one greater than the number of lines in the file.
2311
2312 self.ateof is true if and only if the final "" line has been read,
2313 at which point self.lineno stops incrementing, and further calls
2314 to readline() continue to return "".
2315 """
2316
2317 lineno = 0
2318 ateof = 0
2319 def readline(self):
2320 if self.ateof:
2321 return ""
2322 s = file.readline(self)
2323 # Next line works too.
2324 # s = super(CountedInput, self).readline()
2325 self.lineno += 1
2326 if s == "":
2327 self.ateof = 1
2328 return s
2329
Tim Peters561f8992001-09-13 19:36:36 +00002330 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002331 lines = ['a\n', 'b\n', 'c\n']
2332 try:
2333 f.writelines(lines)
2334 f.close()
2335 f = CountedInput(TESTFN)
2336 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2337 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002338 vereq(expected, got)
2339 vereq(f.lineno, i)
2340 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002341 f.close()
2342 finally:
2343 try:
2344 f.close()
2345 except:
2346 pass
2347 try:
2348 import os
2349 os.unlink(TESTFN)
2350 except:
2351 pass
2352
Tim Peters808b94e2001-09-13 19:33:07 +00002353def keywords():
2354 if verbose:
2355 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002356 vereq(int(x=1), 1)
2357 vereq(float(x=2), 2.0)
2358 vereq(long(x=3), 3L)
2359 vereq(complex(imag=42, real=666), complex(666, 42))
2360 vereq(str(object=500), '500')
2361 vereq(unicode(string='abc', errors='strict'), u'abc')
2362 vereq(tuple(sequence=range(3)), (0, 1, 2))
2363 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002364 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002365
2366 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002367 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002368 try:
2369 constructor(bogus_keyword_arg=1)
2370 except TypeError:
2371 pass
2372 else:
2373 raise TestFailed("expected TypeError from bogus keyword "
2374 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002375
Tim Peters8fa45672001-09-13 21:01:29 +00002376def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002377 # XXX This test is disabled because rexec is not deemed safe
2378 return
Tim Peters8fa45672001-09-13 21:01:29 +00002379 import rexec
2380 if verbose:
2381 print "Testing interaction with restricted execution ..."
2382
2383 sandbox = rexec.RExec()
2384
2385 code1 = """f = open(%r, 'w')""" % TESTFN
2386 code2 = """f = file(%r, 'w')""" % TESTFN
2387 code3 = """\
2388f = open(%r)
2389t = type(f) # a sneaky way to get the file() constructor
2390f.close()
2391f = t(%r, 'w') # rexec can't catch this by itself
2392""" % (TESTFN, TESTFN)
2393
2394 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2395 f.close()
2396
2397 try:
2398 for code in code1, code2, code3:
2399 try:
2400 sandbox.r_exec(code)
2401 except IOError, msg:
2402 if str(msg).find("restricted") >= 0:
2403 outcome = "OK"
2404 else:
2405 outcome = "got an exception, but not an expected one"
2406 else:
2407 outcome = "expected a restricted-execution exception"
2408
2409 if outcome != "OK":
2410 raise TestFailed("%s, in %r" % (outcome, code))
2411
2412 finally:
2413 try:
2414 import os
2415 os.unlink(TESTFN)
2416 except:
2417 pass
2418
Tim Peters0ab085c2001-09-14 00:25:33 +00002419def str_subclass_as_dict_key():
2420 if verbose:
2421 print "Testing a str subclass used as dict key .."
2422
2423 class cistr(str):
2424 """Sublcass of str that computes __eq__ case-insensitively.
2425
2426 Also computes a hash code of the string in canonical form.
2427 """
2428
2429 def __init__(self, value):
2430 self.canonical = value.lower()
2431 self.hashcode = hash(self.canonical)
2432
2433 def __eq__(self, other):
2434 if not isinstance(other, cistr):
2435 other = cistr(other)
2436 return self.canonical == other.canonical
2437
2438 def __hash__(self):
2439 return self.hashcode
2440
Guido van Rossum45704552001-10-08 16:35:45 +00002441 vereq(cistr('ABC'), 'abc')
2442 vereq('aBc', cistr('ABC'))
2443 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002444
2445 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002446 vereq(d[cistr('one')], 1)
2447 vereq(d[cistr('tWo')], 2)
2448 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002449 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002450 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002451
Guido van Rossumab3b0342001-09-18 20:38:53 +00002452def classic_comparisons():
2453 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002454 class classic:
2455 pass
2456 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002457 if verbose: print " (base = %s)" % base
2458 class C(base):
2459 def __init__(self, value):
2460 self.value = int(value)
2461 def __cmp__(self, other):
2462 if isinstance(other, C):
2463 return cmp(self.value, other.value)
2464 if isinstance(other, int) or isinstance(other, long):
2465 return cmp(self.value, other)
2466 return NotImplemented
2467 c1 = C(1)
2468 c2 = C(2)
2469 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002470 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002471 c = {1: c1, 2: c2, 3: c3}
2472 for x in 1, 2, 3:
2473 for y in 1, 2, 3:
2474 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2475 for op in "<", "<=", "==", "!=", ">", ">=":
2476 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2477 "x=%d, y=%d" % (x, y))
2478 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2479 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2480
Guido van Rossum0639f592001-09-18 21:06:04 +00002481def rich_comparisons():
2482 if verbose:
2483 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002484 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002485 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002486 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002487 vereq(z, 1+0j)
2488 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002489 class ZZ(complex):
2490 def __eq__(self, other):
2491 try:
2492 return abs(self - other) <= 1e-6
2493 except:
2494 return NotImplemented
2495 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002496 vereq(zz, 1+0j)
2497 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002498
Guido van Rossum0639f592001-09-18 21:06:04 +00002499 class classic:
2500 pass
2501 for base in (classic, int, object, list):
2502 if verbose: print " (base = %s)" % base
2503 class C(base):
2504 def __init__(self, value):
2505 self.value = int(value)
2506 def __cmp__(self, other):
2507 raise TestFailed, "shouldn't call __cmp__"
2508 def __eq__(self, other):
2509 if isinstance(other, C):
2510 return self.value == other.value
2511 if isinstance(other, int) or isinstance(other, long):
2512 return self.value == other
2513 return NotImplemented
2514 def __ne__(self, other):
2515 if isinstance(other, C):
2516 return self.value != other.value
2517 if isinstance(other, int) or isinstance(other, long):
2518 return self.value != other
2519 return NotImplemented
2520 def __lt__(self, other):
2521 if isinstance(other, C):
2522 return self.value < other.value
2523 if isinstance(other, int) or isinstance(other, long):
2524 return self.value < other
2525 return NotImplemented
2526 def __le__(self, other):
2527 if isinstance(other, C):
2528 return self.value <= other.value
2529 if isinstance(other, int) or isinstance(other, long):
2530 return self.value <= other
2531 return NotImplemented
2532 def __gt__(self, other):
2533 if isinstance(other, C):
2534 return self.value > other.value
2535 if isinstance(other, int) or isinstance(other, long):
2536 return self.value > other
2537 return NotImplemented
2538 def __ge__(self, other):
2539 if isinstance(other, C):
2540 return self.value >= other.value
2541 if isinstance(other, int) or isinstance(other, long):
2542 return self.value >= other
2543 return NotImplemented
2544 c1 = C(1)
2545 c2 = C(2)
2546 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002547 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002548 c = {1: c1, 2: c2, 3: c3}
2549 for x in 1, 2, 3:
2550 for y in 1, 2, 3:
2551 for op in "<", "<=", "==", "!=", ">", ">=":
2552 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2553 "x=%d, y=%d" % (x, y))
2554 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2555 "x=%d, y=%d" % (x, y))
2556 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2557 "x=%d, y=%d" % (x, y))
2558
Guido van Rossum1952e382001-09-19 01:25:16 +00002559def coercions():
2560 if verbose: print "Testing coercions..."
2561 class I(int): pass
2562 coerce(I(0), 0)
2563 coerce(0, I(0))
2564 class L(long): pass
2565 coerce(L(0), 0)
2566 coerce(L(0), 0L)
2567 coerce(0, L(0))
2568 coerce(0L, L(0))
2569 class F(float): pass
2570 coerce(F(0), 0)
2571 coerce(F(0), 0L)
2572 coerce(F(0), 0.)
2573 coerce(0, F(0))
2574 coerce(0L, F(0))
2575 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002576 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002577 coerce(C(0), 0)
2578 coerce(C(0), 0L)
2579 coerce(C(0), 0.)
2580 coerce(C(0), 0j)
2581 coerce(0, C(0))
2582 coerce(0L, C(0))
2583 coerce(0., C(0))
2584 coerce(0j, C(0))
2585
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002586def descrdoc():
2587 if verbose: print "Testing descriptor doc strings..."
2588 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002589 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002590 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002591 check(file.name, "file name") # member descriptor
2592
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002593def setclass():
2594 if verbose: print "Testing __class__ assignment..."
2595 class C(object): pass
2596 class D(object): pass
2597 class E(object): pass
2598 class F(D, E): pass
2599 for cls in C, D, E, F:
2600 for cls2 in C, D, E, F:
2601 x = cls()
2602 x.__class__ = cls2
2603 verify(x.__class__ is cls2)
2604 x.__class__ = cls
2605 verify(x.__class__ is cls)
2606 def cant(x, C):
2607 try:
2608 x.__class__ = C
2609 except TypeError:
2610 pass
2611 else:
2612 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002613 try:
2614 delattr(x, "__class__")
2615 except TypeError:
2616 pass
2617 else:
2618 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002619 cant(C(), list)
2620 cant(list(), C)
2621 cant(C(), 1)
2622 cant(C(), object)
2623 cant(object(), list)
2624 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002625 class Int(int): __slots__ = []
2626 cant(2, Int)
2627 cant(Int(), int)
2628 cant(True, int)
2629 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002630 o = object()
2631 cant(o, type(1))
2632 cant(o, type(None))
2633 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002634
Guido van Rossum6661be32001-10-26 04:26:12 +00002635def setdict():
2636 if verbose: print "Testing __dict__ assignment..."
2637 class C(object): pass
2638 a = C()
2639 a.__dict__ = {'b': 1}
2640 vereq(a.b, 1)
2641 def cant(x, dict):
2642 try:
2643 x.__dict__ = dict
2644 except TypeError:
2645 pass
2646 else:
2647 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2648 cant(a, None)
2649 cant(a, [])
2650 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002651 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002652 # Classes don't allow __dict__ assignment
2653 cant(C, {})
2654
Guido van Rossum3926a632001-09-25 16:25:58 +00002655def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002656 if verbose:
2657 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002658 import pickle, cPickle
2659
2660 def sorteditems(d):
2661 L = d.items()
2662 L.sort()
2663 return L
2664
2665 global C
2666 class C(object):
2667 def __init__(self, a, b):
2668 super(C, self).__init__()
2669 self.a = a
2670 self.b = b
2671 def __repr__(self):
2672 return "C(%r, %r)" % (self.a, self.b)
2673
2674 global C1
2675 class C1(list):
2676 def __new__(cls, a, b):
2677 return super(C1, cls).__new__(cls)
2678 def __init__(self, a, b):
2679 self.a = a
2680 self.b = b
2681 def __repr__(self):
2682 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2683
2684 global C2
2685 class C2(int):
2686 def __new__(cls, a, b, val=0):
2687 return super(C2, cls).__new__(cls, val)
2688 def __init__(self, a, b, val=0):
2689 self.a = a
2690 self.b = b
2691 def __repr__(self):
2692 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2693
Guido van Rossum90c45142001-11-24 21:07:01 +00002694 global C3
2695 class C3(object):
2696 def __init__(self, foo):
2697 self.foo = foo
2698 def __getstate__(self):
2699 return self.foo
2700 def __setstate__(self, foo):
2701 self.foo = foo
2702
2703 global C4classic, C4
2704 class C4classic: # classic
2705 pass
2706 class C4(C4classic, object): # mixed inheritance
2707 pass
2708
Guido van Rossum3926a632001-09-25 16:25:58 +00002709 for p in pickle, cPickle:
2710 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002711 if verbose:
2712 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002713
2714 for cls in C, C1, C2:
2715 s = p.dumps(cls, bin)
2716 cls2 = p.loads(s)
2717 verify(cls2 is cls)
2718
2719 a = C1(1, 2); a.append(42); a.append(24)
2720 b = C2("hello", "world", 42)
2721 s = p.dumps((a, b), bin)
2722 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002723 vereq(x.__class__, a.__class__)
2724 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2725 vereq(y.__class__, b.__class__)
2726 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2727 vereq(`x`, `a`)
2728 vereq(`y`, `b`)
Guido van Rossum3926a632001-09-25 16:25:58 +00002729 if verbose:
2730 print "a = x =", a
2731 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002732 # Test for __getstate__ and __setstate__ on new style class
2733 u = C3(42)
2734 s = p.dumps(u, bin)
2735 v = p.loads(s)
2736 veris(u.__class__, v.__class__)
2737 vereq(u.foo, v.foo)
2738 # Test for picklability of hybrid class
2739 u = C4()
2740 u.foo = 42
2741 s = p.dumps(u, bin)
2742 v = p.loads(s)
2743 veris(u.__class__, v.__class__)
2744 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002745
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002746 # Testing copy.deepcopy()
2747 if verbose:
2748 print "deepcopy"
2749 import copy
2750 for cls in C, C1, C2:
2751 cls2 = copy.deepcopy(cls)
2752 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002753
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002754 a = C1(1, 2); a.append(42); a.append(24)
2755 b = C2("hello", "world", 42)
2756 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002757 vereq(x.__class__, a.__class__)
2758 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2759 vereq(y.__class__, b.__class__)
2760 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2761 vereq(`x`, `a`)
2762 vereq(`y`, `b`)
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002763 if verbose:
2764 print "a = x =", a
2765 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002766
Guido van Rossum8c842552002-03-14 23:05:54 +00002767def pickleslots():
2768 if verbose: print "Testing pickling of classes with __slots__ ..."
2769 import pickle, cPickle
2770 # Pickling of classes with __slots__ but without __getstate__ should fail
2771 global B, C, D, E
2772 class B(object):
2773 pass
2774 for base in [object, B]:
2775 class C(base):
2776 __slots__ = ['a']
2777 class D(C):
2778 pass
2779 try:
2780 pickle.dumps(C())
2781 except TypeError:
2782 pass
2783 else:
2784 raise TestFailed, "should fail: pickle C instance - %s" % base
2785 try:
2786 cPickle.dumps(C())
2787 except TypeError:
2788 pass
2789 else:
2790 raise TestFailed, "should fail: cPickle C instance - %s" % base
2791 try:
2792 pickle.dumps(C())
2793 except TypeError:
2794 pass
2795 else:
2796 raise TestFailed, "should fail: pickle D instance - %s" % base
2797 try:
2798 cPickle.dumps(D())
2799 except TypeError:
2800 pass
2801 else:
2802 raise TestFailed, "should fail: cPickle D instance - %s" % base
2803 # Give C a __getstate__ and __setstate__
2804 class C(base):
2805 __slots__ = ['a']
2806 def __getstate__(self):
2807 try:
2808 d = self.__dict__.copy()
2809 except AttributeError:
2810 d = {}
2811 try:
2812 d['a'] = self.a
2813 except AttributeError:
2814 pass
2815 return d
2816 def __setstate__(self, d):
2817 for k, v in d.items():
2818 setattr(self, k, v)
2819 class D(C):
2820 pass
2821 # Now it should work
2822 x = C()
2823 y = pickle.loads(pickle.dumps(x))
2824 vereq(hasattr(y, 'a'), 0)
2825 y = cPickle.loads(cPickle.dumps(x))
2826 vereq(hasattr(y, 'a'), 0)
2827 x.a = 42
2828 y = pickle.loads(pickle.dumps(x))
2829 vereq(y.a, 42)
2830 y = cPickle.loads(cPickle.dumps(x))
2831 vereq(y.a, 42)
2832 x = D()
2833 x.a = 42
2834 x.b = 100
2835 y = pickle.loads(pickle.dumps(x))
2836 vereq(y.a + y.b, 142)
2837 y = cPickle.loads(cPickle.dumps(x))
2838 vereq(y.a + y.b, 142)
2839 # But a subclass that adds a slot should not work
2840 class E(C):
2841 __slots__ = ['b']
2842 try:
2843 pickle.dumps(E())
2844 except TypeError:
2845 pass
2846 else:
2847 raise TestFailed, "should fail: pickle E instance - %s" % base
2848 try:
2849 cPickle.dumps(E())
2850 except TypeError:
2851 pass
2852 else:
2853 raise TestFailed, "should fail: cPickle E instance - %s" % base
2854
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002855def copies():
2856 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2857 import copy
2858 class C(object):
2859 pass
2860
2861 a = C()
2862 a.foo = 12
2863 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002864 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002865
2866 a.bar = [1,2,3]
2867 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002868 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002869 verify(c.bar is a.bar)
2870
2871 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002872 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002873 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002874 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002875
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002876def binopoverride():
2877 if verbose: print "Testing overrides of binary operations..."
2878 class I(int):
2879 def __repr__(self):
2880 return "I(%r)" % int(self)
2881 def __add__(self, other):
2882 return I(int(self) + int(other))
2883 __radd__ = __add__
2884 def __pow__(self, other, mod=None):
2885 if mod is None:
2886 return I(pow(int(self), int(other)))
2887 else:
2888 return I(pow(int(self), int(other), int(mod)))
2889 def __rpow__(self, other, mod=None):
2890 if mod is None:
2891 return I(pow(int(other), int(self), mod))
2892 else:
2893 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00002894
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002895 vereq(`I(1) + I(2)`, "I(3)")
2896 vereq(`I(1) + 2`, "I(3)")
2897 vereq(`1 + I(2)`, "I(3)")
2898 vereq(`I(2) ** I(3)`, "I(8)")
2899 vereq(`2 ** I(3)`, "I(8)")
2900 vereq(`I(2) ** 3`, "I(8)")
2901 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2902 class S(str):
2903 def __eq__(self, other):
2904 return self.lower() == other.lower()
2905
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002906def subclasspropagation():
2907 if verbose: print "Testing propagation of slot functions to subclasses..."
2908 class A(object):
2909 pass
2910 class B(A):
2911 pass
2912 class C(A):
2913 pass
2914 class D(B, C):
2915 pass
2916 d = D()
2917 vereq(hash(d), id(d))
2918 A.__hash__ = lambda self: 42
2919 vereq(hash(d), 42)
2920 C.__hash__ = lambda self: 314
2921 vereq(hash(d), 314)
2922 B.__hash__ = lambda self: 144
2923 vereq(hash(d), 144)
2924 D.__hash__ = lambda self: 100
2925 vereq(hash(d), 100)
2926 del D.__hash__
2927 vereq(hash(d), 144)
2928 del B.__hash__
2929 vereq(hash(d), 314)
2930 del C.__hash__
2931 vereq(hash(d), 42)
2932 del A.__hash__
2933 vereq(hash(d), id(d))
2934 d.foo = 42
2935 d.bar = 42
2936 vereq(d.foo, 42)
2937 vereq(d.bar, 42)
2938 def __getattribute__(self, name):
2939 if name == "foo":
2940 return 24
2941 return object.__getattribute__(self, name)
2942 A.__getattribute__ = __getattribute__
2943 vereq(d.foo, 24)
2944 vereq(d.bar, 42)
2945 def __getattr__(self, name):
2946 if name in ("spam", "foo", "bar"):
2947 return "hello"
2948 raise AttributeError, name
2949 B.__getattr__ = __getattr__
2950 vereq(d.spam, "hello")
2951 vereq(d.foo, 24)
2952 vereq(d.bar, 42)
2953 del A.__getattribute__
2954 vereq(d.foo, 42)
2955 del d.foo
2956 vereq(d.foo, "hello")
2957 vereq(d.bar, 42)
2958 del B.__getattr__
2959 try:
2960 d.foo
2961 except AttributeError:
2962 pass
2963 else:
2964 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00002965
Guido van Rossume7f3e242002-06-14 02:35:45 +00002966 # Test a nasty bug in recurse_down_subclasses()
2967 import gc
2968 class A(object):
2969 pass
2970 class B(A):
2971 pass
2972 del B
2973 gc.collect()
2974 A.__setitem__ = lambda *a: None # crash
2975
Tim Petersfc57ccb2001-10-12 02:38:24 +00002976def buffer_inherit():
2977 import binascii
2978 # SF bug [#470040] ParseTuple t# vs subclasses.
2979 if verbose:
2980 print "Testing that buffer interface is inherited ..."
2981
2982 class MyStr(str):
2983 pass
2984 base = 'abc'
2985 m = MyStr(base)
2986 # b2a_hex uses the buffer interface to get its argument's value, via
2987 # PyArg_ParseTuple 't#' code.
2988 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2989
2990 # It's not clear that unicode will continue to support the character
2991 # buffer interface, and this test will fail if that's taken away.
2992 class MyUni(unicode):
2993 pass
2994 base = u'abc'
2995 m = MyUni(base)
2996 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2997
2998 class MyInt(int):
2999 pass
3000 m = MyInt(42)
3001 try:
3002 binascii.b2a_hex(m)
3003 raise TestFailed('subclass of int should not have a buffer interface')
3004 except TypeError:
3005 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003006
Tim Petersc9933152001-10-16 20:18:24 +00003007def str_of_str_subclass():
3008 import binascii
3009 import cStringIO
3010
3011 if verbose:
3012 print "Testing __str__ defined in subclass of str ..."
3013
3014 class octetstring(str):
3015 def __str__(self):
3016 return binascii.b2a_hex(self)
3017 def __repr__(self):
3018 return self + " repr"
3019
3020 o = octetstring('A')
3021 vereq(type(o), octetstring)
3022 vereq(type(str(o)), str)
3023 vereq(type(repr(o)), str)
3024 vereq(ord(o), 0x41)
3025 vereq(str(o), '41')
3026 vereq(repr(o), 'A repr')
3027 vereq(o.__str__(), '41')
3028 vereq(o.__repr__(), 'A repr')
3029
3030 capture = cStringIO.StringIO()
3031 # Calling str() or not exercises different internal paths.
3032 print >> capture, o
3033 print >> capture, str(o)
3034 vereq(capture.getvalue(), '41\n41\n')
3035 capture.close()
3036
Guido van Rossumc8e56452001-10-22 00:43:43 +00003037def kwdargs():
3038 if verbose: print "Testing keyword arguments to __init__, __call__..."
3039 def f(a): return a
3040 vereq(f.__call__(a=42), 42)
3041 a = []
3042 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003043 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003044
Guido van Rossumed87ad82001-10-30 02:33:02 +00003045def delhook():
3046 if verbose: print "Testing __del__ hook..."
3047 log = []
3048 class C(object):
3049 def __del__(self):
3050 log.append(1)
3051 c = C()
3052 vereq(log, [])
3053 del c
3054 vereq(log, [1])
3055
Guido van Rossum29d26062001-12-11 04:37:34 +00003056 class D(object): pass
3057 d = D()
3058 try: del d[0]
3059 except TypeError: pass
3060 else: raise TestFailed, "invalid del() didn't raise TypeError"
3061
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003062def hashinherit():
3063 if verbose: print "Testing hash of mutable subclasses..."
3064
3065 class mydict(dict):
3066 pass
3067 d = mydict()
3068 try:
3069 hash(d)
3070 except TypeError:
3071 pass
3072 else:
3073 raise TestFailed, "hash() of dict subclass should fail"
3074
3075 class mylist(list):
3076 pass
3077 d = mylist()
3078 try:
3079 hash(d)
3080 except TypeError:
3081 pass
3082 else:
3083 raise TestFailed, "hash() of list subclass should fail"
3084
Guido van Rossum29d26062001-12-11 04:37:34 +00003085def strops():
3086 try: 'a' + 5
3087 except TypeError: pass
3088 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3089
3090 try: ''.split('')
3091 except ValueError: pass
3092 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3093
3094 try: ''.join([0])
3095 except TypeError: pass
3096 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3097
3098 try: ''.rindex('5')
3099 except ValueError: pass
3100 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3101
Guido van Rossum29d26062001-12-11 04:37:34 +00003102 try: '%(n)s' % None
3103 except TypeError: pass
3104 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3105
3106 try: '%(n' % {}
3107 except ValueError: pass
3108 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3109
3110 try: '%*s' % ('abc')
3111 except TypeError: pass
3112 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3113
3114 try: '%*.*s' % ('abc', 5)
3115 except TypeError: pass
3116 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3117
3118 try: '%s' % (1, 2)
3119 except TypeError: pass
3120 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3121
3122 try: '%' % None
3123 except ValueError: pass
3124 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3125
3126 vereq('534253'.isdigit(), 1)
3127 vereq('534253x'.isdigit(), 0)
3128 vereq('%c' % 5, '\x05')
3129 vereq('%c' % '5', '5')
3130
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003131def deepcopyrecursive():
3132 if verbose: print "Testing deepcopy of recursive objects..."
3133 class Node:
3134 pass
3135 a = Node()
3136 b = Node()
3137 a.b = b
3138 b.a = a
3139 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003140
Guido van Rossumd7035672002-03-12 20:43:31 +00003141def modules():
3142 if verbose: print "Testing uninitialized module objects..."
3143 from types import ModuleType as M
3144 m = M.__new__(M)
3145 str(m)
3146 vereq(hasattr(m, "__name__"), 0)
3147 vereq(hasattr(m, "__file__"), 0)
3148 vereq(hasattr(m, "foo"), 0)
3149 vereq(m.__dict__, None)
3150 m.foo = 1
3151 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003152
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003153def dictproxyiterkeys():
3154 class C(object):
3155 def meth(self):
3156 pass
3157 if verbose: print "Testing dict-proxy iterkeys..."
3158 keys = [ key for key in C.__dict__.iterkeys() ]
3159 keys.sort()
3160 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3161
3162def dictproxyitervalues():
3163 class C(object):
3164 def meth(self):
3165 pass
3166 if verbose: print "Testing dict-proxy itervalues..."
3167 values = [ values for values in C.__dict__.itervalues() ]
3168 vereq(len(values), 5)
3169
3170def dictproxyiteritems():
3171 class C(object):
3172 def meth(self):
3173 pass
3174 if verbose: print "Testing dict-proxy iteritems..."
3175 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3176 keys.sort()
3177 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3178
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003179def funnynew():
3180 if verbose: print "Testing __new__ returning something unexpected..."
3181 class C(object):
3182 def __new__(cls, arg):
3183 if isinstance(arg, str): return [1, 2, 3]
3184 elif isinstance(arg, int): return object.__new__(D)
3185 else: return object.__new__(cls)
3186 class D(C):
3187 def __init__(self, arg):
3188 self.foo = arg
3189 vereq(C("1"), [1, 2, 3])
3190 vereq(D("1"), [1, 2, 3])
3191 d = D(None)
3192 veris(d.foo, None)
3193 d = C(1)
3194 vereq(isinstance(d, D), True)
3195 vereq(d.foo, 1)
3196 d = D(1)
3197 vereq(isinstance(d, D), True)
3198 vereq(d.foo, 1)
3199
Guido van Rossume8fc6402002-04-16 16:44:51 +00003200def imulbug():
3201 # SF bug 544647
3202 if verbose: print "Testing for __imul__ problems..."
3203 class C(object):
3204 def __imul__(self, other):
3205 return (self, other)
3206 x = C()
3207 y = x
3208 y *= 1.0
3209 vereq(y, (x, 1.0))
3210 y = x
3211 y *= 2
3212 vereq(y, (x, 2))
3213 y = x
3214 y *= 3L
3215 vereq(y, (x, 3L))
3216 y = x
3217 y *= 1L<<100
3218 vereq(y, (x, 1L<<100))
3219 y = x
3220 y *= None
3221 vereq(y, (x, None))
3222 y = x
3223 y *= "foo"
3224 vereq(y, (x, "foo"))
3225
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003226def docdescriptor():
3227 # SF bug 542984
3228 if verbose: print "Testing __doc__ descriptor..."
3229 class DocDescr(object):
3230 def __get__(self, object, otype):
3231 if object:
3232 object = object.__class__.__name__ + ' instance'
3233 if otype:
3234 otype = otype.__name__
3235 return 'object=%s; type=%s' % (object, otype)
3236 class OldClass:
3237 __doc__ = DocDescr()
3238 class NewClass(object):
3239 __doc__ = DocDescr()
3240 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3241 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3242 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3243 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3244
Tim Petersafb2c802002-04-18 18:06:20 +00003245def string_exceptions():
3246 if verbose:
3247 print "Testing string exceptions ..."
3248
3249 # Ensure builtin strings work OK as exceptions.
3250 astring = "An exception string."
3251 try:
3252 raise astring
3253 except astring:
3254 pass
3255 else:
3256 raise TestFailed, "builtin string not usable as exception"
3257
3258 # Ensure string subclass instances do not.
3259 class MyStr(str):
3260 pass
3261
3262 newstring = MyStr("oops -- shouldn't work")
3263 try:
3264 raise newstring
3265 except TypeError:
3266 pass
3267 except:
3268 raise TestFailed, "string subclass allowed as exception"
3269
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003270def copy_setstate():
3271 if verbose:
3272 print "Testing that copy.*copy() correctly uses __setstate__..."
3273 import copy
3274 class C(object):
3275 def __init__(self, foo=None):
3276 self.foo = foo
3277 self.__foo = foo
3278 def setfoo(self, foo=None):
3279 self.foo = foo
3280 def getfoo(self):
3281 return self.__foo
3282 def __getstate__(self):
3283 return [self.foo]
3284 def __setstate__(self, lst):
3285 assert len(lst) == 1
3286 self.__foo = self.foo = lst[0]
3287 a = C(42)
3288 a.setfoo(24)
3289 vereq(a.foo, 24)
3290 vereq(a.getfoo(), 42)
3291 b = copy.copy(a)
3292 vereq(b.foo, 24)
3293 vereq(b.getfoo(), 24)
3294 b = copy.deepcopy(a)
3295 vereq(b.foo, 24)
3296 vereq(b.getfoo(), 24)
3297
Guido van Rossum09638c12002-06-13 19:17:46 +00003298def slices():
3299 if verbose:
3300 print "Testing cases with slices and overridden __getitem__ ..."
3301 # Strings
3302 vereq("hello"[:4], "hell")
3303 vereq("hello"[slice(4)], "hell")
3304 vereq(str.__getitem__("hello", slice(4)), "hell")
3305 class S(str):
3306 def __getitem__(self, x):
3307 return str.__getitem__(self, x)
3308 vereq(S("hello")[:4], "hell")
3309 vereq(S("hello")[slice(4)], "hell")
3310 vereq(S("hello").__getitem__(slice(4)), "hell")
3311 # Tuples
3312 vereq((1,2,3)[:2], (1,2))
3313 vereq((1,2,3)[slice(2)], (1,2))
3314 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3315 class T(tuple):
3316 def __getitem__(self, x):
3317 return tuple.__getitem__(self, x)
3318 vereq(T((1,2,3))[:2], (1,2))
3319 vereq(T((1,2,3))[slice(2)], (1,2))
3320 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3321 # Lists
3322 vereq([1,2,3][:2], [1,2])
3323 vereq([1,2,3][slice(2)], [1,2])
3324 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3325 class L(list):
3326 def __getitem__(self, x):
3327 return list.__getitem__(self, x)
3328 vereq(L([1,2,3])[:2], [1,2])
3329 vereq(L([1,2,3])[slice(2)], [1,2])
3330 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3331 # Now do lists and __setitem__
3332 a = L([1,2,3])
3333 a[slice(1, 3)] = [3,2]
3334 vereq(a, [1,3,2])
3335 a[slice(0, 2, 1)] = [3,1]
3336 vereq(a, [3,1,2])
3337 a.__setitem__(slice(1, 3), [2,1])
3338 vereq(a, [3,2,1])
3339 a.__setitem__(slice(0, 2, 1), [2,3])
3340 vereq(a, [2,3,1])
3341
Tim Peters2484aae2002-07-11 06:56:07 +00003342def subtype_resurrection():
3343 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003344 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003345
3346 class C(object):
3347 container = []
3348
3349 def __del__(self):
3350 # resurrect the instance
3351 C.container.append(self)
3352
3353 c = C()
3354 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003355 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003356 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003357 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003358
3359 # If that didn't blow up, it's also interesting to see whether clearing
3360 # the last container slot works: that will attempt to delete c again,
3361 # which will cause c to get appended back to the container again "during"
3362 # the del.
3363 del C.container[-1]
3364 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003365 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003366
Tim Peters14cb1e12002-07-11 18:26:21 +00003367 # Make c mortal again, so that the test framework with -l doesn't report
3368 # it as a leak.
3369 del C.__del__
3370
Guido van Rossum2d702462002-08-06 21:28:28 +00003371def slottrash():
3372 # Deallocating deeply nested slotted trash caused stack overflows
3373 if verbose:
3374 print "Testing slot trash..."
3375 class trash(object):
3376 __slots__ = ['x']
3377 def __init__(self, x):
3378 self.x = x
3379 o = None
3380 for i in xrange(50000):
3381 o = trash(o)
3382 del o
3383
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003384def slotmultipleinheritance():
3385 # SF bug 575229, multiple inheritance w/ slots dumps core
3386 class A(object):
3387 __slots__=()
3388 class B(object):
3389 pass
3390 class C(A,B) :
3391 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003392 vereq(C.__basicsize__, B.__basicsize__)
3393 verify(hasattr(C, '__dict__'))
3394 verify(hasattr(C, '__weakref__'))
3395 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003396
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003397def testrmul():
3398 # SF patch 592646
3399 if verbose:
3400 print "Testing correct invocation of __rmul__..."
3401 class C(object):
3402 def __mul__(self, other):
3403 return "mul"
3404 def __rmul__(self, other):
3405 return "rmul"
3406 a = C()
3407 vereq(a*2, "mul")
3408 vereq(a*2.2, "mul")
3409 vereq(2*a, "rmul")
3410 vereq(2.2*a, "rmul")
3411
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003412def testipow():
3413 # [SF bug 620179]
3414 if verbose:
3415 print "Testing correct invocation of __ipow__..."
3416 class C(object):
3417 def __ipow__(self, other):
3418 pass
3419 a = C()
3420 a **= 2
3421
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003422def do_this_first():
3423 if verbose:
3424 print "Testing SF bug 551412 ..."
3425 # This dumps core when SF bug 551412 isn't fixed --
3426 # but only when test_descr.py is run separately.
3427 # (That can't be helped -- as soon as PyType_Ready()
3428 # is called for PyLong_Type, the bug is gone.)
3429 class UserLong(object):
3430 def __pow__(self, *args):
3431 pass
3432 try:
3433 pow(0L, UserLong(), 0L)
3434 except:
3435 pass
3436
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003437 if verbose:
3438 print "Testing SF bug 570483..."
3439 # Another segfault only when run early
3440 # (before PyType_Ready(tuple) is called)
3441 type.mro(tuple)
3442
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003443def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003444 if verbose:
3445 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003446 # stuff that should work:
3447 class C(object):
3448 pass
3449 class C2(object):
3450 def __getattribute__(self, attr):
3451 if attr == 'a':
3452 return 2
3453 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003454 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003455 def meth(self):
3456 return 1
3457 class D(C):
3458 pass
3459 class E(D):
3460 pass
3461 d = D()
3462 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003463 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003464 D.__bases__ = (C2,)
3465 vereq(d.meth(), 1)
3466 vereq(e.meth(), 1)
3467 vereq(d.a, 2)
3468 vereq(e.a, 2)
3469 vereq(C2.__subclasses__(), [D])
3470
3471 # stuff that shouldn't:
3472 class L(list):
3473 pass
3474
3475 try:
3476 L.__bases__ = (dict,)
3477 except TypeError:
3478 pass
3479 else:
3480 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3481
3482 try:
3483 list.__bases__ = (dict,)
3484 except TypeError:
3485 pass
3486 else:
3487 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3488
3489 try:
3490 del D.__bases__
3491 except TypeError:
3492 pass
3493 else:
3494 raise TestFailed, "shouldn't be able to delete .__bases__"
3495
3496 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003497 D.__bases__ = ()
3498 except TypeError, msg:
3499 if str(msg) == "a new-style class can't have only classic bases":
3500 raise TestFailed, "wrong error message for .__bases__ = ()"
3501 else:
3502 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3503
3504 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003505 D.__bases__ = (D,)
3506 except TypeError:
3507 pass
3508 else:
3509 # actually, we'll have crashed by here...
3510 raise TestFailed, "shouldn't be able to create inheritance cycles"
3511
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003512 try:
3513 D.__bases__ = (E,)
3514 except TypeError:
3515 pass
3516 else:
3517 raise TestFailed, "shouldn't be able to create inheritance cycles"
3518
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003519 # let's throw a classic class into the mix:
3520 class Classic:
3521 def meth2(self):
3522 return 3
3523
3524 D.__bases__ = (C, Classic)
3525
3526 vereq(d.meth2(), 3)
3527 vereq(e.meth2(), 3)
3528 try:
3529 d.a
3530 except AttributeError:
3531 pass
3532 else:
3533 raise TestFailed, "attribute should have vanished"
3534
3535 try:
3536 D.__bases__ = (Classic,)
3537 except TypeError:
3538 pass
3539 else:
3540 raise TestFailed, "new-style class must have a new-style base"
3541
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003542def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003543 if verbose:
3544 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003545 class WorkOnce(type):
3546 def __new__(self, name, bases, ns):
3547 self.flag = 0
3548 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3549 def mro(self):
3550 if self.flag > 0:
3551 raise RuntimeError, "bozo"
3552 else:
3553 self.flag += 1
3554 return type.mro(self)
3555
3556 class WorkAlways(type):
3557 def mro(self):
3558 # this is here to make sure that .mro()s aren't called
3559 # with an exception set (which was possible at one point).
3560 # An error message will be printed in a debug build.
3561 # What's a good way to test for this?
3562 return type.mro(self)
3563
3564 class C(object):
3565 pass
3566
3567 class C2(object):
3568 pass
3569
3570 class D(C):
3571 pass
3572
3573 class E(D):
3574 pass
3575
3576 class F(D):
3577 __metaclass__ = WorkOnce
3578
3579 class G(D):
3580 __metaclass__ = WorkAlways
3581
3582 # Immediate subclasses have their mro's adjusted in alphabetical
3583 # order, so E's will get adjusted before adjusting F's fails. We
3584 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003585
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003586 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003587 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003588
3589 try:
3590 D.__bases__ = (C2,)
3591 except RuntimeError:
3592 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003593 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003594 else:
3595 raise TestFailed, "exception not propagated"
3596
3597def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003598 if verbose:
3599 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003600 class A(object):
3601 pass
3602
3603 class B(object):
3604 pass
3605
3606 class C(A, B):
3607 pass
3608
3609 class D(A, B):
3610 pass
3611
3612 class E(C, D):
3613 pass
3614
3615 try:
3616 C.__bases__ = (B, A)
3617 except TypeError:
3618 pass
3619 else:
3620 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003621
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003622def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003623 if verbose:
3624 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003625 class C(object):
3626 pass
3627
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003628 # C.__module__ could be 'test_descr' or '__main__'
3629 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003630
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003631 C.__name__ = 'D'
3632 vereq((C.__module__, C.__name__), (mod, 'D'))
3633
3634 C.__name__ = 'D.E'
3635 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003636
Guido van Rossum613f24f2003-01-06 23:00:59 +00003637def subclass_right_op():
3638 if verbose:
3639 print "Testing correct dispatch of subclass overloading __r<op>__..."
3640
3641 # This code tests various cases where right-dispatch of a subclass
3642 # should be preferred over left-dispatch of a base class.
3643
3644 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3645
3646 class B(int):
3647 def __div__(self, other):
3648 return "B.__div__"
3649 def __rdiv__(self, other):
3650 return "B.__rdiv__"
3651
3652 vereq(B(1) / 1, "B.__div__")
3653 vereq(1 / B(1), "B.__rdiv__")
3654
3655 # Case 2: subclass of object; this is just the baseline for case 3
3656
3657 class C(object):
3658 def __div__(self, other):
3659 return "C.__div__"
3660 def __rdiv__(self, other):
3661 return "C.__rdiv__"
3662
3663 vereq(C(1) / 1, "C.__div__")
3664 vereq(1 / C(1), "C.__rdiv__")
3665
3666 # Case 3: subclass of new-style class; here it gets interesting
3667
3668 class D(C):
3669 def __div__(self, other):
3670 return "D.__div__"
3671 def __rdiv__(self, other):
3672 return "D.__rdiv__"
3673
3674 vereq(D(1) / C(1), "D.__div__")
3675 vereq(C(1) / D(1), "D.__rdiv__")
3676
3677 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3678
3679 class E(C):
3680 pass
3681
3682 vereq(E.__rdiv__, C.__rdiv__)
3683
3684 vereq(E(1) / 1, "C.__div__")
3685 vereq(1 / E(1), "C.__rdiv__")
3686 vereq(E(1) / C(1), "C.__div__")
3687 vereq(C(1) / E(1), "C.__div__") # This one would fail
3688
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003689
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003690def test_main():
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003691 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00003692 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 lists()
3694 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00003695 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00003696 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697 ints()
3698 longs()
3699 floats()
3700 complexes()
3701 spamlists()
3702 spamdicts()
3703 pydicts()
3704 pylists()
3705 metaclass()
3706 pymods()
3707 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00003708 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00003710 ex5()
3711 monotonicity()
3712 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00003713 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003715 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716 dynamics()
3717 errors()
3718 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003719 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003721 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722 classic()
3723 compattr()
3724 newslot()
3725 altmro()
3726 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00003727 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00003728 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00003729 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00003730 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00003731 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00003732 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00003733 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00003734 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00003735 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00003736 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00003737 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00003738 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00003739 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003740 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00003741 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00003742 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003743 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003744 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003745 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00003746 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00003747 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00003748 kwdargs()
Guido van Rossumed87ad82001-10-30 02:33:02 +00003749 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003750 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00003751 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003752 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00003753 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003754 dictproxyiterkeys()
3755 dictproxyitervalues()
3756 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00003757 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003758 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00003759 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003760 docdescriptor()
Tim Petersafb2c802002-04-18 18:06:20 +00003761 string_exceptions()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003762 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00003763 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00003764 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00003765 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003766 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003767 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003768 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003769 test_mutable_bases()
3770 test_mutable_bases_with_failing_mro()
3771 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003772 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00003773 subclass_right_op()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003774
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003775 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003777if __name__ == "__main__":
3778 test_main()