blob: e8d94f4bc52e7ad7239a088e74a4728fce078ad5 [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
Guido van Rossum360e4b82007-05-14 22:51:27 +00006import types
Tim Peters4d9b4662002-04-16 01:59:17 +00007
8warnings.filterwarnings("ignore",
9 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +000010 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Guido van Rossum875eeaa2001-10-11 18:33:53 +000012def veris(a, b):
13 if a is not b:
14 raise TestFailed, "%r is %r" % (a, b)
15
Tim Peters6d6c1a32001-08-02 04:15:00 +000016def testunop(a, res, expr="len(a)", meth="__len__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000017 if verbose: print("checking", expr)
Tim Peters6d6c1a32001-08-02 04:15:00 +000018 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000019 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000020 t = type(a)
21 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000022 while meth not in t.__dict__:
23 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000024 vereq(m, t.__dict__[meth])
25 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000026 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000027 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000028
29def testbinop(a, b, res, expr="a+b", meth="__add__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000030 if verbose: print("checking", expr)
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000032
Guido van Rossum45704552001-10-08 16:35:45 +000033 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000034 t = type(a)
35 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000036 while meth not in t.__dict__:
37 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000038 vereq(m, t.__dict__[meth])
39 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000040 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000041 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
43def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000044 if verbose: print("checking", expr)
Tim Peters6d6c1a32001-08-02 04:15:00 +000045 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000046 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000047 t = type(a)
48 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000049 while meth not in t.__dict__:
50 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000051 vereq(m, t.__dict__[meth])
52 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000053 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000054 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000055
56def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000057 if verbose: print("checking", stmt)
Tim Peters6d6c1a32001-08-02 04:15:00 +000058 dict = {'a': deepcopy(a), 'b': b}
Georg Brandl7cae87c2006-09-06 06:51:57 +000059 exec(stmt, dict)
Guido van Rossum45704552001-10-08 16:35:45 +000060 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000061 t = type(a)
62 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000063 while meth not in t.__dict__:
64 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000065 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000066 dict['a'] = deepcopy(a)
67 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000068 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000069 dict['a'] = deepcopy(a)
70 bm = getattr(dict['a'], meth)
71 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000072 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000073
74def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000075 if verbose: print("checking", stmt)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076 dict = {'a': deepcopy(a), 'b': b, 'c': c}
Georg Brandl7cae87c2006-09-06 06:51:57 +000077 exec(stmt, dict)
Guido van Rossum45704552001-10-08 16:35:45 +000078 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000079 t = type(a)
80 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000081 while meth not in t.__dict__:
82 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000083 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000084 dict['a'] = deepcopy(a)
85 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000086 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 dict['a'] = deepcopy(a)
88 bm = getattr(dict['a'], meth)
89 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000090 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000091
92def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000093 if verbose: print("checking", stmt)
Tim Peters6d6c1a32001-08-02 04:15:00 +000094 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
Georg Brandl7cae87c2006-09-06 06:51:57 +000095 exec(stmt, dict)
Guido van Rossum45704552001-10-08 16:35:45 +000096 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000097 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000098 while meth not in t.__dict__:
99 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000101 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000102 dict['a'] = deepcopy(a)
103 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000104 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000105 dict['a'] = deepcopy(a)
106 bm = getattr(dict['a'], meth)
107 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000108 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000109
Tim Peters2f93e282001-10-04 05:27:00 +0000110def class_docstrings():
111 class Classic:
112 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000113 vereq(Classic.__doc__, "A classic docstring.")
114 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000115
116 class Classic2:
117 pass
118 verify(Classic2.__doc__ is None)
119
Tim Peters4fb1fe82001-10-04 05:48:13 +0000120 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000121 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000122 vereq(NewStatic.__doc__, "Another docstring.")
123 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000124
Tim Peters4fb1fe82001-10-04 05:48:13 +0000125 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000126 pass
127 verify(NewStatic2.__doc__ is None)
128
Tim Peters4fb1fe82001-10-04 05:48:13 +0000129 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000130 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000131 vereq(NewDynamic.__doc__, "Another docstring.")
132 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000133
Tim Peters4fb1fe82001-10-04 05:48:13 +0000134 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000135 pass
136 verify(NewDynamic2.__doc__ is None)
137
Tim Peters6d6c1a32001-08-02 04:15:00 +0000138def lists():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000139 if verbose: print("Testing list operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000140 testbinop([1], [2], [1,2], "a+b", "__add__")
141 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
142 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
143 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
144 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
145 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
146 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
147 testunop([1,2,3], 3, "len(a)", "__len__")
148 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
149 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
150 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
151 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
152
153def dicts():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 if verbose: print("Testing dict operations...")
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000155 ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000156 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
157 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
158 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
159 d = {1:2,3:4}
160 l1 = []
161 for i in d.keys(): l1.append(i)
162 l = []
163 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000164 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000165 l = []
166 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000167 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000168 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000169 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000170 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 d = {1:2, 3:4}
172 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000173 vereq(eval(repr(d), {}), d)
174 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000175 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
176
Tim Peters25786c02001-09-02 08:22:48 +0000177def dict_constructor():
178 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000179 print("Testing dict constructor ...")
Tim Petersa427a2b2001-10-29 22:25:45 +0000180 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000181 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000182 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000183 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000184 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000185 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000186 vereq(d, dict(d.items()))
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000187 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000188 d = dict({'one':1, 'two':2})
189 vereq(d, dict(one=1, two=2))
190 vereq(d, dict(**d))
191 vereq(d, dict({"one": 1}, two=2))
192 vereq(d, dict([("two", 2)], one=1))
193 vereq(d, dict([("one", 100), ("two", 200)], **d))
194 verify(d is not dict(**d))
Guido van Rossume2a383d2007-01-15 16:59:06 +0000195 for badarg in 0, 0, 0j, "0", [0], (0,):
Tim Peters25786c02001-09-02 08:22:48 +0000196 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000197 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000198 except TypeError:
199 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000200 except ValueError:
201 if badarg == "0":
202 # It's a sequence, and its elements are also sequences (gotta
203 # love strings <wink>), but they aren't of length 2, so this
204 # one seemed better as a ValueError than a TypeError.
205 pass
206 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000207 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000208 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000209 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000210
211 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000212 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000213 except TypeError:
214 pass
215 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000216 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000217
218 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000219 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000220 dict = {1:2, 3:4, 'a':1j}
221
Tim Peters25786c02001-09-02 08:22:48 +0000222 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000223 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000224 except TypeError:
225 pass
226 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000227 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000228
229 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000230 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000231 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000232 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000233
Tim Peters1fc240e2001-10-26 05:06:50 +0000234 # Init from sequence of iterable objects, each producing a 2-sequence.
235 class AddressBookEntry:
236 def __init__(self, first, last):
237 self.first = first
238 self.last = last
239 def __iter__(self):
240 return iter([self.first, self.last])
241
Tim Petersa427a2b2001-10-29 22:25:45 +0000242 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000243 AddressBookEntry('Barry', 'Peters'),
244 AddressBookEntry('Tim', 'Peters'),
245 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000246 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
247
Tim Petersa427a2b2001-10-29 22:25:45 +0000248 d = dict(zip(range(4), range(1, 5)))
249 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000250
251 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000252 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000253 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000254 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000255 except ValueError:
256 pass
257 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000258 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000259
Tim Peters5d2b77c2001-09-03 05:47:38 +0000260def test_dir():
261 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000262 print("Testing dir() ...")
Tim Peters5d2b77c2001-09-03 05:47:38 +0000263 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000264 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000265 del junk
266
267 # Just make sure these don't blow up!
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000268 for arg in 2, 2, 2j, 2e0, [2], "2", "2", (2,), {2:2}, type, test_dir:
Tim Peters5d2b77c2001-09-03 05:47:38 +0000269 dir(arg)
270
Thomas Wouters0725cf22006-04-15 09:04:57 +0000271 # Test dir on custom classes. Since these have object as a
272 # base class, a lot of stuff gets sucked in.
Tim Peters37a309d2001-09-04 01:20:04 +0000273 def interesting(strings):
274 return [s for s in strings if not s.startswith('_')]
275
Tim Peters5d2b77c2001-09-03 05:47:38 +0000276 class C(object):
277 Cdata = 1
278 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000279
280 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000281 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000282
283 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000284 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000285 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000286
287 c.cdata = 2
288 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000289 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000290 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000291
Tim Peters5d2b77c2001-09-03 05:47:38 +0000292 class A(C):
293 Adata = 1
294 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000295
296 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000297 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000298 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000299 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000300 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000301 a.adata = 42
302 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000303 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000304 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000305
Tim Peterscaaff8d2001-09-10 23:12:14 +0000306 # Try a module subclass.
307 import sys
308 class M(type(sys)):
309 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000310 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000311 minstance.b = 2
312 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000313 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
314 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000315
316 class M2(M):
317 def getdict(self):
318 return "Not a dict!"
319 __dict__ = property(getdict)
320
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000321 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000322 m2instance.b = 2
323 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000324 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000325 try:
326 dir(m2instance)
327 except TypeError:
328 pass
329
Tim Peters9e6a3992001-10-30 05:45:26 +0000330 # Two essentially featureless objects, just inheriting stuff from
331 # object.
332 vereq(dir(None), dir(Ellipsis))
333
Guido van Rossum44022412002-05-13 18:29:46 +0000334 # Nasty test case for proxied objects
335 class Wrapper(object):
336 def __init__(self, obj):
337 self.__obj = obj
338 def __repr__(self):
339 return "Wrapper(%s)" % repr(self.__obj)
340 def __getitem__(self, key):
341 return Wrapper(self.__obj[key])
342 def __len__(self):
343 return len(self.__obj)
344 def __getattr__(self, name):
345 return Wrapper(getattr(self.__obj, name))
346
347 class C(object):
348 def __getclass(self):
349 return Wrapper(type(self))
350 __class__ = property(__getclass)
351
352 dir(C()) # This used to segfault
353
Tim Peters6d6c1a32001-08-02 04:15:00 +0000354binops = {
355 'add': '+',
356 'sub': '-',
357 'mul': '*',
358 'div': '/',
359 'mod': '%',
360 'divmod': 'divmod',
361 'pow': '**',
362 'lshift': '<<',
363 'rshift': '>>',
364 'and': '&',
365 'xor': '^',
366 'or': '|',
367 'cmp': 'cmp',
368 'lt': '<',
369 'le': '<=',
370 'eq': '==',
371 'ne': '!=',
372 'gt': '>',
373 'ge': '>=',
374 }
375
376for name, expr in binops.items():
377 if expr.islower():
378 expr = expr + "(a, b)"
379 else:
380 expr = 'a %s b' % expr
381 binops[name] = expr
382
383unops = {
384 'pos': '+',
385 'neg': '-',
386 'abs': 'abs',
387 'invert': '~',
388 'int': 'int',
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389 '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():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000417 if verbose: print("Testing int operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000419 # The following crashes in Python 2.2
Jack Diederich4dafcc42006-11-28 19:15:13 +0000420 vereq((1).__bool__(), True)
421 vereq((0).__bool__(), False)
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
Guido van Rossume2a383d2007-01-15 16:59:06 +0000426 vereq(C(5), 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"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433
434def longs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000435 if verbose: print("Testing long operations...")
Guido van Rossume2a383d2007-01-15 16:59:06 +0000436 numops(100, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437
438def floats():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000439 if verbose: print("Testing float operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000440 numops(100.0, 3.0)
441
442def complexes():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000443 if verbose: print("Testing complex operations...")
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000444 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000445 class Number(complex):
446 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000447 def __new__(cls, *args, **kwds):
448 result = complex.__new__(cls, *args)
449 result.prec = kwds.get('prec', 12)
450 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 def __repr__(self):
452 prec = self.prec
453 if self.imag == 0.0:
454 return "%.*g" % (prec, self.real)
455 if self.real == 0.0:
456 return "%.*gj" % (prec, self.imag)
457 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
458 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000459
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000461 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000462 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463
Tim Peters3f996e72001-09-13 19:18:27 +0000464 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000465 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000466 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000467
468 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000469 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000470 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000471
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472def spamlists():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000473 if verbose: print("Testing spamlist operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474 import copy, xxsubtype as spam
475 def spamlist(l, memo=None):
476 import xxsubtype as spam
477 return spam.spamlist(l)
478 # This is an ugly hack:
479 copy._deepcopy_dispatch[spam.spamlist] = spamlist
480
481 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
482 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
483 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
484 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
485 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
486 "a[b:c]", "__getslice__")
487 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
488 "a+=b", "__iadd__")
489 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
490 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
491 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
492 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
493 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
494 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
495 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
496 # Test subclassing
497 class C(spam.spamlist):
498 def foo(self): return 1
499 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000500 vereq(a, [])
501 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000502 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000503 vereq(a, [100])
504 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000505 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000506 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000507
508def spamdicts():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000509 if verbose: print("Testing spamdict operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000510 import copy, xxsubtype as spam
511 def spamdict(d, memo=None):
512 import xxsubtype as spam
513 sd = spam.spamdict()
514 for k, v in d.items(): sd[k] = v
515 return sd
516 # This is an ugly hack:
517 copy._deepcopy_dispatch[spam.spamdict] = spamdict
518
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000519 ##testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000520 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
521 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
522 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
523 d = spamdict({1:2,3:4})
524 l1 = []
525 for i in d.keys(): l1.append(i)
526 l = []
527 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000528 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000529 l = []
530 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000531 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000532 l = []
533 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000534 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000535 straightd = {1:2, 3:4}
536 spamd = spamdict(straightd)
537 testunop(spamd, 2, "len(a)", "__len__")
538 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
539 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
540 "a[b]=c", "__setitem__")
541 # Test subclassing
542 class C(spam.spamdict):
543 def foo(self): return 1
544 a = C()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000545 vereq(list(a.items()), [])
Guido van Rossum45704552001-10-08 16:35:45 +0000546 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 a['foo'] = 'bar'
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000548 vereq(list(a.items()), [('foo', 'bar')])
Guido van Rossum45704552001-10-08 16:35:45 +0000549 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000550 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000551 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000552
553def pydicts():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000554 if verbose: print("Testing Python subclass of dict...")
Tim Petersa427a2b2001-10-29 22:25:45 +0000555 verify(issubclass(dict, dict))
556 verify(isinstance({}, dict))
557 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000558 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000559 verify(d.__class__ is dict)
560 verify(isinstance(d, dict))
561 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562 state = -1
563 def __init__(self, *a, **kw):
564 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000565 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000566 self.state = a[0]
567 if kw:
568 for k, v in kw.items(): self[v] = k
569 def __getitem__(self, key):
570 return self.get(key, 0)
571 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000572 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000573 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000574 def setstate(self, state):
575 self.state = state
576 def getstate(self):
577 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000578 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000579 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000580 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000582 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000584 vereq(a.state, -1)
585 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000587 vereq(a.state, 0)
588 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000590 vereq(a.state, 10)
591 vereq(a.getstate(), 10)
592 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000594 vereq(a[42], 24)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000595 if verbose: print("pydict stress test ...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 N = 50
597 for i in range(N):
598 a[i] = C()
599 for j in range(N):
600 a[i][j] = i*j
601 for i in range(N):
602 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000603 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604
605def pylists():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000606 if verbose: print("Testing Python subclass of list...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000607 class C(list):
608 def __getitem__(self, i):
609 return list.__getitem__(self, i) + 100
610 def __getslice__(self, i, j):
611 return (i, j)
612 a = C()
613 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000614 vereq(a[0], 100)
615 vereq(a[1], 101)
616 vereq(a[2], 102)
617 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618
619def metaclass():
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000620 if verbose: print("Testing metaclass...")
621 class C(metaclass=type):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 def __init__(self):
623 self.__state = 0
624 def getstate(self):
625 return self.__state
626 def setstate(self, state):
627 self.__state = state
628 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000629 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000631 vereq(a.getstate(), 10)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000632 class _metaclass(type):
633 def myself(cls): return cls
634 class D(metaclass=_metaclass):
635 pass
Guido van Rossum45704552001-10-08 16:35:45 +0000636 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000637 d = D()
638 verify(d.__class__ is D)
639 class M1(type):
640 def __new__(cls, name, bases, dict):
641 dict['__spam__'] = 1
642 return type.__new__(cls, name, bases, dict)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000643 class C(metaclass=M1):
644 pass
Guido van Rossum45704552001-10-08 16:35:45 +0000645 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000646 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000647 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000648
Guido van Rossum309b5662001-08-17 11:43:17 +0000649 class _instance(object):
650 pass
651 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000652 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000653 def __new__(cls, name, bases, dict):
654 self = object.__new__(cls)
655 self.name = name
656 self.bases = bases
657 self.dict = dict
658 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000659 def __call__(self):
660 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000661 # Early binding of methods
662 for key in self.dict:
663 if key.startswith("__"):
664 continue
665 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000666 return it
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000667 class C(metaclass=M2):
Guido van Rossum309b5662001-08-17 11:43:17 +0000668 def spam(self):
669 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000670 vereq(C.name, 'C')
671 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000672 verify('spam' in C.dict)
673 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000674 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
Guido van Rossum91ee7982001-08-30 20:52:40 +0000676 # More metaclass examples
677
678 class autosuper(type):
679 # Automatically add __super to the class
680 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000681 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000682 cls = super(autosuper, metaclass).__new__(metaclass,
683 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000684 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000685 while name[:1] == "_":
686 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000687 if name:
688 name = "_%s__super" % name
689 else:
690 name = "__super"
691 setattr(cls, name, super(cls))
692 return cls
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000693 class A(metaclass=autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000694 def meth(self):
695 return "A"
696 class B(A):
697 def meth(self):
698 return "B" + self.__super.meth()
699 class C(A):
700 def meth(self):
701 return "C" + self.__super.meth()
702 class D(C, B):
703 def meth(self):
704 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000705 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000706 class E(B, C):
707 def meth(self):
708 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000709 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000710
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000711 class autoproperty(type):
712 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000713 # named _get_x and/or _set_x are found
714 def __new__(metaclass, name, bases, dict):
715 hits = {}
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000716 for key, val in dict.items():
Guido van Rossum91ee7982001-08-30 20:52:40 +0000717 if key.startswith("_get_"):
718 key = key[5:]
719 get, set = hits.get(key, (None, None))
720 get = val
721 hits[key] = get, set
722 elif key.startswith("_set_"):
723 key = key[5:]
724 get, set = hits.get(key, (None, None))
725 set = val
726 hits[key] = get, set
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000727 for key, (get, set) in hits.items():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000728 dict[key] = property(get, set)
729 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000730 name, bases, dict)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000731 class A(metaclass=autoproperty):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000732 def _get_x(self):
733 return -self.__x
734 def _set_x(self, x):
735 self.__x = -x
736 a = A()
737 verify(not hasattr(a, "x"))
738 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000739 vereq(a.x, 12)
740 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000741
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000742 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000743 # Merge of multiple cooperating metaclasses
744 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000745 class A(metaclass=multimetaclass):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000746 def _get_x(self):
747 return "A"
748 class B(A):
749 def _get_x(self):
750 return "B" + self.__super._get_x()
751 class C(A):
752 def _get_x(self):
753 return "C" + self.__super._get_x()
754 class D(C, B):
755 def _get_x(self):
756 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000757 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000758
Guido van Rossumf76de622001-10-18 15:49:21 +0000759 # Make sure type(x) doesn't call x.__class__.__init__
760 class T(type):
761 counter = 0
762 def __init__(self, *args):
763 T.counter += 1
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000764 class C(metaclass=T):
765 pass
Guido van Rossumf76de622001-10-18 15:49:21 +0000766 vereq(T.counter, 1)
767 a = C()
768 vereq(type(a), C)
769 vereq(T.counter, 1)
770
Guido van Rossum29d26062001-12-11 04:37:34 +0000771 class C(object): pass
772 c = C()
773 try: c()
774 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000775 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000776
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 # Testing code to find most derived baseclass
778 class A(type):
779 def __new__(*args, **kwargs):
780 return type.__new__(*args, **kwargs)
781
782 class B(object):
783 pass
784
785 class C(object, metaclass=A):
786 pass
787
788 # The most derived metaclass of D is A rather than type.
789 class D(B, C):
790 pass
791
792
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793def pymods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000794 if verbose: print("Testing Python subclass of module...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000796 import sys
797 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000799 def __init__(self, name):
800 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000801 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000802 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000803 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000804 def __setattr__(self, name, value):
805 log.append(("setattr", name, value))
806 MT.__setattr__(self, name, value)
807 def __delattr__(self, name):
808 log.append(("delattr", name))
809 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000810 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811 a.foo = 12
812 x = a.foo
813 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000814 vereq(log, [("setattr", "foo", 12),
815 ("getattr", "foo"),
816 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817
Guido van Rossum360e4b82007-05-14 22:51:27 +0000818 # http://python.org/sf/1174712
819 try:
820 class Module(types.ModuleType, str):
821 pass
822 except TypeError:
823 pass
824 else:
825 raise TestFailed("inheriting from ModuleType and str at the "
826 "same time should fail")
827
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828def multi():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000829 if verbose: print("Testing multiple inheritance...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 class C(object):
831 def __init__(self):
832 self.__state = 0
833 def getstate(self):
834 return self.__state
835 def setstate(self, state):
836 self.__state = state
837 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000838 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000840 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000841 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 def __init__(self):
843 type({}).__init__(self)
844 C.__init__(self)
845 d = D()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000846 vereq(list(d.keys()), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847 d["hello"] = "world"
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000848 vereq(list(d.items()), [("hello", "world")])
Guido van Rossum45704552001-10-08 16:35:45 +0000849 vereq(d["hello"], "world")
850 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000852 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000853 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854
Guido van Rossume45763a2001-08-10 21:28:46 +0000855 # SF bug #442833
856 class Node(object):
857 def __int__(self):
858 return int(self.foo())
859 def foo(self):
860 return "23"
861 class Frag(Node, list):
862 def foo(self):
863 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000864 vereq(Node().__int__(), 23)
865 vereq(int(Node()), 23)
866 vereq(Frag().__int__(), 42)
867 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000868
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869def diamond():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000870 if verbose: print("Testing multiple inheritance special cases...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871 class A(object):
872 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000873 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874 class B(A):
875 def boo(self): return "B"
876 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000877 vereq(B().spam(), "B")
878 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 class C(A):
880 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000881 vereq(C().spam(), "A")
882 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000884 vereq(D().spam(), "B")
885 vereq(D().boo(), "B")
886 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000888 vereq(E().spam(), "B")
889 vereq(E().boo(), "C")
890 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000891 # MRO order disagreement
892 try:
893 class F(D, E): pass
894 except TypeError:
895 pass
896 else:
897 raise TestFailed, "expected MRO order disagreement (F)"
898 try:
899 class G(E, D): pass
900 except TypeError:
901 pass
902 else:
903 raise TestFailed, "expected MRO order disagreement (G)"
904
905
906# see thread python-dev/2002-October/029035.html
907def ex5():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000908 if verbose: print("Testing ex5 from C3 switch discussion...")
Guido van Rossum9a818922002-11-14 19:50:14 +0000909 class A(object): pass
910 class B(object): pass
911 class C(object): pass
912 class X(A): pass
913 class Y(A): pass
914 class Z(X,B,Y,C): pass
915 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
916
917# see "A Monotonic Superclass Linearization for Dylan",
918# by Kim Barrett et al. (OOPSLA 1996)
919def monotonicity():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000920 if verbose: print("Testing MRO monotonicity...")
Guido van Rossum9a818922002-11-14 19:50:14 +0000921 class Boat(object): pass
922 class DayBoat(Boat): pass
923 class WheelBoat(Boat): pass
924 class EngineLess(DayBoat): pass
925 class SmallMultihull(DayBoat): pass
926 class PedalWheelBoat(EngineLess,WheelBoat): pass
927 class SmallCatamaran(SmallMultihull): pass
928 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
929
930 vereq(PedalWheelBoat.__mro__,
931 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
932 object))
933 vereq(SmallCatamaran.__mro__,
934 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
935
936 vereq(Pedalo.__mro__,
937 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
938 SmallMultihull, DayBoat, WheelBoat, Boat, object))
939
940# see "A Monotonic Superclass Linearization for Dylan",
941# by Kim Barrett et al. (OOPSLA 1996)
942def consistency_with_epg():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000943 if verbose: print("Testing consistentcy with EPG...")
Guido van Rossum9a818922002-11-14 19:50:14 +0000944 class Pane(object): pass
945 class ScrollingMixin(object): pass
946 class EditingMixin(object): pass
947 class ScrollablePane(Pane,ScrollingMixin): pass
948 class EditablePane(Pane,EditingMixin): pass
949 class EditableScrollablePane(ScrollablePane,EditablePane): pass
950
951 vereq(EditableScrollablePane.__mro__,
952 (EditableScrollablePane, ScrollablePane, EditablePane,
953 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000954
Raymond Hettingerf394df42003-04-06 19:13:41 +0000955mro_err_msg = """Cannot create a consistent method resolution
956order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000957
Guido van Rossumd32047f2002-11-25 21:38:52 +0000958def mro_disagreement():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000959 if verbose: print("Testing error messages for MRO disagreement...")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000960 def raises(exc, expected, callable, *args):
961 try:
962 callable(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +0000963 except exc as msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +0000964 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +0000965 raise TestFailed, "Message %r, expected %r" % (str(msg),
966 expected)
967 else:
968 raise TestFailed, "Expected %s" % exc
969 class A(object): pass
970 class B(A): pass
971 class C(object): pass
972 # Test some very simple errors
973 raises(TypeError, "duplicate base class A",
974 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +0000975 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000976 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +0000977 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000978 type, "X", (A, C, B), {})
979 # Test a slightly more complex error
980 class GridLayout(object): pass
981 class HorizontalGrid(GridLayout): pass
982 class VerticalGrid(GridLayout): pass
983 class HVGrid(HorizontalGrid, VerticalGrid): pass
984 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +0000985 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000986 type, "ConfusedGrid", (HVGrid, VHGrid), {})
987
Guido van Rossum37202612001-08-09 19:45:21 +0000988def objects():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000989 if verbose: print("Testing object class...")
Guido van Rossum37202612001-08-09 19:45:21 +0000990 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +0000991 vereq(a.__class__, object)
992 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +0000993 b = object()
994 verify(a is not b)
995 verify(not hasattr(a, "foo"))
996 try:
997 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000998 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000999 pass
1000 else:
1001 verify(0, "object() should not allow setting a foo attribute")
1002 verify(not hasattr(object(), "__dict__"))
1003
1004 class Cdict(object):
1005 pass
1006 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001007 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001008 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001009 vereq(x.foo, 1)
1010 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001011
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012def slots():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001013 if verbose: print("Testing __slots__...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 class C0(object):
1015 __slots__ = []
1016 x = C0()
1017 verify(not hasattr(x, "__dict__"))
1018 verify(not hasattr(x, "foo"))
1019
1020 class C1(object):
1021 __slots__ = ['a']
1022 x = C1()
1023 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001024 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001026 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001027 x.a = None
1028 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001030 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031
1032 class C3(object):
1033 __slots__ = ['a', 'b', 'c']
1034 x = C3()
1035 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001036 verify(not hasattr(x, 'a'))
1037 verify(not hasattr(x, 'b'))
1038 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 x.a = 1
1040 x.b = 2
1041 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001042 vereq(x.a, 1)
1043 vereq(x.b, 2)
1044 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001046 class C4(object):
1047 """Validate name mangling"""
1048 __slots__ = ['__a']
1049 def __init__(self, value):
1050 self.__a = value
1051 def get(self):
1052 return self.__a
1053 x = C4(5)
1054 verify(not hasattr(x, '__dict__'))
1055 verify(not hasattr(x, '__a'))
1056 vereq(x.get(), 5)
1057 try:
1058 x.__a = 6
1059 except AttributeError:
1060 pass
1061 else:
1062 raise TestFailed, "Double underscored names not mangled"
1063
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001064 # Make sure slot names are proper identifiers
1065 try:
1066 class C(object):
1067 __slots__ = [None]
1068 except TypeError:
1069 pass
1070 else:
1071 raise TestFailed, "[None] slots not caught"
1072 try:
1073 class C(object):
1074 __slots__ = ["foo bar"]
1075 except TypeError:
1076 pass
1077 else:
1078 raise TestFailed, "['foo bar'] slots not caught"
1079 try:
1080 class C(object):
1081 __slots__ = ["foo\0bar"]
1082 except TypeError:
1083 pass
1084 else:
1085 raise TestFailed, "['foo\\0bar'] slots not caught"
1086 try:
1087 class C(object):
1088 __slots__ = ["1"]
1089 except TypeError:
1090 pass
1091 else:
1092 raise TestFailed, "['1'] slots not caught"
1093 try:
1094 class C(object):
1095 __slots__ = [""]
1096 except TypeError:
1097 pass
1098 else:
1099 raise TestFailed, "[''] slots not caught"
1100 class C(object):
1101 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102 # XXX(nnorwitz): was there supposed to be something tested
1103 # from the class above?
1104
1105 # Test a single string is not expanded as a sequence.
1106 class C(object):
1107 __slots__ = "abc"
1108 c = C()
1109 c.abc = 5
1110 vereq(c.abc, 5)
1111
1112 # Test unicode slot names
1113 try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001114 str
Guido van Rossumd8faa362007-04-27 19:54:29 +00001115 except NameError:
1116 pass
1117 else:
1118 # Test a single unicode string is not expanded as a sequence.
1119 class C(object):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001120 __slots__ = str("abc")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001121 c = C()
1122 c.abc = 5
1123 vereq(c.abc, 5)
1124
1125 # _unicode_to_string used to modify slots in certain circumstances
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001126 slots = (str("foo"), str("bar"))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001127 class C(object):
1128 __slots__ = slots
1129 x = C()
1130 x.foo = 5
1131 vereq(x.foo, 5)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001132 veris(type(slots[0]), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133 # this used to leak references
1134 try:
1135 class C(object):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001136 __slots__ = [chr(128)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001137 except (TypeError, UnicodeEncodeError):
1138 pass
1139 else:
1140 raise TestFailed, "[unichr(128)] slots not caught"
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001141
Guido van Rossum33bab012001-12-05 22:45:48 +00001142 # Test leaks
1143 class Counted(object):
1144 counter = 0 # counts the number of instances alive
1145 def __init__(self):
1146 Counted.counter += 1
1147 def __del__(self):
1148 Counted.counter -= 1
1149 class C(object):
1150 __slots__ = ['a', 'b', 'c']
1151 x = C()
1152 x.a = Counted()
1153 x.b = Counted()
1154 x.c = Counted()
1155 vereq(Counted.counter, 3)
1156 del x
1157 vereq(Counted.counter, 0)
1158 class D(C):
1159 pass
1160 x = D()
1161 x.a = Counted()
1162 x.z = Counted()
1163 vereq(Counted.counter, 2)
1164 del x
1165 vereq(Counted.counter, 0)
1166 class E(D):
1167 __slots__ = ['e']
1168 x = E()
1169 x.a = Counted()
1170 x.z = Counted()
1171 x.e = Counted()
1172 vereq(Counted.counter, 3)
1173 del x
1174 vereq(Counted.counter, 0)
1175
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001176 # Test cyclical leaks [SF bug 519621]
1177 class F(object):
1178 __slots__ = ['a', 'b']
1179 log = []
1180 s = F()
1181 s.a = [Counted(), s]
1182 vereq(Counted.counter, 1)
1183 s = None
1184 import gc
1185 gc.collect()
1186 vereq(Counted.counter, 0)
1187
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001188 # Test lookup leaks [SF bug 572567]
1189 import sys,gc
1190 class G(object):
1191 def __cmp__(self, other):
1192 return 0
1193 g = G()
1194 orig_objects = len(gc.get_objects())
Guido van Rossum805365e2007-05-07 22:24:25 +00001195 for i in range(10):
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001196 g==g
1197 new_objects = len(gc.get_objects())
1198 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001199 class H(object):
1200 __slots__ = ['a', 'b']
1201 def __init__(self):
1202 self.a = 1
1203 self.b = 2
1204 def __del__(self):
1205 assert self.a == 1
1206 assert self.b == 2
1207
1208 save_stderr = sys.stderr
1209 sys.stderr = sys.stdout
1210 h = H()
1211 try:
1212 del h
1213 finally:
1214 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001215
Guido van Rossum8b056da2002-08-13 18:26:26 +00001216def slotspecials():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001217 if verbose: print("Testing __dict__ and __weakref__ in __slots__...")
Guido van Rossum8b056da2002-08-13 18:26:26 +00001218
1219 class D(object):
1220 __slots__ = ["__dict__"]
1221 a = D()
1222 verify(hasattr(a, "__dict__"))
1223 verify(not hasattr(a, "__weakref__"))
1224 a.foo = 42
1225 vereq(a.__dict__, {"foo": 42})
1226
1227 class W(object):
1228 __slots__ = ["__weakref__"]
1229 a = W()
1230 verify(hasattr(a, "__weakref__"))
1231 verify(not hasattr(a, "__dict__"))
1232 try:
1233 a.foo = 42
1234 except AttributeError:
1235 pass
1236 else:
1237 raise TestFailed, "shouldn't be allowed to set a.foo"
1238
1239 class C1(W, D):
1240 __slots__ = []
1241 a = C1()
1242 verify(hasattr(a, "__dict__"))
1243 verify(hasattr(a, "__weakref__"))
1244 a.foo = 42
1245 vereq(a.__dict__, {"foo": 42})
1246
1247 class C2(D, W):
1248 __slots__ = []
1249 a = C2()
1250 verify(hasattr(a, "__dict__"))
1251 verify(hasattr(a, "__weakref__"))
1252 a.foo = 42
1253 vereq(a.__dict__, {"foo": 42})
1254
Guido van Rossum9a818922002-11-14 19:50:14 +00001255# MRO order disagreement
1256#
1257# class C3(C1, C2):
1258# __slots__ = []
1259#
1260# class C4(C2, C1):
1261# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001262
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263def dynamics():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001264 if verbose: print("Testing class attribute propagation...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001267 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001269 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001272 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001274 vereq(E.foo, 1)
1275 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001276 # Test dynamic instances
1277 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001278 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001279 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001280 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001281 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001282 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001283 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001284 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001285 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001286 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001287 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001288 vereq(int(a), 100)
1289 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001290 verify(not hasattr(a, "spam"))
1291 def mygetattr(self, name):
1292 if name == "spam":
1293 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001294 raise AttributeError
1295 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001296 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001297 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001298 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001299 def mysetattr(self, name, value):
1300 if name == "spam":
1301 raise AttributeError
1302 return object.__setattr__(self, name, value)
1303 C.__setattr__ = mysetattr
1304 try:
1305 a.spam = "not spam"
1306 except AttributeError:
1307 pass
1308 else:
1309 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001310 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001311 class D(C):
1312 pass
1313 d = D()
1314 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001315 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316
Guido van Rossum7e35d572001-09-15 03:14:32 +00001317 # Test handling of int*seq and seq*int
1318 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001319 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001320 vereq("a"*I(2), "aa")
1321 vereq(I(2)*"a", "aa")
1322 vereq(2*I(3), 6)
1323 vereq(I(3)*2, 6)
1324 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001325
1326 # Test handling of long*seq and seq*long
Guido van Rossume2a383d2007-01-15 16:59:06 +00001327 class L(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001328 pass
Guido van Rossume2a383d2007-01-15 16:59:06 +00001329 vereq("a"*L(2), "aa")
1330 vereq(L(2)*"a", "aa")
Guido van Rossum45704552001-10-08 16:35:45 +00001331 vereq(2*L(3), 6)
1332 vereq(L(3)*2, 6)
1333 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001334
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001335 # Test comparison of classes with dynamic metaclasses
1336 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001337 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001338 class someclass(metaclass=dynamicmetaclass):
1339 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001340 verify(someclass != object)
1341
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342def errors():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001343 if verbose: print("Testing errors...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344
1345 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001346 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 pass
1348 except TypeError:
1349 pass
1350 else:
1351 verify(0, "inheritance from both list and dict should be illegal")
1352
1353 try:
1354 class C(object, None):
1355 pass
1356 except TypeError:
1357 pass
1358 else:
1359 verify(0, "inheritance from non-type should be illegal")
1360 class Classic:
1361 pass
1362
1363 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001364 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 pass
1366 except TypeError:
1367 pass
1368 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001369 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370
1371 try:
1372 class C(object):
1373 __slots__ = 1
1374 except TypeError:
1375 pass
1376 else:
1377 verify(0, "__slots__ = 1 should be illegal")
1378
1379 try:
1380 class C(object):
1381 __slots__ = [1]
1382 except TypeError:
1383 pass
1384 else:
1385 verify(0, "__slots__ = [1] should be illegal")
1386
Guido van Rossumd8faa362007-04-27 19:54:29 +00001387 class M1(type):
1388 pass
1389 class M2(type):
1390 pass
1391 class A1(object, metaclass=M1):
1392 pass
1393 class A2(object, metaclass=M2):
1394 pass
1395 try:
1396 class B(A1, A2):
1397 pass
1398 except TypeError:
1399 pass
1400 else:
1401 verify(0, "finding the most derived metaclass should have failed")
1402
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403def classmethods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001404 if verbose: print("Testing class methods...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 class C(object):
1406 def foo(*a): return a
1407 goo = classmethod(foo)
1408 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001409 vereq(C.goo(1), (C, 1))
1410 vereq(c.goo(1), (C, 1))
1411 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 class D(C):
1413 pass
1414 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001415 vereq(D.goo(1), (D, 1))
1416 vereq(d.goo(1), (D, 1))
1417 vereq(d.foo(1), (d, 1))
1418 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001419 # Test for a specific crash (SF bug 528132)
1420 def f(cls, arg): return (cls, arg)
1421 ff = classmethod(f)
1422 vereq(ff.__get__(0, int)(42), (int, 42))
1423 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424
Guido van Rossum155db9a2002-04-02 17:53:47 +00001425 # Test super() with classmethods (SF bug 535444)
1426 veris(C.goo.im_self, C)
1427 veris(D.goo.im_self, D)
1428 veris(super(D,D).goo.im_self, D)
1429 veris(super(D,d).goo.im_self, D)
1430 vereq(super(D,D).goo(), (D,))
1431 vereq(super(D,d).goo(), (D,))
1432
Raymond Hettingerbe971532003-06-18 01:13:41 +00001433 # Verify that argument is checked for callability (SF bug 753451)
1434 try:
1435 classmethod(1).__get__(1)
1436 except TypeError:
1437 pass
1438 else:
1439 raise TestFailed, "classmethod should check for callability"
1440
Georg Brandl6a29c322006-02-21 22:17:46 +00001441 # Verify that classmethod() doesn't allow keyword args
1442 try:
1443 classmethod(f, kw=1)
1444 except TypeError:
1445 pass
1446 else:
1447 raise TestFailed, "classmethod shouldn't accept keyword args"
1448
Fred Drakef841aa62002-03-28 15:49:54 +00001449def classmethods_in_c():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001450 if verbose: print("Testing C-based class methods...")
Fred Drakef841aa62002-03-28 15:49:54 +00001451 import xxsubtype as spam
1452 a = (1, 2, 3)
1453 d = {'abc': 123}
1454 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001455 veris(x, spam.spamlist)
1456 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001457 vereq(d, d1)
1458 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001459 veris(x, spam.spamlist)
1460 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001461 vereq(d, d1)
1462
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463def staticmethods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001464 if verbose: print("Testing static methods...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465 class C(object):
1466 def foo(*a): return a
1467 goo = staticmethod(foo)
1468 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001469 vereq(C.goo(1), (1,))
1470 vereq(c.goo(1), (1,))
1471 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 class D(C):
1473 pass
1474 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001475 vereq(D.goo(1), (1,))
1476 vereq(d.goo(1), (1,))
1477 vereq(d.foo(1), (d, 1))
1478 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479
Fred Drakef841aa62002-03-28 15:49:54 +00001480def staticmethods_in_c():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001481 if verbose: print("Testing C-based static methods...")
Fred Drakef841aa62002-03-28 15:49:54 +00001482 import xxsubtype as spam
1483 a = (1, 2, 3)
1484 d = {"abc": 123}
1485 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1486 veris(x, None)
1487 vereq(a, a1)
1488 vereq(d, d1)
1489 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1490 veris(x, None)
1491 vereq(a, a1)
1492 vereq(d, d1)
1493
Tim Peters6d6c1a32001-08-02 04:15:00 +00001494def classic():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001495 if verbose: print("Testing classic classes...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 class C:
1497 def foo(*a): return a
1498 goo = classmethod(foo)
1499 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001500 vereq(C.goo(1), (C, 1))
1501 vereq(c.goo(1), (C, 1))
1502 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503 class D(C):
1504 pass
1505 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001506 vereq(D.goo(1), (D, 1))
1507 vereq(d.goo(1), (D, 1))
1508 vereq(d.foo(1), (d, 1))
1509 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001510 class E: # *not* subclassing from C
1511 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001512 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001513 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514
1515def compattr():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001516 if verbose: print("Testing computed attributes...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517 class C(object):
1518 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001519 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 self.__get = get
1521 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001522 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 def __get__(self, obj, type=None):
1524 return self.__get(obj)
1525 def __set__(self, obj, value):
1526 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001527 def __delete__(self, obj):
1528 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 def __init__(self):
1530 self.__x = 0
1531 def __get_x(self):
1532 x = self.__x
1533 self.__x = x+1
1534 return x
1535 def __set_x(self, x):
1536 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001537 def __delete_x(self):
1538 del self.__x
1539 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001541 vereq(a.x, 0)
1542 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001544 vereq(a.x, 10)
1545 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001546 del a.x
1547 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001548
1549def newslot():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001550 if verbose: print("Testing __new__ slot override...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 class C(list):
1552 def __new__(cls):
1553 self = list.__new__(cls)
1554 self.foo = 1
1555 return self
1556 def __init__(self):
1557 self.foo = self.foo + 2
1558 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001559 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 verify(a.__class__ is C)
1561 class D(C):
1562 pass
1563 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001564 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 verify(b.__class__ is D)
1566
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567def altmro():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001568 if verbose: print("Testing mro() and overriding it...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 class A(object):
1570 def f(self): return "A"
1571 class B(A):
1572 pass
1573 class C(A):
1574 def f(self): return "C"
1575 class D(B, C):
1576 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001577 vereq(D.mro(), [D, B, C, A, object])
1578 vereq(D.__mro__, (D, B, C, A, object))
1579 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001580
Guido van Rossumd3077402001-08-12 05:24:18 +00001581 class PerverseMetaType(type):
1582 def mro(cls):
1583 L = type.mro(cls)
1584 L.reverse()
1585 return L
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001586 class X(D,B,C,A, metaclass=PerverseMetaType):
1587 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001588 vereq(X.__mro__, (object, A, C, B, D, X))
1589 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590
Armin Rigo037d1e02005-12-29 17:07:39 +00001591 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001592 class _metaclass(type):
1593 def mro(self):
1594 return [self, dict, object]
1595 class X(object, metaclass=_metaclass):
1596 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001597 except TypeError:
1598 pass
1599 else:
1600 raise TestFailed, "devious mro() return not caught"
1601
1602 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001603 class _metaclass(type):
1604 def mro(self):
1605 return [1]
1606 class X(object, metaclass=_metaclass):
1607 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001608 except TypeError:
1609 pass
1610 else:
1611 raise TestFailed, "non-class mro() return not caught"
1612
1613 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001614 class _metaclass(type):
1615 def mro(self):
1616 return 1
1617 class X(object, metaclass=_metaclass):
1618 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001619 except TypeError:
1620 pass
1621 else:
1622 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001623
Armin Rigo037d1e02005-12-29 17:07:39 +00001624
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625def overloading():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001626 if verbose: print("Testing operator overloading...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627
1628 class B(object):
1629 "Intermediate class because object doesn't have a __setattr__"
1630
1631 class C(B):
1632
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001633 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634 if name == "foo":
1635 return ("getattr", name)
1636 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001637 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638 def __setattr__(self, name, value):
1639 if name == "foo":
1640 self.setattr = (name, value)
1641 else:
1642 return B.__setattr__(self, name, value)
1643 def __delattr__(self, name):
1644 if name == "foo":
1645 self.delattr = name
1646 else:
1647 return B.__delattr__(self, name)
1648
1649 def __getitem__(self, key):
1650 return ("getitem", key)
1651 def __setitem__(self, key, value):
1652 self.setitem = (key, value)
1653 def __delitem__(self, key):
1654 self.delitem = key
1655
1656 def __getslice__(self, i, j):
1657 return ("getslice", i, j)
1658 def __setslice__(self, i, j, value):
1659 self.setslice = (i, j, value)
1660 def __delslice__(self, i, j):
1661 self.delslice = (i, j)
1662
1663 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001664 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001666 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001668 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669
Guido van Rossum45704552001-10-08 16:35:45 +00001670 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001672 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001674 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675
Guido van Rossum45704552001-10-08 16:35:45 +00001676 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001678 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001680 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001682def methods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001683 if verbose: print("Testing methods...")
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001684 class C(object):
1685 def __init__(self, x):
1686 self.x = x
1687 def foo(self):
1688 return self.x
1689 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001690 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001691 class D(C):
1692 boo = C.foo
1693 goo = c1.foo
1694 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001695 vereq(d2.foo(), 2)
1696 vereq(d2.boo(), 2)
1697 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001698 class E(object):
1699 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001700 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001701 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001702
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001703def specials():
1704 # Test operators like __hash__ for which a built-in default exists
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001705 if verbose: print("Testing special operators...")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001706 # Test the default behavior for static classes
1707 class C(object):
1708 def __getitem__(self, i):
1709 if 0 <= i < 10: return i
1710 raise IndexError
1711 c1 = C()
1712 c2 = C()
1713 verify(not not c1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001714 verify(id(c1) != id(c2))
1715 hash(c1)
1716 hash(c2)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001717 ##vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
Guido van Rossum45704552001-10-08 16:35:45 +00001718 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001719 verify(c1 != c2)
1720 verify(not c1 != c1)
1721 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001722 # Note that the module name appears in str/repr, and that varies
1723 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001724 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001725 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001726 verify(-1 not in c1)
1727 for i in range(10):
1728 verify(i in c1)
1729 verify(10 not in c1)
1730 # Test the default behavior for dynamic classes
1731 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001732 def __getitem__(self, i):
1733 if 0 <= i < 10: return i
1734 raise IndexError
1735 d1 = D()
1736 d2 = D()
1737 verify(not not d1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001738 verify(id(d1) != id(d2))
1739 hash(d1)
1740 hash(d2)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001741 ##vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
Guido van Rossum45704552001-10-08 16:35:45 +00001742 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001743 verify(d1 != d2)
1744 verify(not d1 != d1)
1745 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001746 # Note that the module name appears in str/repr, and that varies
1747 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001748 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001749 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001750 verify(-1 not in d1)
1751 for i in range(10):
1752 verify(i in d1)
1753 verify(10 not in d1)
1754 # Test overridden behavior for static classes
1755 class Proxy(object):
1756 def __init__(self, x):
1757 self.x = x
Jack Diederich4dafcc42006-11-28 19:15:13 +00001758 def __bool__(self):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001759 return not not self.x
1760 def __hash__(self):
1761 return hash(self.x)
1762 def __eq__(self, other):
1763 return self.x == other
1764 def __ne__(self, other):
1765 return self.x != other
1766 def __cmp__(self, other):
1767 return cmp(self.x, other.x)
1768 def __str__(self):
1769 return "Proxy:%s" % self.x
1770 def __repr__(self):
1771 return "Proxy(%r)" % self.x
1772 def __contains__(self, value):
1773 return value in self.x
1774 p0 = Proxy(0)
1775 p1 = Proxy(1)
1776 p_1 = Proxy(-1)
1777 verify(not p0)
1778 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001779 vereq(hash(p0), hash(0))
1780 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001781 verify(p0 != p1)
1782 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001783 vereq(not p0, p1)
1784 vereq(cmp(p0, p1), -1)
1785 vereq(cmp(p0, p0), 0)
1786 vereq(cmp(p0, p_1), 1)
1787 vereq(str(p0), "Proxy:0")
1788 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001789 p10 = Proxy(range(10))
1790 verify(-1 not in p10)
1791 for i in range(10):
1792 verify(i in p10)
1793 verify(10 not in p10)
1794 # Test overridden behavior for dynamic classes
1795 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001796 def __init__(self, x):
1797 self.x = x
Jack Diederich4dafcc42006-11-28 19:15:13 +00001798 def __bool__(self):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001799 return not not self.x
1800 def __hash__(self):
1801 return hash(self.x)
1802 def __eq__(self, other):
1803 return self.x == other
1804 def __ne__(self, other):
1805 return self.x != other
1806 def __cmp__(self, other):
1807 return cmp(self.x, other.x)
1808 def __str__(self):
1809 return "DProxy:%s" % self.x
1810 def __repr__(self):
1811 return "DProxy(%r)" % self.x
1812 def __contains__(self, value):
1813 return value in self.x
1814 p0 = DProxy(0)
1815 p1 = DProxy(1)
1816 p_1 = DProxy(-1)
1817 verify(not p0)
1818 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001819 vereq(hash(p0), hash(0))
1820 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001821 verify(p0 != p1)
1822 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001823 vereq(not p0, p1)
1824 vereq(cmp(p0, p1), -1)
1825 vereq(cmp(p0, p0), 0)
1826 vereq(cmp(p0, p_1), 1)
1827 vereq(str(p0), "DProxy:0")
1828 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001829 p10 = DProxy(range(10))
1830 verify(-1 not in p10)
1831 for i in range(10):
1832 verify(i in p10)
1833 verify(10 not in p10)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001834## # Safety test for __cmp__
1835## def unsafecmp(a, b):
1836## try:
1837## a.__class__.__cmp__(a, b)
1838## except TypeError:
1839## pass
1840## else:
1841## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1842## a.__class__, a, b)
1843## unsafecmp(u"123", "123")
1844## unsafecmp("123", u"123")
1845## unsafecmp(1, 1.0)
1846## unsafecmp(1.0, 1)
1847## unsafecmp(1, 1L)
1848## unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001849
Neal Norwitz1a997502003-01-13 20:13:12 +00001850 class Letter(str):
1851 def __new__(cls, letter):
1852 if letter == 'EPS':
1853 return str.__new__(cls)
1854 return str.__new__(cls, letter)
1855 def __str__(self):
1856 if not self:
1857 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001858 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001859
1860 # sys.stdout needs to be the original to trigger the recursion bug
1861 import sys
1862 test_stdout = sys.stdout
1863 sys.stdout = get_original_stdout()
1864 try:
1865 # nothing should actually be printed, this should raise an exception
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001866 print(Letter('w'))
Neal Norwitz1a997502003-01-13 20:13:12 +00001867 except RuntimeError:
1868 pass
1869 else:
1870 raise TestFailed, "expected a RuntimeError for print recursion"
1871 sys.stdout = test_stdout
1872
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001873def weakrefs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001874 if verbose: print("Testing weak references...")
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001875 import weakref
1876 class C(object):
1877 pass
1878 c = C()
1879 r = weakref.ref(c)
1880 verify(r() is c)
1881 del c
1882 verify(r() is None)
1883 del r
1884 class NoWeak(object):
1885 __slots__ = ['foo']
1886 no = NoWeak()
1887 try:
1888 weakref.ref(no)
Guido van Rossumb940e112007-01-10 16:19:56 +00001889 except TypeError as msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001890 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001891 else:
1892 verify(0, "weakref.ref(no) should be illegal")
1893 class Weak(object):
1894 __slots__ = ['foo', '__weakref__']
1895 yes = Weak()
1896 r = weakref.ref(yes)
1897 verify(r() is yes)
1898 del yes
1899 verify(r() is None)
1900 del r
1901
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001902def properties():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001903 if verbose: print("Testing property...")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001904 class C(object):
1905 def getx(self):
1906 return self.__x
1907 def setx(self, value):
1908 self.__x = value
1909 def delx(self):
1910 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001911 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001912 a = C()
1913 verify(not hasattr(a, "x"))
1914 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001915 vereq(a._C__x, 42)
1916 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001917 del a.x
1918 verify(not hasattr(a, "x"))
1919 verify(not hasattr(a, "_C__x"))
1920 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001921 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001922 C.x.__delete__(a)
1923 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001924
Tim Peters66c1a522001-09-24 21:17:50 +00001925 raw = C.__dict__['x']
1926 verify(isinstance(raw, property))
1927
1928 attrs = dir(raw)
1929 verify("__doc__" in attrs)
1930 verify("fget" in attrs)
1931 verify("fset" in attrs)
1932 verify("fdel" in attrs)
1933
Guido van Rossum45704552001-10-08 16:35:45 +00001934 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001935 verify(raw.fget is C.__dict__['getx'])
1936 verify(raw.fset is C.__dict__['setx'])
1937 verify(raw.fdel is C.__dict__['delx'])
1938
1939 for attr in "__doc__", "fget", "fset", "fdel":
1940 try:
1941 setattr(raw, attr, 42)
Collin Winter42dae6a2007-03-28 21:44:53 +00001942 except AttributeError as msg:
Tim Peters66c1a522001-09-24 21:17:50 +00001943 if str(msg).find('readonly') < 0:
1944 raise TestFailed("when setting readonly attr %r on a "
Collin Winter42dae6a2007-03-28 21:44:53 +00001945 "property, got unexpected AttributeError "
Tim Peters66c1a522001-09-24 21:17:50 +00001946 "msg %r" % (attr, str(msg)))
1947 else:
Collin Winter42dae6a2007-03-28 21:44:53 +00001948 raise TestFailed("expected AttributeError from trying to set "
Tim Peters66c1a522001-09-24 21:17:50 +00001949 "readonly %r attr on a property" % attr)
1950
Neal Norwitz673cd822002-10-18 16:33:13 +00001951 class D(object):
1952 __getitem__ = property(lambda s: 1/0)
1953
1954 d = D()
1955 try:
1956 for i in d:
1957 str(i)
1958 except ZeroDivisionError:
1959 pass
1960 else:
1961 raise TestFailed, "expected ZeroDivisionError from bad property"
1962
Georg Brandl533ff6f2006-03-08 18:09:27 +00001963 class E(object):
1964 def getter(self):
1965 "getter method"
1966 return 0
1967 def setter(self, value):
1968 "setter method"
1969 pass
1970 prop = property(getter)
1971 vereq(prop.__doc__, "getter method")
1972 prop2 = property(fset=setter)
1973 vereq(prop2.__doc__, None)
1974
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001975 # this segfaulted in 2.5b2
1976 try:
1977 import _testcapi
1978 except ImportError:
1979 pass
1980 else:
1981 class X(object):
1982 p = property(_testcapi.test_with_docstring)
1983
1984
Guido van Rossumc4a18802001-08-24 16:55:27 +00001985def supers():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001986 if verbose: print("Testing super...")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001987
1988 class A(object):
1989 def meth(self, a):
1990 return "A(%r)" % a
1991
Guido van Rossum45704552001-10-08 16:35:45 +00001992 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001993
1994 class B(A):
1995 def __init__(self):
1996 self.__super = super(B, self)
1997 def meth(self, a):
1998 return "B(%r)" % a + self.__super.meth(a)
1999
Guido van Rossum45704552001-10-08 16:35:45 +00002000 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002001
2002 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002003 def meth(self, a):
2004 return "C(%r)" % a + self.__super.meth(a)
2005 C._C__super = super(C)
2006
Guido van Rossum45704552001-10-08 16:35:45 +00002007 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002008
2009 class D(C, B):
2010 def meth(self, a):
2011 return "D(%r)" % a + super(D, self).meth(a)
2012
Guido van Rossum5b443c62001-12-03 15:38:28 +00002013 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2014
2015 # Test for subclassing super
2016
2017 class mysuper(super):
2018 def __init__(self, *args):
2019 return super(mysuper, self).__init__(*args)
2020
2021 class E(D):
2022 def meth(self, a):
2023 return "E(%r)" % a + mysuper(E, self).meth(a)
2024
2025 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2026
2027 class F(E):
2028 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002029 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002030 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2031 F._F__super = mysuper(F)
2032
2033 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2034
2035 # Make sure certain errors are raised
2036
2037 try:
2038 super(D, 42)
2039 except TypeError:
2040 pass
2041 else:
2042 raise TestFailed, "shouldn't allow super(D, 42)"
2043
2044 try:
2045 super(D, C())
2046 except TypeError:
2047 pass
2048 else:
2049 raise TestFailed, "shouldn't allow super(D, C())"
2050
2051 try:
2052 super(D).__get__(12)
2053 except TypeError:
2054 pass
2055 else:
2056 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2057
2058 try:
2059 super(D).__get__(C())
2060 except TypeError:
2061 pass
2062 else:
2063 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002064
Guido van Rossuma4541a32003-04-16 20:02:22 +00002065 # Make sure data descriptors can be overridden and accessed via super
2066 # (new feature in Python 2.3)
2067
2068 class DDbase(object):
2069 def getx(self): return 42
2070 x = property(getx)
2071
2072 class DDsub(DDbase):
2073 def getx(self): return "hello"
2074 x = property(getx)
2075
2076 dd = DDsub()
2077 vereq(dd.x, "hello")
2078 vereq(super(DDsub, dd).x, 42)
2079
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002080 # Ensure that super() lookup of descriptor from classmethod
2081 # works (SF ID# 743627)
2082
2083 class Base(object):
2084 aProp = property(lambda self: "foo")
2085
2086 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002087 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002088 def test(klass):
2089 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002090
2091 veris(Sub.test(), Base.aProp)
2092
Thomas Wouters89f507f2006-12-13 04:49:30 +00002093 # Verify that super() doesn't allow keyword args
2094 try:
2095 super(Base, kw=1)
2096 except TypeError:
2097 pass
2098 else:
2099 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002100
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002101def inherits():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002102 if verbose: print("Testing inheritance from basic types...")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002103
2104 class hexint(int):
2105 def __repr__(self):
2106 return hex(self)
2107 def __add__(self, other):
2108 return hexint(int.__add__(self, other))
2109 # (Note that overriding __radd__ doesn't work,
2110 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002111 vereq(repr(hexint(7) + 9), "0x10")
2112 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002113 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002114 vereq(a, 12345)
2115 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002116 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002117 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002118 verify((+a).__class__ is int)
2119 verify((a >> 0).__class__ is int)
2120 verify((a << 0).__class__ is int)
2121 verify((hexint(0) << 12).__class__ is int)
2122 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002123
Guido van Rossume2a383d2007-01-15 16:59:06 +00002124 class octlong(int):
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002125 __slots__ = []
2126 def __str__(self):
2127 s = oct(self)
2128 if s[-1] == 'L':
2129 s = s[:-1]
2130 return s
2131 def __add__(self, other):
2132 return self.__class__(super(octlong, self).__add__(other))
2133 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002134 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002135 # (Note that overriding __radd__ here only seems to work
2136 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002137 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002138 a = octlong(12345)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002139 vereq(a, 12345)
2140 vereq(int(a), 12345)
2141 vereq(hash(a), hash(12345))
2142 verify(int(a).__class__ is int)
2143 verify((+a).__class__ is int)
2144 verify((-a).__class__ is int)
2145 verify((-octlong(0)).__class__ is int)
2146 verify((a >> 0).__class__ is int)
2147 verify((a << 0).__class__ is int)
2148 verify((a - 0).__class__ is int)
2149 verify((a * 1).__class__ is int)
2150 verify((a ** 1).__class__ is int)
2151 verify((a // 1).__class__ is int)
2152 verify((1 * a).__class__ is int)
2153 verify((a | 0).__class__ is int)
2154 verify((a ^ 0).__class__ is int)
2155 verify((a & -1).__class__ is int)
2156 verify((octlong(0) << 12).__class__ is int)
2157 verify((octlong(0) >> 12).__class__ is int)
2158 verify(abs(octlong(0)).__class__ is int)
Tim Peters69c2de32001-09-11 22:31:33 +00002159
2160 # Because octlong overrides __add__, we can't check the absence of +0
2161 # optimizations using octlong.
Guido van Rossume2a383d2007-01-15 16:59:06 +00002162 class longclone(int):
Tim Peters69c2de32001-09-11 22:31:33 +00002163 pass
2164 a = longclone(1)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002165 verify((a + 0).__class__ is int)
2166 verify((0 + a).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002167
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002168 # Check that negative clones don't segfault
2169 a = longclone(-1)
2170 vereq(a.__dict__, {})
Guido van Rossume2a383d2007-01-15 16:59:06 +00002171 vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002172
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002173 class precfloat(float):
2174 __slots__ = ['prec']
2175 def __init__(self, value=0.0, prec=12):
2176 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002177 def __repr__(self):
2178 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002179 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002180 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002181 vereq(a, 12345.0)
2182 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002183 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002184 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002185 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002186
Tim Peters2400fa42001-09-12 19:12:49 +00002187 class madcomplex(complex):
2188 def __repr__(self):
2189 return "%.17gj%+.17g" % (self.imag, self.real)
2190 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002191 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002192 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002193 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002194 vereq(a, base)
2195 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002196 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002197 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002198 vereq(repr(a), "4j-3")
2199 vereq(a, base)
2200 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002201 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002202 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002203 veris((+a).__class__, complex)
2204 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002205 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002206 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002207 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002208 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002209 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002210 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002211 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002212
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002213 class madtuple(tuple):
2214 _rev = None
2215 def rev(self):
2216 if self._rev is not None:
2217 return self._rev
2218 L = list(self)
2219 L.reverse()
2220 self._rev = self.__class__(L)
2221 return self._rev
2222 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002223 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2224 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2225 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002226 for i in range(512):
2227 t = madtuple(range(i))
2228 u = t.rev()
2229 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002230 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002231 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002232 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002233 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002234 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002235 verify(a[:].__class__ is tuple)
2236 verify((a * 1).__class__ is tuple)
2237 verify((a * 0).__class__ is tuple)
2238 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002239 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002240 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002241 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002242 verify((a + a).__class__ is tuple)
2243 verify((a * 0).__class__ is tuple)
2244 verify((a * 1).__class__ is tuple)
2245 verify((a * 2).__class__ is tuple)
2246 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002247
2248 class madstring(str):
2249 _rev = None
2250 def rev(self):
2251 if self._rev is not None:
2252 return self._rev
2253 L = list(self)
2254 L.reverse()
2255 self._rev = self.__class__("".join(L))
2256 return self._rev
2257 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002258 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2259 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2260 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002261 for i in range(256):
2262 s = madstring("".join(map(chr, range(i))))
2263 t = s.rev()
2264 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002265 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002266 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002267 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002268 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002269
Tim Peters8fa5dd02001-09-12 02:18:30 +00002270 base = "\x00" * 5
2271 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002272 vereq(s, base)
2273 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002274 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002275 vereq(hash(s), hash(base))
2276 vereq({s: 1}[base], 1)
2277 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002278 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002279 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002280 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002281 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002282 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002283 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002284 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002285 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002286 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002287 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002288 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002289 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002290 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002291 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002292 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002293 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002294 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002295 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002296 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002297 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002298 identitytab = ''.join([chr(i) for i in range(256)])
2299 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002300 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002301 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002302 vereq(s.translate(identitytab, "x"), base)
2303 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002304 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002305 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002306 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002308 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002309 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002310 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002312 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002313 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002314
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002315 class madunicode(str):
Guido van Rossum91ee7982001-08-30 20:52:40 +00002316 _rev = None
2317 def rev(self):
2318 if self._rev is not None:
2319 return self._rev
2320 L = list(self)
2321 L.reverse()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002322 self._rev = self.__class__("".join(L))
Guido van Rossum91ee7982001-08-30 20:52:40 +00002323 return self._rev
2324 u = madunicode("ABCDEF")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002325 vereq(u, "ABCDEF")
2326 vereq(u.rev(), madunicode("FEDCBA"))
2327 vereq(u.rev().rev(), madunicode("ABCDEF"))
2328 base = "12345"
Tim Peters7a29bd52001-09-12 03:03:31 +00002329 u = madunicode(base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002330 vereq(str(u), base)
2331 verify(str(u).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002332 vereq(hash(u), hash(base))
2333 vereq({u: 1}[base], 1)
2334 vereq({base: 1}[u], 1)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002335 verify(u.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002336 vereq(u.strip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002337 verify(u.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002338 vereq(u.lstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002339 verify(u.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002340 vereq(u.rstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002341 verify(u.replace("x", "x").__class__ is str)
2342 vereq(u.replace("x", "x"), base)
2343 verify(u.replace("xy", "xy").__class__ is str)
2344 vereq(u.replace("xy", "xy"), base)
2345 verify(u.center(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002346 vereq(u.center(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002347 verify(u.ljust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002348 vereq(u.ljust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002349 verify(u.rjust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002350 vereq(u.rjust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002351 verify(u.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002352 vereq(u.lower(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002353 verify(u.upper().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002354 vereq(u.upper(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002355 verify(u.capitalize().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002356 vereq(u.capitalize(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002357 verify(u.title().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002358 vereq(u.title(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002359 verify((u + "").__class__ is str)
2360 vereq(u + "", base)
2361 verify(("" + u).__class__ is str)
2362 vereq("" + u, base)
2363 verify((u * 0).__class__ is str)
2364 vereq(u * 0, "")
2365 verify((u * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002366 vereq(u * 1, base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002367 verify((u * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002368 vereq(u * 2, base + base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002369 verify(u[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002370 vereq(u[:], base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002371 verify(u[0:0].__class__ is str)
2372 vereq(u[0:0], "")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002373
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002374 class sublist(list):
2375 pass
2376 a = sublist(range(5))
Guido van Rossum805365e2007-05-07 22:24:25 +00002377 vereq(a, list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002378 a.append("hello")
Guido van Rossum805365e2007-05-07 22:24:25 +00002379 vereq(a, list(range(5)) + ["hello"])
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002380 a[5] = 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002381 vereq(a, list(range(6)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002382 a.extend(range(6, 20))
Guido van Rossum805365e2007-05-07 22:24:25 +00002383 vereq(a, list(range(20)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002384 a[-5:] = []
Guido van Rossum805365e2007-05-07 22:24:25 +00002385 vereq(a, list(range(15)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002386 del a[10:15]
2387 vereq(len(a), 10)
Guido van Rossum805365e2007-05-07 22:24:25 +00002388 vereq(a, list(range(10)))
2389 vereq(list(a), list(range(10)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002390 vereq(a[0], 0)
2391 vereq(a[9], 9)
2392 vereq(a[-10], 0)
2393 vereq(a[-1], 9)
Guido van Rossum805365e2007-05-07 22:24:25 +00002394 vereq(a[:5], list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002395
Tim Peters59c9a642001-09-13 05:38:56 +00002396 class CountedInput(file):
2397 """Counts lines read by self.readline().
2398
2399 self.lineno is the 0-based ordinal of the last line read, up to
2400 a maximum of one greater than the number of lines in the file.
2401
2402 self.ateof is true if and only if the final "" line has been read,
2403 at which point self.lineno stops incrementing, and further calls
2404 to readline() continue to return "".
2405 """
2406
2407 lineno = 0
2408 ateof = 0
2409 def readline(self):
2410 if self.ateof:
2411 return ""
2412 s = file.readline(self)
2413 # Next line works too.
2414 # s = super(CountedInput, self).readline()
2415 self.lineno += 1
2416 if s == "":
2417 self.ateof = 1
2418 return s
2419
Alex Martelli01c77c62006-08-24 02:58:11 +00002420 f = open(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002421 lines = ['a\n', 'b\n', 'c\n']
2422 try:
2423 f.writelines(lines)
2424 f.close()
2425 f = CountedInput(TESTFN)
Guido van Rossum805365e2007-05-07 22:24:25 +00002426 for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]):
Tim Peters59c9a642001-09-13 05:38:56 +00002427 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002428 vereq(expected, got)
2429 vereq(f.lineno, i)
2430 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002431 f.close()
2432 finally:
2433 try:
2434 f.close()
2435 except:
2436 pass
2437 try:
2438 import os
2439 os.unlink(TESTFN)
2440 except:
2441 pass
2442
Tim Peters808b94e2001-09-13 19:33:07 +00002443def keywords():
2444 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002445 print("Testing keyword args to basic type constructors ...")
Guido van Rossum45704552001-10-08 16:35:45 +00002446 vereq(int(x=1), 1)
2447 vereq(float(x=2), 2.0)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002448 vereq(int(x=3), 3)
Guido van Rossum45704552001-10-08 16:35:45 +00002449 vereq(complex(imag=42, real=666), complex(666, 42))
2450 vereq(str(object=500), '500')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002451 vereq(str(string='abc', errors='strict'), 'abc')
Guido van Rossum45704552001-10-08 16:35:45 +00002452 vereq(tuple(sequence=range(3)), (0, 1, 2))
Guido van Rossum805365e2007-05-07 22:24:25 +00002453 vereq(list(sequence=(0, 1, 2)), list(range(3)))
Just van Rossuma797d812002-11-23 09:45:04 +00002454 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002455
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002456 for constructor in (int, float, int, complex, str, str,
Just van Rossuma797d812002-11-23 09:45:04 +00002457 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002458 try:
2459 constructor(bogus_keyword_arg=1)
2460 except TypeError:
2461 pass
2462 else:
2463 raise TestFailed("expected TypeError from bogus keyword "
2464 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002465
Tim Peters0ab085c2001-09-14 00:25:33 +00002466def str_subclass_as_dict_key():
2467 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002468 print("Testing a str subclass used as dict key ..")
Tim Peters0ab085c2001-09-14 00:25:33 +00002469
2470 class cistr(str):
2471 """Sublcass of str that computes __eq__ case-insensitively.
2472
2473 Also computes a hash code of the string in canonical form.
2474 """
2475
2476 def __init__(self, value):
2477 self.canonical = value.lower()
2478 self.hashcode = hash(self.canonical)
2479
2480 def __eq__(self, other):
2481 if not isinstance(other, cistr):
2482 other = cistr(other)
2483 return self.canonical == other.canonical
2484
2485 def __hash__(self):
2486 return self.hashcode
2487
Guido van Rossum45704552001-10-08 16:35:45 +00002488 vereq(cistr('ABC'), 'abc')
2489 vereq('aBc', cistr('ABC'))
2490 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002491
2492 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002493 vereq(d[cistr('one')], 1)
2494 vereq(d[cistr('tWo')], 2)
2495 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002496 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002497 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002498
Guido van Rossumab3b0342001-09-18 20:38:53 +00002499def classic_comparisons():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002500 if verbose: print("Testing classic comparisons...")
Guido van Rossum0639f592001-09-18 21:06:04 +00002501 class classic:
2502 pass
2503 for base in (classic, int, object):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002504 if verbose: print(" (base = %s)" % base)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002505 class C(base):
2506 def __init__(self, value):
2507 self.value = int(value)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002508 def __eq__(self, other):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002509 if isinstance(other, C):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002510 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002511 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002512 return self.value == other
Guido van Rossumab3b0342001-09-18 20:38:53 +00002513 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002514 def __ne__(self, other):
2515 if isinstance(other, C):
2516 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002517 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002518 return self.value != other
2519 return NotImplemented
2520 def __lt__(self, other):
2521 if isinstance(other, C):
2522 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002523 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002524 return self.value < other
2525 return NotImplemented
2526 def __le__(self, other):
2527 if isinstance(other, C):
2528 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002529 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002530 return self.value <= other
2531 return NotImplemented
2532 def __gt__(self, other):
2533 if isinstance(other, C):
2534 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002535 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002536 return self.value > other
2537 return NotImplemented
2538 def __ge__(self, other):
2539 if isinstance(other, C):
2540 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002541 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002542 return self.value >= other
2543 return NotImplemented
2544
Guido van Rossumab3b0342001-09-18 20:38:53 +00002545 c1 = C(1)
2546 c2 = C(2)
2547 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002548 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002549 c = {1: c1, 2: c2, 3: c3}
2550 for x in 1, 2, 3:
2551 for y in 1, 2, 3:
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002552 ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002553 for op in "<", "<=", "==", "!=", ">", ">=":
2554 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2555 "x=%d, y=%d" % (x, y))
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002556 ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2557 ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002558
Guido van Rossum0639f592001-09-18 21:06:04 +00002559def rich_comparisons():
2560 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002561 print("Testing rich comparisons...")
Guido van Rossum22056422001-09-24 17:52:04 +00002562 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002563 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002564 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002565 vereq(z, 1+0j)
2566 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002567 class ZZ(complex):
2568 def __eq__(self, other):
2569 try:
2570 return abs(self - other) <= 1e-6
2571 except:
2572 return NotImplemented
2573 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002574 vereq(zz, 1+0j)
2575 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002576
Guido van Rossum0639f592001-09-18 21:06:04 +00002577 class classic:
2578 pass
2579 for base in (classic, int, object, list):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002580 if verbose: print(" (base = %s)" % base)
Guido van Rossum0639f592001-09-18 21:06:04 +00002581 class C(base):
2582 def __init__(self, value):
2583 self.value = int(value)
2584 def __cmp__(self, other):
2585 raise TestFailed, "shouldn't call __cmp__"
2586 def __eq__(self, other):
2587 if isinstance(other, C):
2588 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002589 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002590 return self.value == other
2591 return NotImplemented
2592 def __ne__(self, other):
2593 if isinstance(other, C):
2594 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002595 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002596 return self.value != other
2597 return NotImplemented
2598 def __lt__(self, other):
2599 if isinstance(other, C):
2600 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002601 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002602 return self.value < other
2603 return NotImplemented
2604 def __le__(self, other):
2605 if isinstance(other, C):
2606 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002607 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002608 return self.value <= other
2609 return NotImplemented
2610 def __gt__(self, other):
2611 if isinstance(other, C):
2612 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002613 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002614 return self.value > other
2615 return NotImplemented
2616 def __ge__(self, other):
2617 if isinstance(other, C):
2618 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002619 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002620 return self.value >= other
2621 return NotImplemented
2622 c1 = C(1)
2623 c2 = C(2)
2624 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002625 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002626 c = {1: c1, 2: c2, 3: c3}
2627 for x in 1, 2, 3:
2628 for y in 1, 2, 3:
2629 for op in "<", "<=", "==", "!=", ">", ">=":
2630 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2631 "x=%d, y=%d" % (x, y))
2632 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2633 "x=%d, y=%d" % (x, y))
2634 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2635 "x=%d, y=%d" % (x, y))
2636
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002637def descrdoc():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002638 if verbose: print("Testing descriptor doc strings...")
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002639 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002640 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002641 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002642 check(file.name, "file name") # member descriptor
2643
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002644def setclass():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002645 if verbose: print("Testing __class__ assignment...")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002646 class C(object): pass
2647 class D(object): pass
2648 class E(object): pass
2649 class F(D, E): pass
2650 for cls in C, D, E, F:
2651 for cls2 in C, D, E, F:
2652 x = cls()
2653 x.__class__ = cls2
2654 verify(x.__class__ is cls2)
2655 x.__class__ = cls
2656 verify(x.__class__ is cls)
2657 def cant(x, C):
2658 try:
2659 x.__class__ = C
2660 except TypeError:
2661 pass
2662 else:
2663 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002664 try:
2665 delattr(x, "__class__")
2666 except TypeError:
2667 pass
2668 else:
2669 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002670 cant(C(), list)
2671 cant(list(), C)
2672 cant(C(), 1)
2673 cant(C(), object)
2674 cant(object(), list)
2675 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002676 class Int(int): __slots__ = []
2677 cant(2, Int)
2678 cant(Int(), int)
2679 cant(True, int)
2680 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002681 o = object()
2682 cant(o, type(1))
2683 cant(o, type(None))
2684 del o
Guido van Rossumd8faa362007-04-27 19:54:29 +00002685 class G(object):
2686 __slots__ = ["a", "b"]
2687 class H(object):
2688 __slots__ = ["b", "a"]
2689 try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002690 str
Guido van Rossumd8faa362007-04-27 19:54:29 +00002691 except NameError:
2692 class I(object):
2693 __slots__ = ["a", "b"]
2694 else:
2695 class I(object):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002696 __slots__ = [str("a"), str("b")]
Guido van Rossumd8faa362007-04-27 19:54:29 +00002697 class J(object):
2698 __slots__ = ["c", "b"]
2699 class K(object):
2700 __slots__ = ["a", "b", "d"]
2701 class L(H):
2702 __slots__ = ["e"]
2703 class M(I):
2704 __slots__ = ["e"]
2705 class N(J):
2706 __slots__ = ["__weakref__"]
2707 class P(J):
2708 __slots__ = ["__dict__"]
2709 class Q(J):
2710 pass
2711 class R(J):
2712 __slots__ = ["__dict__", "__weakref__"]
2713
2714 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2715 x = cls()
2716 x.a = 1
2717 x.__class__ = cls2
2718 verify(x.__class__ is cls2,
2719 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2720 vereq(x.a, 1)
2721 x.__class__ = cls
2722 verify(x.__class__ is cls,
2723 "assigning %r as __class__ for %r silently failed" % (cls, x))
2724 vereq(x.a, 1)
2725 for cls in G, J, K, L, M, N, P, R, list, Int:
2726 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2727 if cls is cls2:
2728 continue
2729 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002730
Guido van Rossum6661be32001-10-26 04:26:12 +00002731def setdict():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002732 if verbose: print("Testing __dict__ assignment...")
Guido van Rossum6661be32001-10-26 04:26:12 +00002733 class C(object): pass
2734 a = C()
2735 a.__dict__ = {'b': 1}
2736 vereq(a.b, 1)
2737 def cant(x, dict):
2738 try:
2739 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002740 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002741 pass
2742 else:
2743 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2744 cant(a, None)
2745 cant(a, [])
2746 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002747 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum360e4b82007-05-14 22:51:27 +00002748
2749 class Base(object):
2750 pass
2751 def verify_dict_readonly(x):
2752 """
2753 x has to be an instance of a class inheriting from Base.
2754 """
2755 cant(x, {})
2756 try:
2757 del x.__dict__
2758 except (AttributeError, TypeError):
2759 pass
2760 else:
2761 raise TestFailed, "shouldn't allow del %r.__dict__" % x
2762 dict_descr = Base.__dict__["__dict__"]
2763 try:
2764 dict_descr.__set__(x, {})
2765 except (AttributeError, TypeError):
2766 pass
2767 else:
2768 raise TestFailed, "dict_descr allowed access to %r's dict" % x
2769
2770 # Classes don't allow __dict__ assignment and have readonly dicts
2771 class Meta1(type, Base):
2772 pass
2773 class Meta2(Base, type):
2774 pass
2775 class D(object):
2776 __metaclass__ = Meta1
2777 class E(object):
2778 __metaclass__ = Meta2
2779 for cls in C, D, E:
2780 verify_dict_readonly(cls)
2781 class_dict = cls.__dict__
2782 try:
2783 class_dict["spam"] = "eggs"
2784 except TypeError:
2785 pass
2786 else:
2787 raise TestFailed, "%r's __dict__ can be modified" % cls
2788
2789 # Modules also disallow __dict__ assignment
2790 class Module1(types.ModuleType, Base):
2791 pass
2792 class Module2(Base, types.ModuleType):
2793 pass
2794 for ModuleType in Module1, Module2:
2795 mod = ModuleType("spam")
2796 verify_dict_readonly(mod)
2797 mod.__dict__["spam"] = "eggs"
2798
2799 # Exception's __dict__ can be replaced, but not deleted
2800 class Exception1(Exception, Base):
2801 pass
2802 class Exception2(Base, Exception):
2803 pass
2804 for ExceptionType in Exception, Exception1, Exception2:
2805 e = ExceptionType()
2806 e.__dict__ = {"a": 1}
2807 vereq(e.a, 1)
2808 try:
2809 del e.__dict__
2810 except (TypeError, AttributeError):
2811 pass
2812 else:
2813 raise TestFaied, "%r's __dict__ can be deleted" % e
2814
Guido van Rossum6661be32001-10-26 04:26:12 +00002815
Guido van Rossum3926a632001-09-25 16:25:58 +00002816def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002817 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002818 print("Testing pickling and copying new-style classes and objects...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002819 import pickle
2820 try:
2821 import cPickle
2822 except ImportError:
2823 cPickle = None
Guido van Rossum3926a632001-09-25 16:25:58 +00002824
2825 def sorteditems(d):
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002826 return sorted(d.items())
Guido van Rossum3926a632001-09-25 16:25:58 +00002827
2828 global C
2829 class C(object):
2830 def __init__(self, a, b):
2831 super(C, self).__init__()
2832 self.a = a
2833 self.b = b
2834 def __repr__(self):
2835 return "C(%r, %r)" % (self.a, self.b)
2836
2837 global C1
2838 class C1(list):
2839 def __new__(cls, a, b):
2840 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002841 def __getnewargs__(self):
2842 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002843 def __init__(self, a, b):
2844 self.a = a
2845 self.b = b
2846 def __repr__(self):
2847 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2848
2849 global C2
2850 class C2(int):
2851 def __new__(cls, a, b, val=0):
2852 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002853 def __getnewargs__(self):
2854 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002855 def __init__(self, a, b, val=0):
2856 self.a = a
2857 self.b = b
2858 def __repr__(self):
2859 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2860
Guido van Rossum90c45142001-11-24 21:07:01 +00002861 global C3
2862 class C3(object):
2863 def __init__(self, foo):
2864 self.foo = foo
2865 def __getstate__(self):
2866 return self.foo
2867 def __setstate__(self, foo):
2868 self.foo = foo
2869
2870 global C4classic, C4
2871 class C4classic: # classic
2872 pass
2873 class C4(C4classic, object): # mixed inheritance
2874 pass
2875
Guido van Rossum3926a632001-09-25 16:25:58 +00002876 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002877 if p is None:
2878 continue # cPickle not found -- skip it
Guido van Rossum3926a632001-09-25 16:25:58 +00002879 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002880 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002881 print(p.__name__, ["text", "binary"][bin])
Guido van Rossum3926a632001-09-25 16:25:58 +00002882
2883 for cls in C, C1, C2:
2884 s = p.dumps(cls, bin)
2885 cls2 = p.loads(s)
2886 verify(cls2 is cls)
2887
2888 a = C1(1, 2); a.append(42); a.append(24)
2889 b = C2("hello", "world", 42)
2890 s = p.dumps((a, b), bin)
2891 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002892 vereq(x.__class__, a.__class__)
2893 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2894 vereq(y.__class__, b.__class__)
2895 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002896 vereq(repr(x), repr(a))
2897 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002898 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002899 print("a = x =", a)
2900 print("b = y =", b)
Guido van Rossum90c45142001-11-24 21:07:01 +00002901 # Test for __getstate__ and __setstate__ on new style class
2902 u = C3(42)
2903 s = p.dumps(u, bin)
2904 v = p.loads(s)
2905 veris(u.__class__, v.__class__)
2906 vereq(u.foo, v.foo)
2907 # Test for picklability of hybrid class
2908 u = C4()
2909 u.foo = 42
2910 s = p.dumps(u, bin)
2911 v = p.loads(s)
2912 veris(u.__class__, v.__class__)
2913 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002914
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002915 # Testing copy.deepcopy()
2916 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002917 print("deepcopy")
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002918 import copy
2919 for cls in C, C1, C2:
2920 cls2 = copy.deepcopy(cls)
2921 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002922
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002923 a = C1(1, 2); a.append(42); a.append(24)
2924 b = C2("hello", "world", 42)
2925 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002926 vereq(x.__class__, a.__class__)
2927 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2928 vereq(y.__class__, b.__class__)
2929 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002930 vereq(repr(x), repr(a))
2931 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002932 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002933 print("a = x =", a)
2934 print("b = y =", b)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002935
Guido van Rossum8c842552002-03-14 23:05:54 +00002936def pickleslots():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002937 if verbose: print("Testing pickling of classes with __slots__ ...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002938 import pickle, pickle as cPickle
Guido van Rossum8c842552002-03-14 23:05:54 +00002939 # Pickling of classes with __slots__ but without __getstate__ should fail
2940 global B, C, D, E
2941 class B(object):
2942 pass
2943 for base in [object, B]:
2944 class C(base):
2945 __slots__ = ['a']
2946 class D(C):
2947 pass
2948 try:
2949 pickle.dumps(C())
2950 except TypeError:
2951 pass
2952 else:
2953 raise TestFailed, "should fail: pickle C instance - %s" % base
2954 try:
2955 cPickle.dumps(C())
2956 except TypeError:
2957 pass
2958 else:
2959 raise TestFailed, "should fail: cPickle C instance - %s" % base
2960 try:
2961 pickle.dumps(C())
2962 except TypeError:
2963 pass
2964 else:
2965 raise TestFailed, "should fail: pickle D instance - %s" % base
2966 try:
2967 cPickle.dumps(D())
2968 except TypeError:
2969 pass
2970 else:
2971 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002972 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002973 class C(base):
2974 __slots__ = ['a']
2975 def __getstate__(self):
2976 try:
2977 d = self.__dict__.copy()
2978 except AttributeError:
2979 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002980 for cls in self.__class__.__mro__:
2981 for sn in cls.__dict__.get('__slots__', ()):
2982 try:
2983 d[sn] = getattr(self, sn)
2984 except AttributeError:
2985 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002986 return d
2987 def __setstate__(self, d):
2988 for k, v in d.items():
2989 setattr(self, k, v)
2990 class D(C):
2991 pass
2992 # Now it should work
2993 x = C()
2994 y = pickle.loads(pickle.dumps(x))
2995 vereq(hasattr(y, 'a'), 0)
2996 y = cPickle.loads(cPickle.dumps(x))
2997 vereq(hasattr(y, 'a'), 0)
2998 x.a = 42
2999 y = pickle.loads(pickle.dumps(x))
3000 vereq(y.a, 42)
3001 y = cPickle.loads(cPickle.dumps(x))
3002 vereq(y.a, 42)
3003 x = D()
3004 x.a = 42
3005 x.b = 100
3006 y = pickle.loads(pickle.dumps(x))
3007 vereq(y.a + y.b, 142)
3008 y = cPickle.loads(cPickle.dumps(x))
3009 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003010 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003011 class E(C):
3012 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003013 x = E()
3014 x.a = 42
3015 x.b = "foo"
3016 y = pickle.loads(pickle.dumps(x))
3017 vereq(y.a, x.a)
3018 vereq(y.b, x.b)
3019 y = cPickle.loads(cPickle.dumps(x))
3020 vereq(y.a, x.a)
3021 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003022
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003023def copies():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003024 if verbose: print("Testing copy.copy() and copy.deepcopy()...")
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003025 import copy
3026 class C(object):
3027 pass
3028
3029 a = C()
3030 a.foo = 12
3031 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003032 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003033
3034 a.bar = [1,2,3]
3035 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003036 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003037 verify(c.bar is a.bar)
3038
3039 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003040 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003041 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003042 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003043
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003044def binopoverride():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003045 if verbose: print("Testing overrides of binary operations...")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003046 class I(int):
3047 def __repr__(self):
3048 return "I(%r)" % int(self)
3049 def __add__(self, other):
3050 return I(int(self) + int(other))
3051 __radd__ = __add__
3052 def __pow__(self, other, mod=None):
3053 if mod is None:
3054 return I(pow(int(self), int(other)))
3055 else:
3056 return I(pow(int(self), int(other), int(mod)))
3057 def __rpow__(self, other, mod=None):
3058 if mod is None:
3059 return I(pow(int(other), int(self), mod))
3060 else:
3061 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003062
Walter Dörwald70a6b492004-02-12 17:35:32 +00003063 vereq(repr(I(1) + I(2)), "I(3)")
3064 vereq(repr(I(1) + 2), "I(3)")
3065 vereq(repr(1 + I(2)), "I(3)")
3066 vereq(repr(I(2) ** I(3)), "I(8)")
3067 vereq(repr(2 ** I(3)), "I(8)")
3068 vereq(repr(I(2) ** 3), "I(8)")
3069 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003070 class S(str):
3071 def __eq__(self, other):
3072 return self.lower() == other.lower()
3073
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003074def subclasspropagation():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003075 if verbose: print("Testing propagation of slot functions to subclasses...")
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003076 class A(object):
3077 pass
3078 class B(A):
3079 pass
3080 class C(A):
3081 pass
3082 class D(B, C):
3083 pass
3084 d = D()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003085 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003086 A.__hash__ = lambda self: 42
3087 vereq(hash(d), 42)
3088 C.__hash__ = lambda self: 314
3089 vereq(hash(d), 314)
3090 B.__hash__ = lambda self: 144
3091 vereq(hash(d), 144)
3092 D.__hash__ = lambda self: 100
3093 vereq(hash(d), 100)
3094 del D.__hash__
3095 vereq(hash(d), 144)
3096 del B.__hash__
3097 vereq(hash(d), 314)
3098 del C.__hash__
3099 vereq(hash(d), 42)
3100 del A.__hash__
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003101 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003102 d.foo = 42
3103 d.bar = 42
3104 vereq(d.foo, 42)
3105 vereq(d.bar, 42)
3106 def __getattribute__(self, name):
3107 if name == "foo":
3108 return 24
3109 return object.__getattribute__(self, name)
3110 A.__getattribute__ = __getattribute__
3111 vereq(d.foo, 24)
3112 vereq(d.bar, 42)
3113 def __getattr__(self, name):
3114 if name in ("spam", "foo", "bar"):
3115 return "hello"
3116 raise AttributeError, name
3117 B.__getattr__ = __getattr__
3118 vereq(d.spam, "hello")
3119 vereq(d.foo, 24)
3120 vereq(d.bar, 42)
3121 del A.__getattribute__
3122 vereq(d.foo, 42)
3123 del d.foo
3124 vereq(d.foo, "hello")
3125 vereq(d.bar, 42)
3126 del B.__getattr__
3127 try:
3128 d.foo
3129 except AttributeError:
3130 pass
3131 else:
3132 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003133
Guido van Rossume7f3e242002-06-14 02:35:45 +00003134 # Test a nasty bug in recurse_down_subclasses()
3135 import gc
3136 class A(object):
3137 pass
3138 class B(A):
3139 pass
3140 del B
3141 gc.collect()
3142 A.__setitem__ = lambda *a: None # crash
3143
Tim Petersfc57ccb2001-10-12 02:38:24 +00003144def buffer_inherit():
3145 import binascii
3146 # SF bug [#470040] ParseTuple t# vs subclasses.
3147 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003148 print("Testing that buffer interface is inherited ...")
Tim Petersfc57ccb2001-10-12 02:38:24 +00003149
3150 class MyStr(str):
3151 pass
3152 base = 'abc'
3153 m = MyStr(base)
3154 # b2a_hex uses the buffer interface to get its argument's value, via
3155 # PyArg_ParseTuple 't#' code.
3156 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3157
3158 # It's not clear that unicode will continue to support the character
3159 # buffer interface, and this test will fail if that's taken away.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003160 class MyUni(str):
Tim Petersfc57ccb2001-10-12 02:38:24 +00003161 pass
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003162 base = 'abc'
Tim Petersfc57ccb2001-10-12 02:38:24 +00003163 m = MyUni(base)
3164 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3165
3166 class MyInt(int):
3167 pass
3168 m = MyInt(42)
3169 try:
3170 binascii.b2a_hex(m)
3171 raise TestFailed('subclass of int should not have a buffer interface')
3172 except TypeError:
3173 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003174
Tim Petersc9933152001-10-16 20:18:24 +00003175def str_of_str_subclass():
3176 import binascii
3177 import cStringIO
3178
3179 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003180 print("Testing __str__ defined in subclass of str ...")
Tim Petersc9933152001-10-16 20:18:24 +00003181
3182 class octetstring(str):
3183 def __str__(self):
3184 return binascii.b2a_hex(self)
3185 def __repr__(self):
3186 return self + " repr"
3187
3188 o = octetstring('A')
3189 vereq(type(o), octetstring)
3190 vereq(type(str(o)), str)
3191 vereq(type(repr(o)), str)
3192 vereq(ord(o), 0x41)
3193 vereq(str(o), '41')
3194 vereq(repr(o), 'A repr')
3195 vereq(o.__str__(), '41')
3196 vereq(o.__repr__(), 'A repr')
3197
3198 capture = cStringIO.StringIO()
3199 # Calling str() or not exercises different internal paths.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003200 print(o, file=capture)
3201 print(str(o), file=capture)
Tim Petersc9933152001-10-16 20:18:24 +00003202 vereq(capture.getvalue(), '41\n41\n')
3203 capture.close()
3204
Guido van Rossumc8e56452001-10-22 00:43:43 +00003205def kwdargs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003206 if verbose: print("Testing keyword arguments to __init__, __call__...")
Guido van Rossumc8e56452001-10-22 00:43:43 +00003207 def f(a): return a
3208 vereq(f.__call__(a=42), 42)
3209 a = []
3210 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003211 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003212
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003213def recursive__call__():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003214 if verbose: print(("Testing recursive __call__() by setting to instance of "
3215 "class ..."))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003216 class A(object):
3217 pass
3218
3219 A.__call__ = A()
3220 try:
3221 A()()
3222 except RuntimeError:
3223 pass
3224 else:
3225 raise TestFailed("Recursion limit should have been reached for "
3226 "__call__()")
3227
Guido van Rossumed87ad82001-10-30 02:33:02 +00003228def delhook():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003229 if verbose: print("Testing __del__ hook...")
Guido van Rossumed87ad82001-10-30 02:33:02 +00003230 log = []
3231 class C(object):
3232 def __del__(self):
3233 log.append(1)
3234 c = C()
3235 vereq(log, [])
3236 del c
3237 vereq(log, [1])
3238
Guido van Rossum29d26062001-12-11 04:37:34 +00003239 class D(object): pass
3240 d = D()
3241 try: del d[0]
3242 except TypeError: pass
3243 else: raise TestFailed, "invalid del() didn't raise TypeError"
3244
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003245def hashinherit():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003246 if verbose: print("Testing hash of mutable subclasses...")
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003247
3248 class mydict(dict):
3249 pass
3250 d = mydict()
3251 try:
3252 hash(d)
3253 except TypeError:
3254 pass
3255 else:
3256 raise TestFailed, "hash() of dict subclass should fail"
3257
3258 class mylist(list):
3259 pass
3260 d = mylist()
3261 try:
3262 hash(d)
3263 except TypeError:
3264 pass
3265 else:
3266 raise TestFailed, "hash() of list subclass should fail"
3267
Guido van Rossum29d26062001-12-11 04:37:34 +00003268def strops():
3269 try: 'a' + 5
3270 except TypeError: pass
3271 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3272
3273 try: ''.split('')
3274 except ValueError: pass
3275 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3276
3277 try: ''.join([0])
3278 except TypeError: pass
3279 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3280
3281 try: ''.rindex('5')
3282 except ValueError: pass
3283 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3284
Guido van Rossum29d26062001-12-11 04:37:34 +00003285 try: '%(n)s' % None
3286 except TypeError: pass
3287 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3288
3289 try: '%(n' % {}
3290 except ValueError: pass
3291 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3292
3293 try: '%*s' % ('abc')
3294 except TypeError: pass
3295 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3296
3297 try: '%*.*s' % ('abc', 5)
3298 except TypeError: pass
3299 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3300
3301 try: '%s' % (1, 2)
3302 except TypeError: pass
3303 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3304
3305 try: '%' % None
3306 except ValueError: pass
3307 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3308
3309 vereq('534253'.isdigit(), 1)
3310 vereq('534253x'.isdigit(), 0)
3311 vereq('%c' % 5, '\x05')
3312 vereq('%c' % '5', '5')
3313
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003314def deepcopyrecursive():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003315 if verbose: print("Testing deepcopy of recursive objects...")
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003316 class Node:
3317 pass
3318 a = Node()
3319 b = Node()
3320 a.b = b
3321 b.a = a
3322 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003323
Guido van Rossumd7035672002-03-12 20:43:31 +00003324def modules():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003325 if verbose: print("Testing uninitialized module objects...")
Guido van Rossumd7035672002-03-12 20:43:31 +00003326 from types import ModuleType as M
3327 m = M.__new__(M)
3328 str(m)
3329 vereq(hasattr(m, "__name__"), 0)
3330 vereq(hasattr(m, "__file__"), 0)
3331 vereq(hasattr(m, "foo"), 0)
3332 vereq(m.__dict__, None)
3333 m.foo = 1
3334 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003335
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003336def dictproxyiterkeys():
3337 class C(object):
3338 def meth(self):
3339 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003340 if verbose: print("Testing dict-proxy iterkeys...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003341 keys = [ key for key in C.__dict__.keys() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003342 keys.sort()
3343 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3344
3345def dictproxyitervalues():
3346 class C(object):
3347 def meth(self):
3348 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003349 if verbose: print("Testing dict-proxy itervalues...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003350 values = [ values for values in C.__dict__.values() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003351 vereq(len(values), 5)
3352
3353def dictproxyiteritems():
3354 class C(object):
3355 def meth(self):
3356 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003357 if verbose: print("Testing dict-proxy iteritems...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003358 keys = [ key for (key, value) in C.__dict__.items() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003359 keys.sort()
3360 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3361
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003362def funnynew():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003363 if verbose: print("Testing __new__ returning something unexpected...")
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003364 class C(object):
3365 def __new__(cls, arg):
3366 if isinstance(arg, str): return [1, 2, 3]
3367 elif isinstance(arg, int): return object.__new__(D)
3368 else: return object.__new__(cls)
3369 class D(C):
3370 def __init__(self, arg):
3371 self.foo = arg
3372 vereq(C("1"), [1, 2, 3])
3373 vereq(D("1"), [1, 2, 3])
3374 d = D(None)
3375 veris(d.foo, None)
3376 d = C(1)
3377 vereq(isinstance(d, D), True)
3378 vereq(d.foo, 1)
3379 d = D(1)
3380 vereq(isinstance(d, D), True)
3381 vereq(d.foo, 1)
3382
Guido van Rossume8fc6402002-04-16 16:44:51 +00003383def imulbug():
3384 # SF bug 544647
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003385 if verbose: print("Testing for __imul__ problems...")
Guido van Rossume8fc6402002-04-16 16:44:51 +00003386 class C(object):
3387 def __imul__(self, other):
3388 return (self, other)
3389 x = C()
3390 y = x
3391 y *= 1.0
3392 vereq(y, (x, 1.0))
3393 y = x
3394 y *= 2
3395 vereq(y, (x, 2))
3396 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003397 y *= 3
3398 vereq(y, (x, 3))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003399 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003400 y *= 1<<100
3401 vereq(y, (x, 1<<100))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003402 y = x
3403 y *= None
3404 vereq(y, (x, None))
3405 y = x
3406 y *= "foo"
3407 vereq(y, (x, "foo"))
3408
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003409def docdescriptor():
3410 # SF bug 542984
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003411 if verbose: print("Testing __doc__ descriptor...")
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003412 class DocDescr(object):
3413 def __get__(self, object, otype):
3414 if object:
3415 object = object.__class__.__name__ + ' instance'
3416 if otype:
3417 otype = otype.__name__
3418 return 'object=%s; type=%s' % (object, otype)
3419 class OldClass:
3420 __doc__ = DocDescr()
3421 class NewClass(object):
3422 __doc__ = DocDescr()
3423 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3424 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3425 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3426 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3427
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003428def copy_setstate():
3429 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003430 print("Testing that copy.*copy() correctly uses __setstate__...")
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003431 import copy
3432 class C(object):
3433 def __init__(self, foo=None):
3434 self.foo = foo
3435 self.__foo = foo
3436 def setfoo(self, foo=None):
3437 self.foo = foo
3438 def getfoo(self):
3439 return self.__foo
3440 def __getstate__(self):
3441 return [self.foo]
3442 def __setstate__(self, lst):
3443 assert len(lst) == 1
3444 self.__foo = self.foo = lst[0]
3445 a = C(42)
3446 a.setfoo(24)
3447 vereq(a.foo, 24)
3448 vereq(a.getfoo(), 42)
3449 b = copy.copy(a)
3450 vereq(b.foo, 24)
3451 vereq(b.getfoo(), 24)
3452 b = copy.deepcopy(a)
3453 vereq(b.foo, 24)
3454 vereq(b.getfoo(), 24)
3455
Guido van Rossum09638c12002-06-13 19:17:46 +00003456def slices():
3457 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003458 print("Testing cases with slices and overridden __getitem__ ...")
Guido van Rossum09638c12002-06-13 19:17:46 +00003459 # Strings
3460 vereq("hello"[:4], "hell")
3461 vereq("hello"[slice(4)], "hell")
3462 vereq(str.__getitem__("hello", slice(4)), "hell")
3463 class S(str):
3464 def __getitem__(self, x):
3465 return str.__getitem__(self, x)
3466 vereq(S("hello")[:4], "hell")
3467 vereq(S("hello")[slice(4)], "hell")
3468 vereq(S("hello").__getitem__(slice(4)), "hell")
3469 # Tuples
3470 vereq((1,2,3)[:2], (1,2))
3471 vereq((1,2,3)[slice(2)], (1,2))
3472 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3473 class T(tuple):
3474 def __getitem__(self, x):
3475 return tuple.__getitem__(self, x)
3476 vereq(T((1,2,3))[:2], (1,2))
3477 vereq(T((1,2,3))[slice(2)], (1,2))
3478 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3479 # Lists
3480 vereq([1,2,3][:2], [1,2])
3481 vereq([1,2,3][slice(2)], [1,2])
3482 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3483 class L(list):
3484 def __getitem__(self, x):
3485 return list.__getitem__(self, x)
3486 vereq(L([1,2,3])[:2], [1,2])
3487 vereq(L([1,2,3])[slice(2)], [1,2])
3488 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3489 # Now do lists and __setitem__
3490 a = L([1,2,3])
3491 a[slice(1, 3)] = [3,2]
3492 vereq(a, [1,3,2])
3493 a[slice(0, 2, 1)] = [3,1]
3494 vereq(a, [3,1,2])
3495 a.__setitem__(slice(1, 3), [2,1])
3496 vereq(a, [3,2,1])
3497 a.__setitem__(slice(0, 2, 1), [2,3])
3498 vereq(a, [2,3,1])
3499
Tim Peters2484aae2002-07-11 06:56:07 +00003500def subtype_resurrection():
3501 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003502 print("Testing resurrection of new-style instance...")
Tim Peters2484aae2002-07-11 06:56:07 +00003503
3504 class C(object):
3505 container = []
3506
3507 def __del__(self):
3508 # resurrect the instance
3509 C.container.append(self)
3510
3511 c = C()
3512 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003513 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003514 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003515 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003516
3517 # If that didn't blow up, it's also interesting to see whether clearing
3518 # the last container slot works: that will attempt to delete c again,
3519 # which will cause c to get appended back to the container again "during"
3520 # the del.
3521 del C.container[-1]
3522 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003523 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003524
Tim Peters14cb1e12002-07-11 18:26:21 +00003525 # Make c mortal again, so that the test framework with -l doesn't report
3526 # it as a leak.
3527 del C.__del__
3528
Guido van Rossum2d702462002-08-06 21:28:28 +00003529def slottrash():
3530 # Deallocating deeply nested slotted trash caused stack overflows
3531 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003532 print("Testing slot trash...")
Guido van Rossum2d702462002-08-06 21:28:28 +00003533 class trash(object):
3534 __slots__ = ['x']
3535 def __init__(self, x):
3536 self.x = x
3537 o = None
Guido van Rossum805365e2007-05-07 22:24:25 +00003538 for i in range(50000):
Guido van Rossum2d702462002-08-06 21:28:28 +00003539 o = trash(o)
3540 del o
3541
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003542def slotmultipleinheritance():
3543 # SF bug 575229, multiple inheritance w/ slots dumps core
3544 class A(object):
3545 __slots__=()
3546 class B(object):
3547 pass
3548 class C(A,B) :
3549 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003550 vereq(C.__basicsize__, B.__basicsize__)
3551 verify(hasattr(C, '__dict__'))
3552 verify(hasattr(C, '__weakref__'))
3553 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003554
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003555def testrmul():
3556 # SF patch 592646
3557 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003558 print("Testing correct invocation of __rmul__...")
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003559 class C(object):
3560 def __mul__(self, other):
3561 return "mul"
3562 def __rmul__(self, other):
3563 return "rmul"
3564 a = C()
3565 vereq(a*2, "mul")
3566 vereq(a*2.2, "mul")
3567 vereq(2*a, "rmul")
3568 vereq(2.2*a, "rmul")
3569
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003570def testipow():
3571 # [SF bug 620179]
3572 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003573 print("Testing correct invocation of __ipow__...")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003574 class C(object):
3575 def __ipow__(self, other):
3576 pass
3577 a = C()
3578 a **= 2
3579
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003580def do_this_first():
3581 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003582 print("Testing SF bug 551412 ...")
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003583 # This dumps core when SF bug 551412 isn't fixed --
3584 # but only when test_descr.py is run separately.
3585 # (That can't be helped -- as soon as PyType_Ready()
3586 # is called for PyLong_Type, the bug is gone.)
3587 class UserLong(object):
3588 def __pow__(self, *args):
3589 pass
3590 try:
Guido van Rossume2a383d2007-01-15 16:59:06 +00003591 pow(0, UserLong(), 0)
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003592 except:
3593 pass
3594
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003595 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003596 print("Testing SF bug 570483...")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003597 # Another segfault only when run early
3598 # (before PyType_Ready(tuple) is called)
3599 type.mro(tuple)
3600
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003601def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003602 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003603 print("Testing mutable bases...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003604 # stuff that should work:
3605 class C(object):
3606 pass
3607 class C2(object):
3608 def __getattribute__(self, attr):
3609 if attr == 'a':
3610 return 2
3611 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003612 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003613 def meth(self):
3614 return 1
3615 class D(C):
3616 pass
3617 class E(D):
3618 pass
3619 d = D()
3620 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003621 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003622 D.__bases__ = (C2,)
3623 vereq(d.meth(), 1)
3624 vereq(e.meth(), 1)
3625 vereq(d.a, 2)
3626 vereq(e.a, 2)
3627 vereq(C2.__subclasses__(), [D])
3628
3629 # stuff that shouldn't:
3630 class L(list):
3631 pass
3632
3633 try:
3634 L.__bases__ = (dict,)
3635 except TypeError:
3636 pass
3637 else:
3638 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3639
3640 try:
3641 list.__bases__ = (dict,)
3642 except TypeError:
3643 pass
3644 else:
3645 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3646
3647 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00003648 D.__bases__ = (C2, list)
3649 except TypeError:
3650 pass
3651 else:
3652 assert 0, "best_base calculation found wanting"
3653
3654 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003655 del D.__bases__
3656 except TypeError:
3657 pass
3658 else:
3659 raise TestFailed, "shouldn't be able to delete .__bases__"
3660
3661 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003662 D.__bases__ = ()
Guido van Rossumb940e112007-01-10 16:19:56 +00003663 except TypeError as msg:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003664 if str(msg) == "a new-style class can't have only classic bases":
3665 raise TestFailed, "wrong error message for .__bases__ = ()"
3666 else:
3667 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3668
3669 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003670 D.__bases__ = (D,)
3671 except TypeError:
3672 pass
3673 else:
3674 # actually, we'll have crashed by here...
3675 raise TestFailed, "shouldn't be able to create inheritance cycles"
3676
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003677 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003678 D.__bases__ = (C, C)
3679 except TypeError:
3680 pass
3681 else:
3682 raise TestFailed, "didn't detect repeated base classes"
3683
3684 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003685 D.__bases__ = (E,)
3686 except TypeError:
3687 pass
3688 else:
3689 raise TestFailed, "shouldn't be able to create inheritance cycles"
3690
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003691def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003692 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003693 print("Testing mutable bases with failing mro...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003694 class WorkOnce(type):
3695 def __new__(self, name, bases, ns):
3696 self.flag = 0
3697 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3698 def mro(self):
3699 if self.flag > 0:
3700 raise RuntimeError, "bozo"
3701 else:
3702 self.flag += 1
3703 return type.mro(self)
3704
3705 class WorkAlways(type):
3706 def mro(self):
3707 # this is here to make sure that .mro()s aren't called
3708 # with an exception set (which was possible at one point).
3709 # An error message will be printed in a debug build.
3710 # What's a good way to test for this?
3711 return type.mro(self)
3712
3713 class C(object):
3714 pass
3715
3716 class C2(object):
3717 pass
3718
3719 class D(C):
3720 pass
3721
3722 class E(D):
3723 pass
3724
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003725 class F(D, metaclass=WorkOnce):
3726 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003727
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003728 class G(D, metaclass=WorkAlways):
3729 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003730
3731 # Immediate subclasses have their mro's adjusted in alphabetical
3732 # order, so E's will get adjusted before adjusting F's fails. We
3733 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003734
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003735 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003736 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003737
3738 try:
3739 D.__bases__ = (C2,)
3740 except RuntimeError:
3741 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003742 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003743 else:
3744 raise TestFailed, "exception not propagated"
3745
3746def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003747 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003748 print("Testing mutable bases catch mro conflict...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003749 class A(object):
3750 pass
3751
3752 class B(object):
3753 pass
3754
3755 class C(A, B):
3756 pass
3757
3758 class D(A, B):
3759 pass
3760
3761 class E(C, D):
3762 pass
3763
3764 try:
3765 C.__bases__ = (B, A)
3766 except TypeError:
3767 pass
3768 else:
3769 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003770
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003771def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003772 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003773 print("Testing mutable names...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003774 class C(object):
3775 pass
3776
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003777 # C.__module__ could be 'test_descr' or '__main__'
3778 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003779
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003780 C.__name__ = 'D'
3781 vereq((C.__module__, C.__name__), (mod, 'D'))
3782
3783 C.__name__ = 'D.E'
3784 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003785
Guido van Rossum613f24f2003-01-06 23:00:59 +00003786def subclass_right_op():
3787 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003788 print("Testing correct dispatch of subclass overloading __r<op>__...")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003789
3790 # This code tests various cases where right-dispatch of a subclass
3791 # should be preferred over left-dispatch of a base class.
3792
3793 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3794
3795 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003796 def __floordiv__(self, other):
3797 return "B.__floordiv__"
3798 def __rfloordiv__(self, other):
3799 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003800
Guido van Rossumf389c772003-02-27 20:04:19 +00003801 vereq(B(1) // 1, "B.__floordiv__")
3802 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003803
3804 # Case 2: subclass of object; this is just the baseline for case 3
3805
3806 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003807 def __floordiv__(self, other):
3808 return "C.__floordiv__"
3809 def __rfloordiv__(self, other):
3810 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003811
Guido van Rossumf389c772003-02-27 20:04:19 +00003812 vereq(C() // 1, "C.__floordiv__")
3813 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003814
3815 # Case 3: subclass of new-style class; here it gets interesting
3816
3817 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003818 def __floordiv__(self, other):
3819 return "D.__floordiv__"
3820 def __rfloordiv__(self, other):
3821 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003822
Guido van Rossumf389c772003-02-27 20:04:19 +00003823 vereq(D() // C(), "D.__floordiv__")
3824 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003825
3826 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3827
3828 class E(C):
3829 pass
3830
Guido van Rossumf389c772003-02-27 20:04:19 +00003831 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003832
Guido van Rossumf389c772003-02-27 20:04:19 +00003833 vereq(E() // 1, "C.__floordiv__")
3834 vereq(1 // E(), "C.__rfloordiv__")
3835 vereq(E() // C(), "C.__floordiv__")
3836 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003837
Guido van Rossum373c7412003-01-07 13:41:37 +00003838def dict_type_with_metaclass():
3839 if verbose:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003840 print("Testing type of __dict__ when metaclass set...")
Guido van Rossum373c7412003-01-07 13:41:37 +00003841
3842 class B(object):
3843 pass
3844 class M(type):
3845 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003846 class C(metaclass=M):
Guido van Rossum373c7412003-01-07 13:41:37 +00003847 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003848 pass
Guido van Rossum373c7412003-01-07 13:41:37 +00003849 veris(type(C.__dict__), type(B.__dict__))
3850
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003851def meth_class_get():
3852 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003853 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003854 print("Testing __get__ method of METH_CLASS C methods...")
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003855 # Baseline
3856 arg = [1, 2, 3]
3857 res = {1: None, 2: None, 3: None}
3858 vereq(dict.fromkeys(arg), res)
3859 vereq({}.fromkeys(arg), res)
3860 # Now get the descriptor
3861 descr = dict.__dict__["fromkeys"]
3862 # More baseline using the descriptor directly
3863 vereq(descr.__get__(None, dict)(arg), res)
3864 vereq(descr.__get__({})(arg), res)
3865 # Now check various error cases
3866 try:
3867 descr.__get__(None, None)
3868 except TypeError:
3869 pass
3870 else:
3871 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3872 try:
3873 descr.__get__(42)
3874 except TypeError:
3875 pass
3876 else:
3877 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3878 try:
3879 descr.__get__(None, 42)
3880 except TypeError:
3881 pass
3882 else:
3883 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3884 try:
3885 descr.__get__(None, int)
3886 except TypeError:
3887 pass
3888 else:
3889 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3890
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003891def isinst_isclass():
3892 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003893 print("Testing proxy isinstance() and isclass()...")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003894 class Proxy(object):
3895 def __init__(self, obj):
3896 self.__obj = obj
3897 def __getattribute__(self, name):
3898 if name.startswith("_Proxy__"):
3899 return object.__getattribute__(self, name)
3900 else:
3901 return getattr(self.__obj, name)
3902 # Test with a classic class
3903 class C:
3904 pass
3905 a = C()
3906 pa = Proxy(a)
3907 verify(isinstance(a, C)) # Baseline
3908 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003909 # Test with a classic subclass
3910 class D(C):
3911 pass
3912 a = D()
3913 pa = Proxy(a)
3914 verify(isinstance(a, C)) # Baseline
3915 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003916 # Test with a new-style class
3917 class C(object):
3918 pass
3919 a = C()
3920 pa = Proxy(a)
3921 verify(isinstance(a, C)) # Baseline
3922 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003923 # Test with a new-style subclass
3924 class D(C):
3925 pass
3926 a = D()
3927 pa = Proxy(a)
3928 verify(isinstance(a, C)) # Baseline
3929 verify(isinstance(pa, C)) # Test
3930
3931def proxysuper():
3932 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003933 print("Testing super() for a proxy object...")
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003934 class Proxy(object):
3935 def __init__(self, obj):
3936 self.__obj = obj
3937 def __getattribute__(self, name):
3938 if name.startswith("_Proxy__"):
3939 return object.__getattribute__(self, name)
3940 else:
3941 return getattr(self.__obj, name)
3942
3943 class B(object):
3944 def f(self):
3945 return "B.f"
3946
3947 class C(B):
3948 def f(self):
3949 return super(C, self).f() + "->C.f"
3950
3951 obj = C()
3952 p = Proxy(obj)
3953 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003954
Guido van Rossum52b27052003-04-15 20:05:10 +00003955def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003956 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003957 print("Testing prohibition of Carlo Verre's hack...")
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003958 try:
3959 object.__setattr__(str, "foo", 42)
3960 except TypeError:
3961 pass
3962 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003963 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003964 try:
3965 object.__delattr__(str, "lower")
3966 except TypeError:
3967 pass
3968 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003969 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003970
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003971def weakref_segfault():
3972 # SF 742911
3973 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003974 print("Testing weakref segfault...")
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003975
3976 import weakref
3977
3978 class Provoker:
3979 def __init__(self, referrent):
3980 self.ref = weakref.ref(referrent)
3981
3982 def __del__(self):
3983 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003984
3985 class Oops(object):
3986 pass
3987
3988 o = Oops()
3989 o.whatever = Provoker(o)
3990 del o
3991
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003992def wrapper_segfault():
3993 # SF 927248: deeply nested wrappers could cause stack overflow
3994 f = lambda:None
Guido van Rossum805365e2007-05-07 22:24:25 +00003995 for i in range(1000000):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003996 f = f.__call__
3997 f = None
3998
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003999# Fix SF #762455, segfault when sys.stdout is changed in getattr
4000def filefault():
4001 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004002 print("Testing sys.stdout is changed in getattr...")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004003 import sys
4004 class StdoutGuard:
4005 def __getattr__(self, attr):
4006 sys.stdout = sys.__stdout__
4007 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4008 sys.stdout = StdoutGuard()
4009 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004010 print("Oops!")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004011 except RuntimeError:
4012 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004013
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004014def vicious_descriptor_nonsense():
4015 # A potential segfault spotted by Thomas Wouters in mail to
4016 # python-dev 2003-04-17, turned into an example & fixed by Michael
4017 # Hudson just less than four months later...
4018 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004019 print("Testing vicious_descriptor_nonsense...")
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004020
4021 class Evil(object):
4022 def __hash__(self):
4023 return hash('attr')
4024 def __eq__(self, other):
4025 del C.attr
4026 return 0
4027
4028 class Descr(object):
4029 def __get__(self, ob, type=None):
4030 return 1
4031
4032 class C(object):
4033 attr = Descr()
4034
4035 c = C()
4036 c.__dict__[Evil()] = 0
4037
4038 vereq(c.attr, 1)
4039 # this makes a crash more likely:
4040 import gc; gc.collect()
4041 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004042
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004043def test_init():
4044 # SF 1155938
4045 class Foo(object):
4046 def __init__(self):
4047 return 10
4048 try:
4049 Foo()
4050 except TypeError:
4051 pass
4052 else:
4053 raise TestFailed, "did not test __init__() for None return"
4054
Armin Rigoc6686b72005-11-07 08:38:00 +00004055def methodwrapper():
4056 # <type 'method-wrapper'> did not support any reflection before 2.5
4057 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004058 print("Testing method-wrapper objects...")
Armin Rigoc6686b72005-11-07 08:38:00 +00004059
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004060 return # XXX should methods really support __eq__?
4061
Armin Rigoc6686b72005-11-07 08:38:00 +00004062 l = []
4063 vereq(l.__add__, l.__add__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004064 vereq(l.__add__, [].__add__)
4065 verify(l.__add__ != [5].__add__)
4066 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004067 verify(l.__add__.__name__ == '__add__')
4068 verify(l.__add__.__self__ is l)
4069 verify(l.__add__.__objclass__ is list)
4070 vereq(l.__add__.__doc__, list.__add__.__doc__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004071 try:
4072 hash(l.__add__)
4073 except TypeError:
4074 pass
4075 else:
4076 raise TestFailed("no TypeError from hash([].__add__)")
4077
4078 t = ()
4079 t += (7,)
4080 vereq(t.__add__, (7,).__add__)
4081 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004082
Armin Rigofd163f92005-12-29 15:59:19 +00004083def notimplemented():
4084 # all binary methods should be able to return a NotImplemented
4085 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004086 print("Testing NotImplemented...")
Armin Rigofd163f92005-12-29 15:59:19 +00004087
4088 import sys
4089 import types
4090 import operator
4091
4092 def specialmethod(self, other):
4093 return NotImplemented
4094
4095 def check(expr, x, y):
4096 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +00004097 exec(expr, {'x': x, 'y': y, 'operator': operator})
Armin Rigofd163f92005-12-29 15:59:19 +00004098 except TypeError:
4099 pass
4100 else:
4101 raise TestFailed("no TypeError from %r" % (expr,))
4102
Guido van Rossume2a383d2007-01-15 16:59:06 +00004103 N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004104 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4105 # ValueErrors instead of TypeErrors
4106 for metaclass in [type, types.ClassType]:
4107 for name, expr, iexpr in [
4108 ('__add__', 'x + y', 'x += y'),
4109 ('__sub__', 'x - y', 'x -= y'),
4110 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004111 ('__truediv__', 'x / y', None),
4112 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00004113 ('__mod__', 'x % y', 'x %= y'),
4114 ('__divmod__', 'divmod(x, y)', None),
4115 ('__pow__', 'x ** y', 'x **= y'),
4116 ('__lshift__', 'x << y', 'x <<= y'),
4117 ('__rshift__', 'x >> y', 'x >>= y'),
4118 ('__and__', 'x & y', 'x &= y'),
4119 ('__or__', 'x | y', 'x |= y'),
4120 ('__xor__', 'x ^ y', 'x ^= y'),
Neal Norwitz4886cc32006-08-21 17:06:07 +00004121 ]:
4122 rname = '__r' + name[2:]
Armin Rigofd163f92005-12-29 15:59:19 +00004123 A = metaclass('A', (), {name: specialmethod})
4124 B = metaclass('B', (), {rname: specialmethod})
4125 a = A()
4126 b = B()
4127 check(expr, a, a)
4128 check(expr, a, b)
4129 check(expr, b, a)
4130 check(expr, b, b)
4131 check(expr, a, N1)
4132 check(expr, a, N2)
4133 check(expr, N1, b)
4134 check(expr, N2, b)
4135 if iexpr:
4136 check(iexpr, a, a)
4137 check(iexpr, a, b)
4138 check(iexpr, b, a)
4139 check(iexpr, b, b)
4140 check(iexpr, a, N1)
4141 check(iexpr, a, N2)
4142 iname = '__i' + name[2:]
4143 C = metaclass('C', (), {iname: specialmethod})
4144 c = C()
4145 check(iexpr, c, a)
4146 check(iexpr, c, b)
4147 check(iexpr, c, N1)
4148 check(iexpr, c, N2)
4149
Guido van Rossumd8faa362007-04-27 19:54:29 +00004150def test_assign_slice():
4151 # ceval.c's assign_slice used to check for
4152 # tp->tp_as_sequence->sq_slice instead of
4153 # tp->tp_as_sequence->sq_ass_slice
4154
4155 class C(object):
4156 def __setslice__(self, start, stop, value):
4157 self.value = value
4158
4159 c = C()
4160 c[1:2] = 3
4161 vereq(c.value, 3)
4162
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004163def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004164 weakref_segfault() # Must be first, somehow
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004165 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004166 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004167 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168 lists()
4169 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004170 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004171 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004172 ints()
4173 longs()
4174 floats()
4175 complexes()
4176 spamlists()
4177 spamdicts()
4178 pydicts()
4179 pylists()
4180 metaclass()
4181 pymods()
4182 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004183 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004185 ex5()
4186 monotonicity()
4187 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004188 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004190 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191 dynamics()
4192 errors()
4193 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004194 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004196 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197 classic()
4198 compattr()
4199 newslot()
4200 altmro()
4201 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004202 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004203 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004204 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004205 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004206 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004207 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004208 keywords()
Tim Peters0ab085c2001-09-14 00:25:33 +00004209 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004210 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004211 rich_comparisons()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004212 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004213 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004214 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004215 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004216 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004217 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004218 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004219 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004220 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004221 kwdargs()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004222 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004223 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004224 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004225 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004226 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004227 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004228 dictproxyiterkeys()
4229 dictproxyitervalues()
4230 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004231 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004232 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004233 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004234 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004235 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004236 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004237 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004238 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004239 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004240 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004241 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004242 test_mutable_bases()
4243 test_mutable_bases_with_failing_mro()
4244 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004245 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004246 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004247 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004248 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004249 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004250 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004251 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004252 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004253 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004254 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004255 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004256 notimplemented()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004257 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004258
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004259 if verbose: print("All OK")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004261if __name__ == "__main__":
4262 test_main()