blob: 01fd6853cba74fe1ff139e547c704c14dd569a96 [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 Rossumbf12cdb2006-08-17 20:24:18 +00002669 import pickle
2670 try:
2671 import cPickle
2672 except ImportError:
2673 cPickle = None
Guido van Rossum3926a632001-09-25 16:25:58 +00002674
2675 def sorteditems(d):
2676 L = d.items()
2677 L.sort()
2678 return L
2679
2680 global C
2681 class C(object):
2682 def __init__(self, a, b):
2683 super(C, self).__init__()
2684 self.a = a
2685 self.b = b
2686 def __repr__(self):
2687 return "C(%r, %r)" % (self.a, self.b)
2688
2689 global C1
2690 class C1(list):
2691 def __new__(cls, a, b):
2692 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002693 def __getnewargs__(self):
2694 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002695 def __init__(self, a, b):
2696 self.a = a
2697 self.b = b
2698 def __repr__(self):
2699 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2700
2701 global C2
2702 class C2(int):
2703 def __new__(cls, a, b, val=0):
2704 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002705 def __getnewargs__(self):
2706 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002707 def __init__(self, a, b, val=0):
2708 self.a = a
2709 self.b = b
2710 def __repr__(self):
2711 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2712
Guido van Rossum90c45142001-11-24 21:07:01 +00002713 global C3
2714 class C3(object):
2715 def __init__(self, foo):
2716 self.foo = foo
2717 def __getstate__(self):
2718 return self.foo
2719 def __setstate__(self, foo):
2720 self.foo = foo
2721
2722 global C4classic, C4
2723 class C4classic: # classic
2724 pass
2725 class C4(C4classic, object): # mixed inheritance
2726 pass
2727
Guido van Rossum3926a632001-09-25 16:25:58 +00002728 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002729 if p is None:
2730 continue # cPickle not found -- skip it
Guido van Rossum3926a632001-09-25 16:25:58 +00002731 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002732 if verbose:
2733 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002734
2735 for cls in C, C1, C2:
2736 s = p.dumps(cls, bin)
2737 cls2 = p.loads(s)
2738 verify(cls2 is cls)
2739
2740 a = C1(1, 2); a.append(42); a.append(24)
2741 b = C2("hello", "world", 42)
2742 s = p.dumps((a, b), bin)
2743 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002744 vereq(x.__class__, a.__class__)
2745 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2746 vereq(y.__class__, b.__class__)
2747 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002748 vereq(repr(x), repr(a))
2749 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002750 if verbose:
2751 print "a = x =", a
2752 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002753 # Test for __getstate__ and __setstate__ on new style class
2754 u = C3(42)
2755 s = p.dumps(u, bin)
2756 v = p.loads(s)
2757 veris(u.__class__, v.__class__)
2758 vereq(u.foo, v.foo)
2759 # Test for picklability of hybrid class
2760 u = C4()
2761 u.foo = 42
2762 s = p.dumps(u, bin)
2763 v = p.loads(s)
2764 veris(u.__class__, v.__class__)
2765 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002766
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002767 # Testing copy.deepcopy()
2768 if verbose:
2769 print "deepcopy"
2770 import copy
2771 for cls in C, C1, C2:
2772 cls2 = copy.deepcopy(cls)
2773 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002774
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002775 a = C1(1, 2); a.append(42); a.append(24)
2776 b = C2("hello", "world", 42)
2777 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002778 vereq(x.__class__, a.__class__)
2779 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2780 vereq(y.__class__, b.__class__)
2781 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002782 vereq(repr(x), repr(a))
2783 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002784 if verbose:
2785 print "a = x =", a
2786 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002787
Guido van Rossum8c842552002-03-14 23:05:54 +00002788def pickleslots():
2789 if verbose: print "Testing pickling of classes with __slots__ ..."
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002790 import pickle, pickle as cPickle
Guido van Rossum8c842552002-03-14 23:05:54 +00002791 # Pickling of classes with __slots__ but without __getstate__ should fail
2792 global B, C, D, E
2793 class B(object):
2794 pass
2795 for base in [object, B]:
2796 class C(base):
2797 __slots__ = ['a']
2798 class D(C):
2799 pass
2800 try:
2801 pickle.dumps(C())
2802 except TypeError:
2803 pass
2804 else:
2805 raise TestFailed, "should fail: pickle C instance - %s" % base
2806 try:
2807 cPickle.dumps(C())
2808 except TypeError:
2809 pass
2810 else:
2811 raise TestFailed, "should fail: cPickle C instance - %s" % base
2812 try:
2813 pickle.dumps(C())
2814 except TypeError:
2815 pass
2816 else:
2817 raise TestFailed, "should fail: pickle D instance - %s" % base
2818 try:
2819 cPickle.dumps(D())
2820 except TypeError:
2821 pass
2822 else:
2823 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002824 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002825 class C(base):
2826 __slots__ = ['a']
2827 def __getstate__(self):
2828 try:
2829 d = self.__dict__.copy()
2830 except AttributeError:
2831 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002832 for cls in self.__class__.__mro__:
2833 for sn in cls.__dict__.get('__slots__', ()):
2834 try:
2835 d[sn] = getattr(self, sn)
2836 except AttributeError:
2837 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002838 return d
2839 def __setstate__(self, d):
2840 for k, v in d.items():
2841 setattr(self, k, v)
2842 class D(C):
2843 pass
2844 # Now it should work
2845 x = C()
2846 y = pickle.loads(pickle.dumps(x))
2847 vereq(hasattr(y, 'a'), 0)
2848 y = cPickle.loads(cPickle.dumps(x))
2849 vereq(hasattr(y, 'a'), 0)
2850 x.a = 42
2851 y = pickle.loads(pickle.dumps(x))
2852 vereq(y.a, 42)
2853 y = cPickle.loads(cPickle.dumps(x))
2854 vereq(y.a, 42)
2855 x = D()
2856 x.a = 42
2857 x.b = 100
2858 y = pickle.loads(pickle.dumps(x))
2859 vereq(y.a + y.b, 142)
2860 y = cPickle.loads(cPickle.dumps(x))
2861 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002862 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00002863 class E(C):
2864 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002865 x = E()
2866 x.a = 42
2867 x.b = "foo"
2868 y = pickle.loads(pickle.dumps(x))
2869 vereq(y.a, x.a)
2870 vereq(y.b, x.b)
2871 y = cPickle.loads(cPickle.dumps(x))
2872 vereq(y.a, x.a)
2873 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00002874
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002875def copies():
2876 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2877 import copy
2878 class C(object):
2879 pass
2880
2881 a = C()
2882 a.foo = 12
2883 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002884 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002885
2886 a.bar = [1,2,3]
2887 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002888 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002889 verify(c.bar is a.bar)
2890
2891 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002892 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002893 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002894 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002895
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002896def binopoverride():
2897 if verbose: print "Testing overrides of binary operations..."
2898 class I(int):
2899 def __repr__(self):
2900 return "I(%r)" % int(self)
2901 def __add__(self, other):
2902 return I(int(self) + int(other))
2903 __radd__ = __add__
2904 def __pow__(self, other, mod=None):
2905 if mod is None:
2906 return I(pow(int(self), int(other)))
2907 else:
2908 return I(pow(int(self), int(other), int(mod)))
2909 def __rpow__(self, other, mod=None):
2910 if mod is None:
2911 return I(pow(int(other), int(self), mod))
2912 else:
2913 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00002914
Walter Dörwald70a6b492004-02-12 17:35:32 +00002915 vereq(repr(I(1) + I(2)), "I(3)")
2916 vereq(repr(I(1) + 2), "I(3)")
2917 vereq(repr(1 + I(2)), "I(3)")
2918 vereq(repr(I(2) ** I(3)), "I(8)")
2919 vereq(repr(2 ** I(3)), "I(8)")
2920 vereq(repr(I(2) ** 3), "I(8)")
2921 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002922 class S(str):
2923 def __eq__(self, other):
2924 return self.lower() == other.lower()
2925
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002926def subclasspropagation():
2927 if verbose: print "Testing propagation of slot functions to subclasses..."
2928 class A(object):
2929 pass
2930 class B(A):
2931 pass
2932 class C(A):
2933 pass
2934 class D(B, C):
2935 pass
2936 d = D()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002937 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002938 A.__hash__ = lambda self: 42
2939 vereq(hash(d), 42)
2940 C.__hash__ = lambda self: 314
2941 vereq(hash(d), 314)
2942 B.__hash__ = lambda self: 144
2943 vereq(hash(d), 144)
2944 D.__hash__ = lambda self: 100
2945 vereq(hash(d), 100)
2946 del D.__hash__
2947 vereq(hash(d), 144)
2948 del B.__hash__
2949 vereq(hash(d), 314)
2950 del C.__hash__
2951 vereq(hash(d), 42)
2952 del A.__hash__
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002953 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002954 d.foo = 42
2955 d.bar = 42
2956 vereq(d.foo, 42)
2957 vereq(d.bar, 42)
2958 def __getattribute__(self, name):
2959 if name == "foo":
2960 return 24
2961 return object.__getattribute__(self, name)
2962 A.__getattribute__ = __getattribute__
2963 vereq(d.foo, 24)
2964 vereq(d.bar, 42)
2965 def __getattr__(self, name):
2966 if name in ("spam", "foo", "bar"):
2967 return "hello"
2968 raise AttributeError, name
2969 B.__getattr__ = __getattr__
2970 vereq(d.spam, "hello")
2971 vereq(d.foo, 24)
2972 vereq(d.bar, 42)
2973 del A.__getattribute__
2974 vereq(d.foo, 42)
2975 del d.foo
2976 vereq(d.foo, "hello")
2977 vereq(d.bar, 42)
2978 del B.__getattr__
2979 try:
2980 d.foo
2981 except AttributeError:
2982 pass
2983 else:
2984 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00002985
Guido van Rossume7f3e242002-06-14 02:35:45 +00002986 # Test a nasty bug in recurse_down_subclasses()
2987 import gc
2988 class A(object):
2989 pass
2990 class B(A):
2991 pass
2992 del B
2993 gc.collect()
2994 A.__setitem__ = lambda *a: None # crash
2995
Tim Petersfc57ccb2001-10-12 02:38:24 +00002996def buffer_inherit():
2997 import binascii
2998 # SF bug [#470040] ParseTuple t# vs subclasses.
2999 if verbose:
3000 print "Testing that buffer interface is inherited ..."
3001
3002 class MyStr(str):
3003 pass
3004 base = 'abc'
3005 m = MyStr(base)
3006 # b2a_hex uses the buffer interface to get its argument's value, via
3007 # PyArg_ParseTuple 't#' code.
3008 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3009
3010 # It's not clear that unicode will continue to support the character
3011 # buffer interface, and this test will fail if that's taken away.
3012 class MyUni(unicode):
3013 pass
3014 base = u'abc'
3015 m = MyUni(base)
3016 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3017
3018 class MyInt(int):
3019 pass
3020 m = MyInt(42)
3021 try:
3022 binascii.b2a_hex(m)
3023 raise TestFailed('subclass of int should not have a buffer interface')
3024 except TypeError:
3025 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003026
Tim Petersc9933152001-10-16 20:18:24 +00003027def str_of_str_subclass():
3028 import binascii
3029 import cStringIO
3030
3031 if verbose:
3032 print "Testing __str__ defined in subclass of str ..."
3033
3034 class octetstring(str):
3035 def __str__(self):
3036 return binascii.b2a_hex(self)
3037 def __repr__(self):
3038 return self + " repr"
3039
3040 o = octetstring('A')
3041 vereq(type(o), octetstring)
3042 vereq(type(str(o)), str)
3043 vereq(type(repr(o)), str)
3044 vereq(ord(o), 0x41)
3045 vereq(str(o), '41')
3046 vereq(repr(o), 'A repr')
3047 vereq(o.__str__(), '41')
3048 vereq(o.__repr__(), 'A repr')
3049
3050 capture = cStringIO.StringIO()
3051 # Calling str() or not exercises different internal paths.
3052 print >> capture, o
3053 print >> capture, str(o)
3054 vereq(capture.getvalue(), '41\n41\n')
3055 capture.close()
3056
Guido van Rossumc8e56452001-10-22 00:43:43 +00003057def kwdargs():
3058 if verbose: print "Testing keyword arguments to __init__, __call__..."
3059 def f(a): return a
3060 vereq(f.__call__(a=42), 42)
3061 a = []
3062 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003063 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003064
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003065def recursive__call__():
3066 if verbose: print ("Testing recursive __call__() by setting to instance of "
3067 "class ...")
3068 class A(object):
3069 pass
3070
3071 A.__call__ = A()
3072 try:
3073 A()()
3074 except RuntimeError:
3075 pass
3076 else:
3077 raise TestFailed("Recursion limit should have been reached for "
3078 "__call__()")
3079
Guido van Rossumed87ad82001-10-30 02:33:02 +00003080def delhook():
3081 if verbose: print "Testing __del__ hook..."
3082 log = []
3083 class C(object):
3084 def __del__(self):
3085 log.append(1)
3086 c = C()
3087 vereq(log, [])
3088 del c
3089 vereq(log, [1])
3090
Guido van Rossum29d26062001-12-11 04:37:34 +00003091 class D(object): pass
3092 d = D()
3093 try: del d[0]
3094 except TypeError: pass
3095 else: raise TestFailed, "invalid del() didn't raise TypeError"
3096
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003097def hashinherit():
3098 if verbose: print "Testing hash of mutable subclasses..."
3099
3100 class mydict(dict):
3101 pass
3102 d = mydict()
3103 try:
3104 hash(d)
3105 except TypeError:
3106 pass
3107 else:
3108 raise TestFailed, "hash() of dict subclass should fail"
3109
3110 class mylist(list):
3111 pass
3112 d = mylist()
3113 try:
3114 hash(d)
3115 except TypeError:
3116 pass
3117 else:
3118 raise TestFailed, "hash() of list subclass should fail"
3119
Guido van Rossum29d26062001-12-11 04:37:34 +00003120def strops():
3121 try: 'a' + 5
3122 except TypeError: pass
3123 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3124
3125 try: ''.split('')
3126 except ValueError: pass
3127 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3128
3129 try: ''.join([0])
3130 except TypeError: pass
3131 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3132
3133 try: ''.rindex('5')
3134 except ValueError: pass
3135 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3136
Guido van Rossum29d26062001-12-11 04:37:34 +00003137 try: '%(n)s' % None
3138 except TypeError: pass
3139 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3140
3141 try: '%(n' % {}
3142 except ValueError: pass
3143 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3144
3145 try: '%*s' % ('abc')
3146 except TypeError: pass
3147 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3148
3149 try: '%*.*s' % ('abc', 5)
3150 except TypeError: pass
3151 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3152
3153 try: '%s' % (1, 2)
3154 except TypeError: pass
3155 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3156
3157 try: '%' % None
3158 except ValueError: pass
3159 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3160
3161 vereq('534253'.isdigit(), 1)
3162 vereq('534253x'.isdigit(), 0)
3163 vereq('%c' % 5, '\x05')
3164 vereq('%c' % '5', '5')
3165
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003166def deepcopyrecursive():
3167 if verbose: print "Testing deepcopy of recursive objects..."
3168 class Node:
3169 pass
3170 a = Node()
3171 b = Node()
3172 a.b = b
3173 b.a = a
3174 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003175
Guido van Rossumd7035672002-03-12 20:43:31 +00003176def modules():
3177 if verbose: print "Testing uninitialized module objects..."
3178 from types import ModuleType as M
3179 m = M.__new__(M)
3180 str(m)
3181 vereq(hasattr(m, "__name__"), 0)
3182 vereq(hasattr(m, "__file__"), 0)
3183 vereq(hasattr(m, "foo"), 0)
3184 vereq(m.__dict__, None)
3185 m.foo = 1
3186 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003187
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003188def dictproxyiterkeys():
3189 class C(object):
3190 def meth(self):
3191 pass
3192 if verbose: print "Testing dict-proxy iterkeys..."
3193 keys = [ key for key in C.__dict__.iterkeys() ]
3194 keys.sort()
3195 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3196
3197def dictproxyitervalues():
3198 class C(object):
3199 def meth(self):
3200 pass
3201 if verbose: print "Testing dict-proxy itervalues..."
3202 values = [ values for values in C.__dict__.itervalues() ]
3203 vereq(len(values), 5)
3204
3205def dictproxyiteritems():
3206 class C(object):
3207 def meth(self):
3208 pass
3209 if verbose: print "Testing dict-proxy iteritems..."
3210 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3211 keys.sort()
3212 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3213
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003214def funnynew():
3215 if verbose: print "Testing __new__ returning something unexpected..."
3216 class C(object):
3217 def __new__(cls, arg):
3218 if isinstance(arg, str): return [1, 2, 3]
3219 elif isinstance(arg, int): return object.__new__(D)
3220 else: return object.__new__(cls)
3221 class D(C):
3222 def __init__(self, arg):
3223 self.foo = arg
3224 vereq(C("1"), [1, 2, 3])
3225 vereq(D("1"), [1, 2, 3])
3226 d = D(None)
3227 veris(d.foo, None)
3228 d = C(1)
3229 vereq(isinstance(d, D), True)
3230 vereq(d.foo, 1)
3231 d = D(1)
3232 vereq(isinstance(d, D), True)
3233 vereq(d.foo, 1)
3234
Guido van Rossume8fc6402002-04-16 16:44:51 +00003235def imulbug():
3236 # SF bug 544647
3237 if verbose: print "Testing for __imul__ problems..."
3238 class C(object):
3239 def __imul__(self, other):
3240 return (self, other)
3241 x = C()
3242 y = x
3243 y *= 1.0
3244 vereq(y, (x, 1.0))
3245 y = x
3246 y *= 2
3247 vereq(y, (x, 2))
3248 y = x
3249 y *= 3L
3250 vereq(y, (x, 3L))
3251 y = x
3252 y *= 1L<<100
3253 vereq(y, (x, 1L<<100))
3254 y = x
3255 y *= None
3256 vereq(y, (x, None))
3257 y = x
3258 y *= "foo"
3259 vereq(y, (x, "foo"))
3260
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003261def docdescriptor():
3262 # SF bug 542984
3263 if verbose: print "Testing __doc__ descriptor..."
3264 class DocDescr(object):
3265 def __get__(self, object, otype):
3266 if object:
3267 object = object.__class__.__name__ + ' instance'
3268 if otype:
3269 otype = otype.__name__
3270 return 'object=%s; type=%s' % (object, otype)
3271 class OldClass:
3272 __doc__ = DocDescr()
3273 class NewClass(object):
3274 __doc__ = DocDescr()
3275 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3276 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3277 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3278 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3279
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003280def copy_setstate():
3281 if verbose:
3282 print "Testing that copy.*copy() correctly uses __setstate__..."
3283 import copy
3284 class C(object):
3285 def __init__(self, foo=None):
3286 self.foo = foo
3287 self.__foo = foo
3288 def setfoo(self, foo=None):
3289 self.foo = foo
3290 def getfoo(self):
3291 return self.__foo
3292 def __getstate__(self):
3293 return [self.foo]
3294 def __setstate__(self, lst):
3295 assert len(lst) == 1
3296 self.__foo = self.foo = lst[0]
3297 a = C(42)
3298 a.setfoo(24)
3299 vereq(a.foo, 24)
3300 vereq(a.getfoo(), 42)
3301 b = copy.copy(a)
3302 vereq(b.foo, 24)
3303 vereq(b.getfoo(), 24)
3304 b = copy.deepcopy(a)
3305 vereq(b.foo, 24)
3306 vereq(b.getfoo(), 24)
3307
Guido van Rossum09638c12002-06-13 19:17:46 +00003308def slices():
3309 if verbose:
3310 print "Testing cases with slices and overridden __getitem__ ..."
3311 # Strings
3312 vereq("hello"[:4], "hell")
3313 vereq("hello"[slice(4)], "hell")
3314 vereq(str.__getitem__("hello", slice(4)), "hell")
3315 class S(str):
3316 def __getitem__(self, x):
3317 return str.__getitem__(self, x)
3318 vereq(S("hello")[:4], "hell")
3319 vereq(S("hello")[slice(4)], "hell")
3320 vereq(S("hello").__getitem__(slice(4)), "hell")
3321 # Tuples
3322 vereq((1,2,3)[:2], (1,2))
3323 vereq((1,2,3)[slice(2)], (1,2))
3324 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3325 class T(tuple):
3326 def __getitem__(self, x):
3327 return tuple.__getitem__(self, x)
3328 vereq(T((1,2,3))[:2], (1,2))
3329 vereq(T((1,2,3))[slice(2)], (1,2))
3330 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3331 # Lists
3332 vereq([1,2,3][:2], [1,2])
3333 vereq([1,2,3][slice(2)], [1,2])
3334 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3335 class L(list):
3336 def __getitem__(self, x):
3337 return list.__getitem__(self, x)
3338 vereq(L([1,2,3])[:2], [1,2])
3339 vereq(L([1,2,3])[slice(2)], [1,2])
3340 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3341 # Now do lists and __setitem__
3342 a = L([1,2,3])
3343 a[slice(1, 3)] = [3,2]
3344 vereq(a, [1,3,2])
3345 a[slice(0, 2, 1)] = [3,1]
3346 vereq(a, [3,1,2])
3347 a.__setitem__(slice(1, 3), [2,1])
3348 vereq(a, [3,2,1])
3349 a.__setitem__(slice(0, 2, 1), [2,3])
3350 vereq(a, [2,3,1])
3351
Tim Peters2484aae2002-07-11 06:56:07 +00003352def subtype_resurrection():
3353 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003354 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003355
3356 class C(object):
3357 container = []
3358
3359 def __del__(self):
3360 # resurrect the instance
3361 C.container.append(self)
3362
3363 c = C()
3364 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003365 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003366 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003367 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003368
3369 # If that didn't blow up, it's also interesting to see whether clearing
3370 # the last container slot works: that will attempt to delete c again,
3371 # which will cause c to get appended back to the container again "during"
3372 # the del.
3373 del C.container[-1]
3374 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003375 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003376
Tim Peters14cb1e12002-07-11 18:26:21 +00003377 # Make c mortal again, so that the test framework with -l doesn't report
3378 # it as a leak.
3379 del C.__del__
3380
Guido van Rossum2d702462002-08-06 21:28:28 +00003381def slottrash():
3382 # Deallocating deeply nested slotted trash caused stack overflows
3383 if verbose:
3384 print "Testing slot trash..."
3385 class trash(object):
3386 __slots__ = ['x']
3387 def __init__(self, x):
3388 self.x = x
3389 o = None
3390 for i in xrange(50000):
3391 o = trash(o)
3392 del o
3393
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003394def slotmultipleinheritance():
3395 # SF bug 575229, multiple inheritance w/ slots dumps core
3396 class A(object):
3397 __slots__=()
3398 class B(object):
3399 pass
3400 class C(A,B) :
3401 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003402 vereq(C.__basicsize__, B.__basicsize__)
3403 verify(hasattr(C, '__dict__'))
3404 verify(hasattr(C, '__weakref__'))
3405 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003406
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003407def testrmul():
3408 # SF patch 592646
3409 if verbose:
3410 print "Testing correct invocation of __rmul__..."
3411 class C(object):
3412 def __mul__(self, other):
3413 return "mul"
3414 def __rmul__(self, other):
3415 return "rmul"
3416 a = C()
3417 vereq(a*2, "mul")
3418 vereq(a*2.2, "mul")
3419 vereq(2*a, "rmul")
3420 vereq(2.2*a, "rmul")
3421
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003422def testipow():
3423 # [SF bug 620179]
3424 if verbose:
3425 print "Testing correct invocation of __ipow__..."
3426 class C(object):
3427 def __ipow__(self, other):
3428 pass
3429 a = C()
3430 a **= 2
3431
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003432def do_this_first():
3433 if verbose:
3434 print "Testing SF bug 551412 ..."
3435 # This dumps core when SF bug 551412 isn't fixed --
3436 # but only when test_descr.py is run separately.
3437 # (That can't be helped -- as soon as PyType_Ready()
3438 # is called for PyLong_Type, the bug is gone.)
3439 class UserLong(object):
3440 def __pow__(self, *args):
3441 pass
3442 try:
3443 pow(0L, UserLong(), 0L)
3444 except:
3445 pass
3446
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003447 if verbose:
3448 print "Testing SF bug 570483..."
3449 # Another segfault only when run early
3450 # (before PyType_Ready(tuple) is called)
3451 type.mro(tuple)
3452
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003453def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003454 if verbose:
3455 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003456 # stuff that should work:
3457 class C(object):
3458 pass
3459 class C2(object):
3460 def __getattribute__(self, attr):
3461 if attr == 'a':
3462 return 2
3463 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003464 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003465 def meth(self):
3466 return 1
3467 class D(C):
3468 pass
3469 class E(D):
3470 pass
3471 d = D()
3472 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003473 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003474 D.__bases__ = (C2,)
3475 vereq(d.meth(), 1)
3476 vereq(e.meth(), 1)
3477 vereq(d.a, 2)
3478 vereq(e.a, 2)
3479 vereq(C2.__subclasses__(), [D])
3480
3481 # stuff that shouldn't:
3482 class L(list):
3483 pass
3484
3485 try:
3486 L.__bases__ = (dict,)
3487 except TypeError:
3488 pass
3489 else:
3490 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3491
3492 try:
3493 list.__bases__ = (dict,)
3494 except TypeError:
3495 pass
3496 else:
3497 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3498
3499 try:
3500 del D.__bases__
3501 except TypeError:
3502 pass
3503 else:
3504 raise TestFailed, "shouldn't be able to delete .__bases__"
3505
3506 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003507 D.__bases__ = ()
3508 except TypeError, msg:
3509 if str(msg) == "a new-style class can't have only classic bases":
3510 raise TestFailed, "wrong error message for .__bases__ = ()"
3511 else:
3512 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3513
3514 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003515 D.__bases__ = (D,)
3516 except TypeError:
3517 pass
3518 else:
3519 # actually, we'll have crashed by here...
3520 raise TestFailed, "shouldn't be able to create inheritance cycles"
3521
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003522 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003523 D.__bases__ = (C, C)
3524 except TypeError:
3525 pass
3526 else:
3527 raise TestFailed, "didn't detect repeated base classes"
3528
3529 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003530 D.__bases__ = (E,)
3531 except TypeError:
3532 pass
3533 else:
3534 raise TestFailed, "shouldn't be able to create inheritance cycles"
3535
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003536def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003537 if verbose:
3538 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003539 class WorkOnce(type):
3540 def __new__(self, name, bases, ns):
3541 self.flag = 0
3542 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3543 def mro(self):
3544 if self.flag > 0:
3545 raise RuntimeError, "bozo"
3546 else:
3547 self.flag += 1
3548 return type.mro(self)
3549
3550 class WorkAlways(type):
3551 def mro(self):
3552 # this is here to make sure that .mro()s aren't called
3553 # with an exception set (which was possible at one point).
3554 # An error message will be printed in a debug build.
3555 # What's a good way to test for this?
3556 return type.mro(self)
3557
3558 class C(object):
3559 pass
3560
3561 class C2(object):
3562 pass
3563
3564 class D(C):
3565 pass
3566
3567 class E(D):
3568 pass
3569
3570 class F(D):
3571 __metaclass__ = WorkOnce
3572
3573 class G(D):
3574 __metaclass__ = WorkAlways
3575
3576 # Immediate subclasses have their mro's adjusted in alphabetical
3577 # order, so E's will get adjusted before adjusting F's fails. We
3578 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003579
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003580 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003581 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003582
3583 try:
3584 D.__bases__ = (C2,)
3585 except RuntimeError:
3586 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003587 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003588 else:
3589 raise TestFailed, "exception not propagated"
3590
3591def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003592 if verbose:
3593 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003594 class A(object):
3595 pass
3596
3597 class B(object):
3598 pass
3599
3600 class C(A, B):
3601 pass
3602
3603 class D(A, B):
3604 pass
3605
3606 class E(C, D):
3607 pass
3608
3609 try:
3610 C.__bases__ = (B, A)
3611 except TypeError:
3612 pass
3613 else:
3614 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003615
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003616def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003617 if verbose:
3618 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003619 class C(object):
3620 pass
3621
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003622 # C.__module__ could be 'test_descr' or '__main__'
3623 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003624
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003625 C.__name__ = 'D'
3626 vereq((C.__module__, C.__name__), (mod, 'D'))
3627
3628 C.__name__ = 'D.E'
3629 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003630
Guido van Rossum613f24f2003-01-06 23:00:59 +00003631def subclass_right_op():
3632 if verbose:
3633 print "Testing correct dispatch of subclass overloading __r<op>__..."
3634
3635 # This code tests various cases where right-dispatch of a subclass
3636 # should be preferred over left-dispatch of a base class.
3637
3638 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3639
3640 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003641 def __floordiv__(self, other):
3642 return "B.__floordiv__"
3643 def __rfloordiv__(self, other):
3644 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003645
Guido van Rossumf389c772003-02-27 20:04:19 +00003646 vereq(B(1) // 1, "B.__floordiv__")
3647 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003648
3649 # Case 2: subclass of object; this is just the baseline for case 3
3650
3651 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003652 def __floordiv__(self, other):
3653 return "C.__floordiv__"
3654 def __rfloordiv__(self, other):
3655 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003656
Guido van Rossumf389c772003-02-27 20:04:19 +00003657 vereq(C() // 1, "C.__floordiv__")
3658 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003659
3660 # Case 3: subclass of new-style class; here it gets interesting
3661
3662 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003663 def __floordiv__(self, other):
3664 return "D.__floordiv__"
3665 def __rfloordiv__(self, other):
3666 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003667
Guido van Rossumf389c772003-02-27 20:04:19 +00003668 vereq(D() // C(), "D.__floordiv__")
3669 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003670
3671 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3672
3673 class E(C):
3674 pass
3675
Guido van Rossumf389c772003-02-27 20:04:19 +00003676 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003677
Guido van Rossumf389c772003-02-27 20:04:19 +00003678 vereq(E() // 1, "C.__floordiv__")
3679 vereq(1 // E(), "C.__rfloordiv__")
3680 vereq(E() // C(), "C.__floordiv__")
3681 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003682
Guido van Rossum373c7412003-01-07 13:41:37 +00003683def dict_type_with_metaclass():
3684 if verbose:
3685 print "Testing type of __dict__ when __metaclass__ set..."
3686
3687 class B(object):
3688 pass
3689 class M(type):
3690 pass
3691 class C:
3692 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3693 __metaclass__ = M
3694 veris(type(C.__dict__), type(B.__dict__))
3695
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003696def meth_class_get():
3697 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003698 if verbose:
3699 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003700 # Baseline
3701 arg = [1, 2, 3]
3702 res = {1: None, 2: None, 3: None}
3703 vereq(dict.fromkeys(arg), res)
3704 vereq({}.fromkeys(arg), res)
3705 # Now get the descriptor
3706 descr = dict.__dict__["fromkeys"]
3707 # More baseline using the descriptor directly
3708 vereq(descr.__get__(None, dict)(arg), res)
3709 vereq(descr.__get__({})(arg), res)
3710 # Now check various error cases
3711 try:
3712 descr.__get__(None, None)
3713 except TypeError:
3714 pass
3715 else:
3716 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3717 try:
3718 descr.__get__(42)
3719 except TypeError:
3720 pass
3721 else:
3722 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3723 try:
3724 descr.__get__(None, 42)
3725 except TypeError:
3726 pass
3727 else:
3728 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3729 try:
3730 descr.__get__(None, int)
3731 except TypeError:
3732 pass
3733 else:
3734 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3735
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003736def isinst_isclass():
3737 if verbose:
3738 print "Testing proxy isinstance() and isclass()..."
3739 class Proxy(object):
3740 def __init__(self, obj):
3741 self.__obj = obj
3742 def __getattribute__(self, name):
3743 if name.startswith("_Proxy__"):
3744 return object.__getattribute__(self, name)
3745 else:
3746 return getattr(self.__obj, name)
3747 # Test with a classic class
3748 class C:
3749 pass
3750 a = C()
3751 pa = Proxy(a)
3752 verify(isinstance(a, C)) # Baseline
3753 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003754 # Test with a classic subclass
3755 class D(C):
3756 pass
3757 a = D()
3758 pa = Proxy(a)
3759 verify(isinstance(a, C)) # Baseline
3760 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003761 # Test with a new-style class
3762 class C(object):
3763 pass
3764 a = C()
3765 pa = Proxy(a)
3766 verify(isinstance(a, C)) # Baseline
3767 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003768 # Test with a new-style subclass
3769 class D(C):
3770 pass
3771 a = D()
3772 pa = Proxy(a)
3773 verify(isinstance(a, C)) # Baseline
3774 verify(isinstance(pa, C)) # Test
3775
3776def proxysuper():
3777 if verbose:
3778 print "Testing super() for a proxy object..."
3779 class Proxy(object):
3780 def __init__(self, obj):
3781 self.__obj = obj
3782 def __getattribute__(self, name):
3783 if name.startswith("_Proxy__"):
3784 return object.__getattribute__(self, name)
3785 else:
3786 return getattr(self.__obj, name)
3787
3788 class B(object):
3789 def f(self):
3790 return "B.f"
3791
3792 class C(B):
3793 def f(self):
3794 return super(C, self).f() + "->C.f"
3795
3796 obj = C()
3797 p = Proxy(obj)
3798 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003799
Guido van Rossum52b27052003-04-15 20:05:10 +00003800def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003801 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00003802 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003803 try:
3804 object.__setattr__(str, "foo", 42)
3805 except TypeError:
3806 pass
3807 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003808 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003809 try:
3810 object.__delattr__(str, "lower")
3811 except TypeError:
3812 pass
3813 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003814 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003815
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003816def weakref_segfault():
3817 # SF 742911
3818 if verbose:
3819 print "Testing weakref segfault..."
3820
3821 import weakref
3822
3823 class Provoker:
3824 def __init__(self, referrent):
3825 self.ref = weakref.ref(referrent)
3826
3827 def __del__(self):
3828 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003829
3830 class Oops(object):
3831 pass
3832
3833 o = Oops()
3834 o.whatever = Provoker(o)
3835 del o
3836
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003837def wrapper_segfault():
3838 # SF 927248: deeply nested wrappers could cause stack overflow
3839 f = lambda:None
3840 for i in xrange(1000000):
3841 f = f.__call__
3842 f = None
3843
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003844# Fix SF #762455, segfault when sys.stdout is changed in getattr
3845def filefault():
3846 if verbose:
3847 print "Testing sys.stdout is changed in getattr..."
3848 import sys
3849 class StdoutGuard:
3850 def __getattr__(self, attr):
3851 sys.stdout = sys.__stdout__
3852 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3853 sys.stdout = StdoutGuard()
3854 try:
3855 print "Oops!"
3856 except RuntimeError:
3857 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003858
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003859def vicious_descriptor_nonsense():
3860 # A potential segfault spotted by Thomas Wouters in mail to
3861 # python-dev 2003-04-17, turned into an example & fixed by Michael
3862 # Hudson just less than four months later...
3863 if verbose:
3864 print "Testing vicious_descriptor_nonsense..."
3865
3866 class Evil(object):
3867 def __hash__(self):
3868 return hash('attr')
3869 def __eq__(self, other):
3870 del C.attr
3871 return 0
3872
3873 class Descr(object):
3874 def __get__(self, ob, type=None):
3875 return 1
3876
3877 class C(object):
3878 attr = Descr()
3879
3880 c = C()
3881 c.__dict__[Evil()] = 0
3882
3883 vereq(c.attr, 1)
3884 # this makes a crash more likely:
3885 import gc; gc.collect()
3886 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00003887
Raymond Hettingerb67cc802005-03-03 16:45:19 +00003888def test_init():
3889 # SF 1155938
3890 class Foo(object):
3891 def __init__(self):
3892 return 10
3893 try:
3894 Foo()
3895 except TypeError:
3896 pass
3897 else:
3898 raise TestFailed, "did not test __init__() for None return"
3899
Armin Rigoc6686b72005-11-07 08:38:00 +00003900def methodwrapper():
3901 # <type 'method-wrapper'> did not support any reflection before 2.5
3902 if verbose:
3903 print "Testing method-wrapper objects..."
3904
3905 l = []
3906 vereq(l.__add__, l.__add__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003907 vereq(l.__add__, [].__add__)
3908 verify(l.__add__ != [5].__add__)
3909 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00003910 verify(l.__add__.__name__ == '__add__')
3911 verify(l.__add__.__self__ is l)
3912 verify(l.__add__.__objclass__ is list)
3913 vereq(l.__add__.__doc__, list.__add__.__doc__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003914 try:
3915 hash(l.__add__)
3916 except TypeError:
3917 pass
3918 else:
3919 raise TestFailed("no TypeError from hash([].__add__)")
3920
3921 t = ()
3922 t += (7,)
3923 vereq(t.__add__, (7,).__add__)
3924 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00003925
Armin Rigofd163f92005-12-29 15:59:19 +00003926def notimplemented():
3927 # all binary methods should be able to return a NotImplemented
3928 if verbose:
3929 print "Testing NotImplemented..."
3930
3931 import sys
3932 import types
3933 import operator
3934
3935 def specialmethod(self, other):
3936 return NotImplemented
3937
3938 def check(expr, x, y):
3939 try:
3940 exec expr in {'x': x, 'y': y, 'operator': operator}
3941 except TypeError:
3942 pass
3943 else:
3944 raise TestFailed("no TypeError from %r" % (expr,))
3945
3946 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
3947 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
3948 # ValueErrors instead of TypeErrors
3949 for metaclass in [type, types.ClassType]:
3950 for name, expr, iexpr in [
3951 ('__add__', 'x + y', 'x += y'),
3952 ('__sub__', 'x - y', 'x -= y'),
3953 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003954 ('__truediv__', 'x / y', None),
3955 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00003956 ('__mod__', 'x % y', 'x %= y'),
3957 ('__divmod__', 'divmod(x, y)', None),
3958 ('__pow__', 'x ** y', 'x **= y'),
3959 ('__lshift__', 'x << y', 'x <<= y'),
3960 ('__rshift__', 'x >> y', 'x >>= y'),
3961 ('__and__', 'x & y', 'x &= y'),
3962 ('__or__', 'x | y', 'x |= y'),
3963 ('__xor__', 'x ^ y', 'x ^= y'),
3964 ('__coerce__', 'coerce(x, y)', None)]:
3965 if name == '__coerce__':
3966 rname = name
3967 else:
3968 rname = '__r' + name[2:]
3969 A = metaclass('A', (), {name: specialmethod})
3970 B = metaclass('B', (), {rname: specialmethod})
3971 a = A()
3972 b = B()
3973 check(expr, a, a)
3974 check(expr, a, b)
3975 check(expr, b, a)
3976 check(expr, b, b)
3977 check(expr, a, N1)
3978 check(expr, a, N2)
3979 check(expr, N1, b)
3980 check(expr, N2, b)
3981 if iexpr:
3982 check(iexpr, a, a)
3983 check(iexpr, a, b)
3984 check(iexpr, b, a)
3985 check(iexpr, b, b)
3986 check(iexpr, a, N1)
3987 check(iexpr, a, N2)
3988 iname = '__i' + name[2:]
3989 C = metaclass('C', (), {iname: specialmethod})
3990 c = C()
3991 check(iexpr, c, a)
3992 check(iexpr, c, b)
3993 check(iexpr, c, N1)
3994 check(iexpr, c, N2)
3995
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003996def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003997 weakref_segfault() # Must be first, somehow
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003998 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003999 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004000 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004001 lists()
4002 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004003 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004004 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005 ints()
4006 longs()
4007 floats()
4008 complexes()
4009 spamlists()
4010 spamdicts()
4011 pydicts()
4012 pylists()
4013 metaclass()
4014 pymods()
4015 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004016 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004017 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004018 ex5()
4019 monotonicity()
4020 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004021 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004023 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024 dynamics()
4025 errors()
4026 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004027 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004029 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004030 classic()
4031 compattr()
4032 newslot()
4033 altmro()
4034 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004035 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004036 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004037 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004038 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004039 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004040 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004041 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004042 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004043 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004044 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004045 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004046 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004047 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004048 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004049 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004050 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004051 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004052 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004053 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004054 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004055 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004056 kwdargs()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004057 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004058 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004059 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004060 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004061 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004062 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004063 dictproxyiterkeys()
4064 dictproxyitervalues()
4065 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004066 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004067 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004068 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004069 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004070 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004071 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004072 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004073 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004074 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004075 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004076 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004077 test_mutable_bases()
4078 test_mutable_bases_with_failing_mro()
4079 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004080 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004081 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004082 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004083 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004084 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004085 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004086 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004087 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004088 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004089 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004090 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004091 notimplemented()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004092
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004093 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004095if __name__ == "__main__":
4096 test_main()