blob: 185edb34d857346e6fba77600cc0514f1ab1c627 [file] [log] [blame]
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001# Test enhancements related to descriptors and new-style classes
Tim Peters6d6c1a32001-08-02 04:15:00 +00002
Neal Norwitz1a997502003-01-13 20:13:12 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
Tim Peters4d9b4662002-04-16 01:59:17 +00005import warnings
6
7warnings.filterwarnings("ignore",
8 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +00009 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Guido van Rossum875eeaa2001-10-11 18:33:53 +000011def veris(a, b):
12 if a is not b:
13 raise TestFailed, "%r is %r" % (a, b)
14
Tim Peters6d6c1a32001-08-02 04:15:00 +000015def testunop(a, res, expr="len(a)", meth="__len__"):
16 if verbose: print "checking", expr
17 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000018 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000019 t = type(a)
20 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000021 while meth not in t.__dict__:
22 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000023 vereq(m, t.__dict__[meth])
24 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000025 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000026 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000027
28def testbinop(a, b, res, expr="a+b", meth="__add__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000031
Guido van Rossum45704552001-10-08 16:35:45 +000032 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000033 t = type(a)
34 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000035 while meth not in t.__dict__:
36 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000037 vereq(m, t.__dict__[meth])
38 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000039 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000040 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000041
42def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
43 if verbose: print "checking", expr
44 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000045 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000046 t = type(a)
47 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000048 while meth not in t.__dict__:
49 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000050 vereq(m, t.__dict__[meth])
51 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000052 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000053 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000054
55def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
56 if verbose: print "checking", stmt
57 dict = {'a': deepcopy(a), 'b': b}
58 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000059 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000060 t = type(a)
61 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000062 while meth not in t.__dict__:
63 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000064 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000065 dict['a'] = deepcopy(a)
66 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000067 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000068 dict['a'] = deepcopy(a)
69 bm = getattr(dict['a'], meth)
70 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000071 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000072
73def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
74 if verbose: print "checking", stmt
75 dict = {'a': deepcopy(a), 'b': b, 'c': c}
76 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000077 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000078 t = type(a)
79 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000080 while meth not in t.__dict__:
81 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000082 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000083 dict['a'] = deepcopy(a)
84 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000085 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 dict['a'] = deepcopy(a)
87 bm = getattr(dict['a'], meth)
88 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000089 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000090
91def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
92 if verbose: print "checking", stmt
93 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
94 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000095 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000097 while meth not in t.__dict__:
98 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +000099 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000100 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101 dict['a'] = deepcopy(a)
102 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000103 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104 dict['a'] = deepcopy(a)
105 bm = getattr(dict['a'], meth)
106 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000107 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108
Tim Peters2f93e282001-10-04 05:27:00 +0000109def class_docstrings():
110 class Classic:
111 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000112 vereq(Classic.__doc__, "A classic docstring.")
113 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000114
115 class Classic2:
116 pass
117 verify(Classic2.__doc__ is None)
118
Tim Peters4fb1fe82001-10-04 05:48:13 +0000119 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000120 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000121 vereq(NewStatic.__doc__, "Another docstring.")
122 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000123
Tim Peters4fb1fe82001-10-04 05:48:13 +0000124 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000125 pass
126 verify(NewStatic2.__doc__ is None)
127
Tim Peters4fb1fe82001-10-04 05:48:13 +0000128 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000129 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000130 vereq(NewDynamic.__doc__, "Another docstring.")
131 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000132
Tim Peters4fb1fe82001-10-04 05:48:13 +0000133 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000134 pass
135 verify(NewDynamic2.__doc__ is None)
136
Tim Peters6d6c1a32001-08-02 04:15:00 +0000137def lists():
138 if verbose: print "Testing list operations..."
139 testbinop([1], [2], [1,2], "a+b", "__add__")
140 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
141 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
142 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
143 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
144 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
145 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
146 testunop([1,2,3], 3, "len(a)", "__len__")
147 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
148 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
149 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
150 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
151
152def dicts():
153 if verbose: print "Testing dict operations..."
154 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
155 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
156 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
157 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
158 d = {1:2,3:4}
159 l1 = []
160 for i in d.keys(): l1.append(i)
161 l = []
162 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000163 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000164 l = []
165 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000166 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000167 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000168 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000169 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170 d = {1:2, 3:4}
171 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000172 vereq(eval(repr(d), {}), d)
173 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
175
Tim Peters25786c02001-09-02 08:22:48 +0000176def dict_constructor():
177 if verbose:
Tim Petersa427a2b2001-10-29 22:25:45 +0000178 print "Testing dict constructor ..."
179 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000180 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000181 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000182 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000183 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000184 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000185 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000186 vereq(d, dict(d.iteritems()))
187 d = dict({'one':1, 'two':2})
188 vereq(d, dict(one=1, two=2))
189 vereq(d, dict(**d))
190 vereq(d, dict({"one": 1}, two=2))
191 vereq(d, dict([("two", 2)], one=1))
192 vereq(d, dict([("one", 100), ("two", 200)], **d))
193 verify(d is not dict(**d))
Tim Peters25786c02001-09-02 08:22:48 +0000194 for badarg in 0, 0L, 0j, "0", [0], (0,):
195 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000196 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000197 except TypeError:
198 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000199 except ValueError:
200 if badarg == "0":
201 # It's a sequence, and its elements are also sequences (gotta
202 # love strings <wink>), but they aren't of length 2, so this
203 # one seemed better as a ValueError than a TypeError.
204 pass
205 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000206 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000207 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000208 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000209
210 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000211 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000212 except TypeError:
213 pass
214 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000215 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000216
217 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000218 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000219 dict = {1:2, 3:4, 'a':1j}
220
Tim Peters25786c02001-09-02 08:22:48 +0000221 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000222 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000223 except TypeError:
224 pass
225 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000226 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000227
228 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000229 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000230 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000231 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000232
Tim Peters1fc240e2001-10-26 05:06:50 +0000233 # Init from sequence of iterable objects, each producing a 2-sequence.
234 class AddressBookEntry:
235 def __init__(self, first, last):
236 self.first = first
237 self.last = last
238 def __iter__(self):
239 return iter([self.first, self.last])
240
Tim Petersa427a2b2001-10-29 22:25:45 +0000241 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000242 AddressBookEntry('Barry', 'Peters'),
243 AddressBookEntry('Tim', 'Peters'),
244 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000245 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
246
Tim Petersa427a2b2001-10-29 22:25:45 +0000247 d = dict(zip(range(4), range(1, 5)))
248 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000249
250 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000251 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000252 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000253 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000254 except ValueError:
255 pass
256 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000257 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000258
Tim Peters5d2b77c2001-09-03 05:47:38 +0000259def test_dir():
260 if verbose:
261 print "Testing dir() ..."
262 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000263 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000264 del junk
265
266 # Just make sure these don't blow up!
267 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
268 dir(arg)
269
Thomas Wouters0725cf22006-04-15 09:04:57 +0000270 # Test dir on custom classes. Since these have object as a
271 # base class, a lot of stuff gets sucked in.
Tim Peters37a309d2001-09-04 01:20:04 +0000272 def interesting(strings):
273 return [s for s in strings if not s.startswith('_')]
274
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275 class C(object):
276 Cdata = 1
277 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000278
279 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000280 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000281
282 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000283 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000284 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000285
286 c.cdata = 2
287 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000288 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000289 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000290
Tim Peters5d2b77c2001-09-03 05:47:38 +0000291 class A(C):
292 Adata = 1
293 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000294
295 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000296 vereq(interesting(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(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000300 a.adata = 42
301 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000302 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000303 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000304
Tim Peterscaaff8d2001-09-10 23:12:14 +0000305 # Try a module subclass.
306 import sys
307 class M(type(sys)):
308 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000309 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000310 minstance.b = 2
311 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000312 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
313 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000314
315 class M2(M):
316 def getdict(self):
317 return "Not a dict!"
318 __dict__ = property(getdict)
319
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000320 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000321 m2instance.b = 2
322 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000323 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000324 try:
325 dir(m2instance)
326 except TypeError:
327 pass
328
Tim Peters9e6a3992001-10-30 05:45:26 +0000329 # Two essentially featureless objects, just inheriting stuff from
330 # object.
331 vereq(dir(None), dir(Ellipsis))
332
Guido van Rossum44022412002-05-13 18:29:46 +0000333 # Nasty test case for proxied objects
334 class Wrapper(object):
335 def __init__(self, obj):
336 self.__obj = obj
337 def __repr__(self):
338 return "Wrapper(%s)" % repr(self.__obj)
339 def __getitem__(self, key):
340 return Wrapper(self.__obj[key])
341 def __len__(self):
342 return len(self.__obj)
343 def __getattr__(self, name):
344 return Wrapper(getattr(self.__obj, name))
345
346 class C(object):
347 def __getclass(self):
348 return Wrapper(type(self))
349 __class__ = property(__getclass)
350
351 dir(C()) # This used to segfault
352
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353binops = {
354 'add': '+',
355 'sub': '-',
356 'mul': '*',
357 'div': '/',
358 'mod': '%',
359 'divmod': 'divmod',
360 'pow': '**',
361 'lshift': '<<',
362 'rshift': '>>',
363 'and': '&',
364 'xor': '^',
365 'or': '|',
366 'cmp': 'cmp',
367 'lt': '<',
368 'le': '<=',
369 'eq': '==',
370 'ne': '!=',
371 'gt': '>',
372 'ge': '>=',
373 }
374
375for name, expr in binops.items():
376 if expr.islower():
377 expr = expr + "(a, b)"
378 else:
379 expr = 'a %s b' % expr
380 binops[name] = expr
381
382unops = {
383 'pos': '+',
384 'neg': '-',
385 'abs': 'abs',
386 'invert': '~',
387 'int': 'int',
388 'long': 'long',
389 'float': 'float',
390 'oct': 'oct',
391 'hex': 'hex',
392 }
393
394for name, expr in unops.items():
395 if expr.islower():
396 expr = expr + "(a)"
397 else:
398 expr = '%s a' % expr
399 unops[name] = expr
400
401def numops(a, b, skip=[]):
402 dict = {'a': a, 'b': b}
403 for name, expr in binops.items():
404 if name not in skip:
405 name = "__%s__" % name
406 if hasattr(a, name):
407 res = eval(expr, dict)
408 testbinop(a, b, res, expr, name)
409 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000410 if name not in skip:
411 name = "__%s__" % name
412 if hasattr(a, name):
413 res = eval(expr, dict)
414 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415
416def ints():
417 if verbose: print "Testing int operations..."
418 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000419 # The following crashes in Python 2.2
420 vereq((1).__nonzero__(), 1)
421 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000422 # This returns 'NotImplemented' in Python 2.2
423 class C(int):
424 def __add__(self, other):
425 return NotImplemented
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000426 vereq(C(5L), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000427 try:
428 C() + ""
429 except TypeError:
430 pass
431 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000432 raise TestFailed, "NotImplemented should have caused TypeError"
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000433 import sys
434 try:
435 C(sys.maxint+1)
436 except OverflowError:
437 pass
438 else:
439 raise TestFailed, "should have raised OverflowError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000440
441def longs():
442 if verbose: print "Testing long operations..."
443 numops(100L, 3L)
444
445def floats():
446 if verbose: print "Testing float operations..."
447 numops(100.0, 3.0)
448
449def complexes():
450 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000451 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000452 class Number(complex):
453 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000454 def __new__(cls, *args, **kwds):
455 result = complex.__new__(cls, *args)
456 result.prec = kwds.get('prec', 12)
457 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 def __repr__(self):
459 prec = self.prec
460 if self.imag == 0.0:
461 return "%.*g" % (prec, self.real)
462 if self.real == 0.0:
463 return "%.*gj" % (prec, self.imag)
464 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
465 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000466
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000468 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000469 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470
Tim Peters3f996e72001-09-13 19:18:27 +0000471 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000472 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000473 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000474
475 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000476 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000477 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000478
Tim Peters6d6c1a32001-08-02 04:15:00 +0000479def spamlists():
480 if verbose: print "Testing spamlist operations..."
481 import copy, xxsubtype as spam
482 def spamlist(l, memo=None):
483 import xxsubtype as spam
484 return spam.spamlist(l)
485 # This is an ugly hack:
486 copy._deepcopy_dispatch[spam.spamlist] = spamlist
487
488 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
489 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
490 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
491 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
492 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
493 "a[b:c]", "__getslice__")
494 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
495 "a+=b", "__iadd__")
496 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
497 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
498 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
499 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
500 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
501 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
502 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
503 # Test subclassing
504 class C(spam.spamlist):
505 def foo(self): return 1
506 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000507 vereq(a, [])
508 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000509 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000510 vereq(a, [100])
511 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000512 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000513 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000514
515def spamdicts():
516 if verbose: print "Testing spamdict operations..."
517 import copy, xxsubtype as spam
518 def spamdict(d, memo=None):
519 import xxsubtype as spam
520 sd = spam.spamdict()
521 for k, v in d.items(): sd[k] = v
522 return sd
523 # This is an ugly hack:
524 copy._deepcopy_dispatch[spam.spamdict] = spamdict
525
526 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
527 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
528 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
529 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
530 d = spamdict({1:2,3:4})
531 l1 = []
532 for i in d.keys(): l1.append(i)
533 l = []
534 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000535 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000536 l = []
537 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000538 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000539 l = []
540 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000541 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000542 straightd = {1:2, 3:4}
543 spamd = spamdict(straightd)
544 testunop(spamd, 2, "len(a)", "__len__")
545 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
546 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
547 "a[b]=c", "__setitem__")
548 # Test subclassing
549 class C(spam.spamdict):
550 def foo(self): return 1
551 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000552 vereq(a.items(), [])
553 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000554 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000555 vereq(a.items(), [('foo', 'bar')])
556 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000557 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000558 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000559
560def pydicts():
561 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000562 verify(issubclass(dict, dict))
563 verify(isinstance({}, dict))
564 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000565 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000566 verify(d.__class__ is dict)
567 verify(isinstance(d, dict))
568 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000569 state = -1
570 def __init__(self, *a, **kw):
571 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000572 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000573 self.state = a[0]
574 if kw:
575 for k, v in kw.items(): self[v] = k
576 def __getitem__(self, key):
577 return self.get(key, 0)
578 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000579 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000580 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 def setstate(self, state):
582 self.state = state
583 def getstate(self):
584 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000585 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000587 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000589 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000590 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000591 vereq(a.state, -1)
592 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000594 vereq(a.state, 0)
595 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000597 vereq(a.state, 10)
598 vereq(a.getstate(), 10)
599 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000600 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000601 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000602 if verbose: print "pydict stress test ..."
603 N = 50
604 for i in range(N):
605 a[i] = C()
606 for j in range(N):
607 a[i][j] = i*j
608 for i in range(N):
609 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000610 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000611
612def pylists():
613 if verbose: print "Testing Python subclass of list..."
614 class C(list):
615 def __getitem__(self, i):
616 return list.__getitem__(self, i) + 100
617 def __getslice__(self, i, j):
618 return (i, j)
619 a = C()
620 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000621 vereq(a[0], 100)
622 vereq(a[1], 101)
623 vereq(a[2], 102)
624 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625
626def metaclass():
627 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628 class C:
629 __metaclass__ = type
630 def __init__(self):
631 self.__state = 0
632 def getstate(self):
633 return self.__state
634 def setstate(self, state):
635 self.__state = state
636 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000637 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000639 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 class D:
641 class __metaclass__(type):
642 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000643 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000644 d = D()
645 verify(d.__class__ is D)
646 class M1(type):
647 def __new__(cls, name, bases, dict):
648 dict['__spam__'] = 1
649 return type.__new__(cls, name, bases, dict)
650 class C:
651 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000652 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000653 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000654 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000655
Guido van Rossum309b5662001-08-17 11:43:17 +0000656 class _instance(object):
657 pass
658 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000659 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000660 def __new__(cls, name, bases, dict):
661 self = object.__new__(cls)
662 self.name = name
663 self.bases = bases
664 self.dict = dict
665 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000666 def __call__(self):
667 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000668 # Early binding of methods
669 for key in self.dict:
670 if key.startswith("__"):
671 continue
672 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000673 return it
674 class C:
675 __metaclass__ = M2
676 def spam(self):
677 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000678 vereq(C.name, 'C')
679 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000680 verify('spam' in C.dict)
681 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000682 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683
Guido van Rossum91ee7982001-08-30 20:52:40 +0000684 # More metaclass examples
685
686 class autosuper(type):
687 # Automatically add __super to the class
688 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000689 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000690 cls = super(autosuper, metaclass).__new__(metaclass,
691 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000692 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000693 while name[:1] == "_":
694 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000695 if name:
696 name = "_%s__super" % name
697 else:
698 name = "__super"
699 setattr(cls, name, super(cls))
700 return cls
701 class A:
702 __metaclass__ = autosuper
703 def meth(self):
704 return "A"
705 class B(A):
706 def meth(self):
707 return "B" + self.__super.meth()
708 class C(A):
709 def meth(self):
710 return "C" + self.__super.meth()
711 class D(C, B):
712 def meth(self):
713 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000714 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000715 class E(B, C):
716 def meth(self):
717 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000718 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000719
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000720 class autoproperty(type):
721 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000722 # named _get_x and/or _set_x are found
723 def __new__(metaclass, name, bases, dict):
724 hits = {}
725 for key, val in dict.iteritems():
726 if key.startswith("_get_"):
727 key = key[5:]
728 get, set = hits.get(key, (None, None))
729 get = val
730 hits[key] = get, set
731 elif key.startswith("_set_"):
732 key = key[5:]
733 get, set = hits.get(key, (None, None))
734 set = val
735 hits[key] = get, set
736 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000737 dict[key] = property(get, set)
738 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000739 name, bases, dict)
740 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000741 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000742 def _get_x(self):
743 return -self.__x
744 def _set_x(self, x):
745 self.__x = -x
746 a = A()
747 verify(not hasattr(a, "x"))
748 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000749 vereq(a.x, 12)
750 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000751
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000752 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000753 # Merge of multiple cooperating metaclasses
754 pass
755 class A:
756 __metaclass__ = multimetaclass
757 def _get_x(self):
758 return "A"
759 class B(A):
760 def _get_x(self):
761 return "B" + self.__super._get_x()
762 class C(A):
763 def _get_x(self):
764 return "C" + self.__super._get_x()
765 class D(C, B):
766 def _get_x(self):
767 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000768 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000769
Guido van Rossumf76de622001-10-18 15:49:21 +0000770 # Make sure type(x) doesn't call x.__class__.__init__
771 class T(type):
772 counter = 0
773 def __init__(self, *args):
774 T.counter += 1
775 class C:
776 __metaclass__ = T
777 vereq(T.counter, 1)
778 a = C()
779 vereq(type(a), C)
780 vereq(T.counter, 1)
781
Guido van Rossum29d26062001-12-11 04:37:34 +0000782 class C(object): pass
783 c = C()
784 try: c()
785 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000786 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000787
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788def pymods():
789 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000791 import sys
792 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000794 def __init__(self, name):
795 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000796 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000798 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000799 def __setattr__(self, name, value):
800 log.append(("setattr", name, value))
801 MT.__setattr__(self, name, value)
802 def __delattr__(self, name):
803 log.append(("delattr", name))
804 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000805 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806 a.foo = 12
807 x = a.foo
808 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000809 vereq(log, [("setattr", "foo", 12),
810 ("getattr", "foo"),
811 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812
813def multi():
814 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815 class C(object):
816 def __init__(self):
817 self.__state = 0
818 def getstate(self):
819 return self.__state
820 def setstate(self, state):
821 self.__state = state
822 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000823 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000825 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000826 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 def __init__(self):
828 type({}).__init__(self)
829 C.__init__(self)
830 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000831 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000833 vereq(d.items(), [("hello", "world")])
834 vereq(d["hello"], "world")
835 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000837 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000838 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839
Guido van Rossume45763a2001-08-10 21:28:46 +0000840 # SF bug #442833
841 class Node(object):
842 def __int__(self):
843 return int(self.foo())
844 def foo(self):
845 return "23"
846 class Frag(Node, list):
847 def foo(self):
848 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000849 vereq(Node().__int__(), 23)
850 vereq(int(Node()), 23)
851 vereq(Frag().__int__(), 42)
852 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000853
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854def diamond():
855 if verbose: print "Testing multiple inheritance special cases..."
856 class A(object):
857 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000858 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859 class B(A):
860 def boo(self): return "B"
861 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000862 vereq(B().spam(), "B")
863 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864 class C(A):
865 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000866 vereq(C().spam(), "A")
867 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000869 vereq(D().spam(), "B")
870 vereq(D().boo(), "B")
871 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000873 vereq(E().spam(), "B")
874 vereq(E().boo(), "C")
875 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000876 # MRO order disagreement
877 try:
878 class F(D, E): pass
879 except TypeError:
880 pass
881 else:
882 raise TestFailed, "expected MRO order disagreement (F)"
883 try:
884 class G(E, D): pass
885 except TypeError:
886 pass
887 else:
888 raise TestFailed, "expected MRO order disagreement (G)"
889
890
891# see thread python-dev/2002-October/029035.html
892def ex5():
893 if verbose: print "Testing ex5 from C3 switch discussion..."
894 class A(object): pass
895 class B(object): pass
896 class C(object): pass
897 class X(A): pass
898 class Y(A): pass
899 class Z(X,B,Y,C): pass
900 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
901
902# see "A Monotonic Superclass Linearization for Dylan",
903# by Kim Barrett et al. (OOPSLA 1996)
904def monotonicity():
905 if verbose: print "Testing MRO monotonicity..."
906 class Boat(object): pass
907 class DayBoat(Boat): pass
908 class WheelBoat(Boat): pass
909 class EngineLess(DayBoat): pass
910 class SmallMultihull(DayBoat): pass
911 class PedalWheelBoat(EngineLess,WheelBoat): pass
912 class SmallCatamaran(SmallMultihull): pass
913 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
914
915 vereq(PedalWheelBoat.__mro__,
916 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
917 object))
918 vereq(SmallCatamaran.__mro__,
919 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
920
921 vereq(Pedalo.__mro__,
922 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
923 SmallMultihull, DayBoat, WheelBoat, Boat, object))
924
925# see "A Monotonic Superclass Linearization for Dylan",
926# by Kim Barrett et al. (OOPSLA 1996)
927def consistency_with_epg():
928 if verbose: print "Testing consistentcy with EPG..."
929 class Pane(object): pass
930 class ScrollingMixin(object): pass
931 class EditingMixin(object): pass
932 class ScrollablePane(Pane,ScrollingMixin): pass
933 class EditablePane(Pane,EditingMixin): pass
934 class EditableScrollablePane(ScrollablePane,EditablePane): pass
935
936 vereq(EditableScrollablePane.__mro__,
937 (EditableScrollablePane, ScrollablePane, EditablePane,
938 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000939
Raymond Hettingerf394df42003-04-06 19:13:41 +0000940mro_err_msg = """Cannot create a consistent method resolution
941order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000942
Guido van Rossumd32047f2002-11-25 21:38:52 +0000943def mro_disagreement():
944 if verbose: print "Testing error messages for MRO disagreement..."
945 def raises(exc, expected, callable, *args):
946 try:
947 callable(*args)
948 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +0000949 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +0000950 raise TestFailed, "Message %r, expected %r" % (str(msg),
951 expected)
952 else:
953 raise TestFailed, "Expected %s" % exc
954 class A(object): pass
955 class B(A): pass
956 class C(object): pass
957 # Test some very simple errors
958 raises(TypeError, "duplicate base class A",
959 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +0000960 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000961 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +0000962 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000963 type, "X", (A, C, B), {})
964 # Test a slightly more complex error
965 class GridLayout(object): pass
966 class HorizontalGrid(GridLayout): pass
967 class VerticalGrid(GridLayout): pass
968 class HVGrid(HorizontalGrid, VerticalGrid): pass
969 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +0000970 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000971 type, "ConfusedGrid", (HVGrid, VHGrid), {})
972
Guido van Rossum37202612001-08-09 19:45:21 +0000973def objects():
974 if verbose: print "Testing object class..."
975 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +0000976 vereq(a.__class__, object)
977 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +0000978 b = object()
979 verify(a is not b)
980 verify(not hasattr(a, "foo"))
981 try:
982 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000983 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000984 pass
985 else:
986 verify(0, "object() should not allow setting a foo attribute")
987 verify(not hasattr(object(), "__dict__"))
988
989 class Cdict(object):
990 pass
991 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +0000992 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +0000993 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000994 vereq(x.foo, 1)
995 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000996
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997def slots():
998 if verbose: print "Testing __slots__..."
999 class C0(object):
1000 __slots__ = []
1001 x = C0()
1002 verify(not hasattr(x, "__dict__"))
1003 verify(not hasattr(x, "foo"))
1004
1005 class C1(object):
1006 __slots__ = ['a']
1007 x = C1()
1008 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001009 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001011 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001012 x.a = None
1013 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001015 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016
1017 class C3(object):
1018 __slots__ = ['a', 'b', 'c']
1019 x = C3()
1020 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001021 verify(not hasattr(x, 'a'))
1022 verify(not hasattr(x, 'b'))
1023 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024 x.a = 1
1025 x.b = 2
1026 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001027 vereq(x.a, 1)
1028 vereq(x.b, 2)
1029 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001031 class C4(object):
1032 """Validate name mangling"""
1033 __slots__ = ['__a']
1034 def __init__(self, value):
1035 self.__a = value
1036 def get(self):
1037 return self.__a
1038 x = C4(5)
1039 verify(not hasattr(x, '__dict__'))
1040 verify(not hasattr(x, '__a'))
1041 vereq(x.get(), 5)
1042 try:
1043 x.__a = 6
1044 except AttributeError:
1045 pass
1046 else:
1047 raise TestFailed, "Double underscored names not mangled"
1048
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001049 # Make sure slot names are proper identifiers
1050 try:
1051 class C(object):
1052 __slots__ = [None]
1053 except TypeError:
1054 pass
1055 else:
1056 raise TestFailed, "[None] slots not caught"
1057 try:
1058 class C(object):
1059 __slots__ = ["foo bar"]
1060 except TypeError:
1061 pass
1062 else:
1063 raise TestFailed, "['foo bar'] slots not caught"
1064 try:
1065 class C(object):
1066 __slots__ = ["foo\0bar"]
1067 except TypeError:
1068 pass
1069 else:
1070 raise TestFailed, "['foo\\0bar'] slots not caught"
1071 try:
1072 class C(object):
1073 __slots__ = ["1"]
1074 except TypeError:
1075 pass
1076 else:
1077 raise TestFailed, "['1'] slots not caught"
1078 try:
1079 class C(object):
1080 __slots__ = [""]
1081 except TypeError:
1082 pass
1083 else:
1084 raise TestFailed, "[''] slots not caught"
1085 class C(object):
1086 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1087
Guido van Rossum33bab012001-12-05 22:45:48 +00001088 # Test leaks
1089 class Counted(object):
1090 counter = 0 # counts the number of instances alive
1091 def __init__(self):
1092 Counted.counter += 1
1093 def __del__(self):
1094 Counted.counter -= 1
1095 class C(object):
1096 __slots__ = ['a', 'b', 'c']
1097 x = C()
1098 x.a = Counted()
1099 x.b = Counted()
1100 x.c = Counted()
1101 vereq(Counted.counter, 3)
1102 del x
1103 vereq(Counted.counter, 0)
1104 class D(C):
1105 pass
1106 x = D()
1107 x.a = Counted()
1108 x.z = Counted()
1109 vereq(Counted.counter, 2)
1110 del x
1111 vereq(Counted.counter, 0)
1112 class E(D):
1113 __slots__ = ['e']
1114 x = E()
1115 x.a = Counted()
1116 x.z = Counted()
1117 x.e = Counted()
1118 vereq(Counted.counter, 3)
1119 del x
1120 vereq(Counted.counter, 0)
1121
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001122 # Test cyclical leaks [SF bug 519621]
1123 class F(object):
1124 __slots__ = ['a', 'b']
1125 log = []
1126 s = F()
1127 s.a = [Counted(), s]
1128 vereq(Counted.counter, 1)
1129 s = None
1130 import gc
1131 gc.collect()
1132 vereq(Counted.counter, 0)
1133
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001134 # Test lookup leaks [SF bug 572567]
1135 import sys,gc
1136 class G(object):
1137 def __cmp__(self, other):
1138 return 0
1139 g = G()
1140 orig_objects = len(gc.get_objects())
1141 for i in xrange(10):
1142 g==g
1143 new_objects = len(gc.get_objects())
1144 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001145 class H(object):
1146 __slots__ = ['a', 'b']
1147 def __init__(self):
1148 self.a = 1
1149 self.b = 2
1150 def __del__(self):
1151 assert self.a == 1
1152 assert self.b == 2
1153
1154 save_stderr = sys.stderr
1155 sys.stderr = sys.stdout
1156 h = H()
1157 try:
1158 del h
1159 finally:
1160 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001161
Guido van Rossum8b056da2002-08-13 18:26:26 +00001162def slotspecials():
1163 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1164
1165 class D(object):
1166 __slots__ = ["__dict__"]
1167 a = D()
1168 verify(hasattr(a, "__dict__"))
1169 verify(not hasattr(a, "__weakref__"))
1170 a.foo = 42
1171 vereq(a.__dict__, {"foo": 42})
1172
1173 class W(object):
1174 __slots__ = ["__weakref__"]
1175 a = W()
1176 verify(hasattr(a, "__weakref__"))
1177 verify(not hasattr(a, "__dict__"))
1178 try:
1179 a.foo = 42
1180 except AttributeError:
1181 pass
1182 else:
1183 raise TestFailed, "shouldn't be allowed to set a.foo"
1184
1185 class C1(W, D):
1186 __slots__ = []
1187 a = C1()
1188 verify(hasattr(a, "__dict__"))
1189 verify(hasattr(a, "__weakref__"))
1190 a.foo = 42
1191 vereq(a.__dict__, {"foo": 42})
1192
1193 class C2(D, W):
1194 __slots__ = []
1195 a = C2()
1196 verify(hasattr(a, "__dict__"))
1197 verify(hasattr(a, "__weakref__"))
1198 a.foo = 42
1199 vereq(a.__dict__, {"foo": 42})
1200
Guido van Rossum9a818922002-11-14 19:50:14 +00001201# MRO order disagreement
1202#
1203# class C3(C1, C2):
1204# __slots__ = []
1205#
1206# class C4(C2, C1):
1207# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001208
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001210 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001213 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001215 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001218 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001220 vereq(E.foo, 1)
1221 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001222 # Test dynamic instances
1223 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001224 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001225 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001226 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001227 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001228 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001229 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001230 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001231 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001232 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001233 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001234 vereq(int(a), 100)
1235 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001236 verify(not hasattr(a, "spam"))
1237 def mygetattr(self, name):
1238 if name == "spam":
1239 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001240 raise AttributeError
1241 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001242 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001243 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001244 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001245 def mysetattr(self, name, value):
1246 if name == "spam":
1247 raise AttributeError
1248 return object.__setattr__(self, name, value)
1249 C.__setattr__ = mysetattr
1250 try:
1251 a.spam = "not spam"
1252 except AttributeError:
1253 pass
1254 else:
1255 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001256 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001257 class D(C):
1258 pass
1259 d = D()
1260 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001261 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262
Guido van Rossum7e35d572001-09-15 03:14:32 +00001263 # Test handling of int*seq and seq*int
1264 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001265 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001266 vereq("a"*I(2), "aa")
1267 vereq(I(2)*"a", "aa")
1268 vereq(2*I(3), 6)
1269 vereq(I(3)*2, 6)
1270 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001271
1272 # Test handling of long*seq and seq*long
1273 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001274 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001275 vereq("a"*L(2L), "aa")
1276 vereq(L(2L)*"a", "aa")
1277 vereq(2*L(3), 6)
1278 vereq(L(3)*2, 6)
1279 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001280
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001281 # Test comparison of classes with dynamic metaclasses
1282 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001283 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001284 class someclass:
1285 __metaclass__ = dynamicmetaclass
1286 verify(someclass != object)
1287
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288def errors():
1289 if verbose: print "Testing errors..."
1290
1291 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001292 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 pass
1294 except TypeError:
1295 pass
1296 else:
1297 verify(0, "inheritance from both list and dict should be illegal")
1298
1299 try:
1300 class C(object, None):
1301 pass
1302 except TypeError:
1303 pass
1304 else:
1305 verify(0, "inheritance from non-type should be illegal")
1306 class Classic:
1307 pass
1308
1309 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001310 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 pass
1312 except TypeError:
1313 pass
1314 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001315 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316
1317 try:
1318 class C(object):
1319 __slots__ = 1
1320 except TypeError:
1321 pass
1322 else:
1323 verify(0, "__slots__ = 1 should be illegal")
1324
1325 try:
1326 class C(object):
1327 __slots__ = [1]
1328 except TypeError:
1329 pass
1330 else:
1331 verify(0, "__slots__ = [1] should be illegal")
1332
1333def classmethods():
1334 if verbose: print "Testing class methods..."
1335 class C(object):
1336 def foo(*a): return a
1337 goo = classmethod(foo)
1338 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001339 vereq(C.goo(1), (C, 1))
1340 vereq(c.goo(1), (C, 1))
1341 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 class D(C):
1343 pass
1344 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001345 vereq(D.goo(1), (D, 1))
1346 vereq(d.goo(1), (D, 1))
1347 vereq(d.foo(1), (d, 1))
1348 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001349 # Test for a specific crash (SF bug 528132)
1350 def f(cls, arg): return (cls, arg)
1351 ff = classmethod(f)
1352 vereq(ff.__get__(0, int)(42), (int, 42))
1353 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354
Guido van Rossum155db9a2002-04-02 17:53:47 +00001355 # Test super() with classmethods (SF bug 535444)
1356 veris(C.goo.im_self, C)
1357 veris(D.goo.im_self, D)
1358 veris(super(D,D).goo.im_self, D)
1359 veris(super(D,d).goo.im_self, D)
1360 vereq(super(D,D).goo(), (D,))
1361 vereq(super(D,d).goo(), (D,))
1362
Raymond Hettingerbe971532003-06-18 01:13:41 +00001363 # Verify that argument is checked for callability (SF bug 753451)
1364 try:
1365 classmethod(1).__get__(1)
1366 except TypeError:
1367 pass
1368 else:
1369 raise TestFailed, "classmethod should check for callability"
1370
Georg Brandl6a29c322006-02-21 22:17:46 +00001371 # Verify that classmethod() doesn't allow keyword args
1372 try:
1373 classmethod(f, kw=1)
1374 except TypeError:
1375 pass
1376 else:
1377 raise TestFailed, "classmethod shouldn't accept keyword args"
1378
Fred Drakef841aa62002-03-28 15:49:54 +00001379def classmethods_in_c():
1380 if verbose: print "Testing C-based class methods..."
1381 import xxsubtype as spam
1382 a = (1, 2, 3)
1383 d = {'abc': 123}
1384 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001385 veris(x, spam.spamlist)
1386 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001387 vereq(d, d1)
1388 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001389 veris(x, spam.spamlist)
1390 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001391 vereq(d, d1)
1392
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393def staticmethods():
1394 if verbose: print "Testing static methods..."
1395 class C(object):
1396 def foo(*a): return a
1397 goo = staticmethod(foo)
1398 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001399 vereq(C.goo(1), (1,))
1400 vereq(c.goo(1), (1,))
1401 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 class D(C):
1403 pass
1404 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001405 vereq(D.goo(1), (1,))
1406 vereq(d.goo(1), (1,))
1407 vereq(d.foo(1), (d, 1))
1408 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409
Fred Drakef841aa62002-03-28 15:49:54 +00001410def staticmethods_in_c():
1411 if verbose: print "Testing C-based static methods..."
1412 import xxsubtype as spam
1413 a = (1, 2, 3)
1414 d = {"abc": 123}
1415 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1416 veris(x, None)
1417 vereq(a, a1)
1418 vereq(d, d1)
1419 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1420 veris(x, None)
1421 vereq(a, a1)
1422 vereq(d, d1)
1423
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424def classic():
1425 if verbose: print "Testing classic classes..."
1426 class C:
1427 def foo(*a): return a
1428 goo = classmethod(foo)
1429 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001430 vereq(C.goo(1), (C, 1))
1431 vereq(c.goo(1), (C, 1))
1432 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433 class D(C):
1434 pass
1435 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001436 vereq(D.goo(1), (D, 1))
1437 vereq(d.goo(1), (D, 1))
1438 vereq(d.foo(1), (d, 1))
1439 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001440 class E: # *not* subclassing from C
1441 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001442 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001443 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444
1445def compattr():
1446 if verbose: print "Testing computed attributes..."
1447 class C(object):
1448 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001449 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450 self.__get = get
1451 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001452 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 def __get__(self, obj, type=None):
1454 return self.__get(obj)
1455 def __set__(self, obj, value):
1456 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001457 def __delete__(self, obj):
1458 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459 def __init__(self):
1460 self.__x = 0
1461 def __get_x(self):
1462 x = self.__x
1463 self.__x = x+1
1464 return x
1465 def __set_x(self, x):
1466 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001467 def __delete_x(self):
1468 del self.__x
1469 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001471 vereq(a.x, 0)
1472 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001473 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001474 vereq(a.x, 10)
1475 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001476 del a.x
1477 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478
1479def newslot():
1480 if verbose: print "Testing __new__ slot override..."
1481 class C(list):
1482 def __new__(cls):
1483 self = list.__new__(cls)
1484 self.foo = 1
1485 return self
1486 def __init__(self):
1487 self.foo = self.foo + 2
1488 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001489 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490 verify(a.__class__ is C)
1491 class D(C):
1492 pass
1493 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001494 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495 verify(b.__class__ is D)
1496
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497def altmro():
1498 if verbose: print "Testing mro() and overriding it..."
1499 class A(object):
1500 def f(self): return "A"
1501 class B(A):
1502 pass
1503 class C(A):
1504 def f(self): return "C"
1505 class D(B, C):
1506 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001507 vereq(D.mro(), [D, B, C, A, object])
1508 vereq(D.__mro__, (D, B, C, A, object))
1509 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001510
Guido van Rossumd3077402001-08-12 05:24:18 +00001511 class PerverseMetaType(type):
1512 def mro(cls):
1513 L = type.mro(cls)
1514 L.reverse()
1515 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001516 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001518 vereq(X.__mro__, (object, A, C, B, D, X))
1519 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520
Armin Rigo037d1e02005-12-29 17:07:39 +00001521 try:
1522 class X(object):
1523 class __metaclass__(type):
1524 def mro(self):
1525 return [self, dict, object]
1526 except TypeError:
1527 pass
1528 else:
1529 raise TestFailed, "devious mro() return not caught"
1530
1531 try:
1532 class X(object):
1533 class __metaclass__(type):
1534 def mro(self):
1535 return [1]
1536 except TypeError:
1537 pass
1538 else:
1539 raise TestFailed, "non-class mro() return not caught"
1540
1541 try:
1542 class X(object):
1543 class __metaclass__(type):
1544 def mro(self):
1545 return 1
1546 except TypeError:
1547 pass
1548 else:
1549 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001550
Armin Rigo037d1e02005-12-29 17:07:39 +00001551
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001553 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554
1555 class B(object):
1556 "Intermediate class because object doesn't have a __setattr__"
1557
1558 class C(B):
1559
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001560 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561 if name == "foo":
1562 return ("getattr", name)
1563 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001564 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 def __setattr__(self, name, value):
1566 if name == "foo":
1567 self.setattr = (name, value)
1568 else:
1569 return B.__setattr__(self, name, value)
1570 def __delattr__(self, name):
1571 if name == "foo":
1572 self.delattr = name
1573 else:
1574 return B.__delattr__(self, name)
1575
1576 def __getitem__(self, key):
1577 return ("getitem", key)
1578 def __setitem__(self, key, value):
1579 self.setitem = (key, value)
1580 def __delitem__(self, key):
1581 self.delitem = key
1582
1583 def __getslice__(self, i, j):
1584 return ("getslice", i, j)
1585 def __setslice__(self, i, j, value):
1586 self.setslice = (i, j, value)
1587 def __delslice__(self, i, j):
1588 self.delslice = (i, j)
1589
1590 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001591 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001593 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001595 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596
Guido van Rossum45704552001-10-08 16:35:45 +00001597 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001599 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001601 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602
Guido van Rossum45704552001-10-08 16:35:45 +00001603 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001605 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001607 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001609def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001610 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001611 class C(object):
1612 def __init__(self, x):
1613 self.x = x
1614 def foo(self):
1615 return self.x
1616 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001617 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001618 class D(C):
1619 boo = C.foo
1620 goo = c1.foo
1621 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001622 vereq(d2.foo(), 2)
1623 vereq(d2.boo(), 2)
1624 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001625 class E(object):
1626 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001627 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001628 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001629
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001630def specials():
1631 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001632 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001633 # Test the default behavior for static classes
1634 class C(object):
1635 def __getitem__(self, i):
1636 if 0 <= i < 10: return i
1637 raise IndexError
1638 c1 = C()
1639 c2 = C()
1640 verify(not not c1)
Guido van Rossum45704552001-10-08 16:35:45 +00001641 vereq(hash(c1), id(c1))
1642 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1643 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001644 verify(c1 != c2)
1645 verify(not c1 != c1)
1646 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001647 # Note that the module name appears in str/repr, and that varies
1648 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001649 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001650 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001651 verify(-1 not in c1)
1652 for i in range(10):
1653 verify(i in c1)
1654 verify(10 not in c1)
1655 # Test the default behavior for dynamic classes
1656 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001657 def __getitem__(self, i):
1658 if 0 <= i < 10: return i
1659 raise IndexError
1660 d1 = D()
1661 d2 = D()
1662 verify(not not d1)
Guido van Rossum45704552001-10-08 16:35:45 +00001663 vereq(hash(d1), id(d1))
1664 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1665 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001666 verify(d1 != d2)
1667 verify(not d1 != d1)
1668 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001669 # Note that the module name appears in str/repr, and that varies
1670 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001671 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001672 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001673 verify(-1 not in d1)
1674 for i in range(10):
1675 verify(i in d1)
1676 verify(10 not in d1)
1677 # Test overridden behavior for static classes
1678 class Proxy(object):
1679 def __init__(self, x):
1680 self.x = x
1681 def __nonzero__(self):
1682 return not not self.x
1683 def __hash__(self):
1684 return hash(self.x)
1685 def __eq__(self, other):
1686 return self.x == other
1687 def __ne__(self, other):
1688 return self.x != other
1689 def __cmp__(self, other):
1690 return cmp(self.x, other.x)
1691 def __str__(self):
1692 return "Proxy:%s" % self.x
1693 def __repr__(self):
1694 return "Proxy(%r)" % self.x
1695 def __contains__(self, value):
1696 return value in self.x
1697 p0 = Proxy(0)
1698 p1 = Proxy(1)
1699 p_1 = Proxy(-1)
1700 verify(not p0)
1701 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001702 vereq(hash(p0), hash(0))
1703 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001704 verify(p0 != p1)
1705 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001706 vereq(not p0, p1)
1707 vereq(cmp(p0, p1), -1)
1708 vereq(cmp(p0, p0), 0)
1709 vereq(cmp(p0, p_1), 1)
1710 vereq(str(p0), "Proxy:0")
1711 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001712 p10 = Proxy(range(10))
1713 verify(-1 not in p10)
1714 for i in range(10):
1715 verify(i in p10)
1716 verify(10 not in p10)
1717 # Test overridden behavior for dynamic classes
1718 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001719 def __init__(self, x):
1720 self.x = x
1721 def __nonzero__(self):
1722 return not not self.x
1723 def __hash__(self):
1724 return hash(self.x)
1725 def __eq__(self, other):
1726 return self.x == other
1727 def __ne__(self, other):
1728 return self.x != other
1729 def __cmp__(self, other):
1730 return cmp(self.x, other.x)
1731 def __str__(self):
1732 return "DProxy:%s" % self.x
1733 def __repr__(self):
1734 return "DProxy(%r)" % self.x
1735 def __contains__(self, value):
1736 return value in self.x
1737 p0 = DProxy(0)
1738 p1 = DProxy(1)
1739 p_1 = DProxy(-1)
1740 verify(not p0)
1741 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001742 vereq(hash(p0), hash(0))
1743 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001744 verify(p0 != p1)
1745 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001746 vereq(not p0, p1)
1747 vereq(cmp(p0, p1), -1)
1748 vereq(cmp(p0, p0), 0)
1749 vereq(cmp(p0, p_1), 1)
1750 vereq(str(p0), "DProxy:0")
1751 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001752 p10 = DProxy(range(10))
1753 verify(-1 not in p10)
1754 for i in range(10):
1755 verify(i in p10)
1756 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001757 # Safety test for __cmp__
1758 def unsafecmp(a, b):
1759 try:
1760 a.__class__.__cmp__(a, b)
1761 except TypeError:
1762 pass
1763 else:
1764 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1765 a.__class__, a, b)
1766 unsafecmp(u"123", "123")
1767 unsafecmp("123", u"123")
1768 unsafecmp(1, 1.0)
1769 unsafecmp(1.0, 1)
1770 unsafecmp(1, 1L)
1771 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001772
Neal Norwitz1a997502003-01-13 20:13:12 +00001773 class Letter(str):
1774 def __new__(cls, letter):
1775 if letter == 'EPS':
1776 return str.__new__(cls)
1777 return str.__new__(cls, letter)
1778 def __str__(self):
1779 if not self:
1780 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001781 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001782
1783 # sys.stdout needs to be the original to trigger the recursion bug
1784 import sys
1785 test_stdout = sys.stdout
1786 sys.stdout = get_original_stdout()
1787 try:
1788 # nothing should actually be printed, this should raise an exception
1789 print Letter('w')
1790 except RuntimeError:
1791 pass
1792 else:
1793 raise TestFailed, "expected a RuntimeError for print recursion"
1794 sys.stdout = test_stdout
1795
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001796def weakrefs():
1797 if verbose: print "Testing weak references..."
1798 import weakref
1799 class C(object):
1800 pass
1801 c = C()
1802 r = weakref.ref(c)
1803 verify(r() is c)
1804 del c
1805 verify(r() is None)
1806 del r
1807 class NoWeak(object):
1808 __slots__ = ['foo']
1809 no = NoWeak()
1810 try:
1811 weakref.ref(no)
1812 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001813 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001814 else:
1815 verify(0, "weakref.ref(no) should be illegal")
1816 class Weak(object):
1817 __slots__ = ['foo', '__weakref__']
1818 yes = Weak()
1819 r = weakref.ref(yes)
1820 verify(r() is yes)
1821 del yes
1822 verify(r() is None)
1823 del r
1824
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001825def properties():
1826 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001827 class C(object):
1828 def getx(self):
1829 return self.__x
1830 def setx(self, value):
1831 self.__x = value
1832 def delx(self):
1833 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001834 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001835 a = C()
1836 verify(not hasattr(a, "x"))
1837 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001838 vereq(a._C__x, 42)
1839 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001840 del a.x
1841 verify(not hasattr(a, "x"))
1842 verify(not hasattr(a, "_C__x"))
1843 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001844 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001845 C.x.__delete__(a)
1846 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001847
Tim Peters66c1a522001-09-24 21:17:50 +00001848 raw = C.__dict__['x']
1849 verify(isinstance(raw, property))
1850
1851 attrs = dir(raw)
1852 verify("__doc__" in attrs)
1853 verify("fget" in attrs)
1854 verify("fset" in attrs)
1855 verify("fdel" in attrs)
1856
Guido van Rossum45704552001-10-08 16:35:45 +00001857 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001858 verify(raw.fget is C.__dict__['getx'])
1859 verify(raw.fset is C.__dict__['setx'])
1860 verify(raw.fdel is C.__dict__['delx'])
1861
1862 for attr in "__doc__", "fget", "fset", "fdel":
1863 try:
1864 setattr(raw, attr, 42)
1865 except TypeError, msg:
1866 if str(msg).find('readonly') < 0:
1867 raise TestFailed("when setting readonly attr %r on a "
1868 "property, got unexpected TypeError "
1869 "msg %r" % (attr, str(msg)))
1870 else:
1871 raise TestFailed("expected TypeError from trying to set "
1872 "readonly %r attr on a property" % attr)
1873
Neal Norwitz673cd822002-10-18 16:33:13 +00001874 class D(object):
1875 __getitem__ = property(lambda s: 1/0)
1876
1877 d = D()
1878 try:
1879 for i in d:
1880 str(i)
1881 except ZeroDivisionError:
1882 pass
1883 else:
1884 raise TestFailed, "expected ZeroDivisionError from bad property"
1885
Georg Brandl533ff6f2006-03-08 18:09:27 +00001886 class E(object):
1887 def getter(self):
1888 "getter method"
1889 return 0
1890 def setter(self, value):
1891 "setter method"
1892 pass
1893 prop = property(getter)
1894 vereq(prop.__doc__, "getter method")
1895 prop2 = property(fset=setter)
1896 vereq(prop2.__doc__, None)
1897
Guido van Rossumc4a18802001-08-24 16:55:27 +00001898def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001899 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001900
1901 class A(object):
1902 def meth(self, a):
1903 return "A(%r)" % a
1904
Guido van Rossum45704552001-10-08 16:35:45 +00001905 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001906
1907 class B(A):
1908 def __init__(self):
1909 self.__super = super(B, self)
1910 def meth(self, a):
1911 return "B(%r)" % a + self.__super.meth(a)
1912
Guido van Rossum45704552001-10-08 16:35:45 +00001913 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001914
1915 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00001916 def meth(self, a):
1917 return "C(%r)" % a + self.__super.meth(a)
1918 C._C__super = super(C)
1919
Guido van Rossum45704552001-10-08 16:35:45 +00001920 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001921
1922 class D(C, B):
1923 def meth(self, a):
1924 return "D(%r)" % a + super(D, self).meth(a)
1925
Guido van Rossum5b443c62001-12-03 15:38:28 +00001926 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1927
1928 # Test for subclassing super
1929
1930 class mysuper(super):
1931 def __init__(self, *args):
1932 return super(mysuper, self).__init__(*args)
1933
1934 class E(D):
1935 def meth(self, a):
1936 return "E(%r)" % a + mysuper(E, self).meth(a)
1937
1938 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1939
1940 class F(E):
1941 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00001942 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00001943 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1944 F._F__super = mysuper(F)
1945
1946 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1947
1948 # Make sure certain errors are raised
1949
1950 try:
1951 super(D, 42)
1952 except TypeError:
1953 pass
1954 else:
1955 raise TestFailed, "shouldn't allow super(D, 42)"
1956
1957 try:
1958 super(D, C())
1959 except TypeError:
1960 pass
1961 else:
1962 raise TestFailed, "shouldn't allow super(D, C())"
1963
1964 try:
1965 super(D).__get__(12)
1966 except TypeError:
1967 pass
1968 else:
1969 raise TestFailed, "shouldn't allow super(D).__get__(12)"
1970
1971 try:
1972 super(D).__get__(C())
1973 except TypeError:
1974 pass
1975 else:
1976 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00001977
Guido van Rossuma4541a32003-04-16 20:02:22 +00001978 # Make sure data descriptors can be overridden and accessed via super
1979 # (new feature in Python 2.3)
1980
1981 class DDbase(object):
1982 def getx(self): return 42
1983 x = property(getx)
1984
1985 class DDsub(DDbase):
1986 def getx(self): return "hello"
1987 x = property(getx)
1988
1989 dd = DDsub()
1990 vereq(dd.x, "hello")
1991 vereq(super(DDsub, dd).x, 42)
1992
Phillip J. Eby91a968a2004-03-25 02:19:34 +00001993 # Ensure that super() lookup of descriptor from classmethod
1994 # works (SF ID# 743627)
1995
1996 class Base(object):
1997 aProp = property(lambda self: "foo")
1998
1999 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002000 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002001 def test(klass):
2002 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002003
2004 veris(Sub.test(), Base.aProp)
2005
2006
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002007def inherits():
2008 if verbose: print "Testing inheritance from basic types..."
2009
2010 class hexint(int):
2011 def __repr__(self):
2012 return hex(self)
2013 def __add__(self, other):
2014 return hexint(int.__add__(self, other))
2015 # (Note that overriding __radd__ doesn't work,
2016 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002017 vereq(repr(hexint(7) + 9), "0x10")
2018 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002019 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002020 vereq(a, 12345)
2021 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002022 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002023 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002024 verify((+a).__class__ is int)
2025 verify((a >> 0).__class__ is int)
2026 verify((a << 0).__class__ is int)
2027 verify((hexint(0) << 12).__class__ is int)
2028 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002029
2030 class octlong(long):
2031 __slots__ = []
2032 def __str__(self):
2033 s = oct(self)
2034 if s[-1] == 'L':
2035 s = s[:-1]
2036 return s
2037 def __add__(self, other):
2038 return self.__class__(super(octlong, self).__add__(other))
2039 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002040 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002041 # (Note that overriding __radd__ here only seems to work
2042 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002043 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002044 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002045 vereq(a, 12345L)
2046 vereq(long(a), 12345L)
2047 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002048 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002049 verify((+a).__class__ is long)
2050 verify((-a).__class__ is long)
2051 verify((-octlong(0)).__class__ is long)
2052 verify((a >> 0).__class__ is long)
2053 verify((a << 0).__class__ is long)
2054 verify((a - 0).__class__ is long)
2055 verify((a * 1).__class__ is long)
2056 verify((a ** 1).__class__ is long)
2057 verify((a // 1).__class__ is long)
2058 verify((1 * a).__class__ is long)
2059 verify((a | 0).__class__ is long)
2060 verify((a ^ 0).__class__ is long)
2061 verify((a & -1L).__class__ is long)
2062 verify((octlong(0) << 12).__class__ is long)
2063 verify((octlong(0) >> 12).__class__ is long)
2064 verify(abs(octlong(0)).__class__ is long)
2065
2066 # Because octlong overrides __add__, we can't check the absence of +0
2067 # optimizations using octlong.
2068 class longclone(long):
2069 pass
2070 a = longclone(1)
2071 verify((a + 0).__class__ is long)
2072 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002073
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002074 # Check that negative clones don't segfault
2075 a = longclone(-1)
2076 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002077 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002078
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002079 class precfloat(float):
2080 __slots__ = ['prec']
2081 def __init__(self, value=0.0, prec=12):
2082 self.prec = int(prec)
2083 float.__init__(value)
2084 def __repr__(self):
2085 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002086 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002087 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002088 vereq(a, 12345.0)
2089 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002090 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002091 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002092 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002093
Tim Peters2400fa42001-09-12 19:12:49 +00002094 class madcomplex(complex):
2095 def __repr__(self):
2096 return "%.17gj%+.17g" % (self.imag, self.real)
2097 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002098 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002099 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002100 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002101 vereq(a, base)
2102 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002103 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002104 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002105 vereq(repr(a), "4j-3")
2106 vereq(a, base)
2107 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002108 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002109 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002110 veris((+a).__class__, complex)
2111 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002112 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002113 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002114 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002115 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002116 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002117 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002118 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002119
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002120 class madtuple(tuple):
2121 _rev = None
2122 def rev(self):
2123 if self._rev is not None:
2124 return self._rev
2125 L = list(self)
2126 L.reverse()
2127 self._rev = self.__class__(L)
2128 return self._rev
2129 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002130 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2131 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2132 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002133 for i in range(512):
2134 t = madtuple(range(i))
2135 u = t.rev()
2136 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002137 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002138 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002139 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002140 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002141 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002142 verify(a[:].__class__ is tuple)
2143 verify((a * 1).__class__ is tuple)
2144 verify((a * 0).__class__ is tuple)
2145 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002146 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002147 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002148 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002149 verify((a + a).__class__ is tuple)
2150 verify((a * 0).__class__ is tuple)
2151 verify((a * 1).__class__ is tuple)
2152 verify((a * 2).__class__ is tuple)
2153 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002154
2155 class madstring(str):
2156 _rev = None
2157 def rev(self):
2158 if self._rev is not None:
2159 return self._rev
2160 L = list(self)
2161 L.reverse()
2162 self._rev = self.__class__("".join(L))
2163 return self._rev
2164 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002165 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2166 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2167 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002168 for i in range(256):
2169 s = madstring("".join(map(chr, range(i))))
2170 t = s.rev()
2171 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002172 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002173 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002174 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002175 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002176
Tim Peters8fa5dd02001-09-12 02:18:30 +00002177 base = "\x00" * 5
2178 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002179 vereq(s, base)
2180 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002181 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002182 vereq(hash(s), hash(base))
2183 vereq({s: 1}[base], 1)
2184 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002185 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002186 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002187 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002188 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002189 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002190 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002191 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002192 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002193 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002194 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002195 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002196 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002197 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002198 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002199 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002200 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002201 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002202 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002203 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002204 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002205 identitytab = ''.join([chr(i) for i in range(256)])
2206 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002207 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002208 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002209 vereq(s.translate(identitytab, "x"), base)
2210 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002211 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002212 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002213 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002214 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002215 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002216 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002217 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002218 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002219 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002220 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002221
Guido van Rossum91ee7982001-08-30 20:52:40 +00002222 class madunicode(unicode):
2223 _rev = None
2224 def rev(self):
2225 if self._rev is not None:
2226 return self._rev
2227 L = list(self)
2228 L.reverse()
2229 self._rev = self.__class__(u"".join(L))
2230 return self._rev
2231 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002232 vereq(u, u"ABCDEF")
2233 vereq(u.rev(), madunicode(u"FEDCBA"))
2234 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002235 base = u"12345"
2236 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002237 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002238 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002239 vereq(hash(u), hash(base))
2240 vereq({u: 1}[base], 1)
2241 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002242 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002243 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002244 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002245 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002246 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002247 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002248 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002249 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002250 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002251 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002252 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002253 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002254 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002255 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002256 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002257 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002258 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002259 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002260 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002261 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002262 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002263 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002264 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002265 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002266 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002267 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002268 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002269 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002270 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002271 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002272 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002273 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002274 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002275 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002276 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002277 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002278 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002279 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002280
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002281 class sublist(list):
2282 pass
2283 a = sublist(range(5))
2284 vereq(a, range(5))
2285 a.append("hello")
2286 vereq(a, range(5) + ["hello"])
2287 a[5] = 5
2288 vereq(a, range(6))
2289 a.extend(range(6, 20))
2290 vereq(a, range(20))
2291 a[-5:] = []
2292 vereq(a, range(15))
2293 del a[10:15]
2294 vereq(len(a), 10)
2295 vereq(a, range(10))
2296 vereq(list(a), range(10))
2297 vereq(a[0], 0)
2298 vereq(a[9], 9)
2299 vereq(a[-10], 0)
2300 vereq(a[-1], 9)
2301 vereq(a[:5], range(5))
2302
Tim Peters59c9a642001-09-13 05:38:56 +00002303 class CountedInput(file):
2304 """Counts lines read by self.readline().
2305
2306 self.lineno is the 0-based ordinal of the last line read, up to
2307 a maximum of one greater than the number of lines in the file.
2308
2309 self.ateof is true if and only if the final "" line has been read,
2310 at which point self.lineno stops incrementing, and further calls
2311 to readline() continue to return "".
2312 """
2313
2314 lineno = 0
2315 ateof = 0
2316 def readline(self):
2317 if self.ateof:
2318 return ""
2319 s = file.readline(self)
2320 # Next line works too.
2321 # s = super(CountedInput, self).readline()
2322 self.lineno += 1
2323 if s == "":
2324 self.ateof = 1
2325 return s
2326
Tim Peters561f8992001-09-13 19:36:36 +00002327 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002328 lines = ['a\n', 'b\n', 'c\n']
2329 try:
2330 f.writelines(lines)
2331 f.close()
2332 f = CountedInput(TESTFN)
2333 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2334 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002335 vereq(expected, got)
2336 vereq(f.lineno, i)
2337 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002338 f.close()
2339 finally:
2340 try:
2341 f.close()
2342 except:
2343 pass
2344 try:
2345 import os
2346 os.unlink(TESTFN)
2347 except:
2348 pass
2349
Tim Peters808b94e2001-09-13 19:33:07 +00002350def keywords():
2351 if verbose:
2352 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002353 vereq(int(x=1), 1)
2354 vereq(float(x=2), 2.0)
2355 vereq(long(x=3), 3L)
2356 vereq(complex(imag=42, real=666), complex(666, 42))
2357 vereq(str(object=500), '500')
2358 vereq(unicode(string='abc', errors='strict'), u'abc')
2359 vereq(tuple(sequence=range(3)), (0, 1, 2))
2360 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002361 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002362
2363 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002364 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002365 try:
2366 constructor(bogus_keyword_arg=1)
2367 except TypeError:
2368 pass
2369 else:
2370 raise TestFailed("expected TypeError from bogus keyword "
2371 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002372
Tim Peters8fa45672001-09-13 21:01:29 +00002373def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002374 # XXX This test is disabled because rexec is not deemed safe
2375 return
Tim Peters8fa45672001-09-13 21:01:29 +00002376 import rexec
2377 if verbose:
2378 print "Testing interaction with restricted execution ..."
2379
2380 sandbox = rexec.RExec()
2381
2382 code1 = """f = open(%r, 'w')""" % TESTFN
2383 code2 = """f = file(%r, 'w')""" % TESTFN
2384 code3 = """\
2385f = open(%r)
2386t = type(f) # a sneaky way to get the file() constructor
2387f.close()
2388f = t(%r, 'w') # rexec can't catch this by itself
2389""" % (TESTFN, TESTFN)
2390
2391 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2392 f.close()
2393
2394 try:
2395 for code in code1, code2, code3:
2396 try:
2397 sandbox.r_exec(code)
2398 except IOError, msg:
2399 if str(msg).find("restricted") >= 0:
2400 outcome = "OK"
2401 else:
2402 outcome = "got an exception, but not an expected one"
2403 else:
2404 outcome = "expected a restricted-execution exception"
2405
2406 if outcome != "OK":
2407 raise TestFailed("%s, in %r" % (outcome, code))
2408
2409 finally:
2410 try:
2411 import os
2412 os.unlink(TESTFN)
2413 except:
2414 pass
2415
Tim Peters0ab085c2001-09-14 00:25:33 +00002416def str_subclass_as_dict_key():
2417 if verbose:
2418 print "Testing a str subclass used as dict key .."
2419
2420 class cistr(str):
2421 """Sublcass of str that computes __eq__ case-insensitively.
2422
2423 Also computes a hash code of the string in canonical form.
2424 """
2425
2426 def __init__(self, value):
2427 self.canonical = value.lower()
2428 self.hashcode = hash(self.canonical)
2429
2430 def __eq__(self, other):
2431 if not isinstance(other, cistr):
2432 other = cistr(other)
2433 return self.canonical == other.canonical
2434
2435 def __hash__(self):
2436 return self.hashcode
2437
Guido van Rossum45704552001-10-08 16:35:45 +00002438 vereq(cistr('ABC'), 'abc')
2439 vereq('aBc', cistr('ABC'))
2440 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002441
2442 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002443 vereq(d[cistr('one')], 1)
2444 vereq(d[cistr('tWo')], 2)
2445 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002446 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002447 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002448
Guido van Rossumab3b0342001-09-18 20:38:53 +00002449def classic_comparisons():
2450 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002451 class classic:
2452 pass
2453 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002454 if verbose: print " (base = %s)" % base
2455 class C(base):
2456 def __init__(self, value):
2457 self.value = int(value)
2458 def __cmp__(self, other):
2459 if isinstance(other, C):
2460 return cmp(self.value, other.value)
2461 if isinstance(other, int) or isinstance(other, long):
2462 return cmp(self.value, other)
2463 return NotImplemented
2464 c1 = C(1)
2465 c2 = C(2)
2466 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002467 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002468 c = {1: c1, 2: c2, 3: c3}
2469 for x in 1, 2, 3:
2470 for y in 1, 2, 3:
2471 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2472 for op in "<", "<=", "==", "!=", ">", ">=":
2473 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2474 "x=%d, y=%d" % (x, y))
2475 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2476 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2477
Guido van Rossum0639f592001-09-18 21:06:04 +00002478def rich_comparisons():
2479 if verbose:
2480 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002481 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002482 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002483 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002484 vereq(z, 1+0j)
2485 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002486 class ZZ(complex):
2487 def __eq__(self, other):
2488 try:
2489 return abs(self - other) <= 1e-6
2490 except:
2491 return NotImplemented
2492 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002493 vereq(zz, 1+0j)
2494 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002495
Guido van Rossum0639f592001-09-18 21:06:04 +00002496 class classic:
2497 pass
2498 for base in (classic, int, object, list):
2499 if verbose: print " (base = %s)" % base
2500 class C(base):
2501 def __init__(self, value):
2502 self.value = int(value)
2503 def __cmp__(self, other):
2504 raise TestFailed, "shouldn't call __cmp__"
2505 def __eq__(self, other):
2506 if isinstance(other, C):
2507 return self.value == other.value
2508 if isinstance(other, int) or isinstance(other, long):
2509 return self.value == other
2510 return NotImplemented
2511 def __ne__(self, other):
2512 if isinstance(other, C):
2513 return self.value != other.value
2514 if isinstance(other, int) or isinstance(other, long):
2515 return self.value != other
2516 return NotImplemented
2517 def __lt__(self, other):
2518 if isinstance(other, C):
2519 return self.value < other.value
2520 if isinstance(other, int) or isinstance(other, long):
2521 return self.value < other
2522 return NotImplemented
2523 def __le__(self, other):
2524 if isinstance(other, C):
2525 return self.value <= other.value
2526 if isinstance(other, int) or isinstance(other, long):
2527 return self.value <= other
2528 return NotImplemented
2529 def __gt__(self, other):
2530 if isinstance(other, C):
2531 return self.value > other.value
2532 if isinstance(other, int) or isinstance(other, long):
2533 return self.value > other
2534 return NotImplemented
2535 def __ge__(self, other):
2536 if isinstance(other, C):
2537 return self.value >= other.value
2538 if isinstance(other, int) or isinstance(other, long):
2539 return self.value >= other
2540 return NotImplemented
2541 c1 = C(1)
2542 c2 = C(2)
2543 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002544 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002545 c = {1: c1, 2: c2, 3: c3}
2546 for x in 1, 2, 3:
2547 for y in 1, 2, 3:
2548 for op in "<", "<=", "==", "!=", ">", ">=":
2549 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2550 "x=%d, y=%d" % (x, y))
2551 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2552 "x=%d, y=%d" % (x, y))
2553 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2554 "x=%d, y=%d" % (x, y))
2555
Guido van Rossum1952e382001-09-19 01:25:16 +00002556def coercions():
2557 if verbose: print "Testing coercions..."
2558 class I(int): pass
2559 coerce(I(0), 0)
2560 coerce(0, I(0))
2561 class L(long): pass
2562 coerce(L(0), 0)
2563 coerce(L(0), 0L)
2564 coerce(0, L(0))
2565 coerce(0L, L(0))
2566 class F(float): pass
2567 coerce(F(0), 0)
2568 coerce(F(0), 0L)
2569 coerce(F(0), 0.)
2570 coerce(0, F(0))
2571 coerce(0L, F(0))
2572 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002573 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002574 coerce(C(0), 0)
2575 coerce(C(0), 0L)
2576 coerce(C(0), 0.)
2577 coerce(C(0), 0j)
2578 coerce(0, C(0))
2579 coerce(0L, C(0))
2580 coerce(0., C(0))
2581 coerce(0j, C(0))
2582
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002583def descrdoc():
2584 if verbose: print "Testing descriptor doc strings..."
2585 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002586 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002587 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002588 check(file.name, "file name") # member descriptor
2589
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002590def setclass():
2591 if verbose: print "Testing __class__ assignment..."
2592 class C(object): pass
2593 class D(object): pass
2594 class E(object): pass
2595 class F(D, E): pass
2596 for cls in C, D, E, F:
2597 for cls2 in C, D, E, F:
2598 x = cls()
2599 x.__class__ = cls2
2600 verify(x.__class__ is cls2)
2601 x.__class__ = cls
2602 verify(x.__class__ is cls)
2603 def cant(x, C):
2604 try:
2605 x.__class__ = C
2606 except TypeError:
2607 pass
2608 else:
2609 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002610 try:
2611 delattr(x, "__class__")
2612 except TypeError:
2613 pass
2614 else:
2615 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002616 cant(C(), list)
2617 cant(list(), C)
2618 cant(C(), 1)
2619 cant(C(), object)
2620 cant(object(), list)
2621 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002622 class Int(int): __slots__ = []
2623 cant(2, Int)
2624 cant(Int(), int)
2625 cant(True, int)
2626 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002627 o = object()
2628 cant(o, type(1))
2629 cant(o, type(None))
2630 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002631
Guido van Rossum6661be32001-10-26 04:26:12 +00002632def setdict():
2633 if verbose: print "Testing __dict__ assignment..."
2634 class C(object): pass
2635 a = C()
2636 a.__dict__ = {'b': 1}
2637 vereq(a.b, 1)
2638 def cant(x, dict):
2639 try:
2640 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002641 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002642 pass
2643 else:
2644 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2645 cant(a, None)
2646 cant(a, [])
2647 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002648 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002649 # Classes don't allow __dict__ assignment
2650 cant(C, {})
2651
Guido van Rossum3926a632001-09-25 16:25:58 +00002652def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002653 if verbose:
2654 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002655 import pickle, cPickle
2656
2657 def sorteditems(d):
2658 L = d.items()
2659 L.sort()
2660 return L
2661
2662 global C
2663 class C(object):
2664 def __init__(self, a, b):
2665 super(C, self).__init__()
2666 self.a = a
2667 self.b = b
2668 def __repr__(self):
2669 return "C(%r, %r)" % (self.a, self.b)
2670
2671 global C1
2672 class C1(list):
2673 def __new__(cls, a, b):
2674 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002675 def __getnewargs__(self):
2676 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002677 def __init__(self, a, b):
2678 self.a = a
2679 self.b = b
2680 def __repr__(self):
2681 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2682
2683 global C2
2684 class C2(int):
2685 def __new__(cls, a, b, val=0):
2686 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002687 def __getnewargs__(self):
2688 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002689 def __init__(self, a, b, val=0):
2690 self.a = a
2691 self.b = b
2692 def __repr__(self):
2693 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2694
Guido van Rossum90c45142001-11-24 21:07:01 +00002695 global C3
2696 class C3(object):
2697 def __init__(self, foo):
2698 self.foo = foo
2699 def __getstate__(self):
2700 return self.foo
2701 def __setstate__(self, foo):
2702 self.foo = foo
2703
2704 global C4classic, C4
2705 class C4classic: # classic
2706 pass
2707 class C4(C4classic, object): # mixed inheritance
2708 pass
2709
Guido van Rossum3926a632001-09-25 16:25:58 +00002710 for p in pickle, cPickle:
2711 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002712 if verbose:
2713 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002714
2715 for cls in C, C1, C2:
2716 s = p.dumps(cls, bin)
2717 cls2 = p.loads(s)
2718 verify(cls2 is cls)
2719
2720 a = C1(1, 2); a.append(42); a.append(24)
2721 b = C2("hello", "world", 42)
2722 s = p.dumps((a, b), bin)
2723 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002724 vereq(x.__class__, a.__class__)
2725 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2726 vereq(y.__class__, b.__class__)
2727 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002728 vereq(repr(x), repr(a))
2729 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002730 if verbose:
2731 print "a = x =", a
2732 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002733 # Test for __getstate__ and __setstate__ on new style class
2734 u = C3(42)
2735 s = p.dumps(u, bin)
2736 v = p.loads(s)
2737 veris(u.__class__, v.__class__)
2738 vereq(u.foo, v.foo)
2739 # Test for picklability of hybrid class
2740 u = C4()
2741 u.foo = 42
2742 s = p.dumps(u, bin)
2743 v = p.loads(s)
2744 veris(u.__class__, v.__class__)
2745 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002746
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002747 # Testing copy.deepcopy()
2748 if verbose:
2749 print "deepcopy"
2750 import copy
2751 for cls in C, C1, C2:
2752 cls2 = copy.deepcopy(cls)
2753 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002754
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002755 a = C1(1, 2); a.append(42); a.append(24)
2756 b = C2("hello", "world", 42)
2757 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002758 vereq(x.__class__, a.__class__)
2759 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2760 vereq(y.__class__, b.__class__)
2761 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002762 vereq(repr(x), repr(a))
2763 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002764 if verbose:
2765 print "a = x =", a
2766 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002767
Guido van Rossum8c842552002-03-14 23:05:54 +00002768def pickleslots():
2769 if verbose: print "Testing pickling of classes with __slots__ ..."
2770 import pickle, cPickle
2771 # Pickling of classes with __slots__ but without __getstate__ should fail
2772 global B, C, D, E
2773 class B(object):
2774 pass
2775 for base in [object, B]:
2776 class C(base):
2777 __slots__ = ['a']
2778 class D(C):
2779 pass
2780 try:
2781 pickle.dumps(C())
2782 except TypeError:
2783 pass
2784 else:
2785 raise TestFailed, "should fail: pickle C instance - %s" % base
2786 try:
2787 cPickle.dumps(C())
2788 except TypeError:
2789 pass
2790 else:
2791 raise TestFailed, "should fail: cPickle C instance - %s" % base
2792 try:
2793 pickle.dumps(C())
2794 except TypeError:
2795 pass
2796 else:
2797 raise TestFailed, "should fail: pickle D instance - %s" % base
2798 try:
2799 cPickle.dumps(D())
2800 except TypeError:
2801 pass
2802 else:
2803 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002804 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002805 class C(base):
2806 __slots__ = ['a']
2807 def __getstate__(self):
2808 try:
2809 d = self.__dict__.copy()
2810 except AttributeError:
2811 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002812 for cls in self.__class__.__mro__:
2813 for sn in cls.__dict__.get('__slots__', ()):
2814 try:
2815 d[sn] = getattr(self, sn)
2816 except AttributeError:
2817 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002818 return d
2819 def __setstate__(self, d):
2820 for k, v in d.items():
2821 setattr(self, k, v)
2822 class D(C):
2823 pass
2824 # Now it should work
2825 x = C()
2826 y = pickle.loads(pickle.dumps(x))
2827 vereq(hasattr(y, 'a'), 0)
2828 y = cPickle.loads(cPickle.dumps(x))
2829 vereq(hasattr(y, 'a'), 0)
2830 x.a = 42
2831 y = pickle.loads(pickle.dumps(x))
2832 vereq(y.a, 42)
2833 y = cPickle.loads(cPickle.dumps(x))
2834 vereq(y.a, 42)
2835 x = D()
2836 x.a = 42
2837 x.b = 100
2838 y = pickle.loads(pickle.dumps(x))
2839 vereq(y.a + y.b, 142)
2840 y = cPickle.loads(cPickle.dumps(x))
2841 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002842 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00002843 class E(C):
2844 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002845 x = E()
2846 x.a = 42
2847 x.b = "foo"
2848 y = pickle.loads(pickle.dumps(x))
2849 vereq(y.a, x.a)
2850 vereq(y.b, x.b)
2851 y = cPickle.loads(cPickle.dumps(x))
2852 vereq(y.a, x.a)
2853 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00002854
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
Walter Dörwald70a6b492004-02-12 17:35:32 +00002895 vereq(repr(I(1) + I(2)), "I(3)")
2896 vereq(repr(I(1) + 2), "I(3)")
2897 vereq(repr(1 + I(2)), "I(3)")
2898 vereq(repr(I(2) ** I(3)), "I(8)")
2899 vereq(repr(2 ** I(3)), "I(8)")
2900 vereq(repr(I(2) ** 3), "I(8)")
2901 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002902 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
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003245def copy_setstate():
3246 if verbose:
3247 print "Testing that copy.*copy() correctly uses __setstate__..."
3248 import copy
3249 class C(object):
3250 def __init__(self, foo=None):
3251 self.foo = foo
3252 self.__foo = foo
3253 def setfoo(self, foo=None):
3254 self.foo = foo
3255 def getfoo(self):
3256 return self.__foo
3257 def __getstate__(self):
3258 return [self.foo]
3259 def __setstate__(self, lst):
3260 assert len(lst) == 1
3261 self.__foo = self.foo = lst[0]
3262 a = C(42)
3263 a.setfoo(24)
3264 vereq(a.foo, 24)
3265 vereq(a.getfoo(), 42)
3266 b = copy.copy(a)
3267 vereq(b.foo, 24)
3268 vereq(b.getfoo(), 24)
3269 b = copy.deepcopy(a)
3270 vereq(b.foo, 24)
3271 vereq(b.getfoo(), 24)
3272
Guido van Rossum09638c12002-06-13 19:17:46 +00003273def slices():
3274 if verbose:
3275 print "Testing cases with slices and overridden __getitem__ ..."
3276 # Strings
3277 vereq("hello"[:4], "hell")
3278 vereq("hello"[slice(4)], "hell")
3279 vereq(str.__getitem__("hello", slice(4)), "hell")
3280 class S(str):
3281 def __getitem__(self, x):
3282 return str.__getitem__(self, x)
3283 vereq(S("hello")[:4], "hell")
3284 vereq(S("hello")[slice(4)], "hell")
3285 vereq(S("hello").__getitem__(slice(4)), "hell")
3286 # Tuples
3287 vereq((1,2,3)[:2], (1,2))
3288 vereq((1,2,3)[slice(2)], (1,2))
3289 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3290 class T(tuple):
3291 def __getitem__(self, x):
3292 return tuple.__getitem__(self, x)
3293 vereq(T((1,2,3))[:2], (1,2))
3294 vereq(T((1,2,3))[slice(2)], (1,2))
3295 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3296 # Lists
3297 vereq([1,2,3][:2], [1,2])
3298 vereq([1,2,3][slice(2)], [1,2])
3299 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3300 class L(list):
3301 def __getitem__(self, x):
3302 return list.__getitem__(self, x)
3303 vereq(L([1,2,3])[:2], [1,2])
3304 vereq(L([1,2,3])[slice(2)], [1,2])
3305 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3306 # Now do lists and __setitem__
3307 a = L([1,2,3])
3308 a[slice(1, 3)] = [3,2]
3309 vereq(a, [1,3,2])
3310 a[slice(0, 2, 1)] = [3,1]
3311 vereq(a, [3,1,2])
3312 a.__setitem__(slice(1, 3), [2,1])
3313 vereq(a, [3,2,1])
3314 a.__setitem__(slice(0, 2, 1), [2,3])
3315 vereq(a, [2,3,1])
3316
Tim Peters2484aae2002-07-11 06:56:07 +00003317def subtype_resurrection():
3318 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003319 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003320
3321 class C(object):
3322 container = []
3323
3324 def __del__(self):
3325 # resurrect the instance
3326 C.container.append(self)
3327
3328 c = C()
3329 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003330 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003331 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003332 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003333
3334 # If that didn't blow up, it's also interesting to see whether clearing
3335 # the last container slot works: that will attempt to delete c again,
3336 # which will cause c to get appended back to the container again "during"
3337 # the del.
3338 del C.container[-1]
3339 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003340 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003341
Tim Peters14cb1e12002-07-11 18:26:21 +00003342 # Make c mortal again, so that the test framework with -l doesn't report
3343 # it as a leak.
3344 del C.__del__
3345
Guido van Rossum2d702462002-08-06 21:28:28 +00003346def slottrash():
3347 # Deallocating deeply nested slotted trash caused stack overflows
3348 if verbose:
3349 print "Testing slot trash..."
3350 class trash(object):
3351 __slots__ = ['x']
3352 def __init__(self, x):
3353 self.x = x
3354 o = None
3355 for i in xrange(50000):
3356 o = trash(o)
3357 del o
3358
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003359def slotmultipleinheritance():
3360 # SF bug 575229, multiple inheritance w/ slots dumps core
3361 class A(object):
3362 __slots__=()
3363 class B(object):
3364 pass
3365 class C(A,B) :
3366 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003367 vereq(C.__basicsize__, B.__basicsize__)
3368 verify(hasattr(C, '__dict__'))
3369 verify(hasattr(C, '__weakref__'))
3370 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003371
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003372def testrmul():
3373 # SF patch 592646
3374 if verbose:
3375 print "Testing correct invocation of __rmul__..."
3376 class C(object):
3377 def __mul__(self, other):
3378 return "mul"
3379 def __rmul__(self, other):
3380 return "rmul"
3381 a = C()
3382 vereq(a*2, "mul")
3383 vereq(a*2.2, "mul")
3384 vereq(2*a, "rmul")
3385 vereq(2.2*a, "rmul")
3386
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003387def testipow():
3388 # [SF bug 620179]
3389 if verbose:
3390 print "Testing correct invocation of __ipow__..."
3391 class C(object):
3392 def __ipow__(self, other):
3393 pass
3394 a = C()
3395 a **= 2
3396
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003397def do_this_first():
3398 if verbose:
3399 print "Testing SF bug 551412 ..."
3400 # This dumps core when SF bug 551412 isn't fixed --
3401 # but only when test_descr.py is run separately.
3402 # (That can't be helped -- as soon as PyType_Ready()
3403 # is called for PyLong_Type, the bug is gone.)
3404 class UserLong(object):
3405 def __pow__(self, *args):
3406 pass
3407 try:
3408 pow(0L, UserLong(), 0L)
3409 except:
3410 pass
3411
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003412 if verbose:
3413 print "Testing SF bug 570483..."
3414 # Another segfault only when run early
3415 # (before PyType_Ready(tuple) is called)
3416 type.mro(tuple)
3417
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003418def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003419 if verbose:
3420 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003421 # stuff that should work:
3422 class C(object):
3423 pass
3424 class C2(object):
3425 def __getattribute__(self, attr):
3426 if attr == 'a':
3427 return 2
3428 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003429 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003430 def meth(self):
3431 return 1
3432 class D(C):
3433 pass
3434 class E(D):
3435 pass
3436 d = D()
3437 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003438 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003439 D.__bases__ = (C2,)
3440 vereq(d.meth(), 1)
3441 vereq(e.meth(), 1)
3442 vereq(d.a, 2)
3443 vereq(e.a, 2)
3444 vereq(C2.__subclasses__(), [D])
3445
3446 # stuff that shouldn't:
3447 class L(list):
3448 pass
3449
3450 try:
3451 L.__bases__ = (dict,)
3452 except TypeError:
3453 pass
3454 else:
3455 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3456
3457 try:
3458 list.__bases__ = (dict,)
3459 except TypeError:
3460 pass
3461 else:
3462 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3463
3464 try:
3465 del D.__bases__
3466 except TypeError:
3467 pass
3468 else:
3469 raise TestFailed, "shouldn't be able to delete .__bases__"
3470
3471 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003472 D.__bases__ = ()
3473 except TypeError, msg:
3474 if str(msg) == "a new-style class can't have only classic bases":
3475 raise TestFailed, "wrong error message for .__bases__ = ()"
3476 else:
3477 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3478
3479 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003480 D.__bases__ = (D,)
3481 except TypeError:
3482 pass
3483 else:
3484 # actually, we'll have crashed by here...
3485 raise TestFailed, "shouldn't be able to create inheritance cycles"
3486
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003487 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003488 D.__bases__ = (C, C)
3489 except TypeError:
3490 pass
3491 else:
3492 raise TestFailed, "didn't detect repeated base classes"
3493
3494 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003495 D.__bases__ = (E,)
3496 except TypeError:
3497 pass
3498 else:
3499 raise TestFailed, "shouldn't be able to create inheritance cycles"
3500
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003501def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003502 if verbose:
3503 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003504 class WorkOnce(type):
3505 def __new__(self, name, bases, ns):
3506 self.flag = 0
3507 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3508 def mro(self):
3509 if self.flag > 0:
3510 raise RuntimeError, "bozo"
3511 else:
3512 self.flag += 1
3513 return type.mro(self)
3514
3515 class WorkAlways(type):
3516 def mro(self):
3517 # this is here to make sure that .mro()s aren't called
3518 # with an exception set (which was possible at one point).
3519 # An error message will be printed in a debug build.
3520 # What's a good way to test for this?
3521 return type.mro(self)
3522
3523 class C(object):
3524 pass
3525
3526 class C2(object):
3527 pass
3528
3529 class D(C):
3530 pass
3531
3532 class E(D):
3533 pass
3534
3535 class F(D):
3536 __metaclass__ = WorkOnce
3537
3538 class G(D):
3539 __metaclass__ = WorkAlways
3540
3541 # Immediate subclasses have their mro's adjusted in alphabetical
3542 # order, so E's will get adjusted before adjusting F's fails. We
3543 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003544
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003545 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003546 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003547
3548 try:
3549 D.__bases__ = (C2,)
3550 except RuntimeError:
3551 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003552 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003553 else:
3554 raise TestFailed, "exception not propagated"
3555
3556def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003557 if verbose:
3558 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003559 class A(object):
3560 pass
3561
3562 class B(object):
3563 pass
3564
3565 class C(A, B):
3566 pass
3567
3568 class D(A, B):
3569 pass
3570
3571 class E(C, D):
3572 pass
3573
3574 try:
3575 C.__bases__ = (B, A)
3576 except TypeError:
3577 pass
3578 else:
3579 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003580
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003581def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003582 if verbose:
3583 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003584 class C(object):
3585 pass
3586
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003587 # C.__module__ could be 'test_descr' or '__main__'
3588 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003589
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003590 C.__name__ = 'D'
3591 vereq((C.__module__, C.__name__), (mod, 'D'))
3592
3593 C.__name__ = 'D.E'
3594 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003595
Guido van Rossum613f24f2003-01-06 23:00:59 +00003596def subclass_right_op():
3597 if verbose:
3598 print "Testing correct dispatch of subclass overloading __r<op>__..."
3599
3600 # This code tests various cases where right-dispatch of a subclass
3601 # should be preferred over left-dispatch of a base class.
3602
3603 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3604
3605 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003606 def __floordiv__(self, other):
3607 return "B.__floordiv__"
3608 def __rfloordiv__(self, other):
3609 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003610
Guido van Rossumf389c772003-02-27 20:04:19 +00003611 vereq(B(1) // 1, "B.__floordiv__")
3612 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003613
3614 # Case 2: subclass of object; this is just the baseline for case 3
3615
3616 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003617 def __floordiv__(self, other):
3618 return "C.__floordiv__"
3619 def __rfloordiv__(self, other):
3620 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003621
Guido van Rossumf389c772003-02-27 20:04:19 +00003622 vereq(C() // 1, "C.__floordiv__")
3623 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003624
3625 # Case 3: subclass of new-style class; here it gets interesting
3626
3627 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003628 def __floordiv__(self, other):
3629 return "D.__floordiv__"
3630 def __rfloordiv__(self, other):
3631 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003632
Guido van Rossumf389c772003-02-27 20:04:19 +00003633 vereq(D() // C(), "D.__floordiv__")
3634 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003635
3636 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3637
3638 class E(C):
3639 pass
3640
Guido van Rossumf389c772003-02-27 20:04:19 +00003641 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003642
Guido van Rossumf389c772003-02-27 20:04:19 +00003643 vereq(E() // 1, "C.__floordiv__")
3644 vereq(1 // E(), "C.__rfloordiv__")
3645 vereq(E() // C(), "C.__floordiv__")
3646 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003647
Guido van Rossum373c7412003-01-07 13:41:37 +00003648def dict_type_with_metaclass():
3649 if verbose:
3650 print "Testing type of __dict__ when __metaclass__ set..."
3651
3652 class B(object):
3653 pass
3654 class M(type):
3655 pass
3656 class C:
3657 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3658 __metaclass__ = M
3659 veris(type(C.__dict__), type(B.__dict__))
3660
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003661def meth_class_get():
3662 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003663 if verbose:
3664 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003665 # Baseline
3666 arg = [1, 2, 3]
3667 res = {1: None, 2: None, 3: None}
3668 vereq(dict.fromkeys(arg), res)
3669 vereq({}.fromkeys(arg), res)
3670 # Now get the descriptor
3671 descr = dict.__dict__["fromkeys"]
3672 # More baseline using the descriptor directly
3673 vereq(descr.__get__(None, dict)(arg), res)
3674 vereq(descr.__get__({})(arg), res)
3675 # Now check various error cases
3676 try:
3677 descr.__get__(None, None)
3678 except TypeError:
3679 pass
3680 else:
3681 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3682 try:
3683 descr.__get__(42)
3684 except TypeError:
3685 pass
3686 else:
3687 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3688 try:
3689 descr.__get__(None, 42)
3690 except TypeError:
3691 pass
3692 else:
3693 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3694 try:
3695 descr.__get__(None, int)
3696 except TypeError:
3697 pass
3698 else:
3699 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3700
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003701def isinst_isclass():
3702 if verbose:
3703 print "Testing proxy isinstance() and isclass()..."
3704 class Proxy(object):
3705 def __init__(self, obj):
3706 self.__obj = obj
3707 def __getattribute__(self, name):
3708 if name.startswith("_Proxy__"):
3709 return object.__getattribute__(self, name)
3710 else:
3711 return getattr(self.__obj, name)
3712 # Test with a classic class
3713 class C:
3714 pass
3715 a = C()
3716 pa = Proxy(a)
3717 verify(isinstance(a, C)) # Baseline
3718 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003719 # Test with a classic subclass
3720 class D(C):
3721 pass
3722 a = D()
3723 pa = Proxy(a)
3724 verify(isinstance(a, C)) # Baseline
3725 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003726 # Test with a new-style class
3727 class C(object):
3728 pass
3729 a = C()
3730 pa = Proxy(a)
3731 verify(isinstance(a, C)) # Baseline
3732 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003733 # Test with a new-style subclass
3734 class D(C):
3735 pass
3736 a = D()
3737 pa = Proxy(a)
3738 verify(isinstance(a, C)) # Baseline
3739 verify(isinstance(pa, C)) # Test
3740
3741def proxysuper():
3742 if verbose:
3743 print "Testing super() for a proxy object..."
3744 class Proxy(object):
3745 def __init__(self, obj):
3746 self.__obj = obj
3747 def __getattribute__(self, name):
3748 if name.startswith("_Proxy__"):
3749 return object.__getattribute__(self, name)
3750 else:
3751 return getattr(self.__obj, name)
3752
3753 class B(object):
3754 def f(self):
3755 return "B.f"
3756
3757 class C(B):
3758 def f(self):
3759 return super(C, self).f() + "->C.f"
3760
3761 obj = C()
3762 p = Proxy(obj)
3763 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003764
Guido van Rossum52b27052003-04-15 20:05:10 +00003765def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003766 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00003767 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003768 try:
3769 object.__setattr__(str, "foo", 42)
3770 except TypeError:
3771 pass
3772 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003773 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003774 try:
3775 object.__delattr__(str, "lower")
3776 except TypeError:
3777 pass
3778 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003779 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003780
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003781def weakref_segfault():
3782 # SF 742911
3783 if verbose:
3784 print "Testing weakref segfault..."
3785
3786 import weakref
3787
3788 class Provoker:
3789 def __init__(self, referrent):
3790 self.ref = weakref.ref(referrent)
3791
3792 def __del__(self):
3793 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003794
3795 class Oops(object):
3796 pass
3797
3798 o = Oops()
3799 o.whatever = Provoker(o)
3800 del o
3801
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003802# Fix SF #762455, segfault when sys.stdout is changed in getattr
3803def filefault():
3804 if verbose:
3805 print "Testing sys.stdout is changed in getattr..."
3806 import sys
3807 class StdoutGuard:
3808 def __getattr__(self, attr):
3809 sys.stdout = sys.__stdout__
3810 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3811 sys.stdout = StdoutGuard()
3812 try:
3813 print "Oops!"
3814 except RuntimeError:
3815 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003816
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003817def vicious_descriptor_nonsense():
3818 # A potential segfault spotted by Thomas Wouters in mail to
3819 # python-dev 2003-04-17, turned into an example & fixed by Michael
3820 # Hudson just less than four months later...
3821 if verbose:
3822 print "Testing vicious_descriptor_nonsense..."
3823
3824 class Evil(object):
3825 def __hash__(self):
3826 return hash('attr')
3827 def __eq__(self, other):
3828 del C.attr
3829 return 0
3830
3831 class Descr(object):
3832 def __get__(self, ob, type=None):
3833 return 1
3834
3835 class C(object):
3836 attr = Descr()
3837
3838 c = C()
3839 c.__dict__[Evil()] = 0
3840
3841 vereq(c.attr, 1)
3842 # this makes a crash more likely:
3843 import gc; gc.collect()
3844 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00003845
Raymond Hettingerb67cc802005-03-03 16:45:19 +00003846def test_init():
3847 # SF 1155938
3848 class Foo(object):
3849 def __init__(self):
3850 return 10
3851 try:
3852 Foo()
3853 except TypeError:
3854 pass
3855 else:
3856 raise TestFailed, "did not test __init__() for None return"
3857
Armin Rigoc6686b72005-11-07 08:38:00 +00003858def methodwrapper():
3859 # <type 'method-wrapper'> did not support any reflection before 2.5
3860 if verbose:
3861 print "Testing method-wrapper objects..."
3862
3863 l = []
3864 vereq(l.__add__, l.__add__)
3865 verify(l.__add__ != [].__add__)
3866 verify(l.__add__.__name__ == '__add__')
3867 verify(l.__add__.__self__ is l)
3868 verify(l.__add__.__objclass__ is list)
3869 vereq(l.__add__.__doc__, list.__add__.__doc__)
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003870
Armin Rigofd163f92005-12-29 15:59:19 +00003871def notimplemented():
3872 # all binary methods should be able to return a NotImplemented
3873 if verbose:
3874 print "Testing NotImplemented..."
3875
3876 import sys
3877 import types
3878 import operator
3879
3880 def specialmethod(self, other):
3881 return NotImplemented
3882
3883 def check(expr, x, y):
3884 try:
3885 exec expr in {'x': x, 'y': y, 'operator': operator}
3886 except TypeError:
3887 pass
3888 else:
3889 raise TestFailed("no TypeError from %r" % (expr,))
3890
3891 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
3892 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
3893 # ValueErrors instead of TypeErrors
3894 for metaclass in [type, types.ClassType]:
3895 for name, expr, iexpr in [
3896 ('__add__', 'x + y', 'x += y'),
3897 ('__sub__', 'x - y', 'x -= y'),
3898 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003899 ('__truediv__', 'x / y', None),
3900 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00003901 ('__mod__', 'x % y', 'x %= y'),
3902 ('__divmod__', 'divmod(x, y)', None),
3903 ('__pow__', 'x ** y', 'x **= y'),
3904 ('__lshift__', 'x << y', 'x <<= y'),
3905 ('__rshift__', 'x >> y', 'x >>= y'),
3906 ('__and__', 'x & y', 'x &= y'),
3907 ('__or__', 'x | y', 'x |= y'),
3908 ('__xor__', 'x ^ y', 'x ^= y'),
3909 ('__coerce__', 'coerce(x, y)', None)]:
3910 if name == '__coerce__':
3911 rname = name
3912 else:
3913 rname = '__r' + name[2:]
3914 A = metaclass('A', (), {name: specialmethod})
3915 B = metaclass('B', (), {rname: specialmethod})
3916 a = A()
3917 b = B()
3918 check(expr, a, a)
3919 check(expr, a, b)
3920 check(expr, b, a)
3921 check(expr, b, b)
3922 check(expr, a, N1)
3923 check(expr, a, N2)
3924 check(expr, N1, b)
3925 check(expr, N2, b)
3926 if iexpr:
3927 check(iexpr, a, a)
3928 check(iexpr, a, b)
3929 check(iexpr, b, a)
3930 check(iexpr, b, b)
3931 check(iexpr, a, N1)
3932 check(iexpr, a, N2)
3933 iname = '__i' + name[2:]
3934 C = metaclass('C', (), {iname: specialmethod})
3935 c = C()
3936 check(iexpr, c, a)
3937 check(iexpr, c, b)
3938 check(iexpr, c, N1)
3939 check(iexpr, c, N2)
3940
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003941def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003942 weakref_segfault() # Must be first, somehow
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003943 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00003944 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945 lists()
3946 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00003947 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00003948 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003949 ints()
3950 longs()
3951 floats()
3952 complexes()
3953 spamlists()
3954 spamdicts()
3955 pydicts()
3956 pylists()
3957 metaclass()
3958 pymods()
3959 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00003960 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00003962 ex5()
3963 monotonicity()
3964 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00003965 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003967 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968 dynamics()
3969 errors()
3970 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003971 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003973 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003974 classic()
3975 compattr()
3976 newslot()
3977 altmro()
3978 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00003979 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00003980 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00003981 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00003982 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00003983 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00003984 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00003985 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00003986 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00003987 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00003988 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00003989 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00003990 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00003991 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003992 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00003993 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00003994 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003995 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003996 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003997 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00003998 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00003999 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004000 kwdargs()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004001 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004002 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004003 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004004 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004005 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004006 dictproxyiterkeys()
4007 dictproxyitervalues()
4008 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004009 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004010 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004011 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004012 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004013 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004014 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004015 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004016 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004017 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004018 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004019 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004020 test_mutable_bases()
4021 test_mutable_bases_with_failing_mro()
4022 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004023 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004024 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004025 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004026 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004027 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004028 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004029 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004030 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004031 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004032 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004033 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004034 notimplemented()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004035
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004036 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004038if __name__ == "__main__":
4039 test_main()