blob: bcbd0964552220de2e4733fefedd564dee087b62 [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!
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000268 for arg in 2, 2, 2j, 2e0, [2], "2", b"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):
Walter Dörwald7815c5e2007-06-11 14:55:19 +00001088 __slots__ = ["foo\u1234bar"]
1089 except TypeError:
1090 pass
1091 else:
1092 raise TestFailed, "['foo\\u1234bar'] slots not caught"
1093 try:
1094 class C(object):
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001095 __slots__ = ["1"]
1096 except TypeError:
1097 pass
1098 else:
1099 raise TestFailed, "['1'] slots not caught"
1100 try:
1101 class C(object):
1102 __slots__ = [""]
1103 except TypeError:
1104 pass
1105 else:
1106 raise TestFailed, "[''] slots not caught"
1107 class C(object):
1108 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109 # XXX(nnorwitz): was there supposed to be something tested
1110 # from the class above?
1111
1112 # Test a single string is not expanded as a sequence.
1113 class C(object):
1114 __slots__ = "abc"
1115 c = C()
1116 c.abc = 5
1117 vereq(c.abc, 5)
1118
1119 # Test unicode slot names
Walter Dörwald5de48bd2007-06-11 21:38:39 +00001120 # Test a single unicode string is not expanded as a sequence.
1121 class C(object):
1122 __slots__ = "abc"
1123 c = C()
1124 c.abc = 5
1125 vereq(c.abc, 5)
1126
1127 # _unicode_to_string used to modify slots in certain circumstances
1128 slots = ("foo", "bar")
1129 class C(object):
1130 __slots__ = slots
1131 x = C()
1132 x.foo = 5
1133 vereq(x.foo, 5)
1134 veris(type(slots[0]), str)
1135 # this used to leak references
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136 try:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00001137 class C(object):
1138 __slots__ = [chr(128)]
1139 except (TypeError, UnicodeEncodeError):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140 pass
1141 else:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00001142 raise TestFailed, "[unichr(128)] slots not caught"
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001143
Guido van Rossum33bab012001-12-05 22:45:48 +00001144 # Test leaks
1145 class Counted(object):
1146 counter = 0 # counts the number of instances alive
1147 def __init__(self):
1148 Counted.counter += 1
1149 def __del__(self):
1150 Counted.counter -= 1
1151 class C(object):
1152 __slots__ = ['a', 'b', 'c']
1153 x = C()
1154 x.a = Counted()
1155 x.b = Counted()
1156 x.c = Counted()
1157 vereq(Counted.counter, 3)
1158 del x
1159 vereq(Counted.counter, 0)
1160 class D(C):
1161 pass
1162 x = D()
1163 x.a = Counted()
1164 x.z = Counted()
1165 vereq(Counted.counter, 2)
1166 del x
1167 vereq(Counted.counter, 0)
1168 class E(D):
1169 __slots__ = ['e']
1170 x = E()
1171 x.a = Counted()
1172 x.z = Counted()
1173 x.e = Counted()
1174 vereq(Counted.counter, 3)
1175 del x
1176 vereq(Counted.counter, 0)
1177
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001178 # Test cyclical leaks [SF bug 519621]
1179 class F(object):
1180 __slots__ = ['a', 'b']
1181 log = []
1182 s = F()
1183 s.a = [Counted(), s]
1184 vereq(Counted.counter, 1)
1185 s = None
1186 import gc
1187 gc.collect()
1188 vereq(Counted.counter, 0)
1189
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001190 # Test lookup leaks [SF bug 572567]
1191 import sys,gc
1192 class G(object):
1193 def __cmp__(self, other):
1194 return 0
1195 g = G()
1196 orig_objects = len(gc.get_objects())
Guido van Rossum805365e2007-05-07 22:24:25 +00001197 for i in range(10):
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001198 g==g
1199 new_objects = len(gc.get_objects())
1200 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001201 class H(object):
1202 __slots__ = ['a', 'b']
1203 def __init__(self):
1204 self.a = 1
1205 self.b = 2
1206 def __del__(self):
1207 assert self.a == 1
1208 assert self.b == 2
1209
1210 save_stderr = sys.stderr
1211 sys.stderr = sys.stdout
1212 h = H()
1213 try:
1214 del h
1215 finally:
1216 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001217
Guido van Rossum8b056da2002-08-13 18:26:26 +00001218def slotspecials():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001219 if verbose: print("Testing __dict__ and __weakref__ in __slots__...")
Guido van Rossum8b056da2002-08-13 18:26:26 +00001220
1221 class D(object):
1222 __slots__ = ["__dict__"]
1223 a = D()
1224 verify(hasattr(a, "__dict__"))
1225 verify(not hasattr(a, "__weakref__"))
1226 a.foo = 42
1227 vereq(a.__dict__, {"foo": 42})
1228
1229 class W(object):
1230 __slots__ = ["__weakref__"]
1231 a = W()
1232 verify(hasattr(a, "__weakref__"))
1233 verify(not hasattr(a, "__dict__"))
1234 try:
1235 a.foo = 42
1236 except AttributeError:
1237 pass
1238 else:
1239 raise TestFailed, "shouldn't be allowed to set a.foo"
1240
1241 class C1(W, D):
1242 __slots__ = []
1243 a = C1()
1244 verify(hasattr(a, "__dict__"))
1245 verify(hasattr(a, "__weakref__"))
1246 a.foo = 42
1247 vereq(a.__dict__, {"foo": 42})
1248
1249 class C2(D, W):
1250 __slots__ = []
1251 a = C2()
1252 verify(hasattr(a, "__dict__"))
1253 verify(hasattr(a, "__weakref__"))
1254 a.foo = 42
1255 vereq(a.__dict__, {"foo": 42})
1256
Guido van Rossum9a818922002-11-14 19:50:14 +00001257# MRO order disagreement
1258#
1259# class C3(C1, C2):
1260# __slots__ = []
1261#
1262# class C4(C2, C1):
1263# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001264
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265def dynamics():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001266 if verbose: print("Testing class attribute propagation...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001269 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001271 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001274 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001276 vereq(E.foo, 1)
1277 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001278 # Test dynamic instances
1279 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001280 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001281 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001282 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001283 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001284 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001285 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001286 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001287 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001288 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001289 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001290 vereq(int(a), 100)
1291 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001292 verify(not hasattr(a, "spam"))
1293 def mygetattr(self, name):
1294 if name == "spam":
1295 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001296 raise AttributeError
1297 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001298 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001299 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001300 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001301 def mysetattr(self, name, value):
1302 if name == "spam":
1303 raise AttributeError
1304 return object.__setattr__(self, name, value)
1305 C.__setattr__ = mysetattr
1306 try:
1307 a.spam = "not spam"
1308 except AttributeError:
1309 pass
1310 else:
1311 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001312 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001313 class D(C):
1314 pass
1315 d = D()
1316 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001317 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318
Guido van Rossum7e35d572001-09-15 03:14:32 +00001319 # Test handling of int*seq and seq*int
1320 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001321 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001322 vereq("a"*I(2), "aa")
1323 vereq(I(2)*"a", "aa")
1324 vereq(2*I(3), 6)
1325 vereq(I(3)*2, 6)
1326 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001327
1328 # Test handling of long*seq and seq*long
Guido van Rossume2a383d2007-01-15 16:59:06 +00001329 class L(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001330 pass
Guido van Rossume2a383d2007-01-15 16:59:06 +00001331 vereq("a"*L(2), "aa")
1332 vereq(L(2)*"a", "aa")
Guido van Rossum45704552001-10-08 16:35:45 +00001333 vereq(2*L(3), 6)
1334 vereq(L(3)*2, 6)
1335 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001336
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001337 # Test comparison of classes with dynamic metaclasses
1338 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001339 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001340 class someclass(metaclass=dynamicmetaclass):
1341 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001342 verify(someclass != object)
1343
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344def errors():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001345 if verbose: print("Testing errors...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001346
1347 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001348 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 pass
1350 except TypeError:
1351 pass
1352 else:
1353 verify(0, "inheritance from both list and dict should be illegal")
1354
1355 try:
1356 class C(object, None):
1357 pass
1358 except TypeError:
1359 pass
1360 else:
1361 verify(0, "inheritance from non-type should be illegal")
1362 class Classic:
1363 pass
1364
1365 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001366 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367 pass
1368 except TypeError:
1369 pass
1370 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001371 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372
1373 try:
1374 class C(object):
1375 __slots__ = 1
1376 except TypeError:
1377 pass
1378 else:
1379 verify(0, "__slots__ = 1 should be illegal")
1380
1381 try:
1382 class C(object):
1383 __slots__ = [1]
1384 except TypeError:
1385 pass
1386 else:
1387 verify(0, "__slots__ = [1] should be illegal")
1388
Guido van Rossumd8faa362007-04-27 19:54:29 +00001389 class M1(type):
1390 pass
1391 class M2(type):
1392 pass
1393 class A1(object, metaclass=M1):
1394 pass
1395 class A2(object, metaclass=M2):
1396 pass
1397 try:
1398 class B(A1, A2):
1399 pass
1400 except TypeError:
1401 pass
1402 else:
1403 verify(0, "finding the most derived metaclass should have failed")
1404
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405def classmethods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001406 if verbose: print("Testing class methods...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 class C(object):
1408 def foo(*a): return a
1409 goo = classmethod(foo)
1410 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001411 vereq(C.goo(1), (C, 1))
1412 vereq(c.goo(1), (C, 1))
1413 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 class D(C):
1415 pass
1416 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001417 vereq(D.goo(1), (D, 1))
1418 vereq(d.goo(1), (D, 1))
1419 vereq(d.foo(1), (d, 1))
1420 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001421 # Test for a specific crash (SF bug 528132)
1422 def f(cls, arg): return (cls, arg)
1423 ff = classmethod(f)
1424 vereq(ff.__get__(0, int)(42), (int, 42))
1425 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426
Guido van Rossum155db9a2002-04-02 17:53:47 +00001427 # Test super() with classmethods (SF bug 535444)
1428 veris(C.goo.im_self, C)
1429 veris(D.goo.im_self, D)
1430 veris(super(D,D).goo.im_self, D)
1431 veris(super(D,d).goo.im_self, D)
1432 vereq(super(D,D).goo(), (D,))
1433 vereq(super(D,d).goo(), (D,))
1434
Raymond Hettingerbe971532003-06-18 01:13:41 +00001435 # Verify that argument is checked for callability (SF bug 753451)
1436 try:
1437 classmethod(1).__get__(1)
1438 except TypeError:
1439 pass
1440 else:
1441 raise TestFailed, "classmethod should check for callability"
1442
Georg Brandl6a29c322006-02-21 22:17:46 +00001443 # Verify that classmethod() doesn't allow keyword args
1444 try:
1445 classmethod(f, kw=1)
1446 except TypeError:
1447 pass
1448 else:
1449 raise TestFailed, "classmethod shouldn't accept keyword args"
1450
Fred Drakef841aa62002-03-28 15:49:54 +00001451def classmethods_in_c():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001452 if verbose: print("Testing C-based class methods...")
Fred Drakef841aa62002-03-28 15:49:54 +00001453 import xxsubtype as spam
1454 a = (1, 2, 3)
1455 d = {'abc': 123}
1456 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001457 veris(x, spam.spamlist)
1458 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001459 vereq(d, d1)
1460 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001461 veris(x, spam.spamlist)
1462 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001463 vereq(d, d1)
1464
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465def staticmethods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001466 if verbose: print("Testing static methods...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 class C(object):
1468 def foo(*a): return a
1469 goo = staticmethod(foo)
1470 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001471 vereq(C.goo(1), (1,))
1472 vereq(c.goo(1), (1,))
1473 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 class D(C):
1475 pass
1476 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001477 vereq(D.goo(1), (1,))
1478 vereq(d.goo(1), (1,))
1479 vereq(d.foo(1), (d, 1))
1480 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481
Fred Drakef841aa62002-03-28 15:49:54 +00001482def staticmethods_in_c():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001483 if verbose: print("Testing C-based static methods...")
Fred Drakef841aa62002-03-28 15:49:54 +00001484 import xxsubtype as spam
1485 a = (1, 2, 3)
1486 d = {"abc": 123}
1487 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1488 veris(x, None)
1489 vereq(a, a1)
1490 vereq(d, d1)
1491 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1492 veris(x, None)
1493 vereq(a, a1)
1494 vereq(d, d1)
1495
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496def classic():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001497 if verbose: print("Testing classic classes...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001498 class C:
1499 def foo(*a): return a
1500 goo = classmethod(foo)
1501 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001502 vereq(C.goo(1), (C, 1))
1503 vereq(c.goo(1), (C, 1))
1504 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001505 class D(C):
1506 pass
1507 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001508 vereq(D.goo(1), (D, 1))
1509 vereq(d.goo(1), (D, 1))
1510 vereq(d.foo(1), (d, 1))
1511 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001512 class E: # *not* subclassing from C
1513 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001514 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001515 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516
1517def compattr():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001518 if verbose: print("Testing computed attributes...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 class C(object):
1520 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001521 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522 self.__get = get
1523 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001524 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 def __get__(self, obj, type=None):
1526 return self.__get(obj)
1527 def __set__(self, obj, value):
1528 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001529 def __delete__(self, obj):
1530 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531 def __init__(self):
1532 self.__x = 0
1533 def __get_x(self):
1534 x = self.__x
1535 self.__x = x+1
1536 return x
1537 def __set_x(self, x):
1538 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001539 def __delete_x(self):
1540 del self.__x
1541 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001543 vereq(a.x, 0)
1544 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001546 vereq(a.x, 10)
1547 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001548 del a.x
1549 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550
1551def newslot():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001552 if verbose: print("Testing __new__ slot override...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 class C(list):
1554 def __new__(cls):
1555 self = list.__new__(cls)
1556 self.foo = 1
1557 return self
1558 def __init__(self):
1559 self.foo = self.foo + 2
1560 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001561 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562 verify(a.__class__ is C)
1563 class D(C):
1564 pass
1565 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001566 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 verify(b.__class__ is D)
1568
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569def altmro():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001570 if verbose: print("Testing mro() and overriding it...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 class A(object):
1572 def f(self): return "A"
1573 class B(A):
1574 pass
1575 class C(A):
1576 def f(self): return "C"
1577 class D(B, C):
1578 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001579 vereq(D.mro(), [D, B, C, A, object])
1580 vereq(D.__mro__, (D, B, C, A, object))
1581 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001582
Guido van Rossumd3077402001-08-12 05:24:18 +00001583 class PerverseMetaType(type):
1584 def mro(cls):
1585 L = type.mro(cls)
1586 L.reverse()
1587 return L
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001588 class X(D,B,C,A, metaclass=PerverseMetaType):
1589 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001590 vereq(X.__mro__, (object, A, C, B, D, X))
1591 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592
Armin Rigo037d1e02005-12-29 17:07:39 +00001593 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001594 class _metaclass(type):
1595 def mro(self):
1596 return [self, dict, object]
1597 class X(object, metaclass=_metaclass):
1598 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001599 except TypeError:
1600 pass
1601 else:
1602 raise TestFailed, "devious mro() return not caught"
1603
1604 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001605 class _metaclass(type):
1606 def mro(self):
1607 return [1]
1608 class X(object, metaclass=_metaclass):
1609 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001610 except TypeError:
1611 pass
1612 else:
1613 raise TestFailed, "non-class mro() return not caught"
1614
1615 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001616 class _metaclass(type):
1617 def mro(self):
1618 return 1
1619 class X(object, metaclass=_metaclass):
1620 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001621 except TypeError:
1622 pass
1623 else:
1624 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001625
Armin Rigo037d1e02005-12-29 17:07:39 +00001626
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627def overloading():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001628 if verbose: print("Testing operator overloading...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629
1630 class B(object):
1631 "Intermediate class because object doesn't have a __setattr__"
1632
1633 class C(B):
1634
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001635 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 if name == "foo":
1637 return ("getattr", name)
1638 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001639 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 def __setattr__(self, name, value):
1641 if name == "foo":
1642 self.setattr = (name, value)
1643 else:
1644 return B.__setattr__(self, name, value)
1645 def __delattr__(self, name):
1646 if name == "foo":
1647 self.delattr = name
1648 else:
1649 return B.__delattr__(self, name)
1650
1651 def __getitem__(self, key):
1652 return ("getitem", key)
1653 def __setitem__(self, key, value):
1654 self.setitem = (key, value)
1655 def __delitem__(self, key):
1656 self.delitem = key
1657
1658 def __getslice__(self, i, j):
1659 return ("getslice", i, j)
1660 def __setslice__(self, i, j, value):
1661 self.setslice = (i, j, value)
1662 def __delslice__(self, i, j):
1663 self.delslice = (i, j)
1664
1665 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001666 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001668 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001670 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671
Guido van Rossum45704552001-10-08 16:35:45 +00001672 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001674 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001676 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677
Guido van Rossum45704552001-10-08 16:35:45 +00001678 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001680 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001682 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001684def methods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001685 if verbose: print("Testing methods...")
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001686 class C(object):
1687 def __init__(self, x):
1688 self.x = x
1689 def foo(self):
1690 return self.x
1691 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001692 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001693 class D(C):
1694 boo = C.foo
1695 goo = c1.foo
1696 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001697 vereq(d2.foo(), 2)
1698 vereq(d2.boo(), 2)
1699 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001700 class E(object):
1701 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001702 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001703 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001704
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001705def specials():
1706 # Test operators like __hash__ for which a built-in default exists
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001707 if verbose: print("Testing special operators...")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001708 # Test the default behavior for static classes
1709 class C(object):
1710 def __getitem__(self, i):
1711 if 0 <= i < 10: return i
1712 raise IndexError
1713 c1 = C()
1714 c2 = C()
1715 verify(not not c1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001716 verify(id(c1) != id(c2))
1717 hash(c1)
1718 hash(c2)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001719 ##vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
Guido van Rossum45704552001-10-08 16:35:45 +00001720 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001721 verify(c1 != c2)
1722 verify(not c1 != c1)
1723 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001724 # Note that the module name appears in str/repr, and that varies
1725 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001726 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001727 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001728 verify(-1 not in c1)
1729 for i in range(10):
1730 verify(i in c1)
1731 verify(10 not in c1)
1732 # Test the default behavior for dynamic classes
1733 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001734 def __getitem__(self, i):
1735 if 0 <= i < 10: return i
1736 raise IndexError
1737 d1 = D()
1738 d2 = D()
1739 verify(not not d1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001740 verify(id(d1) != id(d2))
1741 hash(d1)
1742 hash(d2)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001743 ##vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
Guido van Rossum45704552001-10-08 16:35:45 +00001744 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001745 verify(d1 != d2)
1746 verify(not d1 != d1)
1747 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001748 # Note that the module name appears in str/repr, and that varies
1749 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001750 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001751 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001752 verify(-1 not in d1)
1753 for i in range(10):
1754 verify(i in d1)
1755 verify(10 not in d1)
1756 # Test overridden behavior for static classes
1757 class Proxy(object):
1758 def __init__(self, x):
1759 self.x = x
Jack Diederich4dafcc42006-11-28 19:15:13 +00001760 def __bool__(self):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001761 return not not self.x
1762 def __hash__(self):
1763 return hash(self.x)
1764 def __eq__(self, other):
1765 return self.x == other
1766 def __ne__(self, other):
1767 return self.x != other
1768 def __cmp__(self, other):
1769 return cmp(self.x, other.x)
1770 def __str__(self):
1771 return "Proxy:%s" % self.x
1772 def __repr__(self):
1773 return "Proxy(%r)" % self.x
1774 def __contains__(self, value):
1775 return value in self.x
1776 p0 = Proxy(0)
1777 p1 = Proxy(1)
1778 p_1 = Proxy(-1)
1779 verify(not p0)
1780 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001781 vereq(hash(p0), hash(0))
1782 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001783 verify(p0 != p1)
1784 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001785 vereq(not p0, p1)
1786 vereq(cmp(p0, p1), -1)
1787 vereq(cmp(p0, p0), 0)
1788 vereq(cmp(p0, p_1), 1)
1789 vereq(str(p0), "Proxy:0")
1790 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001791 p10 = Proxy(range(10))
1792 verify(-1 not in p10)
1793 for i in range(10):
1794 verify(i in p10)
1795 verify(10 not in p10)
1796 # Test overridden behavior for dynamic classes
1797 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001798 def __init__(self, x):
1799 self.x = x
Jack Diederich4dafcc42006-11-28 19:15:13 +00001800 def __bool__(self):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001801 return not not self.x
1802 def __hash__(self):
1803 return hash(self.x)
1804 def __eq__(self, other):
1805 return self.x == other
1806 def __ne__(self, other):
1807 return self.x != other
1808 def __cmp__(self, other):
1809 return cmp(self.x, other.x)
1810 def __str__(self):
1811 return "DProxy:%s" % self.x
1812 def __repr__(self):
1813 return "DProxy(%r)" % self.x
1814 def __contains__(self, value):
1815 return value in self.x
1816 p0 = DProxy(0)
1817 p1 = DProxy(1)
1818 p_1 = DProxy(-1)
1819 verify(not p0)
1820 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001821 vereq(hash(p0), hash(0))
1822 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001823 verify(p0 != p1)
1824 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001825 vereq(not p0, p1)
1826 vereq(cmp(p0, p1), -1)
1827 vereq(cmp(p0, p0), 0)
1828 vereq(cmp(p0, p_1), 1)
1829 vereq(str(p0), "DProxy:0")
1830 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001831 p10 = DProxy(range(10))
1832 verify(-1 not in p10)
1833 for i in range(10):
1834 verify(i in p10)
1835 verify(10 not in p10)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001836## # Safety test for __cmp__
1837## def unsafecmp(a, b):
1838## try:
1839## a.__class__.__cmp__(a, b)
1840## except TypeError:
1841## pass
1842## else:
1843## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1844## a.__class__, a, b)
1845## unsafecmp(u"123", "123")
1846## unsafecmp("123", u"123")
1847## unsafecmp(1, 1.0)
1848## unsafecmp(1.0, 1)
1849## unsafecmp(1, 1L)
1850## unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001851
Neal Norwitz1a997502003-01-13 20:13:12 +00001852 class Letter(str):
1853 def __new__(cls, letter):
1854 if letter == 'EPS':
1855 return str.__new__(cls)
1856 return str.__new__(cls, letter)
1857 def __str__(self):
1858 if not self:
1859 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001860 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001861
1862 # sys.stdout needs to be the original to trigger the recursion bug
1863 import sys
1864 test_stdout = sys.stdout
1865 sys.stdout = get_original_stdout()
1866 try:
1867 # nothing should actually be printed, this should raise an exception
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001868 print(Letter('w'))
Neal Norwitz1a997502003-01-13 20:13:12 +00001869 except RuntimeError:
1870 pass
1871 else:
1872 raise TestFailed, "expected a RuntimeError for print recursion"
1873 sys.stdout = test_stdout
1874
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001875def weakrefs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001876 if verbose: print("Testing weak references...")
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001877 import weakref
1878 class C(object):
1879 pass
1880 c = C()
1881 r = weakref.ref(c)
1882 verify(r() is c)
1883 del c
1884 verify(r() is None)
1885 del r
1886 class NoWeak(object):
1887 __slots__ = ['foo']
1888 no = NoWeak()
1889 try:
1890 weakref.ref(no)
Guido van Rossumb940e112007-01-10 16:19:56 +00001891 except TypeError as msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001892 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001893 else:
1894 verify(0, "weakref.ref(no) should be illegal")
1895 class Weak(object):
1896 __slots__ = ['foo', '__weakref__']
1897 yes = Weak()
1898 r = weakref.ref(yes)
1899 verify(r() is yes)
1900 del yes
1901 verify(r() is None)
1902 del r
1903
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001904def properties():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001905 if verbose: print("Testing property...")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001906 class C(object):
1907 def getx(self):
1908 return self.__x
1909 def setx(self, value):
1910 self.__x = value
1911 def delx(self):
1912 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001913 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001914 a = C()
1915 verify(not hasattr(a, "x"))
1916 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001917 vereq(a._C__x, 42)
1918 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001919 del a.x
1920 verify(not hasattr(a, "x"))
1921 verify(not hasattr(a, "_C__x"))
1922 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001923 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001924 C.x.__delete__(a)
1925 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001926
Tim Peters66c1a522001-09-24 21:17:50 +00001927 raw = C.__dict__['x']
1928 verify(isinstance(raw, property))
1929
1930 attrs = dir(raw)
1931 verify("__doc__" in attrs)
1932 verify("fget" in attrs)
1933 verify("fset" in attrs)
1934 verify("fdel" in attrs)
1935
Guido van Rossum45704552001-10-08 16:35:45 +00001936 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001937 verify(raw.fget is C.__dict__['getx'])
1938 verify(raw.fset is C.__dict__['setx'])
1939 verify(raw.fdel is C.__dict__['delx'])
1940
1941 for attr in "__doc__", "fget", "fset", "fdel":
1942 try:
1943 setattr(raw, attr, 42)
Collin Winter42dae6a2007-03-28 21:44:53 +00001944 except AttributeError as msg:
Tim Peters66c1a522001-09-24 21:17:50 +00001945 if str(msg).find('readonly') < 0:
1946 raise TestFailed("when setting readonly attr %r on a "
Collin Winter42dae6a2007-03-28 21:44:53 +00001947 "property, got unexpected AttributeError "
Tim Peters66c1a522001-09-24 21:17:50 +00001948 "msg %r" % (attr, str(msg)))
1949 else:
Collin Winter42dae6a2007-03-28 21:44:53 +00001950 raise TestFailed("expected AttributeError from trying to set "
Tim Peters66c1a522001-09-24 21:17:50 +00001951 "readonly %r attr on a property" % attr)
1952
Neal Norwitz673cd822002-10-18 16:33:13 +00001953 class D(object):
1954 __getitem__ = property(lambda s: 1/0)
1955
1956 d = D()
1957 try:
1958 for i in d:
1959 str(i)
1960 except ZeroDivisionError:
1961 pass
1962 else:
1963 raise TestFailed, "expected ZeroDivisionError from bad property"
1964
Georg Brandl533ff6f2006-03-08 18:09:27 +00001965 class E(object):
1966 def getter(self):
1967 "getter method"
1968 return 0
1969 def setter(self, value):
1970 "setter method"
1971 pass
1972 prop = property(getter)
1973 vereq(prop.__doc__, "getter method")
1974 prop2 = property(fset=setter)
1975 vereq(prop2.__doc__, None)
1976
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001977 # this segfaulted in 2.5b2
1978 try:
1979 import _testcapi
1980 except ImportError:
1981 pass
1982 else:
1983 class X(object):
1984 p = property(_testcapi.test_with_docstring)
1985
1986
Guido van Rossumc4a18802001-08-24 16:55:27 +00001987def supers():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001988 if verbose: print("Testing super...")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001989
1990 class A(object):
1991 def meth(self, a):
1992 return "A(%r)" % a
1993
Guido van Rossum45704552001-10-08 16:35:45 +00001994 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001995
1996 class B(A):
1997 def __init__(self):
1998 self.__super = super(B, self)
1999 def meth(self, a):
2000 return "B(%r)" % a + self.__super.meth(a)
2001
Guido van Rossum45704552001-10-08 16:35:45 +00002002 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002003
2004 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002005 def meth(self, a):
2006 return "C(%r)" % a + self.__super.meth(a)
2007 C._C__super = super(C)
2008
Guido van Rossum45704552001-10-08 16:35:45 +00002009 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002010
2011 class D(C, B):
2012 def meth(self, a):
2013 return "D(%r)" % a + super(D, self).meth(a)
2014
Guido van Rossum5b443c62001-12-03 15:38:28 +00002015 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2016
2017 # Test for subclassing super
2018
2019 class mysuper(super):
2020 def __init__(self, *args):
2021 return super(mysuper, self).__init__(*args)
2022
2023 class E(D):
2024 def meth(self, a):
2025 return "E(%r)" % a + mysuper(E, self).meth(a)
2026
2027 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2028
2029 class F(E):
2030 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002031 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002032 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2033 F._F__super = mysuper(F)
2034
2035 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2036
2037 # Make sure certain errors are raised
2038
2039 try:
2040 super(D, 42)
2041 except TypeError:
2042 pass
2043 else:
2044 raise TestFailed, "shouldn't allow super(D, 42)"
2045
2046 try:
2047 super(D, C())
2048 except TypeError:
2049 pass
2050 else:
2051 raise TestFailed, "shouldn't allow super(D, C())"
2052
2053 try:
2054 super(D).__get__(12)
2055 except TypeError:
2056 pass
2057 else:
2058 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2059
2060 try:
2061 super(D).__get__(C())
2062 except TypeError:
2063 pass
2064 else:
2065 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002066
Guido van Rossuma4541a32003-04-16 20:02:22 +00002067 # Make sure data descriptors can be overridden and accessed via super
2068 # (new feature in Python 2.3)
2069
2070 class DDbase(object):
2071 def getx(self): return 42
2072 x = property(getx)
2073
2074 class DDsub(DDbase):
2075 def getx(self): return "hello"
2076 x = property(getx)
2077
2078 dd = DDsub()
2079 vereq(dd.x, "hello")
2080 vereq(super(DDsub, dd).x, 42)
2081
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002082 # Ensure that super() lookup of descriptor from classmethod
2083 # works (SF ID# 743627)
2084
2085 class Base(object):
2086 aProp = property(lambda self: "foo")
2087
2088 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002089 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002090 def test(klass):
2091 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002092
2093 veris(Sub.test(), Base.aProp)
2094
Thomas Wouters89f507f2006-12-13 04:49:30 +00002095 # Verify that super() doesn't allow keyword args
2096 try:
2097 super(Base, kw=1)
2098 except TypeError:
2099 pass
2100 else:
2101 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002102
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002103def inherits():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002104 if verbose: print("Testing inheritance from basic types...")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002105
2106 class hexint(int):
2107 def __repr__(self):
2108 return hex(self)
2109 def __add__(self, other):
2110 return hexint(int.__add__(self, other))
2111 # (Note that overriding __radd__ doesn't work,
2112 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002113 vereq(repr(hexint(7) + 9), "0x10")
2114 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002115 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002116 vereq(a, 12345)
2117 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002118 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002119 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002120 verify((+a).__class__ is int)
2121 verify((a >> 0).__class__ is int)
2122 verify((a << 0).__class__ is int)
2123 verify((hexint(0) << 12).__class__ is int)
2124 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002125
Guido van Rossume2a383d2007-01-15 16:59:06 +00002126 class octlong(int):
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002127 __slots__ = []
2128 def __str__(self):
2129 s = oct(self)
2130 if s[-1] == 'L':
2131 s = s[:-1]
2132 return s
2133 def __add__(self, other):
2134 return self.__class__(super(octlong, self).__add__(other))
2135 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002136 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002137 # (Note that overriding __radd__ here only seems to work
2138 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002139 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002140 a = octlong(12345)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002141 vereq(a, 12345)
2142 vereq(int(a), 12345)
2143 vereq(hash(a), hash(12345))
2144 verify(int(a).__class__ is int)
2145 verify((+a).__class__ is int)
2146 verify((-a).__class__ is int)
2147 verify((-octlong(0)).__class__ is int)
2148 verify((a >> 0).__class__ is int)
2149 verify((a << 0).__class__ is int)
2150 verify((a - 0).__class__ is int)
2151 verify((a * 1).__class__ is int)
2152 verify((a ** 1).__class__ is int)
2153 verify((a // 1).__class__ is int)
2154 verify((1 * a).__class__ is int)
2155 verify((a | 0).__class__ is int)
2156 verify((a ^ 0).__class__ is int)
2157 verify((a & -1).__class__ is int)
2158 verify((octlong(0) << 12).__class__ is int)
2159 verify((octlong(0) >> 12).__class__ is int)
2160 verify(abs(octlong(0)).__class__ is int)
Tim Peters69c2de32001-09-11 22:31:33 +00002161
2162 # Because octlong overrides __add__, we can't check the absence of +0
2163 # optimizations using octlong.
Guido van Rossume2a383d2007-01-15 16:59:06 +00002164 class longclone(int):
Tim Peters69c2de32001-09-11 22:31:33 +00002165 pass
2166 a = longclone(1)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002167 verify((a + 0).__class__ is int)
2168 verify((0 + a).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002169
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002170 # Check that negative clones don't segfault
2171 a = longclone(-1)
2172 vereq(a.__dict__, {})
Guido van Rossume2a383d2007-01-15 16:59:06 +00002173 vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002174
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002175 class precfloat(float):
2176 __slots__ = ['prec']
2177 def __init__(self, value=0.0, prec=12):
2178 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002179 def __repr__(self):
2180 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002181 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002182 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002183 vereq(a, 12345.0)
2184 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002185 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002186 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002187 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002188
Tim Peters2400fa42001-09-12 19:12:49 +00002189 class madcomplex(complex):
2190 def __repr__(self):
2191 return "%.17gj%+.17g" % (self.imag, self.real)
2192 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002193 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002194 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002195 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002196 vereq(a, base)
2197 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002198 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002199 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002200 vereq(repr(a), "4j-3")
2201 vereq(a, base)
2202 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002203 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002204 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002205 veris((+a).__class__, complex)
2206 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 - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002209 vereq(a - 0, 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)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002212 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002213 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002214
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002215 class madtuple(tuple):
2216 _rev = None
2217 def rev(self):
2218 if self._rev is not None:
2219 return self._rev
2220 L = list(self)
2221 L.reverse()
2222 self._rev = self.__class__(L)
2223 return self._rev
2224 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002225 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2226 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2227 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002228 for i in range(512):
2229 t = madtuple(range(i))
2230 u = t.rev()
2231 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002232 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002233 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002234 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002235 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002236 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002237 verify(a[:].__class__ is tuple)
2238 verify((a * 1).__class__ is tuple)
2239 verify((a * 0).__class__ is tuple)
2240 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002241 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002242 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002243 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002244 verify((a + a).__class__ is tuple)
2245 verify((a * 0).__class__ is tuple)
2246 verify((a * 1).__class__ is tuple)
2247 verify((a * 2).__class__ is tuple)
2248 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002249
2250 class madstring(str):
2251 _rev = None
2252 def rev(self):
2253 if self._rev is not None:
2254 return self._rev
2255 L = list(self)
2256 L.reverse()
2257 self._rev = self.__class__("".join(L))
2258 return self._rev
2259 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002260 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2261 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2262 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002263 for i in range(256):
2264 s = madstring("".join(map(chr, range(i))))
2265 t = s.rev()
2266 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002267 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002268 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002269 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002270 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002271
Tim Peters8fa5dd02001-09-12 02:18:30 +00002272 base = "\x00" * 5
2273 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002274 vereq(s, base)
2275 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002276 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002277 vereq(hash(s), hash(base))
2278 vereq({s: 1}[base], 1)
2279 vereq({base: 1}[s], 1)
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).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002283 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002284 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002285 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002286 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002287 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002288 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002289 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002290 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002291 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002292 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002293 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002294 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002295 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002296 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002297 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002298 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002299 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002300 identitytab = ''.join([chr(i) for i in range(256)])
2301 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002302 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002303 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002304 vereq(s.translate(identitytab, "x"), base)
2305 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002306 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002308 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002309 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002310 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002312 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002313 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002314 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002315 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002316
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002317 class madunicode(str):
Guido van Rossum91ee7982001-08-30 20:52:40 +00002318 _rev = None
2319 def rev(self):
2320 if self._rev is not None:
2321 return self._rev
2322 L = list(self)
2323 L.reverse()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002324 self._rev = self.__class__("".join(L))
Guido van Rossum91ee7982001-08-30 20:52:40 +00002325 return self._rev
2326 u = madunicode("ABCDEF")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002327 vereq(u, "ABCDEF")
2328 vereq(u.rev(), madunicode("FEDCBA"))
2329 vereq(u.rev().rev(), madunicode("ABCDEF"))
2330 base = "12345"
Tim Peters7a29bd52001-09-12 03:03:31 +00002331 u = madunicode(base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002332 vereq(str(u), base)
2333 verify(str(u).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002334 vereq(hash(u), hash(base))
2335 vereq({u: 1}[base], 1)
2336 vereq({base: 1}[u], 1)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002337 verify(u.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002338 vereq(u.strip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002339 verify(u.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002340 vereq(u.lstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002341 verify(u.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002342 vereq(u.rstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002343 verify(u.replace("x", "x").__class__ is str)
2344 vereq(u.replace("x", "x"), base)
2345 verify(u.replace("xy", "xy").__class__ is str)
2346 vereq(u.replace("xy", "xy"), base)
2347 verify(u.center(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002348 vereq(u.center(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002349 verify(u.ljust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002350 vereq(u.ljust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002351 verify(u.rjust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002352 vereq(u.rjust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002353 verify(u.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002354 vereq(u.lower(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002355 verify(u.upper().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002356 vereq(u.upper(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002357 verify(u.capitalize().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002358 vereq(u.capitalize(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002359 verify(u.title().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002360 vereq(u.title(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002361 verify((u + "").__class__ is str)
2362 vereq(u + "", base)
2363 verify(("" + u).__class__ is str)
2364 vereq("" + u, base)
2365 verify((u * 0).__class__ is str)
2366 vereq(u * 0, "")
2367 verify((u * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002368 vereq(u * 1, base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002369 verify((u * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002370 vereq(u * 2, base + base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002371 verify(u[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002372 vereq(u[:], base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002373 verify(u[0:0].__class__ is str)
2374 vereq(u[0:0], "")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002375
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002376 class sublist(list):
2377 pass
2378 a = sublist(range(5))
Guido van Rossum805365e2007-05-07 22:24:25 +00002379 vereq(a, list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002380 a.append("hello")
Guido van Rossum805365e2007-05-07 22:24:25 +00002381 vereq(a, list(range(5)) + ["hello"])
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002382 a[5] = 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002383 vereq(a, list(range(6)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002384 a.extend(range(6, 20))
Guido van Rossum805365e2007-05-07 22:24:25 +00002385 vereq(a, list(range(20)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002386 a[-5:] = []
Guido van Rossum805365e2007-05-07 22:24:25 +00002387 vereq(a, list(range(15)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002388 del a[10:15]
2389 vereq(len(a), 10)
Guido van Rossum805365e2007-05-07 22:24:25 +00002390 vereq(a, list(range(10)))
2391 vereq(list(a), list(range(10)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002392 vereq(a[0], 0)
2393 vereq(a[9], 9)
2394 vereq(a[-10], 0)
2395 vereq(a[-1], 9)
Guido van Rossum805365e2007-05-07 22:24:25 +00002396 vereq(a[:5], list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002397
Tim Peters59c9a642001-09-13 05:38:56 +00002398 class CountedInput(file):
2399 """Counts lines read by self.readline().
2400
2401 self.lineno is the 0-based ordinal of the last line read, up to
2402 a maximum of one greater than the number of lines in the file.
2403
2404 self.ateof is true if and only if the final "" line has been read,
2405 at which point self.lineno stops incrementing, and further calls
2406 to readline() continue to return "".
2407 """
2408
2409 lineno = 0
2410 ateof = 0
2411 def readline(self):
2412 if self.ateof:
2413 return ""
2414 s = file.readline(self)
2415 # Next line works too.
2416 # s = super(CountedInput, self).readline()
2417 self.lineno += 1
2418 if s == "":
2419 self.ateof = 1
2420 return s
2421
Alex Martelli01c77c62006-08-24 02:58:11 +00002422 f = open(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002423 lines = ['a\n', 'b\n', 'c\n']
2424 try:
2425 f.writelines(lines)
2426 f.close()
2427 f = CountedInput(TESTFN)
Guido van Rossum805365e2007-05-07 22:24:25 +00002428 for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]):
Tim Peters59c9a642001-09-13 05:38:56 +00002429 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002430 vereq(expected, got)
2431 vereq(f.lineno, i)
2432 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002433 f.close()
2434 finally:
2435 try:
2436 f.close()
2437 except:
2438 pass
2439 try:
2440 import os
2441 os.unlink(TESTFN)
2442 except:
2443 pass
2444
Tim Peters808b94e2001-09-13 19:33:07 +00002445def keywords():
2446 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002447 print("Testing keyword args to basic type constructors ...")
Guido van Rossum45704552001-10-08 16:35:45 +00002448 vereq(int(x=1), 1)
2449 vereq(float(x=2), 2.0)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002450 vereq(int(x=3), 3)
Guido van Rossum45704552001-10-08 16:35:45 +00002451 vereq(complex(imag=42, real=666), complex(666, 42))
2452 vereq(str(object=500), '500')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002453 vereq(str(string='abc', errors='strict'), 'abc')
Guido van Rossum45704552001-10-08 16:35:45 +00002454 vereq(tuple(sequence=range(3)), (0, 1, 2))
Guido van Rossum805365e2007-05-07 22:24:25 +00002455 vereq(list(sequence=(0, 1, 2)), list(range(3)))
Just van Rossuma797d812002-11-23 09:45:04 +00002456 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002457
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002458 for constructor in (int, float, int, complex, str, str,
Just van Rossuma797d812002-11-23 09:45:04 +00002459 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002460 try:
2461 constructor(bogus_keyword_arg=1)
2462 except TypeError:
2463 pass
2464 else:
2465 raise TestFailed("expected TypeError from bogus keyword "
2466 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002467
Tim Peters0ab085c2001-09-14 00:25:33 +00002468def str_subclass_as_dict_key():
2469 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002470 print("Testing a str subclass used as dict key ..")
Tim Peters0ab085c2001-09-14 00:25:33 +00002471
2472 class cistr(str):
2473 """Sublcass of str that computes __eq__ case-insensitively.
2474
2475 Also computes a hash code of the string in canonical form.
2476 """
2477
2478 def __init__(self, value):
2479 self.canonical = value.lower()
2480 self.hashcode = hash(self.canonical)
2481
2482 def __eq__(self, other):
2483 if not isinstance(other, cistr):
2484 other = cistr(other)
2485 return self.canonical == other.canonical
2486
2487 def __hash__(self):
2488 return self.hashcode
2489
Guido van Rossum45704552001-10-08 16:35:45 +00002490 vereq(cistr('ABC'), 'abc')
2491 vereq('aBc', cistr('ABC'))
2492 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002493
2494 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002495 vereq(d[cistr('one')], 1)
2496 vereq(d[cistr('tWo')], 2)
2497 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002498 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002499 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002500
Guido van Rossumab3b0342001-09-18 20:38:53 +00002501def classic_comparisons():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002502 if verbose: print("Testing classic comparisons...")
Guido van Rossum0639f592001-09-18 21:06:04 +00002503 class classic:
2504 pass
2505 for base in (classic, int, object):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002506 if verbose: print(" (base = %s)" % base)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002507 class C(base):
2508 def __init__(self, value):
2509 self.value = int(value)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002510 def __eq__(self, other):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002511 if isinstance(other, C):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002512 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002513 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002514 return self.value == other
Guido van Rossumab3b0342001-09-18 20:38:53 +00002515 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002516 def __ne__(self, other):
2517 if isinstance(other, C):
2518 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002519 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002520 return self.value != other
2521 return NotImplemented
2522 def __lt__(self, other):
2523 if isinstance(other, C):
2524 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002525 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002526 return self.value < other
2527 return NotImplemented
2528 def __le__(self, other):
2529 if isinstance(other, C):
2530 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002531 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002532 return self.value <= other
2533 return NotImplemented
2534 def __gt__(self, other):
2535 if isinstance(other, C):
2536 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002537 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002538 return self.value > other
2539 return NotImplemented
2540 def __ge__(self, other):
2541 if isinstance(other, C):
2542 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002543 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002544 return self.value >= other
2545 return NotImplemented
2546
Guido van Rossumab3b0342001-09-18 20:38:53 +00002547 c1 = C(1)
2548 c2 = C(2)
2549 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002550 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002551 c = {1: c1, 2: c2, 3: c3}
2552 for x in 1, 2, 3:
2553 for y in 1, 2, 3:
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002554 ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002555 for op in "<", "<=", "==", "!=", ">", ">=":
2556 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2557 "x=%d, y=%d" % (x, y))
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002558 ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2559 ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002560
Guido van Rossum0639f592001-09-18 21:06:04 +00002561def rich_comparisons():
2562 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002563 print("Testing rich comparisons...")
Guido van Rossum22056422001-09-24 17:52:04 +00002564 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002565 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002566 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002567 vereq(z, 1+0j)
2568 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002569 class ZZ(complex):
2570 def __eq__(self, other):
2571 try:
2572 return abs(self - other) <= 1e-6
2573 except:
2574 return NotImplemented
2575 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002576 vereq(zz, 1+0j)
2577 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002578
Guido van Rossum0639f592001-09-18 21:06:04 +00002579 class classic:
2580 pass
2581 for base in (classic, int, object, list):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002582 if verbose: print(" (base = %s)" % base)
Guido van Rossum0639f592001-09-18 21:06:04 +00002583 class C(base):
2584 def __init__(self, value):
2585 self.value = int(value)
2586 def __cmp__(self, other):
2587 raise TestFailed, "shouldn't call __cmp__"
2588 def __eq__(self, other):
2589 if isinstance(other, C):
2590 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002591 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002592 return self.value == other
2593 return NotImplemented
2594 def __ne__(self, other):
2595 if isinstance(other, C):
2596 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002597 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002598 return self.value != other
2599 return NotImplemented
2600 def __lt__(self, other):
2601 if isinstance(other, C):
2602 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002603 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002604 return self.value < other
2605 return NotImplemented
2606 def __le__(self, other):
2607 if isinstance(other, C):
2608 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002609 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002610 return self.value <= other
2611 return NotImplemented
2612 def __gt__(self, other):
2613 if isinstance(other, C):
2614 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002615 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002616 return self.value > other
2617 return NotImplemented
2618 def __ge__(self, other):
2619 if isinstance(other, C):
2620 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002621 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002622 return self.value >= other
2623 return NotImplemented
2624 c1 = C(1)
2625 c2 = C(2)
2626 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002627 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002628 c = {1: c1, 2: c2, 3: c3}
2629 for x in 1, 2, 3:
2630 for y in 1, 2, 3:
2631 for op in "<", "<=", "==", "!=", ">", ">=":
2632 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2633 "x=%d, y=%d" % (x, y))
2634 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2635 "x=%d, y=%d" % (x, y))
2636 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2637 "x=%d, y=%d" % (x, y))
2638
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002639def descrdoc():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002640 if verbose: print("Testing descriptor doc strings...")
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002641 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002642 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002643 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002644 check(file.name, "file name") # member descriptor
2645
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002646def setclass():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002647 if verbose: print("Testing __class__ assignment...")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002648 class C(object): pass
2649 class D(object): pass
2650 class E(object): pass
2651 class F(D, E): pass
2652 for cls in C, D, E, F:
2653 for cls2 in C, D, E, F:
2654 x = cls()
2655 x.__class__ = cls2
2656 verify(x.__class__ is cls2)
2657 x.__class__ = cls
2658 verify(x.__class__ is cls)
2659 def cant(x, C):
2660 try:
2661 x.__class__ = C
2662 except TypeError:
2663 pass
2664 else:
2665 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002666 try:
2667 delattr(x, "__class__")
2668 except TypeError:
2669 pass
2670 else:
2671 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002672 cant(C(), list)
2673 cant(list(), C)
2674 cant(C(), 1)
2675 cant(C(), object)
2676 cant(object(), list)
2677 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002678 class Int(int): __slots__ = []
2679 cant(2, Int)
2680 cant(Int(), int)
2681 cant(True, int)
2682 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002683 o = object()
2684 cant(o, type(1))
2685 cant(o, type(None))
2686 del o
Guido van Rossumd8faa362007-04-27 19:54:29 +00002687 class G(object):
2688 __slots__ = ["a", "b"]
2689 class H(object):
2690 __slots__ = ["b", "a"]
Walter Dörwald5de48bd2007-06-11 21:38:39 +00002691 class I(object):
2692 __slots__ = ["a", "b"]
Guido van Rossumd8faa362007-04-27 19:54:29 +00002693 class J(object):
2694 __slots__ = ["c", "b"]
2695 class K(object):
2696 __slots__ = ["a", "b", "d"]
2697 class L(H):
2698 __slots__ = ["e"]
2699 class M(I):
2700 __slots__ = ["e"]
2701 class N(J):
2702 __slots__ = ["__weakref__"]
2703 class P(J):
2704 __slots__ = ["__dict__"]
2705 class Q(J):
2706 pass
2707 class R(J):
2708 __slots__ = ["__dict__", "__weakref__"]
2709
2710 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2711 x = cls()
2712 x.a = 1
2713 x.__class__ = cls2
2714 verify(x.__class__ is cls2,
2715 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2716 vereq(x.a, 1)
2717 x.__class__ = cls
2718 verify(x.__class__ is cls,
2719 "assigning %r as __class__ for %r silently failed" % (cls, x))
2720 vereq(x.a, 1)
2721 for cls in G, J, K, L, M, N, P, R, list, Int:
2722 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2723 if cls is cls2:
2724 continue
2725 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002726
Guido van Rossum6661be32001-10-26 04:26:12 +00002727def setdict():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002728 if verbose: print("Testing __dict__ assignment...")
Guido van Rossum6661be32001-10-26 04:26:12 +00002729 class C(object): pass
2730 a = C()
2731 a.__dict__ = {'b': 1}
2732 vereq(a.b, 1)
2733 def cant(x, dict):
2734 try:
2735 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002736 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002737 pass
2738 else:
2739 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2740 cant(a, None)
2741 cant(a, [])
2742 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002743 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum360e4b82007-05-14 22:51:27 +00002744
2745 class Base(object):
2746 pass
2747 def verify_dict_readonly(x):
2748 """
2749 x has to be an instance of a class inheriting from Base.
2750 """
2751 cant(x, {})
2752 try:
2753 del x.__dict__
2754 except (AttributeError, TypeError):
2755 pass
2756 else:
2757 raise TestFailed, "shouldn't allow del %r.__dict__" % x
2758 dict_descr = Base.__dict__["__dict__"]
2759 try:
2760 dict_descr.__set__(x, {})
2761 except (AttributeError, TypeError):
2762 pass
2763 else:
2764 raise TestFailed, "dict_descr allowed access to %r's dict" % x
2765
2766 # Classes don't allow __dict__ assignment and have readonly dicts
2767 class Meta1(type, Base):
2768 pass
2769 class Meta2(Base, type):
2770 pass
2771 class D(object):
2772 __metaclass__ = Meta1
2773 class E(object):
2774 __metaclass__ = Meta2
2775 for cls in C, D, E:
2776 verify_dict_readonly(cls)
2777 class_dict = cls.__dict__
2778 try:
2779 class_dict["spam"] = "eggs"
2780 except TypeError:
2781 pass
2782 else:
2783 raise TestFailed, "%r's __dict__ can be modified" % cls
2784
2785 # Modules also disallow __dict__ assignment
2786 class Module1(types.ModuleType, Base):
2787 pass
2788 class Module2(Base, types.ModuleType):
2789 pass
2790 for ModuleType in Module1, Module2:
2791 mod = ModuleType("spam")
2792 verify_dict_readonly(mod)
2793 mod.__dict__["spam"] = "eggs"
2794
2795 # Exception's __dict__ can be replaced, but not deleted
2796 class Exception1(Exception, Base):
2797 pass
2798 class Exception2(Base, Exception):
2799 pass
2800 for ExceptionType in Exception, Exception1, Exception2:
2801 e = ExceptionType()
2802 e.__dict__ = {"a": 1}
2803 vereq(e.a, 1)
2804 try:
2805 del e.__dict__
2806 except (TypeError, AttributeError):
2807 pass
2808 else:
2809 raise TestFaied, "%r's __dict__ can be deleted" % e
2810
Guido van Rossum6661be32001-10-26 04:26:12 +00002811
Guido van Rossum3926a632001-09-25 16:25:58 +00002812def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002813 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002814 print("Testing pickling and copying new-style classes and objects...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002815 import pickle
2816 try:
2817 import cPickle
2818 except ImportError:
2819 cPickle = None
Guido van Rossum3926a632001-09-25 16:25:58 +00002820
2821 def sorteditems(d):
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002822 return sorted(d.items())
Guido van Rossum3926a632001-09-25 16:25:58 +00002823
2824 global C
2825 class C(object):
2826 def __init__(self, a, b):
2827 super(C, self).__init__()
2828 self.a = a
2829 self.b = b
2830 def __repr__(self):
2831 return "C(%r, %r)" % (self.a, self.b)
2832
2833 global C1
2834 class C1(list):
2835 def __new__(cls, a, b):
2836 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002837 def __getnewargs__(self):
2838 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002839 def __init__(self, a, b):
2840 self.a = a
2841 self.b = b
2842 def __repr__(self):
2843 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2844
2845 global C2
2846 class C2(int):
2847 def __new__(cls, a, b, val=0):
2848 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002849 def __getnewargs__(self):
2850 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002851 def __init__(self, a, b, val=0):
2852 self.a = a
2853 self.b = b
2854 def __repr__(self):
2855 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2856
Guido van Rossum90c45142001-11-24 21:07:01 +00002857 global C3
2858 class C3(object):
2859 def __init__(self, foo):
2860 self.foo = foo
2861 def __getstate__(self):
2862 return self.foo
2863 def __setstate__(self, foo):
2864 self.foo = foo
2865
2866 global C4classic, C4
2867 class C4classic: # classic
2868 pass
2869 class C4(C4classic, object): # mixed inheritance
2870 pass
2871
Guido van Rossum3926a632001-09-25 16:25:58 +00002872 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002873 if p is None:
2874 continue # cPickle not found -- skip it
Guido van Rossum3926a632001-09-25 16:25:58 +00002875 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002876 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002877 print(p.__name__, ["text", "binary"][bin])
Guido van Rossum3926a632001-09-25 16:25:58 +00002878
2879 for cls in C, C1, C2:
2880 s = p.dumps(cls, bin)
2881 cls2 = p.loads(s)
2882 verify(cls2 is cls)
2883
2884 a = C1(1, 2); a.append(42); a.append(24)
2885 b = C2("hello", "world", 42)
2886 s = p.dumps((a, b), bin)
2887 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002888 vereq(x.__class__, a.__class__)
2889 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2890 vereq(y.__class__, b.__class__)
2891 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002892 vereq(repr(x), repr(a))
2893 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002894 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002895 print("a = x =", a)
2896 print("b = y =", b)
Guido van Rossum90c45142001-11-24 21:07:01 +00002897 # Test for __getstate__ and __setstate__ on new style class
2898 u = C3(42)
2899 s = p.dumps(u, bin)
2900 v = p.loads(s)
2901 veris(u.__class__, v.__class__)
2902 vereq(u.foo, v.foo)
2903 # Test for picklability of hybrid class
2904 u = C4()
2905 u.foo = 42
2906 s = p.dumps(u, bin)
2907 v = p.loads(s)
2908 veris(u.__class__, v.__class__)
2909 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002910
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002911 # Testing copy.deepcopy()
2912 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002913 print("deepcopy")
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002914 import copy
2915 for cls in C, C1, C2:
2916 cls2 = copy.deepcopy(cls)
2917 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002918
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002919 a = C1(1, 2); a.append(42); a.append(24)
2920 b = C2("hello", "world", 42)
2921 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002922 vereq(x.__class__, a.__class__)
2923 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2924 vereq(y.__class__, b.__class__)
2925 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002926 vereq(repr(x), repr(a))
2927 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002928 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002929 print("a = x =", a)
2930 print("b = y =", b)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002931
Guido van Rossum8c842552002-03-14 23:05:54 +00002932def pickleslots():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002933 if verbose: print("Testing pickling of classes with __slots__ ...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002934 import pickle, pickle as cPickle
Guido van Rossum8c842552002-03-14 23:05:54 +00002935 # Pickling of classes with __slots__ but without __getstate__ should fail
2936 global B, C, D, E
2937 class B(object):
2938 pass
2939 for base in [object, B]:
2940 class C(base):
2941 __slots__ = ['a']
2942 class D(C):
2943 pass
2944 try:
2945 pickle.dumps(C())
2946 except TypeError:
2947 pass
2948 else:
2949 raise TestFailed, "should fail: pickle C instance - %s" % base
2950 try:
2951 cPickle.dumps(C())
2952 except TypeError:
2953 pass
2954 else:
2955 raise TestFailed, "should fail: cPickle C instance - %s" % base
2956 try:
2957 pickle.dumps(C())
2958 except TypeError:
2959 pass
2960 else:
2961 raise TestFailed, "should fail: pickle D instance - %s" % base
2962 try:
2963 cPickle.dumps(D())
2964 except TypeError:
2965 pass
2966 else:
2967 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002968 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002969 class C(base):
2970 __slots__ = ['a']
2971 def __getstate__(self):
2972 try:
2973 d = self.__dict__.copy()
2974 except AttributeError:
2975 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002976 for cls in self.__class__.__mro__:
2977 for sn in cls.__dict__.get('__slots__', ()):
2978 try:
2979 d[sn] = getattr(self, sn)
2980 except AttributeError:
2981 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002982 return d
2983 def __setstate__(self, d):
2984 for k, v in d.items():
2985 setattr(self, k, v)
2986 class D(C):
2987 pass
2988 # Now it should work
2989 x = C()
2990 y = pickle.loads(pickle.dumps(x))
2991 vereq(hasattr(y, 'a'), 0)
2992 y = cPickle.loads(cPickle.dumps(x))
2993 vereq(hasattr(y, 'a'), 0)
2994 x.a = 42
2995 y = pickle.loads(pickle.dumps(x))
2996 vereq(y.a, 42)
2997 y = cPickle.loads(cPickle.dumps(x))
2998 vereq(y.a, 42)
2999 x = D()
3000 x.a = 42
3001 x.b = 100
3002 y = pickle.loads(pickle.dumps(x))
3003 vereq(y.a + y.b, 142)
3004 y = cPickle.loads(cPickle.dumps(x))
3005 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003006 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003007 class E(C):
3008 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003009 x = E()
3010 x.a = 42
3011 x.b = "foo"
3012 y = pickle.loads(pickle.dumps(x))
3013 vereq(y.a, x.a)
3014 vereq(y.b, x.b)
3015 y = cPickle.loads(cPickle.dumps(x))
3016 vereq(y.a, x.a)
3017 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003018
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003019def copies():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003020 if verbose: print("Testing copy.copy() and copy.deepcopy()...")
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003021 import copy
3022 class C(object):
3023 pass
3024
3025 a = C()
3026 a.foo = 12
3027 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003028 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003029
3030 a.bar = [1,2,3]
3031 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003032 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003033 verify(c.bar is a.bar)
3034
3035 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003036 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003037 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003038 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003039
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003040def binopoverride():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003041 if verbose: print("Testing overrides of binary operations...")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003042 class I(int):
3043 def __repr__(self):
3044 return "I(%r)" % int(self)
3045 def __add__(self, other):
3046 return I(int(self) + int(other))
3047 __radd__ = __add__
3048 def __pow__(self, other, mod=None):
3049 if mod is None:
3050 return I(pow(int(self), int(other)))
3051 else:
3052 return I(pow(int(self), int(other), int(mod)))
3053 def __rpow__(self, other, mod=None):
3054 if mod is None:
3055 return I(pow(int(other), int(self), mod))
3056 else:
3057 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003058
Walter Dörwald70a6b492004-02-12 17:35:32 +00003059 vereq(repr(I(1) + I(2)), "I(3)")
3060 vereq(repr(I(1) + 2), "I(3)")
3061 vereq(repr(1 + I(2)), "I(3)")
3062 vereq(repr(I(2) ** I(3)), "I(8)")
3063 vereq(repr(2 ** I(3)), "I(8)")
3064 vereq(repr(I(2) ** 3), "I(8)")
3065 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003066 class S(str):
3067 def __eq__(self, other):
3068 return self.lower() == other.lower()
3069
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003070def subclasspropagation():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003071 if verbose: print("Testing propagation of slot functions to subclasses...")
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003072 class A(object):
3073 pass
3074 class B(A):
3075 pass
3076 class C(A):
3077 pass
3078 class D(B, C):
3079 pass
3080 d = D()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003081 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003082 A.__hash__ = lambda self: 42
3083 vereq(hash(d), 42)
3084 C.__hash__ = lambda self: 314
3085 vereq(hash(d), 314)
3086 B.__hash__ = lambda self: 144
3087 vereq(hash(d), 144)
3088 D.__hash__ = lambda self: 100
3089 vereq(hash(d), 100)
3090 del D.__hash__
3091 vereq(hash(d), 144)
3092 del B.__hash__
3093 vereq(hash(d), 314)
3094 del C.__hash__
3095 vereq(hash(d), 42)
3096 del A.__hash__
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003097 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003098 d.foo = 42
3099 d.bar = 42
3100 vereq(d.foo, 42)
3101 vereq(d.bar, 42)
3102 def __getattribute__(self, name):
3103 if name == "foo":
3104 return 24
3105 return object.__getattribute__(self, name)
3106 A.__getattribute__ = __getattribute__
3107 vereq(d.foo, 24)
3108 vereq(d.bar, 42)
3109 def __getattr__(self, name):
3110 if name in ("spam", "foo", "bar"):
3111 return "hello"
3112 raise AttributeError, name
3113 B.__getattr__ = __getattr__
3114 vereq(d.spam, "hello")
3115 vereq(d.foo, 24)
3116 vereq(d.bar, 42)
3117 del A.__getattribute__
3118 vereq(d.foo, 42)
3119 del d.foo
3120 vereq(d.foo, "hello")
3121 vereq(d.bar, 42)
3122 del B.__getattr__
3123 try:
3124 d.foo
3125 except AttributeError:
3126 pass
3127 else:
3128 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003129
Guido van Rossume7f3e242002-06-14 02:35:45 +00003130 # Test a nasty bug in recurse_down_subclasses()
3131 import gc
3132 class A(object):
3133 pass
3134 class B(A):
3135 pass
3136 del B
3137 gc.collect()
3138 A.__setitem__ = lambda *a: None # crash
3139
Tim Petersfc57ccb2001-10-12 02:38:24 +00003140def buffer_inherit():
3141 import binascii
3142 # SF bug [#470040] ParseTuple t# vs subclasses.
3143 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003144 print("Testing that buffer interface is inherited ...")
Tim Petersfc57ccb2001-10-12 02:38:24 +00003145
3146 class MyStr(str):
3147 pass
3148 base = 'abc'
3149 m = MyStr(base)
3150 # b2a_hex uses the buffer interface to get its argument's value, via
3151 # PyArg_ParseTuple 't#' code.
3152 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3153
3154 # It's not clear that unicode will continue to support the character
3155 # buffer interface, and this test will fail if that's taken away.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003156 class MyUni(str):
Tim Petersfc57ccb2001-10-12 02:38:24 +00003157 pass
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003158 base = 'abc'
Tim Petersfc57ccb2001-10-12 02:38:24 +00003159 m = MyUni(base)
3160 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3161
3162 class MyInt(int):
3163 pass
3164 m = MyInt(42)
3165 try:
3166 binascii.b2a_hex(m)
3167 raise TestFailed('subclass of int should not have a buffer interface')
3168 except TypeError:
3169 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003170
Tim Petersc9933152001-10-16 20:18:24 +00003171def str_of_str_subclass():
3172 import binascii
3173 import cStringIO
3174
3175 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003176 print("Testing __str__ defined in subclass of str ...")
Tim Petersc9933152001-10-16 20:18:24 +00003177
3178 class octetstring(str):
3179 def __str__(self):
3180 return binascii.b2a_hex(self)
3181 def __repr__(self):
3182 return self + " repr"
3183
3184 o = octetstring('A')
3185 vereq(type(o), octetstring)
3186 vereq(type(str(o)), str)
3187 vereq(type(repr(o)), str)
3188 vereq(ord(o), 0x41)
3189 vereq(str(o), '41')
3190 vereq(repr(o), 'A repr')
3191 vereq(o.__str__(), '41')
3192 vereq(o.__repr__(), 'A repr')
3193
3194 capture = cStringIO.StringIO()
3195 # Calling str() or not exercises different internal paths.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003196 print(o, file=capture)
3197 print(str(o), file=capture)
Tim Petersc9933152001-10-16 20:18:24 +00003198 vereq(capture.getvalue(), '41\n41\n')
3199 capture.close()
3200
Guido van Rossumc8e56452001-10-22 00:43:43 +00003201def kwdargs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003202 if verbose: print("Testing keyword arguments to __init__, __call__...")
Guido van Rossumc8e56452001-10-22 00:43:43 +00003203 def f(a): return a
3204 vereq(f.__call__(a=42), 42)
3205 a = []
3206 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003207 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003208
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003209def recursive__call__():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003210 if verbose: print(("Testing recursive __call__() by setting to instance of "
3211 "class ..."))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003212 class A(object):
3213 pass
3214
3215 A.__call__ = A()
3216 try:
3217 A()()
3218 except RuntimeError:
3219 pass
3220 else:
3221 raise TestFailed("Recursion limit should have been reached for "
3222 "__call__()")
3223
Guido van Rossumed87ad82001-10-30 02:33:02 +00003224def delhook():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003225 if verbose: print("Testing __del__ hook...")
Guido van Rossumed87ad82001-10-30 02:33:02 +00003226 log = []
3227 class C(object):
3228 def __del__(self):
3229 log.append(1)
3230 c = C()
3231 vereq(log, [])
3232 del c
3233 vereq(log, [1])
3234
Guido van Rossum29d26062001-12-11 04:37:34 +00003235 class D(object): pass
3236 d = D()
3237 try: del d[0]
3238 except TypeError: pass
3239 else: raise TestFailed, "invalid del() didn't raise TypeError"
3240
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003241def hashinherit():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003242 if verbose: print("Testing hash of mutable subclasses...")
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003243
3244 class mydict(dict):
3245 pass
3246 d = mydict()
3247 try:
3248 hash(d)
3249 except TypeError:
3250 pass
3251 else:
3252 raise TestFailed, "hash() of dict subclass should fail"
3253
3254 class mylist(list):
3255 pass
3256 d = mylist()
3257 try:
3258 hash(d)
3259 except TypeError:
3260 pass
3261 else:
3262 raise TestFailed, "hash() of list subclass should fail"
3263
Guido van Rossum29d26062001-12-11 04:37:34 +00003264def strops():
3265 try: 'a' + 5
3266 except TypeError: pass
3267 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3268
3269 try: ''.split('')
3270 except ValueError: pass
3271 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3272
3273 try: ''.join([0])
3274 except TypeError: pass
3275 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3276
3277 try: ''.rindex('5')
3278 except ValueError: pass
3279 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3280
Guido van Rossum29d26062001-12-11 04:37:34 +00003281 try: '%(n)s' % None
3282 except TypeError: pass
3283 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3284
3285 try: '%(n' % {}
3286 except ValueError: pass
3287 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3288
3289 try: '%*s' % ('abc')
3290 except TypeError: pass
3291 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3292
3293 try: '%*.*s' % ('abc', 5)
3294 except TypeError: pass
3295 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3296
3297 try: '%s' % (1, 2)
3298 except TypeError: pass
3299 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3300
3301 try: '%' % None
3302 except ValueError: pass
3303 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3304
3305 vereq('534253'.isdigit(), 1)
3306 vereq('534253x'.isdigit(), 0)
3307 vereq('%c' % 5, '\x05')
3308 vereq('%c' % '5', '5')
3309
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003310def deepcopyrecursive():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003311 if verbose: print("Testing deepcopy of recursive objects...")
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003312 class Node:
3313 pass
3314 a = Node()
3315 b = Node()
3316 a.b = b
3317 b.a = a
3318 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003319
Guido van Rossumd7035672002-03-12 20:43:31 +00003320def modules():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003321 if verbose: print("Testing uninitialized module objects...")
Guido van Rossumd7035672002-03-12 20:43:31 +00003322 from types import ModuleType as M
3323 m = M.__new__(M)
3324 str(m)
3325 vereq(hasattr(m, "__name__"), 0)
3326 vereq(hasattr(m, "__file__"), 0)
3327 vereq(hasattr(m, "foo"), 0)
3328 vereq(m.__dict__, None)
3329 m.foo = 1
3330 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003331
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003332def dictproxyiterkeys():
3333 class C(object):
3334 def meth(self):
3335 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003336 if verbose: print("Testing dict-proxy iterkeys...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003337 keys = [ key for key in C.__dict__.keys() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003338 keys.sort()
3339 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3340
3341def dictproxyitervalues():
3342 class C(object):
3343 def meth(self):
3344 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003345 if verbose: print("Testing dict-proxy itervalues...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003346 values = [ values for values in C.__dict__.values() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003347 vereq(len(values), 5)
3348
3349def dictproxyiteritems():
3350 class C(object):
3351 def meth(self):
3352 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003353 if verbose: print("Testing dict-proxy iteritems...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003354 keys = [ key for (key, value) in C.__dict__.items() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003355 keys.sort()
3356 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3357
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003358def funnynew():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003359 if verbose: print("Testing __new__ returning something unexpected...")
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003360 class C(object):
3361 def __new__(cls, arg):
3362 if isinstance(arg, str): return [1, 2, 3]
3363 elif isinstance(arg, int): return object.__new__(D)
3364 else: return object.__new__(cls)
3365 class D(C):
3366 def __init__(self, arg):
3367 self.foo = arg
3368 vereq(C("1"), [1, 2, 3])
3369 vereq(D("1"), [1, 2, 3])
3370 d = D(None)
3371 veris(d.foo, None)
3372 d = C(1)
3373 vereq(isinstance(d, D), True)
3374 vereq(d.foo, 1)
3375 d = D(1)
3376 vereq(isinstance(d, D), True)
3377 vereq(d.foo, 1)
3378
Guido van Rossume8fc6402002-04-16 16:44:51 +00003379def imulbug():
3380 # SF bug 544647
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003381 if verbose: print("Testing for __imul__ problems...")
Guido van Rossume8fc6402002-04-16 16:44:51 +00003382 class C(object):
3383 def __imul__(self, other):
3384 return (self, other)
3385 x = C()
3386 y = x
3387 y *= 1.0
3388 vereq(y, (x, 1.0))
3389 y = x
3390 y *= 2
3391 vereq(y, (x, 2))
3392 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003393 y *= 3
3394 vereq(y, (x, 3))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003395 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003396 y *= 1<<100
3397 vereq(y, (x, 1<<100))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003398 y = x
3399 y *= None
3400 vereq(y, (x, None))
3401 y = x
3402 y *= "foo"
3403 vereq(y, (x, "foo"))
3404
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003405def docdescriptor():
3406 # SF bug 542984
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003407 if verbose: print("Testing __doc__ descriptor...")
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003408 class DocDescr(object):
3409 def __get__(self, object, otype):
3410 if object:
3411 object = object.__class__.__name__ + ' instance'
3412 if otype:
3413 otype = otype.__name__
3414 return 'object=%s; type=%s' % (object, otype)
3415 class OldClass:
3416 __doc__ = DocDescr()
3417 class NewClass(object):
3418 __doc__ = DocDescr()
3419 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3420 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3421 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3422 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3423
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003424def copy_setstate():
3425 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003426 print("Testing that copy.*copy() correctly uses __setstate__...")
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003427 import copy
3428 class C(object):
3429 def __init__(self, foo=None):
3430 self.foo = foo
3431 self.__foo = foo
3432 def setfoo(self, foo=None):
3433 self.foo = foo
3434 def getfoo(self):
3435 return self.__foo
3436 def __getstate__(self):
3437 return [self.foo]
3438 def __setstate__(self, lst):
3439 assert len(lst) == 1
3440 self.__foo = self.foo = lst[0]
3441 a = C(42)
3442 a.setfoo(24)
3443 vereq(a.foo, 24)
3444 vereq(a.getfoo(), 42)
3445 b = copy.copy(a)
3446 vereq(b.foo, 24)
3447 vereq(b.getfoo(), 24)
3448 b = copy.deepcopy(a)
3449 vereq(b.foo, 24)
3450 vereq(b.getfoo(), 24)
3451
Guido van Rossum09638c12002-06-13 19:17:46 +00003452def slices():
3453 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003454 print("Testing cases with slices and overridden __getitem__ ...")
Guido van Rossum09638c12002-06-13 19:17:46 +00003455 # Strings
3456 vereq("hello"[:4], "hell")
3457 vereq("hello"[slice(4)], "hell")
3458 vereq(str.__getitem__("hello", slice(4)), "hell")
3459 class S(str):
3460 def __getitem__(self, x):
3461 return str.__getitem__(self, x)
3462 vereq(S("hello")[:4], "hell")
3463 vereq(S("hello")[slice(4)], "hell")
3464 vereq(S("hello").__getitem__(slice(4)), "hell")
3465 # Tuples
3466 vereq((1,2,3)[:2], (1,2))
3467 vereq((1,2,3)[slice(2)], (1,2))
3468 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3469 class T(tuple):
3470 def __getitem__(self, x):
3471 return tuple.__getitem__(self, x)
3472 vereq(T((1,2,3))[:2], (1,2))
3473 vereq(T((1,2,3))[slice(2)], (1,2))
3474 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3475 # Lists
3476 vereq([1,2,3][:2], [1,2])
3477 vereq([1,2,3][slice(2)], [1,2])
3478 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3479 class L(list):
3480 def __getitem__(self, x):
3481 return list.__getitem__(self, x)
3482 vereq(L([1,2,3])[:2], [1,2])
3483 vereq(L([1,2,3])[slice(2)], [1,2])
3484 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3485 # Now do lists and __setitem__
3486 a = L([1,2,3])
3487 a[slice(1, 3)] = [3,2]
3488 vereq(a, [1,3,2])
3489 a[slice(0, 2, 1)] = [3,1]
3490 vereq(a, [3,1,2])
3491 a.__setitem__(slice(1, 3), [2,1])
3492 vereq(a, [3,2,1])
3493 a.__setitem__(slice(0, 2, 1), [2,3])
3494 vereq(a, [2,3,1])
3495
Tim Peters2484aae2002-07-11 06:56:07 +00003496def subtype_resurrection():
3497 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003498 print("Testing resurrection of new-style instance...")
Tim Peters2484aae2002-07-11 06:56:07 +00003499
3500 class C(object):
3501 container = []
3502
3503 def __del__(self):
3504 # resurrect the instance
3505 C.container.append(self)
3506
3507 c = C()
3508 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003509 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003510 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003511 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003512
3513 # If that didn't blow up, it's also interesting to see whether clearing
3514 # the last container slot works: that will attempt to delete c again,
3515 # which will cause c to get appended back to the container again "during"
3516 # the del.
3517 del C.container[-1]
3518 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003519 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003520
Tim Peters14cb1e12002-07-11 18:26:21 +00003521 # Make c mortal again, so that the test framework with -l doesn't report
3522 # it as a leak.
3523 del C.__del__
3524
Guido van Rossum2d702462002-08-06 21:28:28 +00003525def slottrash():
3526 # Deallocating deeply nested slotted trash caused stack overflows
3527 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003528 print("Testing slot trash...")
Guido van Rossum2d702462002-08-06 21:28:28 +00003529 class trash(object):
3530 __slots__ = ['x']
3531 def __init__(self, x):
3532 self.x = x
3533 o = None
Guido van Rossum805365e2007-05-07 22:24:25 +00003534 for i in range(50000):
Guido van Rossum2d702462002-08-06 21:28:28 +00003535 o = trash(o)
3536 del o
3537
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003538def slotmultipleinheritance():
3539 # SF bug 575229, multiple inheritance w/ slots dumps core
3540 class A(object):
3541 __slots__=()
3542 class B(object):
3543 pass
3544 class C(A,B) :
3545 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003546 vereq(C.__basicsize__, B.__basicsize__)
3547 verify(hasattr(C, '__dict__'))
3548 verify(hasattr(C, '__weakref__'))
3549 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003550
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003551def testrmul():
3552 # SF patch 592646
3553 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003554 print("Testing correct invocation of __rmul__...")
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003555 class C(object):
3556 def __mul__(self, other):
3557 return "mul"
3558 def __rmul__(self, other):
3559 return "rmul"
3560 a = C()
3561 vereq(a*2, "mul")
3562 vereq(a*2.2, "mul")
3563 vereq(2*a, "rmul")
3564 vereq(2.2*a, "rmul")
3565
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003566def testipow():
3567 # [SF bug 620179]
3568 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003569 print("Testing correct invocation of __ipow__...")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003570 class C(object):
3571 def __ipow__(self, other):
3572 pass
3573 a = C()
3574 a **= 2
3575
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003576def do_this_first():
3577 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003578 print("Testing SF bug 551412 ...")
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003579 # This dumps core when SF bug 551412 isn't fixed --
3580 # but only when test_descr.py is run separately.
3581 # (That can't be helped -- as soon as PyType_Ready()
3582 # is called for PyLong_Type, the bug is gone.)
3583 class UserLong(object):
3584 def __pow__(self, *args):
3585 pass
3586 try:
Guido van Rossume2a383d2007-01-15 16:59:06 +00003587 pow(0, UserLong(), 0)
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003588 except:
3589 pass
3590
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003591 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003592 print("Testing SF bug 570483...")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003593 # Another segfault only when run early
3594 # (before PyType_Ready(tuple) is called)
3595 type.mro(tuple)
3596
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003597def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003598 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003599 print("Testing mutable bases...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003600 # stuff that should work:
3601 class C(object):
3602 pass
3603 class C2(object):
3604 def __getattribute__(self, attr):
3605 if attr == 'a':
3606 return 2
3607 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003608 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003609 def meth(self):
3610 return 1
3611 class D(C):
3612 pass
3613 class E(D):
3614 pass
3615 d = D()
3616 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003617 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003618 D.__bases__ = (C2,)
3619 vereq(d.meth(), 1)
3620 vereq(e.meth(), 1)
3621 vereq(d.a, 2)
3622 vereq(e.a, 2)
3623 vereq(C2.__subclasses__(), [D])
3624
3625 # stuff that shouldn't:
3626 class L(list):
3627 pass
3628
3629 try:
3630 L.__bases__ = (dict,)
3631 except TypeError:
3632 pass
3633 else:
3634 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3635
3636 try:
3637 list.__bases__ = (dict,)
3638 except TypeError:
3639 pass
3640 else:
3641 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3642
3643 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00003644 D.__bases__ = (C2, list)
3645 except TypeError:
3646 pass
3647 else:
3648 assert 0, "best_base calculation found wanting"
3649
3650 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003651 del D.__bases__
3652 except TypeError:
3653 pass
3654 else:
3655 raise TestFailed, "shouldn't be able to delete .__bases__"
3656
3657 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003658 D.__bases__ = ()
Guido van Rossumb940e112007-01-10 16:19:56 +00003659 except TypeError as msg:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003660 if str(msg) == "a new-style class can't have only classic bases":
3661 raise TestFailed, "wrong error message for .__bases__ = ()"
3662 else:
3663 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3664
3665 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003666 D.__bases__ = (D,)
3667 except TypeError:
3668 pass
3669 else:
3670 # actually, we'll have crashed by here...
3671 raise TestFailed, "shouldn't be able to create inheritance cycles"
3672
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003673 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003674 D.__bases__ = (C, C)
3675 except TypeError:
3676 pass
3677 else:
3678 raise TestFailed, "didn't detect repeated base classes"
3679
3680 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003681 D.__bases__ = (E,)
3682 except TypeError:
3683 pass
3684 else:
3685 raise TestFailed, "shouldn't be able to create inheritance cycles"
3686
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003687def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003688 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003689 print("Testing mutable bases with failing mro...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003690 class WorkOnce(type):
3691 def __new__(self, name, bases, ns):
3692 self.flag = 0
3693 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3694 def mro(self):
3695 if self.flag > 0:
3696 raise RuntimeError, "bozo"
3697 else:
3698 self.flag += 1
3699 return type.mro(self)
3700
3701 class WorkAlways(type):
3702 def mro(self):
3703 # this is here to make sure that .mro()s aren't called
3704 # with an exception set (which was possible at one point).
3705 # An error message will be printed in a debug build.
3706 # What's a good way to test for this?
3707 return type.mro(self)
3708
3709 class C(object):
3710 pass
3711
3712 class C2(object):
3713 pass
3714
3715 class D(C):
3716 pass
3717
3718 class E(D):
3719 pass
3720
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003721 class F(D, metaclass=WorkOnce):
3722 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003723
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003724 class G(D, metaclass=WorkAlways):
3725 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003726
3727 # Immediate subclasses have their mro's adjusted in alphabetical
3728 # order, so E's will get adjusted before adjusting F's fails. We
3729 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003730
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003731 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003732 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003733
3734 try:
3735 D.__bases__ = (C2,)
3736 except RuntimeError:
3737 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003738 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003739 else:
3740 raise TestFailed, "exception not propagated"
3741
3742def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003743 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003744 print("Testing mutable bases catch mro conflict...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003745 class A(object):
3746 pass
3747
3748 class B(object):
3749 pass
3750
3751 class C(A, B):
3752 pass
3753
3754 class D(A, B):
3755 pass
3756
3757 class E(C, D):
3758 pass
3759
3760 try:
3761 C.__bases__ = (B, A)
3762 except TypeError:
3763 pass
3764 else:
3765 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003766
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003767def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003768 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003769 print("Testing mutable names...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003770 class C(object):
3771 pass
3772
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003773 # C.__module__ could be 'test_descr' or '__main__'
3774 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003775
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003776 C.__name__ = 'D'
3777 vereq((C.__module__, C.__name__), (mod, 'D'))
3778
3779 C.__name__ = 'D.E'
3780 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003781
Guido van Rossum613f24f2003-01-06 23:00:59 +00003782def subclass_right_op():
3783 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003784 print("Testing correct dispatch of subclass overloading __r<op>__...")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003785
3786 # This code tests various cases where right-dispatch of a subclass
3787 # should be preferred over left-dispatch of a base class.
3788
3789 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3790
3791 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003792 def __floordiv__(self, other):
3793 return "B.__floordiv__"
3794 def __rfloordiv__(self, other):
3795 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003796
Guido van Rossumf389c772003-02-27 20:04:19 +00003797 vereq(B(1) // 1, "B.__floordiv__")
3798 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003799
3800 # Case 2: subclass of object; this is just the baseline for case 3
3801
3802 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003803 def __floordiv__(self, other):
3804 return "C.__floordiv__"
3805 def __rfloordiv__(self, other):
3806 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003807
Guido van Rossumf389c772003-02-27 20:04:19 +00003808 vereq(C() // 1, "C.__floordiv__")
3809 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003810
3811 # Case 3: subclass of new-style class; here it gets interesting
3812
3813 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003814 def __floordiv__(self, other):
3815 return "D.__floordiv__"
3816 def __rfloordiv__(self, other):
3817 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003818
Guido van Rossumf389c772003-02-27 20:04:19 +00003819 vereq(D() // C(), "D.__floordiv__")
3820 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003821
3822 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3823
3824 class E(C):
3825 pass
3826
Guido van Rossumf389c772003-02-27 20:04:19 +00003827 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003828
Guido van Rossumf389c772003-02-27 20:04:19 +00003829 vereq(E() // 1, "C.__floordiv__")
3830 vereq(1 // E(), "C.__rfloordiv__")
3831 vereq(E() // C(), "C.__floordiv__")
3832 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003833
Guido van Rossum373c7412003-01-07 13:41:37 +00003834def dict_type_with_metaclass():
3835 if verbose:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003836 print("Testing type of __dict__ when metaclass set...")
Guido van Rossum373c7412003-01-07 13:41:37 +00003837
3838 class B(object):
3839 pass
3840 class M(type):
3841 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003842 class C(metaclass=M):
Guido van Rossum373c7412003-01-07 13:41:37 +00003843 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003844 pass
Guido van Rossum373c7412003-01-07 13:41:37 +00003845 veris(type(C.__dict__), type(B.__dict__))
3846
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003847def meth_class_get():
3848 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003849 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003850 print("Testing __get__ method of METH_CLASS C methods...")
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003851 # Baseline
3852 arg = [1, 2, 3]
3853 res = {1: None, 2: None, 3: None}
3854 vereq(dict.fromkeys(arg), res)
3855 vereq({}.fromkeys(arg), res)
3856 # Now get the descriptor
3857 descr = dict.__dict__["fromkeys"]
3858 # More baseline using the descriptor directly
3859 vereq(descr.__get__(None, dict)(arg), res)
3860 vereq(descr.__get__({})(arg), res)
3861 # Now check various error cases
3862 try:
3863 descr.__get__(None, None)
3864 except TypeError:
3865 pass
3866 else:
3867 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3868 try:
3869 descr.__get__(42)
3870 except TypeError:
3871 pass
3872 else:
3873 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3874 try:
3875 descr.__get__(None, 42)
3876 except TypeError:
3877 pass
3878 else:
3879 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3880 try:
3881 descr.__get__(None, int)
3882 except TypeError:
3883 pass
3884 else:
3885 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3886
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003887def isinst_isclass():
3888 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003889 print("Testing proxy isinstance() and isclass()...")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003890 class Proxy(object):
3891 def __init__(self, obj):
3892 self.__obj = obj
3893 def __getattribute__(self, name):
3894 if name.startswith("_Proxy__"):
3895 return object.__getattribute__(self, name)
3896 else:
3897 return getattr(self.__obj, name)
3898 # Test with a classic class
3899 class C:
3900 pass
3901 a = C()
3902 pa = Proxy(a)
3903 verify(isinstance(a, C)) # Baseline
3904 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003905 # Test with a classic subclass
3906 class D(C):
3907 pass
3908 a = D()
3909 pa = Proxy(a)
3910 verify(isinstance(a, C)) # Baseline
3911 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003912 # Test with a new-style class
3913 class C(object):
3914 pass
3915 a = C()
3916 pa = Proxy(a)
3917 verify(isinstance(a, C)) # Baseline
3918 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003919 # Test with a new-style subclass
3920 class D(C):
3921 pass
3922 a = D()
3923 pa = Proxy(a)
3924 verify(isinstance(a, C)) # Baseline
3925 verify(isinstance(pa, C)) # Test
3926
3927def proxysuper():
3928 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003929 print("Testing super() for a proxy object...")
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003930 class Proxy(object):
3931 def __init__(self, obj):
3932 self.__obj = obj
3933 def __getattribute__(self, name):
3934 if name.startswith("_Proxy__"):
3935 return object.__getattribute__(self, name)
3936 else:
3937 return getattr(self.__obj, name)
3938
3939 class B(object):
3940 def f(self):
3941 return "B.f"
3942
3943 class C(B):
3944 def f(self):
3945 return super(C, self).f() + "->C.f"
3946
3947 obj = C()
3948 p = Proxy(obj)
3949 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003950
Guido van Rossum52b27052003-04-15 20:05:10 +00003951def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003952 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003953 print("Testing prohibition of Carlo Verre's hack...")
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003954 try:
3955 object.__setattr__(str, "foo", 42)
3956 except TypeError:
3957 pass
3958 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003959 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003960 try:
3961 object.__delattr__(str, "lower")
3962 except TypeError:
3963 pass
3964 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003965 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003966
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003967def weakref_segfault():
3968 # SF 742911
3969 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003970 print("Testing weakref segfault...")
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003971
3972 import weakref
3973
3974 class Provoker:
3975 def __init__(self, referrent):
3976 self.ref = weakref.ref(referrent)
3977
3978 def __del__(self):
3979 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003980
3981 class Oops(object):
3982 pass
3983
3984 o = Oops()
3985 o.whatever = Provoker(o)
3986 del o
3987
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003988def wrapper_segfault():
3989 # SF 927248: deeply nested wrappers could cause stack overflow
3990 f = lambda:None
Guido van Rossum805365e2007-05-07 22:24:25 +00003991 for i in range(1000000):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003992 f = f.__call__
3993 f = None
3994
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003995# Fix SF #762455, segfault when sys.stdout is changed in getattr
3996def filefault():
3997 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003998 print("Testing sys.stdout is changed in getattr...")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003999 import sys
4000 class StdoutGuard:
4001 def __getattr__(self, attr):
4002 sys.stdout = sys.__stdout__
4003 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4004 sys.stdout = StdoutGuard()
4005 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004006 print("Oops!")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004007 except RuntimeError:
4008 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004009
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004010def vicious_descriptor_nonsense():
4011 # A potential segfault spotted by Thomas Wouters in mail to
4012 # python-dev 2003-04-17, turned into an example & fixed by Michael
4013 # Hudson just less than four months later...
4014 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004015 print("Testing vicious_descriptor_nonsense...")
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004016
4017 class Evil(object):
4018 def __hash__(self):
4019 return hash('attr')
4020 def __eq__(self, other):
4021 del C.attr
4022 return 0
4023
4024 class Descr(object):
4025 def __get__(self, ob, type=None):
4026 return 1
4027
4028 class C(object):
4029 attr = Descr()
4030
4031 c = C()
4032 c.__dict__[Evil()] = 0
4033
4034 vereq(c.attr, 1)
4035 # this makes a crash more likely:
4036 import gc; gc.collect()
4037 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004038
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004039def test_init():
4040 # SF 1155938
4041 class Foo(object):
4042 def __init__(self):
4043 return 10
4044 try:
4045 Foo()
4046 except TypeError:
4047 pass
4048 else:
4049 raise TestFailed, "did not test __init__() for None return"
4050
Armin Rigoc6686b72005-11-07 08:38:00 +00004051def methodwrapper():
4052 # <type 'method-wrapper'> did not support any reflection before 2.5
4053 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004054 print("Testing method-wrapper objects...")
Armin Rigoc6686b72005-11-07 08:38:00 +00004055
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004056 return # XXX should methods really support __eq__?
4057
Armin Rigoc6686b72005-11-07 08:38:00 +00004058 l = []
4059 vereq(l.__add__, l.__add__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004060 vereq(l.__add__, [].__add__)
4061 verify(l.__add__ != [5].__add__)
4062 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004063 verify(l.__add__.__name__ == '__add__')
4064 verify(l.__add__.__self__ is l)
4065 verify(l.__add__.__objclass__ is list)
4066 vereq(l.__add__.__doc__, list.__add__.__doc__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004067 try:
4068 hash(l.__add__)
4069 except TypeError:
4070 pass
4071 else:
4072 raise TestFailed("no TypeError from hash([].__add__)")
4073
4074 t = ()
4075 t += (7,)
4076 vereq(t.__add__, (7,).__add__)
4077 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004078
Armin Rigofd163f92005-12-29 15:59:19 +00004079def notimplemented():
4080 # all binary methods should be able to return a NotImplemented
4081 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004082 print("Testing NotImplemented...")
Armin Rigofd163f92005-12-29 15:59:19 +00004083
4084 import sys
4085 import types
4086 import operator
4087
4088 def specialmethod(self, other):
4089 return NotImplemented
4090
4091 def check(expr, x, y):
4092 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +00004093 exec(expr, {'x': x, 'y': y, 'operator': operator})
Armin Rigofd163f92005-12-29 15:59:19 +00004094 except TypeError:
4095 pass
4096 else:
4097 raise TestFailed("no TypeError from %r" % (expr,))
4098
Guido van Rossume2a383d2007-01-15 16:59:06 +00004099 N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004100 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4101 # ValueErrors instead of TypeErrors
Guido van Rossum13257902007-06-07 23:15:56 +00004102 if 1:
4103 metaclass = type
Armin Rigofd163f92005-12-29 15:59:19 +00004104 for name, expr, iexpr in [
4105 ('__add__', 'x + y', 'x += y'),
4106 ('__sub__', 'x - y', 'x -= y'),
4107 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004108 ('__truediv__', 'x / y', None),
4109 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00004110 ('__mod__', 'x % y', 'x %= y'),
4111 ('__divmod__', 'divmod(x, y)', None),
4112 ('__pow__', 'x ** y', 'x **= y'),
4113 ('__lshift__', 'x << y', 'x <<= y'),
4114 ('__rshift__', 'x >> y', 'x >>= y'),
4115 ('__and__', 'x & y', 'x &= y'),
4116 ('__or__', 'x | y', 'x |= y'),
4117 ('__xor__', 'x ^ y', 'x ^= y'),
Neal Norwitz4886cc32006-08-21 17:06:07 +00004118 ]:
4119 rname = '__r' + name[2:]
Armin Rigofd163f92005-12-29 15:59:19 +00004120 A = metaclass('A', (), {name: specialmethod})
4121 B = metaclass('B', (), {rname: specialmethod})
4122 a = A()
4123 b = B()
4124 check(expr, a, a)
4125 check(expr, a, b)
4126 check(expr, b, a)
4127 check(expr, b, b)
4128 check(expr, a, N1)
4129 check(expr, a, N2)
4130 check(expr, N1, b)
4131 check(expr, N2, b)
4132 if iexpr:
4133 check(iexpr, a, a)
4134 check(iexpr, a, b)
4135 check(iexpr, b, a)
4136 check(iexpr, b, b)
4137 check(iexpr, a, N1)
4138 check(iexpr, a, N2)
4139 iname = '__i' + name[2:]
4140 C = metaclass('C', (), {iname: specialmethod})
4141 c = C()
4142 check(iexpr, c, a)
4143 check(iexpr, c, b)
4144 check(iexpr, c, N1)
4145 check(iexpr, c, N2)
4146
Guido van Rossumd8faa362007-04-27 19:54:29 +00004147def test_assign_slice():
4148 # ceval.c's assign_slice used to check for
4149 # tp->tp_as_sequence->sq_slice instead of
4150 # tp->tp_as_sequence->sq_ass_slice
4151
4152 class C(object):
4153 def __setslice__(self, start, stop, value):
4154 self.value = value
4155
4156 c = C()
4157 c[1:2] = 3
4158 vereq(c.value, 3)
4159
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004160def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004161 weakref_segfault() # Must be first, somehow
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004162 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004163 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004164 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004165 lists()
4166 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004167 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004168 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004169 ints()
4170 longs()
4171 floats()
4172 complexes()
4173 spamlists()
4174 spamdicts()
4175 pydicts()
4176 pylists()
4177 metaclass()
4178 pymods()
4179 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004180 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004182 ex5()
4183 monotonicity()
4184 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004185 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004186 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004187 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188 dynamics()
4189 errors()
4190 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004191 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004193 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194 classic()
4195 compattr()
4196 newslot()
4197 altmro()
4198 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004199 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004200 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004201 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004202 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004203 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004204 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004205 keywords()
Tim Peters0ab085c2001-09-14 00:25:33 +00004206 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004207 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004208 rich_comparisons()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004209 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004210 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004211 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004212 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004213 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004214 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004215 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004216 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004217 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004218 kwdargs()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004219 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004220 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004221 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004222 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004223 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004224 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004225 dictproxyiterkeys()
4226 dictproxyitervalues()
4227 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004228 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004229 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004230 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004231 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004232 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004233 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004234 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004235 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004236 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004237 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004238 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004239 test_mutable_bases()
4240 test_mutable_bases_with_failing_mro()
4241 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004242 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004243 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004244 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004245 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004246 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004247 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004248 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004249 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004250 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004251 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004252 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004253 notimplemented()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004254 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004255
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004256 if verbose: print("All OK")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004258if __name__ == "__main__":
4259 test_main()