blob: 4a39be5b2810645e615f661cef59c8e270399e3e [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)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001641 verify(id(c1) != id(c2))
1642 hash(c1)
1643 hash(c2)
Guido van Rossum45704552001-10-08 16:35:45 +00001644 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1645 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001646 verify(c1 != c2)
1647 verify(not c1 != c1)
1648 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001649 # Note that the module name appears in str/repr, and that varies
1650 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001651 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001652 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001653 verify(-1 not in c1)
1654 for i in range(10):
1655 verify(i in c1)
1656 verify(10 not in c1)
1657 # Test the default behavior for dynamic classes
1658 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001659 def __getitem__(self, i):
1660 if 0 <= i < 10: return i
1661 raise IndexError
1662 d1 = D()
1663 d2 = D()
1664 verify(not not d1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001665 verify(id(d1) != id(d2))
1666 hash(d1)
1667 hash(d2)
Guido van Rossum45704552001-10-08 16:35:45 +00001668 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1669 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001670 verify(d1 != d2)
1671 verify(not d1 != d1)
1672 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001673 # Note that the module name appears in str/repr, and that varies
1674 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001675 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001676 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001677 verify(-1 not in d1)
1678 for i in range(10):
1679 verify(i in d1)
1680 verify(10 not in d1)
1681 # Test overridden behavior for static classes
1682 class Proxy(object):
1683 def __init__(self, x):
1684 self.x = x
1685 def __nonzero__(self):
1686 return not not self.x
1687 def __hash__(self):
1688 return hash(self.x)
1689 def __eq__(self, other):
1690 return self.x == other
1691 def __ne__(self, other):
1692 return self.x != other
1693 def __cmp__(self, other):
1694 return cmp(self.x, other.x)
1695 def __str__(self):
1696 return "Proxy:%s" % self.x
1697 def __repr__(self):
1698 return "Proxy(%r)" % self.x
1699 def __contains__(self, value):
1700 return value in self.x
1701 p0 = Proxy(0)
1702 p1 = Proxy(1)
1703 p_1 = Proxy(-1)
1704 verify(not p0)
1705 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001706 vereq(hash(p0), hash(0))
1707 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001708 verify(p0 != p1)
1709 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001710 vereq(not p0, p1)
1711 vereq(cmp(p0, p1), -1)
1712 vereq(cmp(p0, p0), 0)
1713 vereq(cmp(p0, p_1), 1)
1714 vereq(str(p0), "Proxy:0")
1715 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001716 p10 = Proxy(range(10))
1717 verify(-1 not in p10)
1718 for i in range(10):
1719 verify(i in p10)
1720 verify(10 not in p10)
1721 # Test overridden behavior for dynamic classes
1722 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001723 def __init__(self, x):
1724 self.x = x
1725 def __nonzero__(self):
1726 return not not self.x
1727 def __hash__(self):
1728 return hash(self.x)
1729 def __eq__(self, other):
1730 return self.x == other
1731 def __ne__(self, other):
1732 return self.x != other
1733 def __cmp__(self, other):
1734 return cmp(self.x, other.x)
1735 def __str__(self):
1736 return "DProxy:%s" % self.x
1737 def __repr__(self):
1738 return "DProxy(%r)" % self.x
1739 def __contains__(self, value):
1740 return value in self.x
1741 p0 = DProxy(0)
1742 p1 = DProxy(1)
1743 p_1 = DProxy(-1)
1744 verify(not p0)
1745 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001746 vereq(hash(p0), hash(0))
1747 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001748 verify(p0 != p1)
1749 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001750 vereq(not p0, p1)
1751 vereq(cmp(p0, p1), -1)
1752 vereq(cmp(p0, p0), 0)
1753 vereq(cmp(p0, p_1), 1)
1754 vereq(str(p0), "DProxy:0")
1755 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001756 p10 = DProxy(range(10))
1757 verify(-1 not in p10)
1758 for i in range(10):
1759 verify(i in p10)
1760 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001761 # Safety test for __cmp__
1762 def unsafecmp(a, b):
1763 try:
1764 a.__class__.__cmp__(a, b)
1765 except TypeError:
1766 pass
1767 else:
1768 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1769 a.__class__, a, b)
1770 unsafecmp(u"123", "123")
1771 unsafecmp("123", u"123")
1772 unsafecmp(1, 1.0)
1773 unsafecmp(1.0, 1)
1774 unsafecmp(1, 1L)
1775 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001776
Neal Norwitz1a997502003-01-13 20:13:12 +00001777 class Letter(str):
1778 def __new__(cls, letter):
1779 if letter == 'EPS':
1780 return str.__new__(cls)
1781 return str.__new__(cls, letter)
1782 def __str__(self):
1783 if not self:
1784 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001785 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001786
1787 # sys.stdout needs to be the original to trigger the recursion bug
1788 import sys
1789 test_stdout = sys.stdout
1790 sys.stdout = get_original_stdout()
1791 try:
1792 # nothing should actually be printed, this should raise an exception
1793 print Letter('w')
1794 except RuntimeError:
1795 pass
1796 else:
1797 raise TestFailed, "expected a RuntimeError for print recursion"
1798 sys.stdout = test_stdout
1799
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001800def weakrefs():
1801 if verbose: print "Testing weak references..."
1802 import weakref
1803 class C(object):
1804 pass
1805 c = C()
1806 r = weakref.ref(c)
1807 verify(r() is c)
1808 del c
1809 verify(r() is None)
1810 del r
1811 class NoWeak(object):
1812 __slots__ = ['foo']
1813 no = NoWeak()
1814 try:
1815 weakref.ref(no)
1816 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001817 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001818 else:
1819 verify(0, "weakref.ref(no) should be illegal")
1820 class Weak(object):
1821 __slots__ = ['foo', '__weakref__']
1822 yes = Weak()
1823 r = weakref.ref(yes)
1824 verify(r() is yes)
1825 del yes
1826 verify(r() is None)
1827 del r
1828
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001829def properties():
1830 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001831 class C(object):
1832 def getx(self):
1833 return self.__x
1834 def setx(self, value):
1835 self.__x = value
1836 def delx(self):
1837 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001838 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001839 a = C()
1840 verify(not hasattr(a, "x"))
1841 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001842 vereq(a._C__x, 42)
1843 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001844 del a.x
1845 verify(not hasattr(a, "x"))
1846 verify(not hasattr(a, "_C__x"))
1847 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001848 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001849 C.x.__delete__(a)
1850 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001851
Tim Peters66c1a522001-09-24 21:17:50 +00001852 raw = C.__dict__['x']
1853 verify(isinstance(raw, property))
1854
1855 attrs = dir(raw)
1856 verify("__doc__" in attrs)
1857 verify("fget" in attrs)
1858 verify("fset" in attrs)
1859 verify("fdel" in attrs)
1860
Guido van Rossum45704552001-10-08 16:35:45 +00001861 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001862 verify(raw.fget is C.__dict__['getx'])
1863 verify(raw.fset is C.__dict__['setx'])
1864 verify(raw.fdel is C.__dict__['delx'])
1865
1866 for attr in "__doc__", "fget", "fset", "fdel":
1867 try:
1868 setattr(raw, attr, 42)
1869 except TypeError, msg:
1870 if str(msg).find('readonly') < 0:
1871 raise TestFailed("when setting readonly attr %r on a "
1872 "property, got unexpected TypeError "
1873 "msg %r" % (attr, str(msg)))
1874 else:
1875 raise TestFailed("expected TypeError from trying to set "
1876 "readonly %r attr on a property" % attr)
1877
Neal Norwitz673cd822002-10-18 16:33:13 +00001878 class D(object):
1879 __getitem__ = property(lambda s: 1/0)
1880
1881 d = D()
1882 try:
1883 for i in d:
1884 str(i)
1885 except ZeroDivisionError:
1886 pass
1887 else:
1888 raise TestFailed, "expected ZeroDivisionError from bad property"
1889
Georg Brandl533ff6f2006-03-08 18:09:27 +00001890 class E(object):
1891 def getter(self):
1892 "getter method"
1893 return 0
1894 def setter(self, value):
1895 "setter method"
1896 pass
1897 prop = property(getter)
1898 vereq(prop.__doc__, "getter method")
1899 prop2 = property(fset=setter)
1900 vereq(prop2.__doc__, None)
1901
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001902 # this segfaulted in 2.5b2
1903 try:
1904 import _testcapi
1905 except ImportError:
1906 pass
1907 else:
1908 class X(object):
1909 p = property(_testcapi.test_with_docstring)
1910
1911
Guido van Rossumc4a18802001-08-24 16:55:27 +00001912def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001913 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001914
1915 class A(object):
1916 def meth(self, a):
1917 return "A(%r)" % a
1918
Guido van Rossum45704552001-10-08 16:35:45 +00001919 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001920
1921 class B(A):
1922 def __init__(self):
1923 self.__super = super(B, self)
1924 def meth(self, a):
1925 return "B(%r)" % a + self.__super.meth(a)
1926
Guido van Rossum45704552001-10-08 16:35:45 +00001927 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001928
1929 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00001930 def meth(self, a):
1931 return "C(%r)" % a + self.__super.meth(a)
1932 C._C__super = super(C)
1933
Guido van Rossum45704552001-10-08 16:35:45 +00001934 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001935
1936 class D(C, B):
1937 def meth(self, a):
1938 return "D(%r)" % a + super(D, self).meth(a)
1939
Guido van Rossum5b443c62001-12-03 15:38:28 +00001940 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1941
1942 # Test for subclassing super
1943
1944 class mysuper(super):
1945 def __init__(self, *args):
1946 return super(mysuper, self).__init__(*args)
1947
1948 class E(D):
1949 def meth(self, a):
1950 return "E(%r)" % a + mysuper(E, self).meth(a)
1951
1952 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1953
1954 class F(E):
1955 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00001956 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00001957 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1958 F._F__super = mysuper(F)
1959
1960 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1961
1962 # Make sure certain errors are raised
1963
1964 try:
1965 super(D, 42)
1966 except TypeError:
1967 pass
1968 else:
1969 raise TestFailed, "shouldn't allow super(D, 42)"
1970
1971 try:
1972 super(D, C())
1973 except TypeError:
1974 pass
1975 else:
1976 raise TestFailed, "shouldn't allow super(D, C())"
1977
1978 try:
1979 super(D).__get__(12)
1980 except TypeError:
1981 pass
1982 else:
1983 raise TestFailed, "shouldn't allow super(D).__get__(12)"
1984
1985 try:
1986 super(D).__get__(C())
1987 except TypeError:
1988 pass
1989 else:
1990 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00001991
Guido van Rossuma4541a32003-04-16 20:02:22 +00001992 # Make sure data descriptors can be overridden and accessed via super
1993 # (new feature in Python 2.3)
1994
1995 class DDbase(object):
1996 def getx(self): return 42
1997 x = property(getx)
1998
1999 class DDsub(DDbase):
2000 def getx(self): return "hello"
2001 x = property(getx)
2002
2003 dd = DDsub()
2004 vereq(dd.x, "hello")
2005 vereq(super(DDsub, dd).x, 42)
2006
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002007 # Ensure that super() lookup of descriptor from classmethod
2008 # works (SF ID# 743627)
2009
2010 class Base(object):
2011 aProp = property(lambda self: "foo")
2012
2013 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002014 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002015 def test(klass):
2016 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002017
2018 veris(Sub.test(), Base.aProp)
2019
2020
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002021def inherits():
2022 if verbose: print "Testing inheritance from basic types..."
2023
2024 class hexint(int):
2025 def __repr__(self):
2026 return hex(self)
2027 def __add__(self, other):
2028 return hexint(int.__add__(self, other))
2029 # (Note that overriding __radd__ doesn't work,
2030 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002031 vereq(repr(hexint(7) + 9), "0x10")
2032 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002033 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002034 vereq(a, 12345)
2035 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002036 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002037 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002038 verify((+a).__class__ is int)
2039 verify((a >> 0).__class__ is int)
2040 verify((a << 0).__class__ is int)
2041 verify((hexint(0) << 12).__class__ is int)
2042 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002043
2044 class octlong(long):
2045 __slots__ = []
2046 def __str__(self):
2047 s = oct(self)
2048 if s[-1] == 'L':
2049 s = s[:-1]
2050 return s
2051 def __add__(self, other):
2052 return self.__class__(super(octlong, self).__add__(other))
2053 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002054 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002055 # (Note that overriding __radd__ here only seems to work
2056 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002057 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002058 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002059 vereq(a, 12345L)
2060 vereq(long(a), 12345L)
2061 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002062 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002063 verify((+a).__class__ is long)
2064 verify((-a).__class__ is long)
2065 verify((-octlong(0)).__class__ is long)
2066 verify((a >> 0).__class__ is long)
2067 verify((a << 0).__class__ is long)
2068 verify((a - 0).__class__ is long)
2069 verify((a * 1).__class__ is long)
2070 verify((a ** 1).__class__ is long)
2071 verify((a // 1).__class__ is long)
2072 verify((1 * a).__class__ is long)
2073 verify((a | 0).__class__ is long)
2074 verify((a ^ 0).__class__ is long)
2075 verify((a & -1L).__class__ is long)
2076 verify((octlong(0) << 12).__class__ is long)
2077 verify((octlong(0) >> 12).__class__ is long)
2078 verify(abs(octlong(0)).__class__ is long)
2079
2080 # Because octlong overrides __add__, we can't check the absence of +0
2081 # optimizations using octlong.
2082 class longclone(long):
2083 pass
2084 a = longclone(1)
2085 verify((a + 0).__class__ is long)
2086 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002087
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002088 # Check that negative clones don't segfault
2089 a = longclone(-1)
2090 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002091 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002092
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002093 class precfloat(float):
2094 __slots__ = ['prec']
2095 def __init__(self, value=0.0, prec=12):
2096 self.prec = int(prec)
2097 float.__init__(value)
2098 def __repr__(self):
2099 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002100 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002101 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002102 vereq(a, 12345.0)
2103 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002104 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002105 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002106 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002107
Tim Peters2400fa42001-09-12 19:12:49 +00002108 class madcomplex(complex):
2109 def __repr__(self):
2110 return "%.17gj%+.17g" % (self.imag, self.real)
2111 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002112 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002113 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002114 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002115 vereq(a, base)
2116 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002117 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002118 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002119 vereq(repr(a), "4j-3")
2120 vereq(a, base)
2121 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002122 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002123 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002124 veris((+a).__class__, complex)
2125 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002126 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002127 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002128 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002129 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002130 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002131 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002132 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002133
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002134 class madtuple(tuple):
2135 _rev = None
2136 def rev(self):
2137 if self._rev is not None:
2138 return self._rev
2139 L = list(self)
2140 L.reverse()
2141 self._rev = self.__class__(L)
2142 return self._rev
2143 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002144 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2145 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2146 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002147 for i in range(512):
2148 t = madtuple(range(i))
2149 u = t.rev()
2150 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002151 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002152 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002153 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002154 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002155 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002156 verify(a[:].__class__ is tuple)
2157 verify((a * 1).__class__ is tuple)
2158 verify((a * 0).__class__ is tuple)
2159 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002160 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002161 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002162 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002163 verify((a + a).__class__ is tuple)
2164 verify((a * 0).__class__ is tuple)
2165 verify((a * 1).__class__ is tuple)
2166 verify((a * 2).__class__ is tuple)
2167 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002168
2169 class madstring(str):
2170 _rev = None
2171 def rev(self):
2172 if self._rev is not None:
2173 return self._rev
2174 L = list(self)
2175 L.reverse()
2176 self._rev = self.__class__("".join(L))
2177 return self._rev
2178 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002179 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2180 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2181 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002182 for i in range(256):
2183 s = madstring("".join(map(chr, range(i))))
2184 t = s.rev()
2185 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002186 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002187 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002188 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002189 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002190
Tim Peters8fa5dd02001-09-12 02:18:30 +00002191 base = "\x00" * 5
2192 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002193 vereq(s, base)
2194 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002195 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002196 vereq(hash(s), hash(base))
2197 vereq({s: 1}[base], 1)
2198 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002199 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002200 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002201 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002202 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002203 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002204 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002205 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002206 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002207 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002208 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002209 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002210 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002211 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002212 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002213 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002214 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002215 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002216 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002217 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002218 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002219 identitytab = ''.join([chr(i) for i in range(256)])
2220 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002221 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002222 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002223 vereq(s.translate(identitytab, "x"), base)
2224 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002225 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002226 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002227 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002228 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002229 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002230 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002231 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002232 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002233 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002234 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002235
Guido van Rossum91ee7982001-08-30 20:52:40 +00002236 class madunicode(unicode):
2237 _rev = None
2238 def rev(self):
2239 if self._rev is not None:
2240 return self._rev
2241 L = list(self)
2242 L.reverse()
2243 self._rev = self.__class__(u"".join(L))
2244 return self._rev
2245 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002246 vereq(u, u"ABCDEF")
2247 vereq(u.rev(), madunicode(u"FEDCBA"))
2248 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002249 base = u"12345"
2250 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002251 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002252 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002253 vereq(hash(u), hash(base))
2254 vereq({u: 1}[base], 1)
2255 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002256 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002257 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002258 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002259 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002260 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002261 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002262 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002263 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002264 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002265 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002266 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002267 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002268 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002269 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002270 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002271 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002272 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002273 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002274 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002275 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002276 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002277 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002278 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002279 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002280 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002281 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002282 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002283 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002284 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002285 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002286 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002287 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002288 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002289 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002290 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002291 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002292 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002293 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002294
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002295 class sublist(list):
2296 pass
2297 a = sublist(range(5))
2298 vereq(a, range(5))
2299 a.append("hello")
2300 vereq(a, range(5) + ["hello"])
2301 a[5] = 5
2302 vereq(a, range(6))
2303 a.extend(range(6, 20))
2304 vereq(a, range(20))
2305 a[-5:] = []
2306 vereq(a, range(15))
2307 del a[10:15]
2308 vereq(len(a), 10)
2309 vereq(a, range(10))
2310 vereq(list(a), range(10))
2311 vereq(a[0], 0)
2312 vereq(a[9], 9)
2313 vereq(a[-10], 0)
2314 vereq(a[-1], 9)
2315 vereq(a[:5], range(5))
2316
Tim Peters59c9a642001-09-13 05:38:56 +00002317 class CountedInput(file):
2318 """Counts lines read by self.readline().
2319
2320 self.lineno is the 0-based ordinal of the last line read, up to
2321 a maximum of one greater than the number of lines in the file.
2322
2323 self.ateof is true if and only if the final "" line has been read,
2324 at which point self.lineno stops incrementing, and further calls
2325 to readline() continue to return "".
2326 """
2327
2328 lineno = 0
2329 ateof = 0
2330 def readline(self):
2331 if self.ateof:
2332 return ""
2333 s = file.readline(self)
2334 # Next line works too.
2335 # s = super(CountedInput, self).readline()
2336 self.lineno += 1
2337 if s == "":
2338 self.ateof = 1
2339 return s
2340
Tim Peters561f8992001-09-13 19:36:36 +00002341 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002342 lines = ['a\n', 'b\n', 'c\n']
2343 try:
2344 f.writelines(lines)
2345 f.close()
2346 f = CountedInput(TESTFN)
2347 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2348 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002349 vereq(expected, got)
2350 vereq(f.lineno, i)
2351 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002352 f.close()
2353 finally:
2354 try:
2355 f.close()
2356 except:
2357 pass
2358 try:
2359 import os
2360 os.unlink(TESTFN)
2361 except:
2362 pass
2363
Tim Peters808b94e2001-09-13 19:33:07 +00002364def keywords():
2365 if verbose:
2366 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002367 vereq(int(x=1), 1)
2368 vereq(float(x=2), 2.0)
2369 vereq(long(x=3), 3L)
2370 vereq(complex(imag=42, real=666), complex(666, 42))
2371 vereq(str(object=500), '500')
2372 vereq(unicode(string='abc', errors='strict'), u'abc')
2373 vereq(tuple(sequence=range(3)), (0, 1, 2))
2374 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002375 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002376
2377 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002378 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002379 try:
2380 constructor(bogus_keyword_arg=1)
2381 except TypeError:
2382 pass
2383 else:
2384 raise TestFailed("expected TypeError from bogus keyword "
2385 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002386
Tim Peters8fa45672001-09-13 21:01:29 +00002387def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002388 # XXX This test is disabled because rexec is not deemed safe
2389 return
Tim Peters8fa45672001-09-13 21:01:29 +00002390 import rexec
2391 if verbose:
2392 print "Testing interaction with restricted execution ..."
2393
2394 sandbox = rexec.RExec()
2395
2396 code1 = """f = open(%r, 'w')""" % TESTFN
2397 code2 = """f = file(%r, 'w')""" % TESTFN
2398 code3 = """\
2399f = open(%r)
2400t = type(f) # a sneaky way to get the file() constructor
2401f.close()
2402f = t(%r, 'w') # rexec can't catch this by itself
2403""" % (TESTFN, TESTFN)
2404
2405 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2406 f.close()
2407
2408 try:
2409 for code in code1, code2, code3:
2410 try:
2411 sandbox.r_exec(code)
2412 except IOError, msg:
2413 if str(msg).find("restricted") >= 0:
2414 outcome = "OK"
2415 else:
2416 outcome = "got an exception, but not an expected one"
2417 else:
2418 outcome = "expected a restricted-execution exception"
2419
2420 if outcome != "OK":
2421 raise TestFailed("%s, in %r" % (outcome, code))
2422
2423 finally:
2424 try:
2425 import os
2426 os.unlink(TESTFN)
2427 except:
2428 pass
2429
Tim Peters0ab085c2001-09-14 00:25:33 +00002430def str_subclass_as_dict_key():
2431 if verbose:
2432 print "Testing a str subclass used as dict key .."
2433
2434 class cistr(str):
2435 """Sublcass of str that computes __eq__ case-insensitively.
2436
2437 Also computes a hash code of the string in canonical form.
2438 """
2439
2440 def __init__(self, value):
2441 self.canonical = value.lower()
2442 self.hashcode = hash(self.canonical)
2443
2444 def __eq__(self, other):
2445 if not isinstance(other, cistr):
2446 other = cistr(other)
2447 return self.canonical == other.canonical
2448
2449 def __hash__(self):
2450 return self.hashcode
2451
Guido van Rossum45704552001-10-08 16:35:45 +00002452 vereq(cistr('ABC'), 'abc')
2453 vereq('aBc', cistr('ABC'))
2454 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002455
2456 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002457 vereq(d[cistr('one')], 1)
2458 vereq(d[cistr('tWo')], 2)
2459 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002460 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002461 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002462
Guido van Rossumab3b0342001-09-18 20:38:53 +00002463def classic_comparisons():
2464 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002465 class classic:
2466 pass
2467 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002468 if verbose: print " (base = %s)" % base
2469 class C(base):
2470 def __init__(self, value):
2471 self.value = int(value)
2472 def __cmp__(self, other):
2473 if isinstance(other, C):
2474 return cmp(self.value, other.value)
2475 if isinstance(other, int) or isinstance(other, long):
2476 return cmp(self.value, other)
2477 return NotImplemented
2478 c1 = C(1)
2479 c2 = C(2)
2480 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002481 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002482 c = {1: c1, 2: c2, 3: c3}
2483 for x in 1, 2, 3:
2484 for y in 1, 2, 3:
2485 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2486 for op in "<", "<=", "==", "!=", ">", ">=":
2487 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2488 "x=%d, y=%d" % (x, y))
2489 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2490 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2491
Guido van Rossum0639f592001-09-18 21:06:04 +00002492def rich_comparisons():
2493 if verbose:
2494 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002495 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002496 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002497 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002498 vereq(z, 1+0j)
2499 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002500 class ZZ(complex):
2501 def __eq__(self, other):
2502 try:
2503 return abs(self - other) <= 1e-6
2504 except:
2505 return NotImplemented
2506 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002507 vereq(zz, 1+0j)
2508 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002509
Guido van Rossum0639f592001-09-18 21:06:04 +00002510 class classic:
2511 pass
2512 for base in (classic, int, object, list):
2513 if verbose: print " (base = %s)" % base
2514 class C(base):
2515 def __init__(self, value):
2516 self.value = int(value)
2517 def __cmp__(self, other):
2518 raise TestFailed, "shouldn't call __cmp__"
2519 def __eq__(self, other):
2520 if isinstance(other, C):
2521 return self.value == other.value
2522 if isinstance(other, int) or isinstance(other, long):
2523 return self.value == other
2524 return NotImplemented
2525 def __ne__(self, other):
2526 if isinstance(other, C):
2527 return self.value != other.value
2528 if isinstance(other, int) or isinstance(other, long):
2529 return self.value != other
2530 return NotImplemented
2531 def __lt__(self, other):
2532 if isinstance(other, C):
2533 return self.value < other.value
2534 if isinstance(other, int) or isinstance(other, long):
2535 return self.value < other
2536 return NotImplemented
2537 def __le__(self, other):
2538 if isinstance(other, C):
2539 return self.value <= other.value
2540 if isinstance(other, int) or isinstance(other, long):
2541 return self.value <= other
2542 return NotImplemented
2543 def __gt__(self, other):
2544 if isinstance(other, C):
2545 return self.value > other.value
2546 if isinstance(other, int) or isinstance(other, long):
2547 return self.value > other
2548 return NotImplemented
2549 def __ge__(self, other):
2550 if isinstance(other, C):
2551 return self.value >= other.value
2552 if isinstance(other, int) or isinstance(other, long):
2553 return self.value >= other
2554 return NotImplemented
2555 c1 = C(1)
2556 c2 = C(2)
2557 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002558 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002559 c = {1: c1, 2: c2, 3: c3}
2560 for x in 1, 2, 3:
2561 for y in 1, 2, 3:
2562 for op in "<", "<=", "==", "!=", ">", ">=":
2563 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2564 "x=%d, y=%d" % (x, y))
2565 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2566 "x=%d, y=%d" % (x, y))
2567 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2568 "x=%d, y=%d" % (x, y))
2569
Guido van Rossum1952e382001-09-19 01:25:16 +00002570def coercions():
2571 if verbose: print "Testing coercions..."
2572 class I(int): pass
2573 coerce(I(0), 0)
2574 coerce(0, I(0))
2575 class L(long): pass
2576 coerce(L(0), 0)
2577 coerce(L(0), 0L)
2578 coerce(0, L(0))
2579 coerce(0L, L(0))
2580 class F(float): pass
2581 coerce(F(0), 0)
2582 coerce(F(0), 0L)
2583 coerce(F(0), 0.)
2584 coerce(0, F(0))
2585 coerce(0L, F(0))
2586 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002587 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002588 coerce(C(0), 0)
2589 coerce(C(0), 0L)
2590 coerce(C(0), 0.)
2591 coerce(C(0), 0j)
2592 coerce(0, C(0))
2593 coerce(0L, C(0))
2594 coerce(0., C(0))
2595 coerce(0j, C(0))
2596
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002597def descrdoc():
2598 if verbose: print "Testing descriptor doc strings..."
2599 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002600 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002601 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002602 check(file.name, "file name") # member descriptor
2603
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002604def setclass():
2605 if verbose: print "Testing __class__ assignment..."
2606 class C(object): pass
2607 class D(object): pass
2608 class E(object): pass
2609 class F(D, E): pass
2610 for cls in C, D, E, F:
2611 for cls2 in C, D, E, F:
2612 x = cls()
2613 x.__class__ = cls2
2614 verify(x.__class__ is cls2)
2615 x.__class__ = cls
2616 verify(x.__class__ is cls)
2617 def cant(x, C):
2618 try:
2619 x.__class__ = C
2620 except TypeError:
2621 pass
2622 else:
2623 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002624 try:
2625 delattr(x, "__class__")
2626 except TypeError:
2627 pass
2628 else:
2629 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002630 cant(C(), list)
2631 cant(list(), C)
2632 cant(C(), 1)
2633 cant(C(), object)
2634 cant(object(), list)
2635 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002636 class Int(int): __slots__ = []
2637 cant(2, Int)
2638 cant(Int(), int)
2639 cant(True, int)
2640 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002641 o = object()
2642 cant(o, type(1))
2643 cant(o, type(None))
2644 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002645
Guido van Rossum6661be32001-10-26 04:26:12 +00002646def setdict():
2647 if verbose: print "Testing __dict__ assignment..."
2648 class C(object): pass
2649 a = C()
2650 a.__dict__ = {'b': 1}
2651 vereq(a.b, 1)
2652 def cant(x, dict):
2653 try:
2654 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002655 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002656 pass
2657 else:
2658 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2659 cant(a, None)
2660 cant(a, [])
2661 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002662 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002663 # Classes don't allow __dict__ assignment
2664 cant(C, {})
2665
Guido van Rossum3926a632001-09-25 16:25:58 +00002666def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002667 if verbose:
2668 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002669 import pickle, cPickle
2670
2671 def sorteditems(d):
2672 L = d.items()
2673 L.sort()
2674 return L
2675
2676 global C
2677 class C(object):
2678 def __init__(self, a, b):
2679 super(C, self).__init__()
2680 self.a = a
2681 self.b = b
2682 def __repr__(self):
2683 return "C(%r, %r)" % (self.a, self.b)
2684
2685 global C1
2686 class C1(list):
2687 def __new__(cls, a, b):
2688 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002689 def __getnewargs__(self):
2690 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002691 def __init__(self, a, b):
2692 self.a = a
2693 self.b = b
2694 def __repr__(self):
2695 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2696
2697 global C2
2698 class C2(int):
2699 def __new__(cls, a, b, val=0):
2700 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002701 def __getnewargs__(self):
2702 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002703 def __init__(self, a, b, val=0):
2704 self.a = a
2705 self.b = b
2706 def __repr__(self):
2707 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2708
Guido van Rossum90c45142001-11-24 21:07:01 +00002709 global C3
2710 class C3(object):
2711 def __init__(self, foo):
2712 self.foo = foo
2713 def __getstate__(self):
2714 return self.foo
2715 def __setstate__(self, foo):
2716 self.foo = foo
2717
2718 global C4classic, C4
2719 class C4classic: # classic
2720 pass
2721 class C4(C4classic, object): # mixed inheritance
2722 pass
2723
Guido van Rossum3926a632001-09-25 16:25:58 +00002724 for p in pickle, cPickle:
2725 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002726 if verbose:
2727 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002728
2729 for cls in C, C1, C2:
2730 s = p.dumps(cls, bin)
2731 cls2 = p.loads(s)
2732 verify(cls2 is cls)
2733
2734 a = C1(1, 2); a.append(42); a.append(24)
2735 b = C2("hello", "world", 42)
2736 s = p.dumps((a, b), bin)
2737 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002738 vereq(x.__class__, a.__class__)
2739 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2740 vereq(y.__class__, b.__class__)
2741 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002742 vereq(repr(x), repr(a))
2743 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002744 if verbose:
2745 print "a = x =", a
2746 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002747 # Test for __getstate__ and __setstate__ on new style class
2748 u = C3(42)
2749 s = p.dumps(u, bin)
2750 v = p.loads(s)
2751 veris(u.__class__, v.__class__)
2752 vereq(u.foo, v.foo)
2753 # Test for picklability of hybrid class
2754 u = C4()
2755 u.foo = 42
2756 s = p.dumps(u, bin)
2757 v = p.loads(s)
2758 veris(u.__class__, v.__class__)
2759 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002760
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002761 # Testing copy.deepcopy()
2762 if verbose:
2763 print "deepcopy"
2764 import copy
2765 for cls in C, C1, C2:
2766 cls2 = copy.deepcopy(cls)
2767 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002768
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002769 a = C1(1, 2); a.append(42); a.append(24)
2770 b = C2("hello", "world", 42)
2771 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002772 vereq(x.__class__, a.__class__)
2773 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2774 vereq(y.__class__, b.__class__)
2775 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002776 vereq(repr(x), repr(a))
2777 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002778 if verbose:
2779 print "a = x =", a
2780 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002781
Guido van Rossum8c842552002-03-14 23:05:54 +00002782def pickleslots():
2783 if verbose: print "Testing pickling of classes with __slots__ ..."
2784 import pickle, cPickle
2785 # Pickling of classes with __slots__ but without __getstate__ should fail
2786 global B, C, D, E
2787 class B(object):
2788 pass
2789 for base in [object, B]:
2790 class C(base):
2791 __slots__ = ['a']
2792 class D(C):
2793 pass
2794 try:
2795 pickle.dumps(C())
2796 except TypeError:
2797 pass
2798 else:
2799 raise TestFailed, "should fail: pickle C instance - %s" % base
2800 try:
2801 cPickle.dumps(C())
2802 except TypeError:
2803 pass
2804 else:
2805 raise TestFailed, "should fail: cPickle C instance - %s" % base
2806 try:
2807 pickle.dumps(C())
2808 except TypeError:
2809 pass
2810 else:
2811 raise TestFailed, "should fail: pickle D instance - %s" % base
2812 try:
2813 cPickle.dumps(D())
2814 except TypeError:
2815 pass
2816 else:
2817 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002818 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002819 class C(base):
2820 __slots__ = ['a']
2821 def __getstate__(self):
2822 try:
2823 d = self.__dict__.copy()
2824 except AttributeError:
2825 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002826 for cls in self.__class__.__mro__:
2827 for sn in cls.__dict__.get('__slots__', ()):
2828 try:
2829 d[sn] = getattr(self, sn)
2830 except AttributeError:
2831 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002832 return d
2833 def __setstate__(self, d):
2834 for k, v in d.items():
2835 setattr(self, k, v)
2836 class D(C):
2837 pass
2838 # Now it should work
2839 x = C()
2840 y = pickle.loads(pickle.dumps(x))
2841 vereq(hasattr(y, 'a'), 0)
2842 y = cPickle.loads(cPickle.dumps(x))
2843 vereq(hasattr(y, 'a'), 0)
2844 x.a = 42
2845 y = pickle.loads(pickle.dumps(x))
2846 vereq(y.a, 42)
2847 y = cPickle.loads(cPickle.dumps(x))
2848 vereq(y.a, 42)
2849 x = D()
2850 x.a = 42
2851 x.b = 100
2852 y = pickle.loads(pickle.dumps(x))
2853 vereq(y.a + y.b, 142)
2854 y = cPickle.loads(cPickle.dumps(x))
2855 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002856 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00002857 class E(C):
2858 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002859 x = E()
2860 x.a = 42
2861 x.b = "foo"
2862 y = pickle.loads(pickle.dumps(x))
2863 vereq(y.a, x.a)
2864 vereq(y.b, x.b)
2865 y = cPickle.loads(cPickle.dumps(x))
2866 vereq(y.a, x.a)
2867 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00002868
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002869def copies():
2870 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2871 import copy
2872 class C(object):
2873 pass
2874
2875 a = C()
2876 a.foo = 12
2877 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002878 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002879
2880 a.bar = [1,2,3]
2881 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002882 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002883 verify(c.bar is a.bar)
2884
2885 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002886 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002887 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002888 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002889
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002890def binopoverride():
2891 if verbose: print "Testing overrides of binary operations..."
2892 class I(int):
2893 def __repr__(self):
2894 return "I(%r)" % int(self)
2895 def __add__(self, other):
2896 return I(int(self) + int(other))
2897 __radd__ = __add__
2898 def __pow__(self, other, mod=None):
2899 if mod is None:
2900 return I(pow(int(self), int(other)))
2901 else:
2902 return I(pow(int(self), int(other), int(mod)))
2903 def __rpow__(self, other, mod=None):
2904 if mod is None:
2905 return I(pow(int(other), int(self), mod))
2906 else:
2907 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00002908
Walter Dörwald70a6b492004-02-12 17:35:32 +00002909 vereq(repr(I(1) + I(2)), "I(3)")
2910 vereq(repr(I(1) + 2), "I(3)")
2911 vereq(repr(1 + I(2)), "I(3)")
2912 vereq(repr(I(2) ** I(3)), "I(8)")
2913 vereq(repr(2 ** I(3)), "I(8)")
2914 vereq(repr(I(2) ** 3), "I(8)")
2915 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002916 class S(str):
2917 def __eq__(self, other):
2918 return self.lower() == other.lower()
2919
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002920def subclasspropagation():
2921 if verbose: print "Testing propagation of slot functions to subclasses..."
2922 class A(object):
2923 pass
2924 class B(A):
2925 pass
2926 class C(A):
2927 pass
2928 class D(B, C):
2929 pass
2930 d = D()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002931 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002932 A.__hash__ = lambda self: 42
2933 vereq(hash(d), 42)
2934 C.__hash__ = lambda self: 314
2935 vereq(hash(d), 314)
2936 B.__hash__ = lambda self: 144
2937 vereq(hash(d), 144)
2938 D.__hash__ = lambda self: 100
2939 vereq(hash(d), 100)
2940 del D.__hash__
2941 vereq(hash(d), 144)
2942 del B.__hash__
2943 vereq(hash(d), 314)
2944 del C.__hash__
2945 vereq(hash(d), 42)
2946 del A.__hash__
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002947 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002948 d.foo = 42
2949 d.bar = 42
2950 vereq(d.foo, 42)
2951 vereq(d.bar, 42)
2952 def __getattribute__(self, name):
2953 if name == "foo":
2954 return 24
2955 return object.__getattribute__(self, name)
2956 A.__getattribute__ = __getattribute__
2957 vereq(d.foo, 24)
2958 vereq(d.bar, 42)
2959 def __getattr__(self, name):
2960 if name in ("spam", "foo", "bar"):
2961 return "hello"
2962 raise AttributeError, name
2963 B.__getattr__ = __getattr__
2964 vereq(d.spam, "hello")
2965 vereq(d.foo, 24)
2966 vereq(d.bar, 42)
2967 del A.__getattribute__
2968 vereq(d.foo, 42)
2969 del d.foo
2970 vereq(d.foo, "hello")
2971 vereq(d.bar, 42)
2972 del B.__getattr__
2973 try:
2974 d.foo
2975 except AttributeError:
2976 pass
2977 else:
2978 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00002979
Guido van Rossume7f3e242002-06-14 02:35:45 +00002980 # Test a nasty bug in recurse_down_subclasses()
2981 import gc
2982 class A(object):
2983 pass
2984 class B(A):
2985 pass
2986 del B
2987 gc.collect()
2988 A.__setitem__ = lambda *a: None # crash
2989
Tim Petersfc57ccb2001-10-12 02:38:24 +00002990def buffer_inherit():
2991 import binascii
2992 # SF bug [#470040] ParseTuple t# vs subclasses.
2993 if verbose:
2994 print "Testing that buffer interface is inherited ..."
2995
2996 class MyStr(str):
2997 pass
2998 base = 'abc'
2999 m = MyStr(base)
3000 # b2a_hex uses the buffer interface to get its argument's value, via
3001 # PyArg_ParseTuple 't#' code.
3002 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3003
3004 # It's not clear that unicode will continue to support the character
3005 # buffer interface, and this test will fail if that's taken away.
3006 class MyUni(unicode):
3007 pass
3008 base = u'abc'
3009 m = MyUni(base)
3010 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3011
3012 class MyInt(int):
3013 pass
3014 m = MyInt(42)
3015 try:
3016 binascii.b2a_hex(m)
3017 raise TestFailed('subclass of int should not have a buffer interface')
3018 except TypeError:
3019 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003020
Tim Petersc9933152001-10-16 20:18:24 +00003021def str_of_str_subclass():
3022 import binascii
3023 import cStringIO
3024
3025 if verbose:
3026 print "Testing __str__ defined in subclass of str ..."
3027
3028 class octetstring(str):
3029 def __str__(self):
3030 return binascii.b2a_hex(self)
3031 def __repr__(self):
3032 return self + " repr"
3033
3034 o = octetstring('A')
3035 vereq(type(o), octetstring)
3036 vereq(type(str(o)), str)
3037 vereq(type(repr(o)), str)
3038 vereq(ord(o), 0x41)
3039 vereq(str(o), '41')
3040 vereq(repr(o), 'A repr')
3041 vereq(o.__str__(), '41')
3042 vereq(o.__repr__(), 'A repr')
3043
3044 capture = cStringIO.StringIO()
3045 # Calling str() or not exercises different internal paths.
3046 print >> capture, o
3047 print >> capture, str(o)
3048 vereq(capture.getvalue(), '41\n41\n')
3049 capture.close()
3050
Guido van Rossumc8e56452001-10-22 00:43:43 +00003051def kwdargs():
3052 if verbose: print "Testing keyword arguments to __init__, __call__..."
3053 def f(a): return a
3054 vereq(f.__call__(a=42), 42)
3055 a = []
3056 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003057 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003058
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003059def recursive__call__():
3060 if verbose: print ("Testing recursive __call__() by setting to instance of "
3061 "class ...")
3062 class A(object):
3063 pass
3064
3065 A.__call__ = A()
3066 try:
3067 A()()
3068 except RuntimeError:
3069 pass
3070 else:
3071 raise TestFailed("Recursion limit should have been reached for "
3072 "__call__()")
3073
Guido van Rossumed87ad82001-10-30 02:33:02 +00003074def delhook():
3075 if verbose: print "Testing __del__ hook..."
3076 log = []
3077 class C(object):
3078 def __del__(self):
3079 log.append(1)
3080 c = C()
3081 vereq(log, [])
3082 del c
3083 vereq(log, [1])
3084
Guido van Rossum29d26062001-12-11 04:37:34 +00003085 class D(object): pass
3086 d = D()
3087 try: del d[0]
3088 except TypeError: pass
3089 else: raise TestFailed, "invalid del() didn't raise TypeError"
3090
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003091def hashinherit():
3092 if verbose: print "Testing hash of mutable subclasses..."
3093
3094 class mydict(dict):
3095 pass
3096 d = mydict()
3097 try:
3098 hash(d)
3099 except TypeError:
3100 pass
3101 else:
3102 raise TestFailed, "hash() of dict subclass should fail"
3103
3104 class mylist(list):
3105 pass
3106 d = mylist()
3107 try:
3108 hash(d)
3109 except TypeError:
3110 pass
3111 else:
3112 raise TestFailed, "hash() of list subclass should fail"
3113
Guido van Rossum29d26062001-12-11 04:37:34 +00003114def strops():
3115 try: 'a' + 5
3116 except TypeError: pass
3117 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3118
3119 try: ''.split('')
3120 except ValueError: pass
3121 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3122
3123 try: ''.join([0])
3124 except TypeError: pass
3125 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3126
3127 try: ''.rindex('5')
3128 except ValueError: pass
3129 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3130
Guido van Rossum29d26062001-12-11 04:37:34 +00003131 try: '%(n)s' % None
3132 except TypeError: pass
3133 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3134
3135 try: '%(n' % {}
3136 except ValueError: pass
3137 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3138
3139 try: '%*s' % ('abc')
3140 except TypeError: pass
3141 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3142
3143 try: '%*.*s' % ('abc', 5)
3144 except TypeError: pass
3145 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3146
3147 try: '%s' % (1, 2)
3148 except TypeError: pass
3149 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3150
3151 try: '%' % None
3152 except ValueError: pass
3153 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3154
3155 vereq('534253'.isdigit(), 1)
3156 vereq('534253x'.isdigit(), 0)
3157 vereq('%c' % 5, '\x05')
3158 vereq('%c' % '5', '5')
3159
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003160def deepcopyrecursive():
3161 if verbose: print "Testing deepcopy of recursive objects..."
3162 class Node:
3163 pass
3164 a = Node()
3165 b = Node()
3166 a.b = b
3167 b.a = a
3168 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003169
Guido van Rossumd7035672002-03-12 20:43:31 +00003170def modules():
3171 if verbose: print "Testing uninitialized module objects..."
3172 from types import ModuleType as M
3173 m = M.__new__(M)
3174 str(m)
3175 vereq(hasattr(m, "__name__"), 0)
3176 vereq(hasattr(m, "__file__"), 0)
3177 vereq(hasattr(m, "foo"), 0)
3178 vereq(m.__dict__, None)
3179 m.foo = 1
3180 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003181
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003182def dictproxyiterkeys():
3183 class C(object):
3184 def meth(self):
3185 pass
3186 if verbose: print "Testing dict-proxy iterkeys..."
3187 keys = [ key for key in C.__dict__.iterkeys() ]
3188 keys.sort()
3189 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3190
3191def dictproxyitervalues():
3192 class C(object):
3193 def meth(self):
3194 pass
3195 if verbose: print "Testing dict-proxy itervalues..."
3196 values = [ values for values in C.__dict__.itervalues() ]
3197 vereq(len(values), 5)
3198
3199def dictproxyiteritems():
3200 class C(object):
3201 def meth(self):
3202 pass
3203 if verbose: print "Testing dict-proxy iteritems..."
3204 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3205 keys.sort()
3206 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3207
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003208def funnynew():
3209 if verbose: print "Testing __new__ returning something unexpected..."
3210 class C(object):
3211 def __new__(cls, arg):
3212 if isinstance(arg, str): return [1, 2, 3]
3213 elif isinstance(arg, int): return object.__new__(D)
3214 else: return object.__new__(cls)
3215 class D(C):
3216 def __init__(self, arg):
3217 self.foo = arg
3218 vereq(C("1"), [1, 2, 3])
3219 vereq(D("1"), [1, 2, 3])
3220 d = D(None)
3221 veris(d.foo, None)
3222 d = C(1)
3223 vereq(isinstance(d, D), True)
3224 vereq(d.foo, 1)
3225 d = D(1)
3226 vereq(isinstance(d, D), True)
3227 vereq(d.foo, 1)
3228
Guido van Rossume8fc6402002-04-16 16:44:51 +00003229def imulbug():
3230 # SF bug 544647
3231 if verbose: print "Testing for __imul__ problems..."
3232 class C(object):
3233 def __imul__(self, other):
3234 return (self, other)
3235 x = C()
3236 y = x
3237 y *= 1.0
3238 vereq(y, (x, 1.0))
3239 y = x
3240 y *= 2
3241 vereq(y, (x, 2))
3242 y = x
3243 y *= 3L
3244 vereq(y, (x, 3L))
3245 y = x
3246 y *= 1L<<100
3247 vereq(y, (x, 1L<<100))
3248 y = x
3249 y *= None
3250 vereq(y, (x, None))
3251 y = x
3252 y *= "foo"
3253 vereq(y, (x, "foo"))
3254
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003255def docdescriptor():
3256 # SF bug 542984
3257 if verbose: print "Testing __doc__ descriptor..."
3258 class DocDescr(object):
3259 def __get__(self, object, otype):
3260 if object:
3261 object = object.__class__.__name__ + ' instance'
3262 if otype:
3263 otype = otype.__name__
3264 return 'object=%s; type=%s' % (object, otype)
3265 class OldClass:
3266 __doc__ = DocDescr()
3267 class NewClass(object):
3268 __doc__ = DocDescr()
3269 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3270 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3271 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3272 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3273
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003274def copy_setstate():
3275 if verbose:
3276 print "Testing that copy.*copy() correctly uses __setstate__..."
3277 import copy
3278 class C(object):
3279 def __init__(self, foo=None):
3280 self.foo = foo
3281 self.__foo = foo
3282 def setfoo(self, foo=None):
3283 self.foo = foo
3284 def getfoo(self):
3285 return self.__foo
3286 def __getstate__(self):
3287 return [self.foo]
3288 def __setstate__(self, lst):
3289 assert len(lst) == 1
3290 self.__foo = self.foo = lst[0]
3291 a = C(42)
3292 a.setfoo(24)
3293 vereq(a.foo, 24)
3294 vereq(a.getfoo(), 42)
3295 b = copy.copy(a)
3296 vereq(b.foo, 24)
3297 vereq(b.getfoo(), 24)
3298 b = copy.deepcopy(a)
3299 vereq(b.foo, 24)
3300 vereq(b.getfoo(), 24)
3301
Guido van Rossum09638c12002-06-13 19:17:46 +00003302def slices():
3303 if verbose:
3304 print "Testing cases with slices and overridden __getitem__ ..."
3305 # Strings
3306 vereq("hello"[:4], "hell")
3307 vereq("hello"[slice(4)], "hell")
3308 vereq(str.__getitem__("hello", slice(4)), "hell")
3309 class S(str):
3310 def __getitem__(self, x):
3311 return str.__getitem__(self, x)
3312 vereq(S("hello")[:4], "hell")
3313 vereq(S("hello")[slice(4)], "hell")
3314 vereq(S("hello").__getitem__(slice(4)), "hell")
3315 # Tuples
3316 vereq((1,2,3)[:2], (1,2))
3317 vereq((1,2,3)[slice(2)], (1,2))
3318 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3319 class T(tuple):
3320 def __getitem__(self, x):
3321 return tuple.__getitem__(self, x)
3322 vereq(T((1,2,3))[:2], (1,2))
3323 vereq(T((1,2,3))[slice(2)], (1,2))
3324 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3325 # Lists
3326 vereq([1,2,3][:2], [1,2])
3327 vereq([1,2,3][slice(2)], [1,2])
3328 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3329 class L(list):
3330 def __getitem__(self, x):
3331 return list.__getitem__(self, x)
3332 vereq(L([1,2,3])[:2], [1,2])
3333 vereq(L([1,2,3])[slice(2)], [1,2])
3334 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3335 # Now do lists and __setitem__
3336 a = L([1,2,3])
3337 a[slice(1, 3)] = [3,2]
3338 vereq(a, [1,3,2])
3339 a[slice(0, 2, 1)] = [3,1]
3340 vereq(a, [3,1,2])
3341 a.__setitem__(slice(1, 3), [2,1])
3342 vereq(a, [3,2,1])
3343 a.__setitem__(slice(0, 2, 1), [2,3])
3344 vereq(a, [2,3,1])
3345
Tim Peters2484aae2002-07-11 06:56:07 +00003346def subtype_resurrection():
3347 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003348 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003349
3350 class C(object):
3351 container = []
3352
3353 def __del__(self):
3354 # resurrect the instance
3355 C.container.append(self)
3356
3357 c = C()
3358 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003359 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003360 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003361 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003362
3363 # If that didn't blow up, it's also interesting to see whether clearing
3364 # the last container slot works: that will attempt to delete c again,
3365 # which will cause c to get appended back to the container again "during"
3366 # the del.
3367 del C.container[-1]
3368 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003369 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003370
Tim Peters14cb1e12002-07-11 18:26:21 +00003371 # Make c mortal again, so that the test framework with -l doesn't report
3372 # it as a leak.
3373 del C.__del__
3374
Guido van Rossum2d702462002-08-06 21:28:28 +00003375def slottrash():
3376 # Deallocating deeply nested slotted trash caused stack overflows
3377 if verbose:
3378 print "Testing slot trash..."
3379 class trash(object):
3380 __slots__ = ['x']
3381 def __init__(self, x):
3382 self.x = x
3383 o = None
3384 for i in xrange(50000):
3385 o = trash(o)
3386 del o
3387
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003388def slotmultipleinheritance():
3389 # SF bug 575229, multiple inheritance w/ slots dumps core
3390 class A(object):
3391 __slots__=()
3392 class B(object):
3393 pass
3394 class C(A,B) :
3395 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003396 vereq(C.__basicsize__, B.__basicsize__)
3397 verify(hasattr(C, '__dict__'))
3398 verify(hasattr(C, '__weakref__'))
3399 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003400
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003401def testrmul():
3402 # SF patch 592646
3403 if verbose:
3404 print "Testing correct invocation of __rmul__..."
3405 class C(object):
3406 def __mul__(self, other):
3407 return "mul"
3408 def __rmul__(self, other):
3409 return "rmul"
3410 a = C()
3411 vereq(a*2, "mul")
3412 vereq(a*2.2, "mul")
3413 vereq(2*a, "rmul")
3414 vereq(2.2*a, "rmul")
3415
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003416def testipow():
3417 # [SF bug 620179]
3418 if verbose:
3419 print "Testing correct invocation of __ipow__..."
3420 class C(object):
3421 def __ipow__(self, other):
3422 pass
3423 a = C()
3424 a **= 2
3425
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003426def do_this_first():
3427 if verbose:
3428 print "Testing SF bug 551412 ..."
3429 # This dumps core when SF bug 551412 isn't fixed --
3430 # but only when test_descr.py is run separately.
3431 # (That can't be helped -- as soon as PyType_Ready()
3432 # is called for PyLong_Type, the bug is gone.)
3433 class UserLong(object):
3434 def __pow__(self, *args):
3435 pass
3436 try:
3437 pow(0L, UserLong(), 0L)
3438 except:
3439 pass
3440
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003441 if verbose:
3442 print "Testing SF bug 570483..."
3443 # Another segfault only when run early
3444 # (before PyType_Ready(tuple) is called)
3445 type.mro(tuple)
3446
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003447def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003448 if verbose:
3449 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003450 # stuff that should work:
3451 class C(object):
3452 pass
3453 class C2(object):
3454 def __getattribute__(self, attr):
3455 if attr == 'a':
3456 return 2
3457 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003458 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003459 def meth(self):
3460 return 1
3461 class D(C):
3462 pass
3463 class E(D):
3464 pass
3465 d = D()
3466 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003467 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003468 D.__bases__ = (C2,)
3469 vereq(d.meth(), 1)
3470 vereq(e.meth(), 1)
3471 vereq(d.a, 2)
3472 vereq(e.a, 2)
3473 vereq(C2.__subclasses__(), [D])
3474
3475 # stuff that shouldn't:
3476 class L(list):
3477 pass
3478
3479 try:
3480 L.__bases__ = (dict,)
3481 except TypeError:
3482 pass
3483 else:
3484 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3485
3486 try:
3487 list.__bases__ = (dict,)
3488 except TypeError:
3489 pass
3490 else:
3491 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3492
3493 try:
3494 del D.__bases__
3495 except TypeError:
3496 pass
3497 else:
3498 raise TestFailed, "shouldn't be able to delete .__bases__"
3499
3500 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003501 D.__bases__ = ()
3502 except TypeError, msg:
3503 if str(msg) == "a new-style class can't have only classic bases":
3504 raise TestFailed, "wrong error message for .__bases__ = ()"
3505 else:
3506 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3507
3508 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003509 D.__bases__ = (D,)
3510 except TypeError:
3511 pass
3512 else:
3513 # actually, we'll have crashed by here...
3514 raise TestFailed, "shouldn't be able to create inheritance cycles"
3515
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003516 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003517 D.__bases__ = (C, C)
3518 except TypeError:
3519 pass
3520 else:
3521 raise TestFailed, "didn't detect repeated base classes"
3522
3523 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003524 D.__bases__ = (E,)
3525 except TypeError:
3526 pass
3527 else:
3528 raise TestFailed, "shouldn't be able to create inheritance cycles"
3529
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003530def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003531 if verbose:
3532 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003533 class WorkOnce(type):
3534 def __new__(self, name, bases, ns):
3535 self.flag = 0
3536 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3537 def mro(self):
3538 if self.flag > 0:
3539 raise RuntimeError, "bozo"
3540 else:
3541 self.flag += 1
3542 return type.mro(self)
3543
3544 class WorkAlways(type):
3545 def mro(self):
3546 # this is here to make sure that .mro()s aren't called
3547 # with an exception set (which was possible at one point).
3548 # An error message will be printed in a debug build.
3549 # What's a good way to test for this?
3550 return type.mro(self)
3551
3552 class C(object):
3553 pass
3554
3555 class C2(object):
3556 pass
3557
3558 class D(C):
3559 pass
3560
3561 class E(D):
3562 pass
3563
3564 class F(D):
3565 __metaclass__ = WorkOnce
3566
3567 class G(D):
3568 __metaclass__ = WorkAlways
3569
3570 # Immediate subclasses have their mro's adjusted in alphabetical
3571 # order, so E's will get adjusted before adjusting F's fails. We
3572 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003573
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003574 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003575 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003576
3577 try:
3578 D.__bases__ = (C2,)
3579 except RuntimeError:
3580 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003581 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003582 else:
3583 raise TestFailed, "exception not propagated"
3584
3585def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003586 if verbose:
3587 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003588 class A(object):
3589 pass
3590
3591 class B(object):
3592 pass
3593
3594 class C(A, B):
3595 pass
3596
3597 class D(A, B):
3598 pass
3599
3600 class E(C, D):
3601 pass
3602
3603 try:
3604 C.__bases__ = (B, A)
3605 except TypeError:
3606 pass
3607 else:
3608 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003609
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003610def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003611 if verbose:
3612 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003613 class C(object):
3614 pass
3615
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003616 # C.__module__ could be 'test_descr' or '__main__'
3617 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003618
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003619 C.__name__ = 'D'
3620 vereq((C.__module__, C.__name__), (mod, 'D'))
3621
3622 C.__name__ = 'D.E'
3623 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003624
Guido van Rossum613f24f2003-01-06 23:00:59 +00003625def subclass_right_op():
3626 if verbose:
3627 print "Testing correct dispatch of subclass overloading __r<op>__..."
3628
3629 # This code tests various cases where right-dispatch of a subclass
3630 # should be preferred over left-dispatch of a base class.
3631
3632 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3633
3634 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003635 def __floordiv__(self, other):
3636 return "B.__floordiv__"
3637 def __rfloordiv__(self, other):
3638 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003639
Guido van Rossumf389c772003-02-27 20:04:19 +00003640 vereq(B(1) // 1, "B.__floordiv__")
3641 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003642
3643 # Case 2: subclass of object; this is just the baseline for case 3
3644
3645 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003646 def __floordiv__(self, other):
3647 return "C.__floordiv__"
3648 def __rfloordiv__(self, other):
3649 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003650
Guido van Rossumf389c772003-02-27 20:04:19 +00003651 vereq(C() // 1, "C.__floordiv__")
3652 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003653
3654 # Case 3: subclass of new-style class; here it gets interesting
3655
3656 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003657 def __floordiv__(self, other):
3658 return "D.__floordiv__"
3659 def __rfloordiv__(self, other):
3660 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003661
Guido van Rossumf389c772003-02-27 20:04:19 +00003662 vereq(D() // C(), "D.__floordiv__")
3663 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003664
3665 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3666
3667 class E(C):
3668 pass
3669
Guido van Rossumf389c772003-02-27 20:04:19 +00003670 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003671
Guido van Rossumf389c772003-02-27 20:04:19 +00003672 vereq(E() // 1, "C.__floordiv__")
3673 vereq(1 // E(), "C.__rfloordiv__")
3674 vereq(E() // C(), "C.__floordiv__")
3675 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003676
Guido van Rossum373c7412003-01-07 13:41:37 +00003677def dict_type_with_metaclass():
3678 if verbose:
3679 print "Testing type of __dict__ when __metaclass__ set..."
3680
3681 class B(object):
3682 pass
3683 class M(type):
3684 pass
3685 class C:
3686 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3687 __metaclass__ = M
3688 veris(type(C.__dict__), type(B.__dict__))
3689
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003690def meth_class_get():
3691 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003692 if verbose:
3693 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003694 # Baseline
3695 arg = [1, 2, 3]
3696 res = {1: None, 2: None, 3: None}
3697 vereq(dict.fromkeys(arg), res)
3698 vereq({}.fromkeys(arg), res)
3699 # Now get the descriptor
3700 descr = dict.__dict__["fromkeys"]
3701 # More baseline using the descriptor directly
3702 vereq(descr.__get__(None, dict)(arg), res)
3703 vereq(descr.__get__({})(arg), res)
3704 # Now check various error cases
3705 try:
3706 descr.__get__(None, None)
3707 except TypeError:
3708 pass
3709 else:
3710 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3711 try:
3712 descr.__get__(42)
3713 except TypeError:
3714 pass
3715 else:
3716 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3717 try:
3718 descr.__get__(None, 42)
3719 except TypeError:
3720 pass
3721 else:
3722 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3723 try:
3724 descr.__get__(None, int)
3725 except TypeError:
3726 pass
3727 else:
3728 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3729
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003730def isinst_isclass():
3731 if verbose:
3732 print "Testing proxy isinstance() and isclass()..."
3733 class Proxy(object):
3734 def __init__(self, obj):
3735 self.__obj = obj
3736 def __getattribute__(self, name):
3737 if name.startswith("_Proxy__"):
3738 return object.__getattribute__(self, name)
3739 else:
3740 return getattr(self.__obj, name)
3741 # Test with a classic class
3742 class C:
3743 pass
3744 a = C()
3745 pa = Proxy(a)
3746 verify(isinstance(a, C)) # Baseline
3747 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003748 # Test with a classic subclass
3749 class D(C):
3750 pass
3751 a = D()
3752 pa = Proxy(a)
3753 verify(isinstance(a, C)) # Baseline
3754 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003755 # Test with a new-style class
3756 class C(object):
3757 pass
3758 a = C()
3759 pa = Proxy(a)
3760 verify(isinstance(a, C)) # Baseline
3761 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003762 # Test with a new-style subclass
3763 class D(C):
3764 pass
3765 a = D()
3766 pa = Proxy(a)
3767 verify(isinstance(a, C)) # Baseline
3768 verify(isinstance(pa, C)) # Test
3769
3770def proxysuper():
3771 if verbose:
3772 print "Testing super() for a proxy object..."
3773 class Proxy(object):
3774 def __init__(self, obj):
3775 self.__obj = obj
3776 def __getattribute__(self, name):
3777 if name.startswith("_Proxy__"):
3778 return object.__getattribute__(self, name)
3779 else:
3780 return getattr(self.__obj, name)
3781
3782 class B(object):
3783 def f(self):
3784 return "B.f"
3785
3786 class C(B):
3787 def f(self):
3788 return super(C, self).f() + "->C.f"
3789
3790 obj = C()
3791 p = Proxy(obj)
3792 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003793
Guido van Rossum52b27052003-04-15 20:05:10 +00003794def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003795 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00003796 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003797 try:
3798 object.__setattr__(str, "foo", 42)
3799 except TypeError:
3800 pass
3801 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003802 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003803 try:
3804 object.__delattr__(str, "lower")
3805 except TypeError:
3806 pass
3807 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003808 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003809
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003810def weakref_segfault():
3811 # SF 742911
3812 if verbose:
3813 print "Testing weakref segfault..."
3814
3815 import weakref
3816
3817 class Provoker:
3818 def __init__(self, referrent):
3819 self.ref = weakref.ref(referrent)
3820
3821 def __del__(self):
3822 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003823
3824 class Oops(object):
3825 pass
3826
3827 o = Oops()
3828 o.whatever = Provoker(o)
3829 del o
3830
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003831def wrapper_segfault():
3832 # SF 927248: deeply nested wrappers could cause stack overflow
3833 f = lambda:None
3834 for i in xrange(1000000):
3835 f = f.__call__
3836 f = None
3837
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003838# Fix SF #762455, segfault when sys.stdout is changed in getattr
3839def filefault():
3840 if verbose:
3841 print "Testing sys.stdout is changed in getattr..."
3842 import sys
3843 class StdoutGuard:
3844 def __getattr__(self, attr):
3845 sys.stdout = sys.__stdout__
3846 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3847 sys.stdout = StdoutGuard()
3848 try:
3849 print "Oops!"
3850 except RuntimeError:
3851 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003852
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003853def vicious_descriptor_nonsense():
3854 # A potential segfault spotted by Thomas Wouters in mail to
3855 # python-dev 2003-04-17, turned into an example & fixed by Michael
3856 # Hudson just less than four months later...
3857 if verbose:
3858 print "Testing vicious_descriptor_nonsense..."
3859
3860 class Evil(object):
3861 def __hash__(self):
3862 return hash('attr')
3863 def __eq__(self, other):
3864 del C.attr
3865 return 0
3866
3867 class Descr(object):
3868 def __get__(self, ob, type=None):
3869 return 1
3870
3871 class C(object):
3872 attr = Descr()
3873
3874 c = C()
3875 c.__dict__[Evil()] = 0
3876
3877 vereq(c.attr, 1)
3878 # this makes a crash more likely:
3879 import gc; gc.collect()
3880 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00003881
Raymond Hettingerb67cc802005-03-03 16:45:19 +00003882def test_init():
3883 # SF 1155938
3884 class Foo(object):
3885 def __init__(self):
3886 return 10
3887 try:
3888 Foo()
3889 except TypeError:
3890 pass
3891 else:
3892 raise TestFailed, "did not test __init__() for None return"
3893
Armin Rigoc6686b72005-11-07 08:38:00 +00003894def methodwrapper():
3895 # <type 'method-wrapper'> did not support any reflection before 2.5
3896 if verbose:
3897 print "Testing method-wrapper objects..."
3898
3899 l = []
3900 vereq(l.__add__, l.__add__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003901 vereq(l.__add__, [].__add__)
3902 verify(l.__add__ != [5].__add__)
3903 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00003904 verify(l.__add__.__name__ == '__add__')
3905 verify(l.__add__.__self__ is l)
3906 verify(l.__add__.__objclass__ is list)
3907 vereq(l.__add__.__doc__, list.__add__.__doc__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003908 try:
3909 hash(l.__add__)
3910 except TypeError:
3911 pass
3912 else:
3913 raise TestFailed("no TypeError from hash([].__add__)")
3914
3915 t = ()
3916 t += (7,)
3917 vereq(t.__add__, (7,).__add__)
3918 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003919
Armin Rigofd163f92005-12-29 15:59:19 +00003920def notimplemented():
3921 # all binary methods should be able to return a NotImplemented
3922 if verbose:
3923 print "Testing NotImplemented..."
3924
3925 import sys
3926 import types
3927 import operator
3928
3929 def specialmethod(self, other):
3930 return NotImplemented
3931
3932 def check(expr, x, y):
3933 try:
3934 exec expr in {'x': x, 'y': y, 'operator': operator}
3935 except TypeError:
3936 pass
3937 else:
3938 raise TestFailed("no TypeError from %r" % (expr,))
3939
3940 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
3941 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
3942 # ValueErrors instead of TypeErrors
3943 for metaclass in [type, types.ClassType]:
3944 for name, expr, iexpr in [
3945 ('__add__', 'x + y', 'x += y'),
3946 ('__sub__', 'x - y', 'x -= y'),
3947 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003948 ('__truediv__', 'x / y', None),
3949 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00003950 ('__mod__', 'x % y', 'x %= y'),
3951 ('__divmod__', 'divmod(x, y)', None),
3952 ('__pow__', 'x ** y', 'x **= y'),
3953 ('__lshift__', 'x << y', 'x <<= y'),
3954 ('__rshift__', 'x >> y', 'x >>= y'),
3955 ('__and__', 'x & y', 'x &= y'),
3956 ('__or__', 'x | y', 'x |= y'),
3957 ('__xor__', 'x ^ y', 'x ^= y'),
3958 ('__coerce__', 'coerce(x, y)', None)]:
3959 if name == '__coerce__':
3960 rname = name
3961 else:
3962 rname = '__r' + name[2:]
3963 A = metaclass('A', (), {name: specialmethod})
3964 B = metaclass('B', (), {rname: specialmethod})
3965 a = A()
3966 b = B()
3967 check(expr, a, a)
3968 check(expr, a, b)
3969 check(expr, b, a)
3970 check(expr, b, b)
3971 check(expr, a, N1)
3972 check(expr, a, N2)
3973 check(expr, N1, b)
3974 check(expr, N2, b)
3975 if iexpr:
3976 check(iexpr, a, a)
3977 check(iexpr, a, b)
3978 check(iexpr, b, a)
3979 check(iexpr, b, b)
3980 check(iexpr, a, N1)
3981 check(iexpr, a, N2)
3982 iname = '__i' + name[2:]
3983 C = metaclass('C', (), {iname: specialmethod})
3984 c = C()
3985 check(iexpr, c, a)
3986 check(iexpr, c, b)
3987 check(iexpr, c, N1)
3988 check(iexpr, c, N2)
3989
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003990def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003991 weakref_segfault() # Must be first, somehow
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003992 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003993 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00003994 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995 lists()
3996 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00003997 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00003998 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003999 ints()
4000 longs()
4001 floats()
4002 complexes()
4003 spamlists()
4004 spamdicts()
4005 pydicts()
4006 pylists()
4007 metaclass()
4008 pymods()
4009 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004010 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004012 ex5()
4013 monotonicity()
4014 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004015 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004017 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018 dynamics()
4019 errors()
4020 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004021 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004023 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024 classic()
4025 compattr()
4026 newslot()
4027 altmro()
4028 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004029 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004030 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004031 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004032 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004033 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004034 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004035 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004036 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004037 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004038 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004039 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004040 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004041 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004042 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004043 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004044 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004045 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004046 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004047 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004048 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004049 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004050 kwdargs()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004051 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004052 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004053 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004054 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004055 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004056 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004057 dictproxyiterkeys()
4058 dictproxyitervalues()
4059 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004060 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004061 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004062 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004063 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004064 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004065 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004066 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004067 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004068 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004069 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004070 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004071 test_mutable_bases()
4072 test_mutable_bases_with_failing_mro()
4073 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004074 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004075 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004076 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004077 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004078 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004079 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004080 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004081 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004082 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004083 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004084 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004085 notimplemented()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004086
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004087 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004089if __name__ == "__main__":
4090 test_main()