blob: 7dc84426482e606815e661cec14f556a855ac9b7 [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):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002129 return oct(self)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002130 def __add__(self, other):
2131 return self.__class__(super(octlong, self).__add__(other))
2132 __radd__ = __add__
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002133 vereq(str(octlong(3) + 5), "0o10")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002134 # (Note that overriding __radd__ here only seems to work
2135 # because the example uses a short int left argument.)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002136 vereq(str(5 + octlong(3000)), "0o5675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002137 a = octlong(12345)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002138 vereq(a, 12345)
2139 vereq(int(a), 12345)
2140 vereq(hash(a), hash(12345))
2141 verify(int(a).__class__ is int)
2142 verify((+a).__class__ is int)
2143 verify((-a).__class__ is int)
2144 verify((-octlong(0)).__class__ is int)
2145 verify((a >> 0).__class__ is int)
2146 verify((a << 0).__class__ is int)
2147 verify((a - 0).__class__ is int)
2148 verify((a * 1).__class__ is int)
2149 verify((a ** 1).__class__ is int)
2150 verify((a // 1).__class__ is int)
2151 verify((1 * a).__class__ is int)
2152 verify((a | 0).__class__ is int)
2153 verify((a ^ 0).__class__ is int)
2154 verify((a & -1).__class__ is int)
2155 verify((octlong(0) << 12).__class__ is int)
2156 verify((octlong(0) >> 12).__class__ is int)
2157 verify(abs(octlong(0)).__class__ is int)
Tim Peters69c2de32001-09-11 22:31:33 +00002158
2159 # Because octlong overrides __add__, we can't check the absence of +0
2160 # optimizations using octlong.
Guido van Rossume2a383d2007-01-15 16:59:06 +00002161 class longclone(int):
Tim Peters69c2de32001-09-11 22:31:33 +00002162 pass
2163 a = longclone(1)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002164 verify((a + 0).__class__ is int)
2165 verify((0 + a).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002166
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002167 # Check that negative clones don't segfault
2168 a = longclone(-1)
2169 vereq(a.__dict__, {})
Guido van Rossume2a383d2007-01-15 16:59:06 +00002170 vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002171
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002172 class precfloat(float):
2173 __slots__ = ['prec']
2174 def __init__(self, value=0.0, prec=12):
2175 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002176 def __repr__(self):
2177 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002178 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002179 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002180 vereq(a, 12345.0)
2181 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002182 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002183 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002184 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002185
Tim Peters2400fa42001-09-12 19:12:49 +00002186 class madcomplex(complex):
2187 def __repr__(self):
2188 return "%.17gj%+.17g" % (self.imag, self.real)
2189 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002190 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002191 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002192 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002193 vereq(a, base)
2194 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002195 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002196 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002197 vereq(repr(a), "4j-3")
2198 vereq(a, base)
2199 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002200 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002201 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002202 veris((+a).__class__, complex)
2203 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002204 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002205 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002206 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002207 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002208 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002209 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002210 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002211
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002212 class madtuple(tuple):
2213 _rev = None
2214 def rev(self):
2215 if self._rev is not None:
2216 return self._rev
2217 L = list(self)
2218 L.reverse()
2219 self._rev = self.__class__(L)
2220 return self._rev
2221 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002222 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2223 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2224 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002225 for i in range(512):
2226 t = madtuple(range(i))
2227 u = t.rev()
2228 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002229 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002230 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002231 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002232 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002233 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002234 verify(a[:].__class__ is tuple)
2235 verify((a * 1).__class__ is tuple)
2236 verify((a * 0).__class__ is tuple)
2237 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002238 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002239 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002240 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002241 verify((a + a).__class__ is tuple)
2242 verify((a * 0).__class__ is tuple)
2243 verify((a * 1).__class__ is tuple)
2244 verify((a * 2).__class__ is tuple)
2245 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002246
2247 class madstring(str):
2248 _rev = None
2249 def rev(self):
2250 if self._rev is not None:
2251 return self._rev
2252 L = list(self)
2253 L.reverse()
2254 self._rev = self.__class__("".join(L))
2255 return self._rev
2256 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002257 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2258 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2259 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002260 for i in range(256):
2261 s = madstring("".join(map(chr, range(i))))
2262 t = s.rev()
2263 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002264 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002265 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002266 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002267 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002268
Tim Peters8fa5dd02001-09-12 02:18:30 +00002269 base = "\x00" * 5
2270 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002271 vereq(s, base)
2272 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002273 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002274 vereq(hash(s), hash(base))
2275 vereq({s: 1}[base], 1)
2276 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002277 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002278 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002279 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002280 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002281 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002282 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002283 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002284 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002285 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002286 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002287 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002288 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002289 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002290 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002291 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002292 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002293 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002294 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002295 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002296 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002297 identitytab = ''.join([chr(i) for i in range(256)])
2298 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002299 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002300 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002301 vereq(s.translate(identitytab, "x"), base)
2302 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002303 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002304 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002305 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002306 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002307 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002308 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002309 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002310 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002311 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002312 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002313
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002314 class madunicode(str):
Guido van Rossum91ee7982001-08-30 20:52:40 +00002315 _rev = None
2316 def rev(self):
2317 if self._rev is not None:
2318 return self._rev
2319 L = list(self)
2320 L.reverse()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002321 self._rev = self.__class__("".join(L))
Guido van Rossum91ee7982001-08-30 20:52:40 +00002322 return self._rev
2323 u = madunicode("ABCDEF")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002324 vereq(u, "ABCDEF")
2325 vereq(u.rev(), madunicode("FEDCBA"))
2326 vereq(u.rev().rev(), madunicode("ABCDEF"))
2327 base = "12345"
Tim Peters7a29bd52001-09-12 03:03:31 +00002328 u = madunicode(base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002329 vereq(str(u), base)
2330 verify(str(u).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002331 vereq(hash(u), hash(base))
2332 vereq({u: 1}[base], 1)
2333 vereq({base: 1}[u], 1)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002334 verify(u.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002335 vereq(u.strip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002336 verify(u.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002337 vereq(u.lstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002338 verify(u.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002339 vereq(u.rstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002340 verify(u.replace("x", "x").__class__ is str)
2341 vereq(u.replace("x", "x"), base)
2342 verify(u.replace("xy", "xy").__class__ is str)
2343 vereq(u.replace("xy", "xy"), base)
2344 verify(u.center(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002345 vereq(u.center(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002346 verify(u.ljust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002347 vereq(u.ljust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002348 verify(u.rjust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002349 vereq(u.rjust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002350 verify(u.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002351 vereq(u.lower(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002352 verify(u.upper().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002353 vereq(u.upper(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002354 verify(u.capitalize().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002355 vereq(u.capitalize(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002356 verify(u.title().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002357 vereq(u.title(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002358 verify((u + "").__class__ is str)
2359 vereq(u + "", base)
2360 verify(("" + u).__class__ is str)
2361 vereq("" + u, base)
2362 verify((u * 0).__class__ is str)
2363 vereq(u * 0, "")
2364 verify((u * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002365 vereq(u * 1, base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002366 verify((u * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002367 vereq(u * 2, base + base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002368 verify(u[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002369 vereq(u[:], base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002370 verify(u[0:0].__class__ is str)
2371 vereq(u[0:0], "")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002372
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002373 class sublist(list):
2374 pass
2375 a = sublist(range(5))
Guido van Rossum805365e2007-05-07 22:24:25 +00002376 vereq(a, list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002377 a.append("hello")
Guido van Rossum805365e2007-05-07 22:24:25 +00002378 vereq(a, list(range(5)) + ["hello"])
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002379 a[5] = 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002380 vereq(a, list(range(6)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002381 a.extend(range(6, 20))
Guido van Rossum805365e2007-05-07 22:24:25 +00002382 vereq(a, list(range(20)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002383 a[-5:] = []
Guido van Rossum805365e2007-05-07 22:24:25 +00002384 vereq(a, list(range(15)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002385 del a[10:15]
2386 vereq(len(a), 10)
Guido van Rossum805365e2007-05-07 22:24:25 +00002387 vereq(a, list(range(10)))
2388 vereq(list(a), list(range(10)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002389 vereq(a[0], 0)
2390 vereq(a[9], 9)
2391 vereq(a[-10], 0)
2392 vereq(a[-1], 9)
Guido van Rossum805365e2007-05-07 22:24:25 +00002393 vereq(a[:5], list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002394
Tim Peters59c9a642001-09-13 05:38:56 +00002395 class CountedInput(file):
2396 """Counts lines read by self.readline().
2397
2398 self.lineno is the 0-based ordinal of the last line read, up to
2399 a maximum of one greater than the number of lines in the file.
2400
2401 self.ateof is true if and only if the final "" line has been read,
2402 at which point self.lineno stops incrementing, and further calls
2403 to readline() continue to return "".
2404 """
2405
2406 lineno = 0
2407 ateof = 0
2408 def readline(self):
2409 if self.ateof:
2410 return ""
2411 s = file.readline(self)
2412 # Next line works too.
2413 # s = super(CountedInput, self).readline()
2414 self.lineno += 1
2415 if s == "":
2416 self.ateof = 1
2417 return s
2418
Alex Martelli01c77c62006-08-24 02:58:11 +00002419 f = open(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002420 lines = ['a\n', 'b\n', 'c\n']
2421 try:
2422 f.writelines(lines)
2423 f.close()
2424 f = CountedInput(TESTFN)
Guido van Rossum805365e2007-05-07 22:24:25 +00002425 for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]):
Tim Peters59c9a642001-09-13 05:38:56 +00002426 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002427 vereq(expected, got)
2428 vereq(f.lineno, i)
2429 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002430 f.close()
2431 finally:
2432 try:
2433 f.close()
2434 except:
2435 pass
2436 try:
2437 import os
2438 os.unlink(TESTFN)
2439 except:
2440 pass
2441
Tim Peters808b94e2001-09-13 19:33:07 +00002442def keywords():
2443 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002444 print("Testing keyword args to basic type constructors ...")
Guido van Rossum45704552001-10-08 16:35:45 +00002445 vereq(int(x=1), 1)
2446 vereq(float(x=2), 2.0)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002447 vereq(int(x=3), 3)
Guido van Rossum45704552001-10-08 16:35:45 +00002448 vereq(complex(imag=42, real=666), complex(666, 42))
2449 vereq(str(object=500), '500')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002450 vereq(str(string='abc', errors='strict'), 'abc')
Guido van Rossum45704552001-10-08 16:35:45 +00002451 vereq(tuple(sequence=range(3)), (0, 1, 2))
Guido van Rossum805365e2007-05-07 22:24:25 +00002452 vereq(list(sequence=(0, 1, 2)), list(range(3)))
Just van Rossuma797d812002-11-23 09:45:04 +00002453 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002454
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002455 for constructor in (int, float, int, complex, str, str,
Just van Rossuma797d812002-11-23 09:45:04 +00002456 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002457 try:
2458 constructor(bogus_keyword_arg=1)
2459 except TypeError:
2460 pass
2461 else:
2462 raise TestFailed("expected TypeError from bogus keyword "
2463 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002464
Tim Peters0ab085c2001-09-14 00:25:33 +00002465def str_subclass_as_dict_key():
2466 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002467 print("Testing a str subclass used as dict key ..")
Tim Peters0ab085c2001-09-14 00:25:33 +00002468
2469 class cistr(str):
2470 """Sublcass of str that computes __eq__ case-insensitively.
2471
2472 Also computes a hash code of the string in canonical form.
2473 """
2474
2475 def __init__(self, value):
2476 self.canonical = value.lower()
2477 self.hashcode = hash(self.canonical)
2478
2479 def __eq__(self, other):
2480 if not isinstance(other, cistr):
2481 other = cistr(other)
2482 return self.canonical == other.canonical
2483
2484 def __hash__(self):
2485 return self.hashcode
2486
Guido van Rossum45704552001-10-08 16:35:45 +00002487 vereq(cistr('ABC'), 'abc')
2488 vereq('aBc', cistr('ABC'))
2489 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002490
2491 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002492 vereq(d[cistr('one')], 1)
2493 vereq(d[cistr('tWo')], 2)
2494 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002495 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002496 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002497
Guido van Rossumab3b0342001-09-18 20:38:53 +00002498def classic_comparisons():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002499 if verbose: print("Testing classic comparisons...")
Guido van Rossum0639f592001-09-18 21:06:04 +00002500 class classic:
2501 pass
2502 for base in (classic, int, object):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002503 if verbose: print(" (base = %s)" % base)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002504 class C(base):
2505 def __init__(self, value):
2506 self.value = int(value)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002507 def __eq__(self, other):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002508 if isinstance(other, C):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002509 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002510 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002511 return self.value == other
Guido van Rossumab3b0342001-09-18 20:38:53 +00002512 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002513 def __ne__(self, other):
2514 if isinstance(other, C):
2515 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002516 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002517 return self.value != other
2518 return NotImplemented
2519 def __lt__(self, other):
2520 if isinstance(other, C):
2521 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002522 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002523 return self.value < other
2524 return NotImplemented
2525 def __le__(self, other):
2526 if isinstance(other, C):
2527 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002528 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002529 return self.value <= other
2530 return NotImplemented
2531 def __gt__(self, other):
2532 if isinstance(other, C):
2533 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002534 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002535 return self.value > other
2536 return NotImplemented
2537 def __ge__(self, other):
2538 if isinstance(other, C):
2539 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002540 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002541 return self.value >= other
2542 return NotImplemented
2543
Guido van Rossumab3b0342001-09-18 20:38:53 +00002544 c1 = C(1)
2545 c2 = C(2)
2546 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002547 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002548 c = {1: c1, 2: c2, 3: c3}
2549 for x in 1, 2, 3:
2550 for y in 1, 2, 3:
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002551 ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002552 for op in "<", "<=", "==", "!=", ">", ">=":
2553 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2554 "x=%d, y=%d" % (x, y))
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002555 ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2556 ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002557
Guido van Rossum0639f592001-09-18 21:06:04 +00002558def rich_comparisons():
2559 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002560 print("Testing rich comparisons...")
Guido van Rossum22056422001-09-24 17:52:04 +00002561 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002562 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002563 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002564 vereq(z, 1+0j)
2565 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002566 class ZZ(complex):
2567 def __eq__(self, other):
2568 try:
2569 return abs(self - other) <= 1e-6
2570 except:
2571 return NotImplemented
2572 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002573 vereq(zz, 1+0j)
2574 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002575
Guido van Rossum0639f592001-09-18 21:06:04 +00002576 class classic:
2577 pass
2578 for base in (classic, int, object, list):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002579 if verbose: print(" (base = %s)" % base)
Guido van Rossum0639f592001-09-18 21:06:04 +00002580 class C(base):
2581 def __init__(self, value):
2582 self.value = int(value)
2583 def __cmp__(self, other):
2584 raise TestFailed, "shouldn't call __cmp__"
2585 def __eq__(self, other):
2586 if isinstance(other, C):
2587 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002588 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002589 return self.value == other
2590 return NotImplemented
2591 def __ne__(self, other):
2592 if isinstance(other, C):
2593 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002594 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002595 return self.value != other
2596 return NotImplemented
2597 def __lt__(self, other):
2598 if isinstance(other, C):
2599 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002600 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002601 return self.value < other
2602 return NotImplemented
2603 def __le__(self, other):
2604 if isinstance(other, C):
2605 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002606 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002607 return self.value <= other
2608 return NotImplemented
2609 def __gt__(self, other):
2610 if isinstance(other, C):
2611 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002612 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002613 return self.value > other
2614 return NotImplemented
2615 def __ge__(self, other):
2616 if isinstance(other, C):
2617 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002618 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002619 return self.value >= other
2620 return NotImplemented
2621 c1 = C(1)
2622 c2 = C(2)
2623 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002624 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002625 c = {1: c1, 2: c2, 3: c3}
2626 for x in 1, 2, 3:
2627 for y in 1, 2, 3:
2628 for op in "<", "<=", "==", "!=", ">", ">=":
2629 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2630 "x=%d, y=%d" % (x, y))
2631 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2632 "x=%d, y=%d" % (x, y))
2633 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2634 "x=%d, y=%d" % (x, y))
2635
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002636def descrdoc():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002637 if verbose: print("Testing descriptor doc strings...")
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002638 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002639 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002640 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002641 check(file.name, "file name") # member descriptor
2642
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002643def setclass():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002644 if verbose: print("Testing __class__ assignment...")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002645 class C(object): pass
2646 class D(object): pass
2647 class E(object): pass
2648 class F(D, E): pass
2649 for cls in C, D, E, F:
2650 for cls2 in C, D, E, F:
2651 x = cls()
2652 x.__class__ = cls2
2653 verify(x.__class__ is cls2)
2654 x.__class__ = cls
2655 verify(x.__class__ is cls)
2656 def cant(x, C):
2657 try:
2658 x.__class__ = C
2659 except TypeError:
2660 pass
2661 else:
2662 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002663 try:
2664 delattr(x, "__class__")
2665 except TypeError:
2666 pass
2667 else:
2668 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002669 cant(C(), list)
2670 cant(list(), C)
2671 cant(C(), 1)
2672 cant(C(), object)
2673 cant(object(), list)
2674 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002675 class Int(int): __slots__ = []
2676 cant(2, Int)
2677 cant(Int(), int)
2678 cant(True, int)
2679 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002680 o = object()
2681 cant(o, type(1))
2682 cant(o, type(None))
2683 del o
Guido van Rossumd8faa362007-04-27 19:54:29 +00002684 class G(object):
2685 __slots__ = ["a", "b"]
2686 class H(object):
2687 __slots__ = ["b", "a"]
Walter Dörwald5de48bd2007-06-11 21:38:39 +00002688 class I(object):
2689 __slots__ = ["a", "b"]
Guido van Rossumd8faa362007-04-27 19:54:29 +00002690 class J(object):
2691 __slots__ = ["c", "b"]
2692 class K(object):
2693 __slots__ = ["a", "b", "d"]
2694 class L(H):
2695 __slots__ = ["e"]
2696 class M(I):
2697 __slots__ = ["e"]
2698 class N(J):
2699 __slots__ = ["__weakref__"]
2700 class P(J):
2701 __slots__ = ["__dict__"]
2702 class Q(J):
2703 pass
2704 class R(J):
2705 __slots__ = ["__dict__", "__weakref__"]
2706
2707 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2708 x = cls()
2709 x.a = 1
2710 x.__class__ = cls2
2711 verify(x.__class__ is cls2,
2712 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2713 vereq(x.a, 1)
2714 x.__class__ = cls
2715 verify(x.__class__ is cls,
2716 "assigning %r as __class__ for %r silently failed" % (cls, x))
2717 vereq(x.a, 1)
2718 for cls in G, J, K, L, M, N, P, R, list, Int:
2719 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2720 if cls is cls2:
2721 continue
2722 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002723
Guido van Rossum6661be32001-10-26 04:26:12 +00002724def setdict():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002725 if verbose: print("Testing __dict__ assignment...")
Guido van Rossum6661be32001-10-26 04:26:12 +00002726 class C(object): pass
2727 a = C()
2728 a.__dict__ = {'b': 1}
2729 vereq(a.b, 1)
2730 def cant(x, dict):
2731 try:
2732 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002733 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002734 pass
2735 else:
2736 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2737 cant(a, None)
2738 cant(a, [])
2739 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002740 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum360e4b82007-05-14 22:51:27 +00002741
2742 class Base(object):
2743 pass
2744 def verify_dict_readonly(x):
2745 """
2746 x has to be an instance of a class inheriting from Base.
2747 """
2748 cant(x, {})
2749 try:
2750 del x.__dict__
2751 except (AttributeError, TypeError):
2752 pass
2753 else:
2754 raise TestFailed, "shouldn't allow del %r.__dict__" % x
2755 dict_descr = Base.__dict__["__dict__"]
2756 try:
2757 dict_descr.__set__(x, {})
2758 except (AttributeError, TypeError):
2759 pass
2760 else:
2761 raise TestFailed, "dict_descr allowed access to %r's dict" % x
2762
2763 # Classes don't allow __dict__ assignment and have readonly dicts
2764 class Meta1(type, Base):
2765 pass
2766 class Meta2(Base, type):
2767 pass
2768 class D(object):
2769 __metaclass__ = Meta1
2770 class E(object):
2771 __metaclass__ = Meta2
2772 for cls in C, D, E:
2773 verify_dict_readonly(cls)
2774 class_dict = cls.__dict__
2775 try:
2776 class_dict["spam"] = "eggs"
2777 except TypeError:
2778 pass
2779 else:
2780 raise TestFailed, "%r's __dict__ can be modified" % cls
2781
2782 # Modules also disallow __dict__ assignment
2783 class Module1(types.ModuleType, Base):
2784 pass
2785 class Module2(Base, types.ModuleType):
2786 pass
2787 for ModuleType in Module1, Module2:
2788 mod = ModuleType("spam")
2789 verify_dict_readonly(mod)
2790 mod.__dict__["spam"] = "eggs"
2791
2792 # Exception's __dict__ can be replaced, but not deleted
2793 class Exception1(Exception, Base):
2794 pass
2795 class Exception2(Base, Exception):
2796 pass
2797 for ExceptionType in Exception, Exception1, Exception2:
2798 e = ExceptionType()
2799 e.__dict__ = {"a": 1}
2800 vereq(e.a, 1)
2801 try:
2802 del e.__dict__
2803 except (TypeError, AttributeError):
2804 pass
2805 else:
2806 raise TestFaied, "%r's __dict__ can be deleted" % e
2807
Guido van Rossum6661be32001-10-26 04:26:12 +00002808
Guido van Rossum3926a632001-09-25 16:25:58 +00002809def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002810 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002811 print("Testing pickling and copying new-style classes and objects...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002812 import pickle
2813 try:
2814 import cPickle
2815 except ImportError:
2816 cPickle = None
Guido van Rossum3926a632001-09-25 16:25:58 +00002817
2818 def sorteditems(d):
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002819 return sorted(d.items())
Guido van Rossum3926a632001-09-25 16:25:58 +00002820
2821 global C
2822 class C(object):
2823 def __init__(self, a, b):
2824 super(C, self).__init__()
2825 self.a = a
2826 self.b = b
2827 def __repr__(self):
2828 return "C(%r, %r)" % (self.a, self.b)
2829
2830 global C1
2831 class C1(list):
2832 def __new__(cls, a, b):
2833 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002834 def __getnewargs__(self):
2835 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002836 def __init__(self, a, b):
2837 self.a = a
2838 self.b = b
2839 def __repr__(self):
2840 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2841
2842 global C2
2843 class C2(int):
2844 def __new__(cls, a, b, val=0):
2845 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002846 def __getnewargs__(self):
2847 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002848 def __init__(self, a, b, val=0):
2849 self.a = a
2850 self.b = b
2851 def __repr__(self):
2852 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2853
Guido van Rossum90c45142001-11-24 21:07:01 +00002854 global C3
2855 class C3(object):
2856 def __init__(self, foo):
2857 self.foo = foo
2858 def __getstate__(self):
2859 return self.foo
2860 def __setstate__(self, foo):
2861 self.foo = foo
2862
2863 global C4classic, C4
2864 class C4classic: # classic
2865 pass
2866 class C4(C4classic, object): # mixed inheritance
2867 pass
2868
Guido van Rossum3926a632001-09-25 16:25:58 +00002869 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002870 if p is None:
2871 continue # cPickle not found -- skip it
Guido van Rossum3926a632001-09-25 16:25:58 +00002872 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002873 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002874 print(p.__name__, ["text", "binary"][bin])
Guido van Rossum3926a632001-09-25 16:25:58 +00002875
2876 for cls in C, C1, C2:
2877 s = p.dumps(cls, bin)
2878 cls2 = p.loads(s)
2879 verify(cls2 is cls)
2880
2881 a = C1(1, 2); a.append(42); a.append(24)
2882 b = C2("hello", "world", 42)
2883 s = p.dumps((a, b), bin)
2884 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002885 vereq(x.__class__, a.__class__)
2886 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2887 vereq(y.__class__, b.__class__)
2888 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002889 vereq(repr(x), repr(a))
2890 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002891 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002892 print("a = x =", a)
2893 print("b = y =", b)
Guido van Rossum90c45142001-11-24 21:07:01 +00002894 # Test for __getstate__ and __setstate__ on new style class
2895 u = C3(42)
2896 s = p.dumps(u, bin)
2897 v = p.loads(s)
2898 veris(u.__class__, v.__class__)
2899 vereq(u.foo, v.foo)
2900 # Test for picklability of hybrid class
2901 u = C4()
2902 u.foo = 42
2903 s = p.dumps(u, bin)
2904 v = p.loads(s)
2905 veris(u.__class__, v.__class__)
2906 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002907
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002908 # Testing copy.deepcopy()
2909 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002910 print("deepcopy")
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002911 import copy
2912 for cls in C, C1, C2:
2913 cls2 = copy.deepcopy(cls)
2914 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002915
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002916 a = C1(1, 2); a.append(42); a.append(24)
2917 b = C2("hello", "world", 42)
2918 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002919 vereq(x.__class__, a.__class__)
2920 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2921 vereq(y.__class__, b.__class__)
2922 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002923 vereq(repr(x), repr(a))
2924 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002925 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002926 print("a = x =", a)
2927 print("b = y =", b)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002928
Guido van Rossum8c842552002-03-14 23:05:54 +00002929def pickleslots():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002930 if verbose: print("Testing pickling of classes with __slots__ ...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002931 import pickle, pickle as cPickle
Guido van Rossum8c842552002-03-14 23:05:54 +00002932 # Pickling of classes with __slots__ but without __getstate__ should fail
2933 global B, C, D, E
2934 class B(object):
2935 pass
2936 for base in [object, B]:
2937 class C(base):
2938 __slots__ = ['a']
2939 class D(C):
2940 pass
2941 try:
2942 pickle.dumps(C())
2943 except TypeError:
2944 pass
2945 else:
2946 raise TestFailed, "should fail: pickle C instance - %s" % base
2947 try:
2948 cPickle.dumps(C())
2949 except TypeError:
2950 pass
2951 else:
2952 raise TestFailed, "should fail: cPickle C instance - %s" % base
2953 try:
2954 pickle.dumps(C())
2955 except TypeError:
2956 pass
2957 else:
2958 raise TestFailed, "should fail: pickle D instance - %s" % base
2959 try:
2960 cPickle.dumps(D())
2961 except TypeError:
2962 pass
2963 else:
2964 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002965 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002966 class C(base):
2967 __slots__ = ['a']
2968 def __getstate__(self):
2969 try:
2970 d = self.__dict__.copy()
2971 except AttributeError:
2972 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002973 for cls in self.__class__.__mro__:
2974 for sn in cls.__dict__.get('__slots__', ()):
2975 try:
2976 d[sn] = getattr(self, sn)
2977 except AttributeError:
2978 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002979 return d
2980 def __setstate__(self, d):
2981 for k, v in d.items():
2982 setattr(self, k, v)
2983 class D(C):
2984 pass
2985 # Now it should work
2986 x = C()
2987 y = pickle.loads(pickle.dumps(x))
2988 vereq(hasattr(y, 'a'), 0)
2989 y = cPickle.loads(cPickle.dumps(x))
2990 vereq(hasattr(y, 'a'), 0)
2991 x.a = 42
2992 y = pickle.loads(pickle.dumps(x))
2993 vereq(y.a, 42)
2994 y = cPickle.loads(cPickle.dumps(x))
2995 vereq(y.a, 42)
2996 x = D()
2997 x.a = 42
2998 x.b = 100
2999 y = pickle.loads(pickle.dumps(x))
3000 vereq(y.a + y.b, 142)
3001 y = cPickle.loads(cPickle.dumps(x))
3002 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003003 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003004 class E(C):
3005 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003006 x = E()
3007 x.a = 42
3008 x.b = "foo"
3009 y = pickle.loads(pickle.dumps(x))
3010 vereq(y.a, x.a)
3011 vereq(y.b, x.b)
3012 y = cPickle.loads(cPickle.dumps(x))
3013 vereq(y.a, x.a)
3014 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003015
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003016def copies():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003017 if verbose: print("Testing copy.copy() and copy.deepcopy()...")
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003018 import copy
3019 class C(object):
3020 pass
3021
3022 a = C()
3023 a.foo = 12
3024 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003025 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003026
3027 a.bar = [1,2,3]
3028 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003029 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003030 verify(c.bar is a.bar)
3031
3032 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003033 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003034 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003035 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003036
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003037def binopoverride():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003038 if verbose: print("Testing overrides of binary operations...")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003039 class I(int):
3040 def __repr__(self):
3041 return "I(%r)" % int(self)
3042 def __add__(self, other):
3043 return I(int(self) + int(other))
3044 __radd__ = __add__
3045 def __pow__(self, other, mod=None):
3046 if mod is None:
3047 return I(pow(int(self), int(other)))
3048 else:
3049 return I(pow(int(self), int(other), int(mod)))
3050 def __rpow__(self, other, mod=None):
3051 if mod is None:
3052 return I(pow(int(other), int(self), mod))
3053 else:
3054 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003055
Walter Dörwald70a6b492004-02-12 17:35:32 +00003056 vereq(repr(I(1) + I(2)), "I(3)")
3057 vereq(repr(I(1) + 2), "I(3)")
3058 vereq(repr(1 + I(2)), "I(3)")
3059 vereq(repr(I(2) ** I(3)), "I(8)")
3060 vereq(repr(2 ** I(3)), "I(8)")
3061 vereq(repr(I(2) ** 3), "I(8)")
3062 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003063 class S(str):
3064 def __eq__(self, other):
3065 return self.lower() == other.lower()
3066
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003067def subclasspropagation():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003068 if verbose: print("Testing propagation of slot functions to subclasses...")
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003069 class A(object):
3070 pass
3071 class B(A):
3072 pass
3073 class C(A):
3074 pass
3075 class D(B, C):
3076 pass
3077 d = D()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003078 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003079 A.__hash__ = lambda self: 42
3080 vereq(hash(d), 42)
3081 C.__hash__ = lambda self: 314
3082 vereq(hash(d), 314)
3083 B.__hash__ = lambda self: 144
3084 vereq(hash(d), 144)
3085 D.__hash__ = lambda self: 100
3086 vereq(hash(d), 100)
3087 del D.__hash__
3088 vereq(hash(d), 144)
3089 del B.__hash__
3090 vereq(hash(d), 314)
3091 del C.__hash__
3092 vereq(hash(d), 42)
3093 del A.__hash__
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003094 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003095 d.foo = 42
3096 d.bar = 42
3097 vereq(d.foo, 42)
3098 vereq(d.bar, 42)
3099 def __getattribute__(self, name):
3100 if name == "foo":
3101 return 24
3102 return object.__getattribute__(self, name)
3103 A.__getattribute__ = __getattribute__
3104 vereq(d.foo, 24)
3105 vereq(d.bar, 42)
3106 def __getattr__(self, name):
3107 if name in ("spam", "foo", "bar"):
3108 return "hello"
3109 raise AttributeError, name
3110 B.__getattr__ = __getattr__
3111 vereq(d.spam, "hello")
3112 vereq(d.foo, 24)
3113 vereq(d.bar, 42)
3114 del A.__getattribute__
3115 vereq(d.foo, 42)
3116 del d.foo
3117 vereq(d.foo, "hello")
3118 vereq(d.bar, 42)
3119 del B.__getattr__
3120 try:
3121 d.foo
3122 except AttributeError:
3123 pass
3124 else:
3125 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003126
Guido van Rossume7f3e242002-06-14 02:35:45 +00003127 # Test a nasty bug in recurse_down_subclasses()
3128 import gc
3129 class A(object):
3130 pass
3131 class B(A):
3132 pass
3133 del B
3134 gc.collect()
3135 A.__setitem__ = lambda *a: None # crash
3136
Tim Petersfc57ccb2001-10-12 02:38:24 +00003137def buffer_inherit():
3138 import binascii
3139 # SF bug [#470040] ParseTuple t# vs subclasses.
3140 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003141 print("Testing that buffer interface is inherited ...")
Tim Petersfc57ccb2001-10-12 02:38:24 +00003142
3143 class MyStr(str):
3144 pass
3145 base = 'abc'
3146 m = MyStr(base)
3147 # b2a_hex uses the buffer interface to get its argument's value, via
3148 # PyArg_ParseTuple 't#' code.
3149 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3150
3151 # It's not clear that unicode will continue to support the character
3152 # buffer interface, and this test will fail if that's taken away.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003153 class MyUni(str):
Tim Petersfc57ccb2001-10-12 02:38:24 +00003154 pass
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003155 base = 'abc'
Tim Petersfc57ccb2001-10-12 02:38:24 +00003156 m = MyUni(base)
3157 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3158
3159 class MyInt(int):
3160 pass
3161 m = MyInt(42)
3162 try:
3163 binascii.b2a_hex(m)
3164 raise TestFailed('subclass of int should not have a buffer interface')
3165 except TypeError:
3166 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003167
Tim Petersc9933152001-10-16 20:18:24 +00003168def str_of_str_subclass():
3169 import binascii
3170 import cStringIO
3171
3172 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003173 print("Testing __str__ defined in subclass of str ...")
Tim Petersc9933152001-10-16 20:18:24 +00003174
3175 class octetstring(str):
3176 def __str__(self):
3177 return binascii.b2a_hex(self)
3178 def __repr__(self):
3179 return self + " repr"
3180
3181 o = octetstring('A')
3182 vereq(type(o), octetstring)
3183 vereq(type(str(o)), str)
3184 vereq(type(repr(o)), str)
3185 vereq(ord(o), 0x41)
3186 vereq(str(o), '41')
3187 vereq(repr(o), 'A repr')
3188 vereq(o.__str__(), '41')
3189 vereq(o.__repr__(), 'A repr')
3190
3191 capture = cStringIO.StringIO()
3192 # Calling str() or not exercises different internal paths.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003193 print(o, file=capture)
3194 print(str(o), file=capture)
Tim Petersc9933152001-10-16 20:18:24 +00003195 vereq(capture.getvalue(), '41\n41\n')
3196 capture.close()
3197
Guido van Rossumc8e56452001-10-22 00:43:43 +00003198def kwdargs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003199 if verbose: print("Testing keyword arguments to __init__, __call__...")
Guido van Rossumc8e56452001-10-22 00:43:43 +00003200 def f(a): return a
3201 vereq(f.__call__(a=42), 42)
3202 a = []
3203 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003204 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003205
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003206def recursive__call__():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003207 if verbose: print(("Testing recursive __call__() by setting to instance of "
3208 "class ..."))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003209 class A(object):
3210 pass
3211
3212 A.__call__ = A()
3213 try:
3214 A()()
3215 except RuntimeError:
3216 pass
3217 else:
3218 raise TestFailed("Recursion limit should have been reached for "
3219 "__call__()")
3220
Guido van Rossumed87ad82001-10-30 02:33:02 +00003221def delhook():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003222 if verbose: print("Testing __del__ hook...")
Guido van Rossumed87ad82001-10-30 02:33:02 +00003223 log = []
3224 class C(object):
3225 def __del__(self):
3226 log.append(1)
3227 c = C()
3228 vereq(log, [])
3229 del c
3230 vereq(log, [1])
3231
Guido van Rossum29d26062001-12-11 04:37:34 +00003232 class D(object): pass
3233 d = D()
3234 try: del d[0]
3235 except TypeError: pass
3236 else: raise TestFailed, "invalid del() didn't raise TypeError"
3237
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003238def hashinherit():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003239 if verbose: print("Testing hash of mutable subclasses...")
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003240
3241 class mydict(dict):
3242 pass
3243 d = mydict()
3244 try:
3245 hash(d)
3246 except TypeError:
3247 pass
3248 else:
3249 raise TestFailed, "hash() of dict subclass should fail"
3250
3251 class mylist(list):
3252 pass
3253 d = mylist()
3254 try:
3255 hash(d)
3256 except TypeError:
3257 pass
3258 else:
3259 raise TestFailed, "hash() of list subclass should fail"
3260
Guido van Rossum29d26062001-12-11 04:37:34 +00003261def strops():
3262 try: 'a' + 5
3263 except TypeError: pass
3264 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3265
3266 try: ''.split('')
3267 except ValueError: pass
3268 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3269
3270 try: ''.join([0])
3271 except TypeError: pass
3272 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3273
3274 try: ''.rindex('5')
3275 except ValueError: pass
3276 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3277
Guido van Rossum29d26062001-12-11 04:37:34 +00003278 try: '%(n)s' % None
3279 except TypeError: pass
3280 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3281
3282 try: '%(n' % {}
3283 except ValueError: pass
3284 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3285
3286 try: '%*s' % ('abc')
3287 except TypeError: pass
3288 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3289
3290 try: '%*.*s' % ('abc', 5)
3291 except TypeError: pass
3292 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3293
3294 try: '%s' % (1, 2)
3295 except TypeError: pass
3296 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3297
3298 try: '%' % None
3299 except ValueError: pass
3300 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3301
3302 vereq('534253'.isdigit(), 1)
3303 vereq('534253x'.isdigit(), 0)
3304 vereq('%c' % 5, '\x05')
3305 vereq('%c' % '5', '5')
3306
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003307def deepcopyrecursive():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003308 if verbose: print("Testing deepcopy of recursive objects...")
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003309 class Node:
3310 pass
3311 a = Node()
3312 b = Node()
3313 a.b = b
3314 b.a = a
3315 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003316
Guido van Rossumd7035672002-03-12 20:43:31 +00003317def modules():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003318 if verbose: print("Testing uninitialized module objects...")
Guido van Rossumd7035672002-03-12 20:43:31 +00003319 from types import ModuleType as M
3320 m = M.__new__(M)
3321 str(m)
3322 vereq(hasattr(m, "__name__"), 0)
3323 vereq(hasattr(m, "__file__"), 0)
3324 vereq(hasattr(m, "foo"), 0)
3325 vereq(m.__dict__, None)
3326 m.foo = 1
3327 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003328
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003329def dictproxyiterkeys():
3330 class C(object):
3331 def meth(self):
3332 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003333 if verbose: print("Testing dict-proxy iterkeys...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003334 keys = [ key for key in C.__dict__.keys() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003335 keys.sort()
3336 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3337
3338def dictproxyitervalues():
3339 class C(object):
3340 def meth(self):
3341 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003342 if verbose: print("Testing dict-proxy itervalues...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003343 values = [ values for values in C.__dict__.values() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003344 vereq(len(values), 5)
3345
3346def dictproxyiteritems():
3347 class C(object):
3348 def meth(self):
3349 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003350 if verbose: print("Testing dict-proxy iteritems...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003351 keys = [ key for (key, value) in C.__dict__.items() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003352 keys.sort()
3353 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3354
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003355def funnynew():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003356 if verbose: print("Testing __new__ returning something unexpected...")
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003357 class C(object):
3358 def __new__(cls, arg):
3359 if isinstance(arg, str): return [1, 2, 3]
3360 elif isinstance(arg, int): return object.__new__(D)
3361 else: return object.__new__(cls)
3362 class D(C):
3363 def __init__(self, arg):
3364 self.foo = arg
3365 vereq(C("1"), [1, 2, 3])
3366 vereq(D("1"), [1, 2, 3])
3367 d = D(None)
3368 veris(d.foo, None)
3369 d = C(1)
3370 vereq(isinstance(d, D), True)
3371 vereq(d.foo, 1)
3372 d = D(1)
3373 vereq(isinstance(d, D), True)
3374 vereq(d.foo, 1)
3375
Guido van Rossume8fc6402002-04-16 16:44:51 +00003376def imulbug():
3377 # SF bug 544647
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003378 if verbose: print("Testing for __imul__ problems...")
Guido van Rossume8fc6402002-04-16 16:44:51 +00003379 class C(object):
3380 def __imul__(self, other):
3381 return (self, other)
3382 x = C()
3383 y = x
3384 y *= 1.0
3385 vereq(y, (x, 1.0))
3386 y = x
3387 y *= 2
3388 vereq(y, (x, 2))
3389 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003390 y *= 3
3391 vereq(y, (x, 3))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003392 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003393 y *= 1<<100
3394 vereq(y, (x, 1<<100))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003395 y = x
3396 y *= None
3397 vereq(y, (x, None))
3398 y = x
3399 y *= "foo"
3400 vereq(y, (x, "foo"))
3401
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003402def docdescriptor():
3403 # SF bug 542984
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003404 if verbose: print("Testing __doc__ descriptor...")
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003405 class DocDescr(object):
3406 def __get__(self, object, otype):
3407 if object:
3408 object = object.__class__.__name__ + ' instance'
3409 if otype:
3410 otype = otype.__name__
3411 return 'object=%s; type=%s' % (object, otype)
3412 class OldClass:
3413 __doc__ = DocDescr()
3414 class NewClass(object):
3415 __doc__ = DocDescr()
3416 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3417 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3418 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3419 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3420
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003421def copy_setstate():
3422 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003423 print("Testing that copy.*copy() correctly uses __setstate__...")
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003424 import copy
3425 class C(object):
3426 def __init__(self, foo=None):
3427 self.foo = foo
3428 self.__foo = foo
3429 def setfoo(self, foo=None):
3430 self.foo = foo
3431 def getfoo(self):
3432 return self.__foo
3433 def __getstate__(self):
3434 return [self.foo]
3435 def __setstate__(self, lst):
3436 assert len(lst) == 1
3437 self.__foo = self.foo = lst[0]
3438 a = C(42)
3439 a.setfoo(24)
3440 vereq(a.foo, 24)
3441 vereq(a.getfoo(), 42)
3442 b = copy.copy(a)
3443 vereq(b.foo, 24)
3444 vereq(b.getfoo(), 24)
3445 b = copy.deepcopy(a)
3446 vereq(b.foo, 24)
3447 vereq(b.getfoo(), 24)
3448
Guido van Rossum09638c12002-06-13 19:17:46 +00003449def slices():
3450 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003451 print("Testing cases with slices and overridden __getitem__ ...")
Guido van Rossum09638c12002-06-13 19:17:46 +00003452 # Strings
3453 vereq("hello"[:4], "hell")
3454 vereq("hello"[slice(4)], "hell")
3455 vereq(str.__getitem__("hello", slice(4)), "hell")
3456 class S(str):
3457 def __getitem__(self, x):
3458 return str.__getitem__(self, x)
3459 vereq(S("hello")[:4], "hell")
3460 vereq(S("hello")[slice(4)], "hell")
3461 vereq(S("hello").__getitem__(slice(4)), "hell")
3462 # Tuples
3463 vereq((1,2,3)[:2], (1,2))
3464 vereq((1,2,3)[slice(2)], (1,2))
3465 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3466 class T(tuple):
3467 def __getitem__(self, x):
3468 return tuple.__getitem__(self, x)
3469 vereq(T((1,2,3))[:2], (1,2))
3470 vereq(T((1,2,3))[slice(2)], (1,2))
3471 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3472 # Lists
3473 vereq([1,2,3][:2], [1,2])
3474 vereq([1,2,3][slice(2)], [1,2])
3475 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3476 class L(list):
3477 def __getitem__(self, x):
3478 return list.__getitem__(self, x)
3479 vereq(L([1,2,3])[:2], [1,2])
3480 vereq(L([1,2,3])[slice(2)], [1,2])
3481 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3482 # Now do lists and __setitem__
3483 a = L([1,2,3])
3484 a[slice(1, 3)] = [3,2]
3485 vereq(a, [1,3,2])
3486 a[slice(0, 2, 1)] = [3,1]
3487 vereq(a, [3,1,2])
3488 a.__setitem__(slice(1, 3), [2,1])
3489 vereq(a, [3,2,1])
3490 a.__setitem__(slice(0, 2, 1), [2,3])
3491 vereq(a, [2,3,1])
3492
Tim Peters2484aae2002-07-11 06:56:07 +00003493def subtype_resurrection():
3494 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003495 print("Testing resurrection of new-style instance...")
Tim Peters2484aae2002-07-11 06:56:07 +00003496
3497 class C(object):
3498 container = []
3499
3500 def __del__(self):
3501 # resurrect the instance
3502 C.container.append(self)
3503
3504 c = C()
3505 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003506 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003507 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003508 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003509
3510 # If that didn't blow up, it's also interesting to see whether clearing
3511 # the last container slot works: that will attempt to delete c again,
3512 # which will cause c to get appended back to the container again "during"
3513 # the del.
3514 del C.container[-1]
3515 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003516 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003517
Tim Peters14cb1e12002-07-11 18:26:21 +00003518 # Make c mortal again, so that the test framework with -l doesn't report
3519 # it as a leak.
3520 del C.__del__
3521
Guido van Rossum2d702462002-08-06 21:28:28 +00003522def slottrash():
3523 # Deallocating deeply nested slotted trash caused stack overflows
3524 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003525 print("Testing slot trash...")
Guido van Rossum2d702462002-08-06 21:28:28 +00003526 class trash(object):
3527 __slots__ = ['x']
3528 def __init__(self, x):
3529 self.x = x
3530 o = None
Guido van Rossum805365e2007-05-07 22:24:25 +00003531 for i in range(50000):
Guido van Rossum2d702462002-08-06 21:28:28 +00003532 o = trash(o)
3533 del o
3534
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003535def slotmultipleinheritance():
3536 # SF bug 575229, multiple inheritance w/ slots dumps core
3537 class A(object):
3538 __slots__=()
3539 class B(object):
3540 pass
3541 class C(A,B) :
3542 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003543 vereq(C.__basicsize__, B.__basicsize__)
3544 verify(hasattr(C, '__dict__'))
3545 verify(hasattr(C, '__weakref__'))
3546 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003547
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003548def testrmul():
3549 # SF patch 592646
3550 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003551 print("Testing correct invocation of __rmul__...")
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003552 class C(object):
3553 def __mul__(self, other):
3554 return "mul"
3555 def __rmul__(self, other):
3556 return "rmul"
3557 a = C()
3558 vereq(a*2, "mul")
3559 vereq(a*2.2, "mul")
3560 vereq(2*a, "rmul")
3561 vereq(2.2*a, "rmul")
3562
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003563def testipow():
3564 # [SF bug 620179]
3565 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003566 print("Testing correct invocation of __ipow__...")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003567 class C(object):
3568 def __ipow__(self, other):
3569 pass
3570 a = C()
3571 a **= 2
3572
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003573def do_this_first():
3574 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003575 print("Testing SF bug 551412 ...")
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003576 # This dumps core when SF bug 551412 isn't fixed --
3577 # but only when test_descr.py is run separately.
3578 # (That can't be helped -- as soon as PyType_Ready()
3579 # is called for PyLong_Type, the bug is gone.)
3580 class UserLong(object):
3581 def __pow__(self, *args):
3582 pass
3583 try:
Guido van Rossume2a383d2007-01-15 16:59:06 +00003584 pow(0, UserLong(), 0)
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003585 except:
3586 pass
3587
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003588 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003589 print("Testing SF bug 570483...")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003590 # Another segfault only when run early
3591 # (before PyType_Ready(tuple) is called)
3592 type.mro(tuple)
3593
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003594def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003595 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003596 print("Testing mutable bases...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003597 # stuff that should work:
3598 class C(object):
3599 pass
3600 class C2(object):
3601 def __getattribute__(self, attr):
3602 if attr == 'a':
3603 return 2
3604 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003605 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003606 def meth(self):
3607 return 1
3608 class D(C):
3609 pass
3610 class E(D):
3611 pass
3612 d = D()
3613 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003614 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003615 D.__bases__ = (C2,)
3616 vereq(d.meth(), 1)
3617 vereq(e.meth(), 1)
3618 vereq(d.a, 2)
3619 vereq(e.a, 2)
3620 vereq(C2.__subclasses__(), [D])
3621
3622 # stuff that shouldn't:
3623 class L(list):
3624 pass
3625
3626 try:
3627 L.__bases__ = (dict,)
3628 except TypeError:
3629 pass
3630 else:
3631 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3632
3633 try:
3634 list.__bases__ = (dict,)
3635 except TypeError:
3636 pass
3637 else:
3638 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3639
3640 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00003641 D.__bases__ = (C2, list)
3642 except TypeError:
3643 pass
3644 else:
3645 assert 0, "best_base calculation found wanting"
3646
3647 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003648 del D.__bases__
3649 except TypeError:
3650 pass
3651 else:
3652 raise TestFailed, "shouldn't be able to delete .__bases__"
3653
3654 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003655 D.__bases__ = ()
Guido van Rossumb940e112007-01-10 16:19:56 +00003656 except TypeError as msg:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003657 if str(msg) == "a new-style class can't have only classic bases":
3658 raise TestFailed, "wrong error message for .__bases__ = ()"
3659 else:
3660 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3661
3662 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003663 D.__bases__ = (D,)
3664 except TypeError:
3665 pass
3666 else:
3667 # actually, we'll have crashed by here...
3668 raise TestFailed, "shouldn't be able to create inheritance cycles"
3669
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003670 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003671 D.__bases__ = (C, C)
3672 except TypeError:
3673 pass
3674 else:
3675 raise TestFailed, "didn't detect repeated base classes"
3676
3677 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003678 D.__bases__ = (E,)
3679 except TypeError:
3680 pass
3681 else:
3682 raise TestFailed, "shouldn't be able to create inheritance cycles"
3683
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003684def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003685 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003686 print("Testing mutable bases with failing mro...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003687 class WorkOnce(type):
3688 def __new__(self, name, bases, ns):
3689 self.flag = 0
3690 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3691 def mro(self):
3692 if self.flag > 0:
3693 raise RuntimeError, "bozo"
3694 else:
3695 self.flag += 1
3696 return type.mro(self)
3697
3698 class WorkAlways(type):
3699 def mro(self):
3700 # this is here to make sure that .mro()s aren't called
3701 # with an exception set (which was possible at one point).
3702 # An error message will be printed in a debug build.
3703 # What's a good way to test for this?
3704 return type.mro(self)
3705
3706 class C(object):
3707 pass
3708
3709 class C2(object):
3710 pass
3711
3712 class D(C):
3713 pass
3714
3715 class E(D):
3716 pass
3717
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003718 class F(D, metaclass=WorkOnce):
3719 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003720
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003721 class G(D, metaclass=WorkAlways):
3722 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003723
3724 # Immediate subclasses have their mro's adjusted in alphabetical
3725 # order, so E's will get adjusted before adjusting F's fails. We
3726 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003727
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003728 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003729 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003730
3731 try:
3732 D.__bases__ = (C2,)
3733 except RuntimeError:
3734 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003735 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003736 else:
3737 raise TestFailed, "exception not propagated"
3738
3739def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003740 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003741 print("Testing mutable bases catch mro conflict...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003742 class A(object):
3743 pass
3744
3745 class B(object):
3746 pass
3747
3748 class C(A, B):
3749 pass
3750
3751 class D(A, B):
3752 pass
3753
3754 class E(C, D):
3755 pass
3756
3757 try:
3758 C.__bases__ = (B, A)
3759 except TypeError:
3760 pass
3761 else:
3762 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003763
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003764def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003765 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003766 print("Testing mutable names...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003767 class C(object):
3768 pass
3769
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003770 # C.__module__ could be 'test_descr' or '__main__'
3771 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003772
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003773 C.__name__ = 'D'
3774 vereq((C.__module__, C.__name__), (mod, 'D'))
3775
3776 C.__name__ = 'D.E'
3777 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003778
Guido van Rossum613f24f2003-01-06 23:00:59 +00003779def subclass_right_op():
3780 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003781 print("Testing correct dispatch of subclass overloading __r<op>__...")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003782
3783 # This code tests various cases where right-dispatch of a subclass
3784 # should be preferred over left-dispatch of a base class.
3785
3786 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3787
3788 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003789 def __floordiv__(self, other):
3790 return "B.__floordiv__"
3791 def __rfloordiv__(self, other):
3792 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003793
Guido van Rossumf389c772003-02-27 20:04:19 +00003794 vereq(B(1) // 1, "B.__floordiv__")
3795 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003796
3797 # Case 2: subclass of object; this is just the baseline for case 3
3798
3799 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003800 def __floordiv__(self, other):
3801 return "C.__floordiv__"
3802 def __rfloordiv__(self, other):
3803 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003804
Guido van Rossumf389c772003-02-27 20:04:19 +00003805 vereq(C() // 1, "C.__floordiv__")
3806 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003807
3808 # Case 3: subclass of new-style class; here it gets interesting
3809
3810 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003811 def __floordiv__(self, other):
3812 return "D.__floordiv__"
3813 def __rfloordiv__(self, other):
3814 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003815
Guido van Rossumf389c772003-02-27 20:04:19 +00003816 vereq(D() // C(), "D.__floordiv__")
3817 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003818
3819 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3820
3821 class E(C):
3822 pass
3823
Guido van Rossumf389c772003-02-27 20:04:19 +00003824 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003825
Guido van Rossumf389c772003-02-27 20:04:19 +00003826 vereq(E() // 1, "C.__floordiv__")
3827 vereq(1 // E(), "C.__rfloordiv__")
3828 vereq(E() // C(), "C.__floordiv__")
3829 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003830
Guido van Rossum373c7412003-01-07 13:41:37 +00003831def dict_type_with_metaclass():
3832 if verbose:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003833 print("Testing type of __dict__ when metaclass set...")
Guido van Rossum373c7412003-01-07 13:41:37 +00003834
3835 class B(object):
3836 pass
3837 class M(type):
3838 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003839 class C(metaclass=M):
Guido van Rossum373c7412003-01-07 13:41:37 +00003840 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003841 pass
Guido van Rossum373c7412003-01-07 13:41:37 +00003842 veris(type(C.__dict__), type(B.__dict__))
3843
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003844def meth_class_get():
3845 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003846 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003847 print("Testing __get__ method of METH_CLASS C methods...")
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003848 # Baseline
3849 arg = [1, 2, 3]
3850 res = {1: None, 2: None, 3: None}
3851 vereq(dict.fromkeys(arg), res)
3852 vereq({}.fromkeys(arg), res)
3853 # Now get the descriptor
3854 descr = dict.__dict__["fromkeys"]
3855 # More baseline using the descriptor directly
3856 vereq(descr.__get__(None, dict)(arg), res)
3857 vereq(descr.__get__({})(arg), res)
3858 # Now check various error cases
3859 try:
3860 descr.__get__(None, None)
3861 except TypeError:
3862 pass
3863 else:
3864 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3865 try:
3866 descr.__get__(42)
3867 except TypeError:
3868 pass
3869 else:
3870 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3871 try:
3872 descr.__get__(None, 42)
3873 except TypeError:
3874 pass
3875 else:
3876 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3877 try:
3878 descr.__get__(None, int)
3879 except TypeError:
3880 pass
3881 else:
3882 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3883
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003884def isinst_isclass():
3885 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003886 print("Testing proxy isinstance() and isclass()...")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003887 class Proxy(object):
3888 def __init__(self, obj):
3889 self.__obj = obj
3890 def __getattribute__(self, name):
3891 if name.startswith("_Proxy__"):
3892 return object.__getattribute__(self, name)
3893 else:
3894 return getattr(self.__obj, name)
3895 # Test with a classic class
3896 class C:
3897 pass
3898 a = C()
3899 pa = Proxy(a)
3900 verify(isinstance(a, C)) # Baseline
3901 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003902 # Test with a classic subclass
3903 class D(C):
3904 pass
3905 a = D()
3906 pa = Proxy(a)
3907 verify(isinstance(a, C)) # Baseline
3908 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003909 # Test with a new-style class
3910 class C(object):
3911 pass
3912 a = C()
3913 pa = Proxy(a)
3914 verify(isinstance(a, C)) # Baseline
3915 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003916 # Test with a new-style subclass
3917 class D(C):
3918 pass
3919 a = D()
3920 pa = Proxy(a)
3921 verify(isinstance(a, C)) # Baseline
3922 verify(isinstance(pa, C)) # Test
3923
3924def proxysuper():
3925 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003926 print("Testing super() for a proxy object...")
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003927 class Proxy(object):
3928 def __init__(self, obj):
3929 self.__obj = obj
3930 def __getattribute__(self, name):
3931 if name.startswith("_Proxy__"):
3932 return object.__getattribute__(self, name)
3933 else:
3934 return getattr(self.__obj, name)
3935
3936 class B(object):
3937 def f(self):
3938 return "B.f"
3939
3940 class C(B):
3941 def f(self):
3942 return super(C, self).f() + "->C.f"
3943
3944 obj = C()
3945 p = Proxy(obj)
3946 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003947
Guido van Rossum52b27052003-04-15 20:05:10 +00003948def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003949 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003950 print("Testing prohibition of Carlo Verre's hack...")
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003951 try:
3952 object.__setattr__(str, "foo", 42)
3953 except TypeError:
3954 pass
3955 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003956 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003957 try:
3958 object.__delattr__(str, "lower")
3959 except TypeError:
3960 pass
3961 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003962 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003963
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003964def weakref_segfault():
3965 # SF 742911
3966 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003967 print("Testing weakref segfault...")
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003968
3969 import weakref
3970
3971 class Provoker:
3972 def __init__(self, referrent):
3973 self.ref = weakref.ref(referrent)
3974
3975 def __del__(self):
3976 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003977
3978 class Oops(object):
3979 pass
3980
3981 o = Oops()
3982 o.whatever = Provoker(o)
3983 del o
3984
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003985def wrapper_segfault():
3986 # SF 927248: deeply nested wrappers could cause stack overflow
3987 f = lambda:None
Guido van Rossum805365e2007-05-07 22:24:25 +00003988 for i in range(1000000):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003989 f = f.__call__
3990 f = None
3991
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003992# Fix SF #762455, segfault when sys.stdout is changed in getattr
3993def filefault():
3994 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003995 print("Testing sys.stdout is changed in getattr...")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00003996 import sys
3997 class StdoutGuard:
3998 def __getattr__(self, attr):
3999 sys.stdout = sys.__stdout__
4000 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4001 sys.stdout = StdoutGuard()
4002 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004003 print("Oops!")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004004 except RuntimeError:
4005 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004006
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004007def vicious_descriptor_nonsense():
4008 # A potential segfault spotted by Thomas Wouters in mail to
4009 # python-dev 2003-04-17, turned into an example & fixed by Michael
4010 # Hudson just less than four months later...
4011 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004012 print("Testing vicious_descriptor_nonsense...")
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004013
4014 class Evil(object):
4015 def __hash__(self):
4016 return hash('attr')
4017 def __eq__(self, other):
4018 del C.attr
4019 return 0
4020
4021 class Descr(object):
4022 def __get__(self, ob, type=None):
4023 return 1
4024
4025 class C(object):
4026 attr = Descr()
4027
4028 c = C()
4029 c.__dict__[Evil()] = 0
4030
4031 vereq(c.attr, 1)
4032 # this makes a crash more likely:
4033 import gc; gc.collect()
4034 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004035
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004036def test_init():
4037 # SF 1155938
4038 class Foo(object):
4039 def __init__(self):
4040 return 10
4041 try:
4042 Foo()
4043 except TypeError:
4044 pass
4045 else:
4046 raise TestFailed, "did not test __init__() for None return"
4047
Armin Rigoc6686b72005-11-07 08:38:00 +00004048def methodwrapper():
4049 # <type 'method-wrapper'> did not support any reflection before 2.5
4050 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004051 print("Testing method-wrapper objects...")
Armin Rigoc6686b72005-11-07 08:38:00 +00004052
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004053 return # XXX should methods really support __eq__?
4054
Armin Rigoc6686b72005-11-07 08:38:00 +00004055 l = []
4056 vereq(l.__add__, l.__add__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004057 vereq(l.__add__, [].__add__)
4058 verify(l.__add__ != [5].__add__)
4059 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004060 verify(l.__add__.__name__ == '__add__')
4061 verify(l.__add__.__self__ is l)
4062 verify(l.__add__.__objclass__ is list)
4063 vereq(l.__add__.__doc__, list.__add__.__doc__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004064 try:
4065 hash(l.__add__)
4066 except TypeError:
4067 pass
4068 else:
4069 raise TestFailed("no TypeError from hash([].__add__)")
4070
4071 t = ()
4072 t += (7,)
4073 vereq(t.__add__, (7,).__add__)
4074 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004075
Armin Rigofd163f92005-12-29 15:59:19 +00004076def notimplemented():
4077 # all binary methods should be able to return a NotImplemented
4078 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004079 print("Testing NotImplemented...")
Armin Rigofd163f92005-12-29 15:59:19 +00004080
4081 import sys
4082 import types
4083 import operator
4084
4085 def specialmethod(self, other):
4086 return NotImplemented
4087
4088 def check(expr, x, y):
4089 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +00004090 exec(expr, {'x': x, 'y': y, 'operator': operator})
Armin Rigofd163f92005-12-29 15:59:19 +00004091 except TypeError:
4092 pass
4093 else:
4094 raise TestFailed("no TypeError from %r" % (expr,))
4095
Guido van Rossume2a383d2007-01-15 16:59:06 +00004096 N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004097 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4098 # ValueErrors instead of TypeErrors
Guido van Rossum13257902007-06-07 23:15:56 +00004099 if 1:
4100 metaclass = type
Armin Rigofd163f92005-12-29 15:59:19 +00004101 for name, expr, iexpr in [
4102 ('__add__', 'x + y', 'x += y'),
4103 ('__sub__', 'x - y', 'x -= y'),
4104 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004105 ('__truediv__', 'x / y', None),
4106 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00004107 ('__mod__', 'x % y', 'x %= y'),
4108 ('__divmod__', 'divmod(x, y)', None),
4109 ('__pow__', 'x ** y', 'x **= y'),
4110 ('__lshift__', 'x << y', 'x <<= y'),
4111 ('__rshift__', 'x >> y', 'x >>= y'),
4112 ('__and__', 'x & y', 'x &= y'),
4113 ('__or__', 'x | y', 'x |= y'),
4114 ('__xor__', 'x ^ y', 'x ^= y'),
Neal Norwitz4886cc32006-08-21 17:06:07 +00004115 ]:
4116 rname = '__r' + name[2:]
Armin Rigofd163f92005-12-29 15:59:19 +00004117 A = metaclass('A', (), {name: specialmethod})
4118 B = metaclass('B', (), {rname: specialmethod})
4119 a = A()
4120 b = B()
4121 check(expr, a, a)
4122 check(expr, a, b)
4123 check(expr, b, a)
4124 check(expr, b, b)
4125 check(expr, a, N1)
4126 check(expr, a, N2)
4127 check(expr, N1, b)
4128 check(expr, N2, b)
4129 if iexpr:
4130 check(iexpr, a, a)
4131 check(iexpr, a, b)
4132 check(iexpr, b, a)
4133 check(iexpr, b, b)
4134 check(iexpr, a, N1)
4135 check(iexpr, a, N2)
4136 iname = '__i' + name[2:]
4137 C = metaclass('C', (), {iname: specialmethod})
4138 c = C()
4139 check(iexpr, c, a)
4140 check(iexpr, c, b)
4141 check(iexpr, c, N1)
4142 check(iexpr, c, N2)
4143
Guido van Rossumd8faa362007-04-27 19:54:29 +00004144def test_assign_slice():
4145 # ceval.c's assign_slice used to check for
4146 # tp->tp_as_sequence->sq_slice instead of
4147 # tp->tp_as_sequence->sq_ass_slice
4148
4149 class C(object):
4150 def __setslice__(self, start, stop, value):
4151 self.value = value
4152
4153 c = C()
4154 c[1:2] = 3
4155 vereq(c.value, 3)
4156
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004157def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004158 weakref_segfault() # Must be first, somehow
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004159 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004160 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004161 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004162 lists()
4163 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004164 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004165 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166 ints()
4167 longs()
4168 floats()
4169 complexes()
4170 spamlists()
4171 spamdicts()
4172 pydicts()
4173 pylists()
4174 metaclass()
4175 pymods()
4176 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004177 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004179 ex5()
4180 monotonicity()
4181 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004182 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004184 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185 dynamics()
4186 errors()
4187 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004188 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004190 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191 classic()
4192 compattr()
4193 newslot()
4194 altmro()
4195 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004196 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004197 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004198 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004199 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004200 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004201 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004202 keywords()
Tim Peters0ab085c2001-09-14 00:25:33 +00004203 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004204 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004205 rich_comparisons()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004206 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004207 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004208 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004209 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004210 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004211 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004212 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004213 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004214 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004215 kwdargs()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004216 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004217 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004218 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004219 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004220 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004221 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004222 dictproxyiterkeys()
4223 dictproxyitervalues()
4224 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004225 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004226 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004227 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004228 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004229 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004230 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004231 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004232 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004233 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004234 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004235 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004236 test_mutable_bases()
4237 test_mutable_bases_with_failing_mro()
4238 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004239 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004240 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004241 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004242 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004243 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004244 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004245 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004246 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004247 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004248 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004249 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004250 notimplemented()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004251 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004252
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004253 if verbose: print("All OK")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004255if __name__ == "__main__":
4256 test_main()