blob: fca006158536a30e76c5e328d80c1ff66e1cc99f [file] [log] [blame]
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001# Test enhancements related to descriptors and new-style classes
Tim Peters6d6c1a32001-08-02 04:15:00 +00002
Neal Norwitz1a997502003-01-13 20:13:12 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
Tim Peters4d9b4662002-04-16 01:59:17 +00005import warnings
Guido van Rossum360e4b82007-05-14 22:51:27 +00006import types
Tim Peters4d9b4662002-04-16 01:59:17 +00007
8warnings.filterwarnings("ignore",
9 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +000010 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Guido van Rossum875eeaa2001-10-11 18:33:53 +000012def veris(a, b):
13 if a is not b:
14 raise TestFailed, "%r is %r" % (a, b)
15
Tim Peters6d6c1a32001-08-02 04:15:00 +000016def testunop(a, res, expr="len(a)", meth="__len__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000017 if verbose: print("checking", expr)
Tim Peters6d6c1a32001-08-02 04:15:00 +000018 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000019 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000020 t = type(a)
21 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000022 while meth not in t.__dict__:
23 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000024 vereq(m, t.__dict__[meth])
25 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000026 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000027 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000028
29def testbinop(a, b, res, expr="a+b", meth="__add__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000030 if verbose: print("checking", expr)
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000032
Guido van Rossum45704552001-10-08 16:35:45 +000033 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000034 t = type(a)
35 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000036 while meth not in t.__dict__:
37 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000038 vereq(m, t.__dict__[meth])
39 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000040 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000041 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
43def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000044 if verbose: print("checking", expr)
Tim Peters6d6c1a32001-08-02 04:15:00 +000045 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000046 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000047 t = type(a)
48 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000049 while meth not in t.__dict__:
50 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000051 vereq(m, t.__dict__[meth])
52 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000053 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000054 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000055
56def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000057 if verbose: print("checking", stmt)
Tim Peters6d6c1a32001-08-02 04:15:00 +000058 dict = {'a': deepcopy(a), 'b': b}
Georg Brandl7cae87c2006-09-06 06:51:57 +000059 exec(stmt, dict)
Guido van Rossum45704552001-10-08 16:35:45 +000060 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000061 t = type(a)
62 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000063 while meth not in t.__dict__:
64 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000065 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000066 dict['a'] = deepcopy(a)
67 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000068 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000069 dict['a'] = deepcopy(a)
70 bm = getattr(dict['a'], meth)
71 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000072 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000073
74def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000075 if verbose: print("checking", stmt)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076 dict = {'a': deepcopy(a), 'b': b, 'c': c}
Georg Brandl7cae87c2006-09-06 06:51:57 +000077 exec(stmt, dict)
Guido van Rossum45704552001-10-08 16:35:45 +000078 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000079 t = type(a)
80 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000081 while meth not in t.__dict__:
82 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000083 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000084 dict['a'] = deepcopy(a)
85 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000086 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 dict['a'] = deepcopy(a)
88 bm = getattr(dict['a'], meth)
89 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000090 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000091
92def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000093 if verbose: print("checking", stmt)
Tim Peters6d6c1a32001-08-02 04:15:00 +000094 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
Georg Brandl7cae87c2006-09-06 06:51:57 +000095 exec(stmt, dict)
Guido van Rossum45704552001-10-08 16:35:45 +000096 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000097 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000098 while meth not in t.__dict__:
99 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000101 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000102 dict['a'] = deepcopy(a)
103 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000104 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000105 dict['a'] = deepcopy(a)
106 bm = getattr(dict['a'], meth)
107 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000108 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000109
Tim Peters2f93e282001-10-04 05:27:00 +0000110def class_docstrings():
111 class Classic:
112 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000113 vereq(Classic.__doc__, "A classic docstring.")
114 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000115
116 class Classic2:
117 pass
118 verify(Classic2.__doc__ is None)
119
Tim Peters4fb1fe82001-10-04 05:48:13 +0000120 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000121 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000122 vereq(NewStatic.__doc__, "Another docstring.")
123 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000124
Tim Peters4fb1fe82001-10-04 05:48:13 +0000125 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000126 pass
127 verify(NewStatic2.__doc__ is None)
128
Tim Peters4fb1fe82001-10-04 05:48:13 +0000129 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000130 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000131 vereq(NewDynamic.__doc__, "Another docstring.")
132 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000133
Tim Peters4fb1fe82001-10-04 05:48:13 +0000134 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000135 pass
136 verify(NewDynamic2.__doc__ is None)
137
Tim Peters6d6c1a32001-08-02 04:15:00 +0000138def lists():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000139 if verbose: print("Testing list operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000140 testbinop([1], [2], [1,2], "a+b", "__add__")
141 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
142 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
143 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
144 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
145 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
146 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
147 testunop([1,2,3], 3, "len(a)", "__len__")
148 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
149 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
150 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
151 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
152
153def dicts():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 if verbose: print("Testing dict operations...")
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000155 ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000156 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
157 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
158 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
159 d = {1:2,3:4}
160 l1 = []
161 for i in d.keys(): l1.append(i)
162 l = []
163 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000164 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000165 l = []
166 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000167 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000168 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000169 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000170 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 d = {1:2, 3:4}
172 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000173 vereq(eval(repr(d), {}), d)
174 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000175 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
176
Tim Peters25786c02001-09-02 08:22:48 +0000177def dict_constructor():
178 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000179 print("Testing dict constructor ...")
Tim Petersa427a2b2001-10-29 22:25:45 +0000180 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000181 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000182 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000183 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000184 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000185 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000186 vereq(d, dict(d.items()))
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000187 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000188 d = dict({'one':1, 'two':2})
189 vereq(d, dict(one=1, two=2))
190 vereq(d, dict(**d))
191 vereq(d, dict({"one": 1}, two=2))
192 vereq(d, dict([("two", 2)], one=1))
193 vereq(d, dict([("one", 100), ("two", 200)], **d))
194 verify(d is not dict(**d))
Guido van Rossume2a383d2007-01-15 16:59:06 +0000195 for badarg in 0, 0, 0j, "0", [0], (0,):
Tim Peters25786c02001-09-02 08:22:48 +0000196 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000197 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000198 except TypeError:
199 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000200 except ValueError:
201 if badarg == "0":
202 # It's a sequence, and its elements are also sequences (gotta
203 # love strings <wink>), but they aren't of length 2, so this
204 # one seemed better as a ValueError than a TypeError.
205 pass
206 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000207 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000208 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000209 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000210
211 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000212 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000213 except TypeError:
214 pass
215 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000216 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000217
218 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000219 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000220 dict = {1:2, 3:4, 'a':1j}
221
Tim Peters25786c02001-09-02 08:22:48 +0000222 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000223 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000224 except TypeError:
225 pass
226 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000227 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000228
229 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000230 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000231 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000232 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000233
Tim Peters1fc240e2001-10-26 05:06:50 +0000234 # Init from sequence of iterable objects, each producing a 2-sequence.
235 class AddressBookEntry:
236 def __init__(self, first, last):
237 self.first = first
238 self.last = last
239 def __iter__(self):
240 return iter([self.first, self.last])
241
Tim Petersa427a2b2001-10-29 22:25:45 +0000242 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000243 AddressBookEntry('Barry', 'Peters'),
244 AddressBookEntry('Tim', 'Peters'),
245 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000246 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
247
Tim Petersa427a2b2001-10-29 22:25:45 +0000248 d = dict(zip(range(4), range(1, 5)))
249 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000250
251 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000252 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000253 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000254 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000255 except ValueError:
256 pass
257 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000258 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000259
Tim Peters5d2b77c2001-09-03 05:47:38 +0000260def test_dir():
261 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000262 print("Testing dir() ...")
Tim Peters5d2b77c2001-09-03 05:47:38 +0000263 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000264 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000265 del junk
266
267 # Just make sure these don't blow up!
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000268 for arg in 2, 2, 2j, 2e0, [2], "2", "2", (2,), {2:2}, type, test_dir:
Tim Peters5d2b77c2001-09-03 05:47:38 +0000269 dir(arg)
270
Thomas Wouters0725cf22006-04-15 09:04:57 +0000271 # Test dir on custom classes. Since these have object as a
272 # base class, a lot of stuff gets sucked in.
Tim Peters37a309d2001-09-04 01:20:04 +0000273 def interesting(strings):
274 return [s for s in strings if not s.startswith('_')]
275
Tim Peters5d2b77c2001-09-03 05:47:38 +0000276 class C(object):
277 Cdata = 1
278 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000279
280 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000281 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000282
283 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000284 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000285 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000286
287 c.cdata = 2
288 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000289 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000290 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000291
Tim Peters5d2b77c2001-09-03 05:47:38 +0000292 class A(C):
293 Adata = 1
294 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000295
296 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000297 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000298 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000299 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000300 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000301 a.adata = 42
302 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000303 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000304 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000305
Tim Peterscaaff8d2001-09-10 23:12:14 +0000306 # Try a module subclass.
307 import sys
308 class M(type(sys)):
309 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000310 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000311 minstance.b = 2
312 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000313 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
314 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000315
316 class M2(M):
317 def getdict(self):
318 return "Not a dict!"
319 __dict__ = property(getdict)
320
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000321 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000322 m2instance.b = 2
323 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000324 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000325 try:
326 dir(m2instance)
327 except TypeError:
328 pass
329
Tim Peters9e6a3992001-10-30 05:45:26 +0000330 # Two essentially featureless objects, just inheriting stuff from
331 # object.
332 vereq(dir(None), dir(Ellipsis))
333
Guido van Rossum44022412002-05-13 18:29:46 +0000334 # Nasty test case for proxied objects
335 class Wrapper(object):
336 def __init__(self, obj):
337 self.__obj = obj
338 def __repr__(self):
339 return "Wrapper(%s)" % repr(self.__obj)
340 def __getitem__(self, key):
341 return Wrapper(self.__obj[key])
342 def __len__(self):
343 return len(self.__obj)
344 def __getattr__(self, name):
345 return Wrapper(getattr(self.__obj, name))
346
347 class C(object):
348 def __getclass(self):
349 return Wrapper(type(self))
350 __class__ = property(__getclass)
351
352 dir(C()) # This used to segfault
353
Tim Peters6d6c1a32001-08-02 04:15:00 +0000354binops = {
355 'add': '+',
356 'sub': '-',
357 'mul': '*',
358 'div': '/',
359 'mod': '%',
360 'divmod': 'divmod',
361 'pow': '**',
362 'lshift': '<<',
363 'rshift': '>>',
364 'and': '&',
365 'xor': '^',
366 'or': '|',
367 'cmp': 'cmp',
368 'lt': '<',
369 'le': '<=',
370 'eq': '==',
371 'ne': '!=',
372 'gt': '>',
373 'ge': '>=',
374 }
375
376for name, expr in binops.items():
377 if expr.islower():
378 expr = expr + "(a, b)"
379 else:
380 expr = 'a %s b' % expr
381 binops[name] = expr
382
383unops = {
384 'pos': '+',
385 'neg': '-',
386 'abs': 'abs',
387 'invert': '~',
388 'int': 'int',
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389 'float': 'float',
390 'oct': 'oct',
391 'hex': 'hex',
392 }
393
394for name, expr in unops.items():
395 if expr.islower():
396 expr = expr + "(a)"
397 else:
398 expr = '%s a' % expr
399 unops[name] = expr
400
401def numops(a, b, skip=[]):
402 dict = {'a': a, 'b': b}
403 for name, expr in binops.items():
404 if name not in skip:
405 name = "__%s__" % name
406 if hasattr(a, name):
407 res = eval(expr, dict)
408 testbinop(a, b, res, expr, name)
409 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000410 if name not in skip:
411 name = "__%s__" % name
412 if hasattr(a, name):
413 res = eval(expr, dict)
414 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415
416def ints():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000417 if verbose: print("Testing int operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000419 # The following crashes in Python 2.2
Jack Diederich4dafcc42006-11-28 19:15:13 +0000420 vereq((1).__bool__(), True)
421 vereq((0).__bool__(), False)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000422 # This returns 'NotImplemented' in Python 2.2
423 class C(int):
424 def __add__(self, other):
425 return NotImplemented
Guido van Rossume2a383d2007-01-15 16:59:06 +0000426 vereq(C(5), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000427 try:
428 C() + ""
429 except TypeError:
430 pass
431 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000432 raise TestFailed, "NotImplemented should have caused TypeError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433
434def longs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000435 if verbose: print("Testing long operations...")
Guido van Rossume2a383d2007-01-15 16:59:06 +0000436 numops(100, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437
438def floats():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000439 if verbose: print("Testing float operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000440 numops(100.0, 3.0)
441
442def complexes():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000443 if verbose: print("Testing complex operations...")
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000444 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000445 class Number(complex):
446 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000447 def __new__(cls, *args, **kwds):
448 result = complex.__new__(cls, *args)
449 result.prec = kwds.get('prec', 12)
450 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 def __repr__(self):
452 prec = self.prec
453 if self.imag == 0.0:
454 return "%.*g" % (prec, self.real)
455 if self.real == 0.0:
456 return "%.*gj" % (prec, self.imag)
457 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
458 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000459
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000461 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000462 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463
Tim Peters3f996e72001-09-13 19:18:27 +0000464 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000465 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000466 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000467
468 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000469 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000470 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000471
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472def spamlists():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000473 if verbose: print("Testing spamlist operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474 import copy, xxsubtype as spam
475 def spamlist(l, memo=None):
476 import xxsubtype as spam
477 return spam.spamlist(l)
478 # This is an ugly hack:
479 copy._deepcopy_dispatch[spam.spamlist] = spamlist
480
481 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
482 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
483 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
484 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
485 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
486 "a[b:c]", "__getslice__")
487 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
488 "a+=b", "__iadd__")
489 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
490 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
491 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
492 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
493 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
494 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
495 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
496 # Test subclassing
497 class C(spam.spamlist):
498 def foo(self): return 1
499 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000500 vereq(a, [])
501 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000502 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000503 vereq(a, [100])
504 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000505 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000506 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000507
508def spamdicts():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000509 if verbose: print("Testing spamdict operations...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000510 import copy, xxsubtype as spam
511 def spamdict(d, memo=None):
512 import xxsubtype as spam
513 sd = spam.spamdict()
514 for k, v in d.items(): sd[k] = v
515 return sd
516 # This is an ugly hack:
517 copy._deepcopy_dispatch[spam.spamdict] = spamdict
518
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000519 ##testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000520 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
521 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
522 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
523 d = spamdict({1:2,3:4})
524 l1 = []
525 for i in d.keys(): l1.append(i)
526 l = []
527 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000528 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000529 l = []
530 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000531 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000532 l = []
533 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000534 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000535 straightd = {1:2, 3:4}
536 spamd = spamdict(straightd)
537 testunop(spamd, 2, "len(a)", "__len__")
538 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
539 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
540 "a[b]=c", "__setitem__")
541 # Test subclassing
542 class C(spam.spamdict):
543 def foo(self): return 1
544 a = C()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000545 vereq(list(a.items()), [])
Guido van Rossum45704552001-10-08 16:35:45 +0000546 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 a['foo'] = 'bar'
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000548 vereq(list(a.items()), [('foo', 'bar')])
Guido van Rossum45704552001-10-08 16:35:45 +0000549 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000550 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000551 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000552
553def pydicts():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000554 if verbose: print("Testing Python subclass of dict...")
Tim Petersa427a2b2001-10-29 22:25:45 +0000555 verify(issubclass(dict, dict))
556 verify(isinstance({}, dict))
557 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000558 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000559 verify(d.__class__ is dict)
560 verify(isinstance(d, dict))
561 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562 state = -1
563 def __init__(self, *a, **kw):
564 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000565 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000566 self.state = a[0]
567 if kw:
568 for k, v in kw.items(): self[v] = k
569 def __getitem__(self, key):
570 return self.get(key, 0)
571 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000572 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000573 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000574 def setstate(self, state):
575 self.state = state
576 def getstate(self):
577 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000578 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000579 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000580 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000582 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000584 vereq(a.state, -1)
585 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000587 vereq(a.state, 0)
588 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000590 vereq(a.state, 10)
591 vereq(a.getstate(), 10)
592 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000594 vereq(a[42], 24)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000595 if verbose: print("pydict stress test ...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 N = 50
597 for i in range(N):
598 a[i] = C()
599 for j in range(N):
600 a[i][j] = i*j
601 for i in range(N):
602 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000603 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604
605def pylists():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000606 if verbose: print("Testing Python subclass of list...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000607 class C(list):
608 def __getitem__(self, i):
609 return list.__getitem__(self, i) + 100
610 def __getslice__(self, i, j):
611 return (i, j)
612 a = C()
613 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000614 vereq(a[0], 100)
615 vereq(a[1], 101)
616 vereq(a[2], 102)
617 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618
619def metaclass():
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000620 if verbose: print("Testing metaclass...")
621 class C(metaclass=type):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 def __init__(self):
623 self.__state = 0
624 def getstate(self):
625 return self.__state
626 def setstate(self, state):
627 self.__state = state
628 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000629 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000631 vereq(a.getstate(), 10)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000632 class _metaclass(type):
633 def myself(cls): return cls
634 class D(metaclass=_metaclass):
635 pass
Guido van Rossum45704552001-10-08 16:35:45 +0000636 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000637 d = D()
638 verify(d.__class__ is D)
639 class M1(type):
640 def __new__(cls, name, bases, dict):
641 dict['__spam__'] = 1
642 return type.__new__(cls, name, bases, dict)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000643 class C(metaclass=M1):
644 pass
Guido van Rossum45704552001-10-08 16:35:45 +0000645 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000646 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000647 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000648
Guido van Rossum309b5662001-08-17 11:43:17 +0000649 class _instance(object):
650 pass
651 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000652 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000653 def __new__(cls, name, bases, dict):
654 self = object.__new__(cls)
655 self.name = name
656 self.bases = bases
657 self.dict = dict
658 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000659 def __call__(self):
660 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000661 # Early binding of methods
662 for key in self.dict:
663 if key.startswith("__"):
664 continue
665 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000666 return it
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000667 class C(metaclass=M2):
Guido van Rossum309b5662001-08-17 11:43:17 +0000668 def spam(self):
669 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000670 vereq(C.name, 'C')
671 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000672 verify('spam' in C.dict)
673 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000674 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
Guido van Rossum91ee7982001-08-30 20:52:40 +0000676 # More metaclass examples
677
678 class autosuper(type):
679 # Automatically add __super to the class
680 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000681 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000682 cls = super(autosuper, metaclass).__new__(metaclass,
683 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000684 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000685 while name[:1] == "_":
686 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000687 if name:
688 name = "_%s__super" % name
689 else:
690 name = "__super"
691 setattr(cls, name, super(cls))
692 return cls
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000693 class A(metaclass=autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000694 def meth(self):
695 return "A"
696 class B(A):
697 def meth(self):
698 return "B" + self.__super.meth()
699 class C(A):
700 def meth(self):
701 return "C" + self.__super.meth()
702 class D(C, B):
703 def meth(self):
704 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000705 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000706 class E(B, C):
707 def meth(self):
708 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000709 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000710
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000711 class autoproperty(type):
712 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000713 # named _get_x and/or _set_x are found
714 def __new__(metaclass, name, bases, dict):
715 hits = {}
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000716 for key, val in dict.items():
Guido van Rossum91ee7982001-08-30 20:52:40 +0000717 if key.startswith("_get_"):
718 key = key[5:]
719 get, set = hits.get(key, (None, None))
720 get = val
721 hits[key] = get, set
722 elif key.startswith("_set_"):
723 key = key[5:]
724 get, set = hits.get(key, (None, None))
725 set = val
726 hits[key] = get, set
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000727 for key, (get, set) in hits.items():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000728 dict[key] = property(get, set)
729 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000730 name, bases, dict)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000731 class A(metaclass=autoproperty):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000732 def _get_x(self):
733 return -self.__x
734 def _set_x(self, x):
735 self.__x = -x
736 a = A()
737 verify(not hasattr(a, "x"))
738 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000739 vereq(a.x, 12)
740 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000741
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000742 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000743 # Merge of multiple cooperating metaclasses
744 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000745 class A(metaclass=multimetaclass):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000746 def _get_x(self):
747 return "A"
748 class B(A):
749 def _get_x(self):
750 return "B" + self.__super._get_x()
751 class C(A):
752 def _get_x(self):
753 return "C" + self.__super._get_x()
754 class D(C, B):
755 def _get_x(self):
756 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000757 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000758
Guido van Rossumf76de622001-10-18 15:49:21 +0000759 # Make sure type(x) doesn't call x.__class__.__init__
760 class T(type):
761 counter = 0
762 def __init__(self, *args):
763 T.counter += 1
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000764 class C(metaclass=T):
765 pass
Guido van Rossumf76de622001-10-18 15:49:21 +0000766 vereq(T.counter, 1)
767 a = C()
768 vereq(type(a), C)
769 vereq(T.counter, 1)
770
Guido van Rossum29d26062001-12-11 04:37:34 +0000771 class C(object): pass
772 c = C()
773 try: c()
774 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000775 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000776
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 # Testing code to find most derived baseclass
778 class A(type):
779 def __new__(*args, **kwargs):
780 return type.__new__(*args, **kwargs)
781
782 class B(object):
783 pass
784
785 class C(object, metaclass=A):
786 pass
787
788 # The most derived metaclass of D is A rather than type.
789 class D(B, C):
790 pass
791
792
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793def pymods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000794 if verbose: print("Testing Python subclass of module...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000796 import sys
797 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000799 def __init__(self, name):
800 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000801 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000802 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000803 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000804 def __setattr__(self, name, value):
805 log.append(("setattr", name, value))
806 MT.__setattr__(self, name, value)
807 def __delattr__(self, name):
808 log.append(("delattr", name))
809 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000810 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811 a.foo = 12
812 x = a.foo
813 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000814 vereq(log, [("setattr", "foo", 12),
815 ("getattr", "foo"),
816 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817
Guido van Rossum360e4b82007-05-14 22:51:27 +0000818 # http://python.org/sf/1174712
819 try:
820 class Module(types.ModuleType, str):
821 pass
822 except TypeError:
823 pass
824 else:
825 raise TestFailed("inheriting from ModuleType and str at the "
826 "same time should fail")
827
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828def multi():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000829 if verbose: print("Testing multiple inheritance...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 class C(object):
831 def __init__(self):
832 self.__state = 0
833 def getstate(self):
834 return self.__state
835 def setstate(self, state):
836 self.__state = state
837 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000838 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000840 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000841 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 def __init__(self):
843 type({}).__init__(self)
844 C.__init__(self)
845 d = D()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000846 vereq(list(d.keys()), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847 d["hello"] = "world"
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000848 vereq(list(d.items()), [("hello", "world")])
Guido van Rossum45704552001-10-08 16:35:45 +0000849 vereq(d["hello"], "world")
850 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000852 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000853 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854
Guido van Rossume45763a2001-08-10 21:28:46 +0000855 # SF bug #442833
856 class Node(object):
857 def __int__(self):
858 return int(self.foo())
859 def foo(self):
860 return "23"
861 class Frag(Node, list):
862 def foo(self):
863 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000864 vereq(Node().__int__(), 23)
865 vereq(int(Node()), 23)
866 vereq(Frag().__int__(), 42)
867 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000868
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869def diamond():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000870 if verbose: print("Testing multiple inheritance special cases...")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871 class A(object):
872 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000873 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874 class B(A):
875 def boo(self): return "B"
876 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000877 vereq(B().spam(), "B")
878 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 class C(A):
880 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000881 vereq(C().spam(), "A")
882 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000884 vereq(D().spam(), "B")
885 vereq(D().boo(), "B")
886 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000888 vereq(E().spam(), "B")
889 vereq(E().boo(), "C")
890 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000891 # MRO order disagreement
892 try:
893 class F(D, E): pass
894 except TypeError:
895 pass
896 else:
897 raise TestFailed, "expected MRO order disagreement (F)"
898 try:
899 class G(E, D): pass
900 except TypeError:
901 pass
902 else:
903 raise TestFailed, "expected MRO order disagreement (G)"
904
905
906# see thread python-dev/2002-October/029035.html
907def ex5():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000908 if verbose: print("Testing ex5 from C3 switch discussion...")
Guido van Rossum9a818922002-11-14 19:50:14 +0000909 class A(object): pass
910 class B(object): pass
911 class C(object): pass
912 class X(A): pass
913 class Y(A): pass
914 class Z(X,B,Y,C): pass
915 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
916
917# see "A Monotonic Superclass Linearization for Dylan",
918# by Kim Barrett et al. (OOPSLA 1996)
919def monotonicity():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000920 if verbose: print("Testing MRO monotonicity...")
Guido van Rossum9a818922002-11-14 19:50:14 +0000921 class Boat(object): pass
922 class DayBoat(Boat): pass
923 class WheelBoat(Boat): pass
924 class EngineLess(DayBoat): pass
925 class SmallMultihull(DayBoat): pass
926 class PedalWheelBoat(EngineLess,WheelBoat): pass
927 class SmallCatamaran(SmallMultihull): pass
928 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
929
930 vereq(PedalWheelBoat.__mro__,
931 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
932 object))
933 vereq(SmallCatamaran.__mro__,
934 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
935
936 vereq(Pedalo.__mro__,
937 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
938 SmallMultihull, DayBoat, WheelBoat, Boat, object))
939
940# see "A Monotonic Superclass Linearization for Dylan",
941# by Kim Barrett et al. (OOPSLA 1996)
942def consistency_with_epg():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000943 if verbose: print("Testing consistentcy with EPG...")
Guido van Rossum9a818922002-11-14 19:50:14 +0000944 class Pane(object): pass
945 class ScrollingMixin(object): pass
946 class EditingMixin(object): pass
947 class ScrollablePane(Pane,ScrollingMixin): pass
948 class EditablePane(Pane,EditingMixin): pass
949 class EditableScrollablePane(ScrollablePane,EditablePane): pass
950
951 vereq(EditableScrollablePane.__mro__,
952 (EditableScrollablePane, ScrollablePane, EditablePane,
953 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000954
Raymond Hettingerf394df42003-04-06 19:13:41 +0000955mro_err_msg = """Cannot create a consistent method resolution
956order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000957
Guido van Rossumd32047f2002-11-25 21:38:52 +0000958def mro_disagreement():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000959 if verbose: print("Testing error messages for MRO disagreement...")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000960 def raises(exc, expected, callable, *args):
961 try:
962 callable(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +0000963 except exc as msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +0000964 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +0000965 raise TestFailed, "Message %r, expected %r" % (str(msg),
966 expected)
967 else:
968 raise TestFailed, "Expected %s" % exc
969 class A(object): pass
970 class B(A): pass
971 class C(object): pass
972 # Test some very simple errors
973 raises(TypeError, "duplicate base class A",
974 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +0000975 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000976 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +0000977 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000978 type, "X", (A, C, B), {})
979 # Test a slightly more complex error
980 class GridLayout(object): pass
981 class HorizontalGrid(GridLayout): pass
982 class VerticalGrid(GridLayout): pass
983 class HVGrid(HorizontalGrid, VerticalGrid): pass
984 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +0000985 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +0000986 type, "ConfusedGrid", (HVGrid, VHGrid), {})
987
Guido van Rossum37202612001-08-09 19:45:21 +0000988def objects():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000989 if verbose: print("Testing object class...")
Guido van Rossum37202612001-08-09 19:45:21 +0000990 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +0000991 vereq(a.__class__, object)
992 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +0000993 b = object()
994 verify(a is not b)
995 verify(not hasattr(a, "foo"))
996 try:
997 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +0000998 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +0000999 pass
1000 else:
1001 verify(0, "object() should not allow setting a foo attribute")
1002 verify(not hasattr(object(), "__dict__"))
1003
1004 class Cdict(object):
1005 pass
1006 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001007 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001008 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001009 vereq(x.foo, 1)
1010 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001011
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012def slots():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001013 if verbose: print("Testing __slots__...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 class C0(object):
1015 __slots__ = []
1016 x = C0()
1017 verify(not hasattr(x, "__dict__"))
1018 verify(not hasattr(x, "foo"))
1019
1020 class C1(object):
1021 __slots__ = ['a']
1022 x = C1()
1023 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001024 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001026 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001027 x.a = None
1028 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001030 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031
1032 class C3(object):
1033 __slots__ = ['a', 'b', 'c']
1034 x = C3()
1035 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001036 verify(not hasattr(x, 'a'))
1037 verify(not hasattr(x, 'b'))
1038 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 x.a = 1
1040 x.b = 2
1041 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001042 vereq(x.a, 1)
1043 vereq(x.b, 2)
1044 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001046 class C4(object):
1047 """Validate name mangling"""
1048 __slots__ = ['__a']
1049 def __init__(self, value):
1050 self.__a = value
1051 def get(self):
1052 return self.__a
1053 x = C4(5)
1054 verify(not hasattr(x, '__dict__'))
1055 verify(not hasattr(x, '__a'))
1056 vereq(x.get(), 5)
1057 try:
1058 x.__a = 6
1059 except AttributeError:
1060 pass
1061 else:
1062 raise TestFailed, "Double underscored names not mangled"
1063
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001064 # Make sure slot names are proper identifiers
1065 try:
1066 class C(object):
1067 __slots__ = [None]
1068 except TypeError:
1069 pass
1070 else:
1071 raise TestFailed, "[None] slots not caught"
1072 try:
1073 class C(object):
1074 __slots__ = ["foo bar"]
1075 except TypeError:
1076 pass
1077 else:
1078 raise TestFailed, "['foo bar'] slots not caught"
1079 try:
1080 class C(object):
1081 __slots__ = ["foo\0bar"]
1082 except TypeError:
1083 pass
1084 else:
1085 raise TestFailed, "['foo\\0bar'] slots not caught"
1086 try:
1087 class C(object):
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
1120 try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001121 str
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 except NameError:
1123 pass
1124 else:
1125 # Test a single unicode string is not expanded as a sequence.
1126 class C(object):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001127 __slots__ = str("abc")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001128 c = C()
1129 c.abc = 5
1130 vereq(c.abc, 5)
1131
1132 # _unicode_to_string used to modify slots in certain circumstances
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001133 slots = (str("foo"), str("bar"))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001134 class C(object):
1135 __slots__ = slots
1136 x = C()
1137 x.foo = 5
1138 vereq(x.foo, 5)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001139 veris(type(slots[0]), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140 # this used to leak references
1141 try:
1142 class C(object):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001143 __slots__ = [chr(128)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001144 except (TypeError, UnicodeEncodeError):
1145 pass
1146 else:
1147 raise TestFailed, "[unichr(128)] slots not caught"
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001148
Guido van Rossum33bab012001-12-05 22:45:48 +00001149 # Test leaks
1150 class Counted(object):
1151 counter = 0 # counts the number of instances alive
1152 def __init__(self):
1153 Counted.counter += 1
1154 def __del__(self):
1155 Counted.counter -= 1
1156 class C(object):
1157 __slots__ = ['a', 'b', 'c']
1158 x = C()
1159 x.a = Counted()
1160 x.b = Counted()
1161 x.c = Counted()
1162 vereq(Counted.counter, 3)
1163 del x
1164 vereq(Counted.counter, 0)
1165 class D(C):
1166 pass
1167 x = D()
1168 x.a = Counted()
1169 x.z = Counted()
1170 vereq(Counted.counter, 2)
1171 del x
1172 vereq(Counted.counter, 0)
1173 class E(D):
1174 __slots__ = ['e']
1175 x = E()
1176 x.a = Counted()
1177 x.z = Counted()
1178 x.e = Counted()
1179 vereq(Counted.counter, 3)
1180 del x
1181 vereq(Counted.counter, 0)
1182
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001183 # Test cyclical leaks [SF bug 519621]
1184 class F(object):
1185 __slots__ = ['a', 'b']
1186 log = []
1187 s = F()
1188 s.a = [Counted(), s]
1189 vereq(Counted.counter, 1)
1190 s = None
1191 import gc
1192 gc.collect()
1193 vereq(Counted.counter, 0)
1194
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001195 # Test lookup leaks [SF bug 572567]
1196 import sys,gc
1197 class G(object):
1198 def __cmp__(self, other):
1199 return 0
1200 g = G()
1201 orig_objects = len(gc.get_objects())
Guido van Rossum805365e2007-05-07 22:24:25 +00001202 for i in range(10):
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001203 g==g
1204 new_objects = len(gc.get_objects())
1205 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001206 class H(object):
1207 __slots__ = ['a', 'b']
1208 def __init__(self):
1209 self.a = 1
1210 self.b = 2
1211 def __del__(self):
1212 assert self.a == 1
1213 assert self.b == 2
1214
1215 save_stderr = sys.stderr
1216 sys.stderr = sys.stdout
1217 h = H()
1218 try:
1219 del h
1220 finally:
1221 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001222
Guido van Rossum8b056da2002-08-13 18:26:26 +00001223def slotspecials():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001224 if verbose: print("Testing __dict__ and __weakref__ in __slots__...")
Guido van Rossum8b056da2002-08-13 18:26:26 +00001225
1226 class D(object):
1227 __slots__ = ["__dict__"]
1228 a = D()
1229 verify(hasattr(a, "__dict__"))
1230 verify(not hasattr(a, "__weakref__"))
1231 a.foo = 42
1232 vereq(a.__dict__, {"foo": 42})
1233
1234 class W(object):
1235 __slots__ = ["__weakref__"]
1236 a = W()
1237 verify(hasattr(a, "__weakref__"))
1238 verify(not hasattr(a, "__dict__"))
1239 try:
1240 a.foo = 42
1241 except AttributeError:
1242 pass
1243 else:
1244 raise TestFailed, "shouldn't be allowed to set a.foo"
1245
1246 class C1(W, D):
1247 __slots__ = []
1248 a = C1()
1249 verify(hasattr(a, "__dict__"))
1250 verify(hasattr(a, "__weakref__"))
1251 a.foo = 42
1252 vereq(a.__dict__, {"foo": 42})
1253
1254 class C2(D, W):
1255 __slots__ = []
1256 a = C2()
1257 verify(hasattr(a, "__dict__"))
1258 verify(hasattr(a, "__weakref__"))
1259 a.foo = 42
1260 vereq(a.__dict__, {"foo": 42})
1261
Guido van Rossum9a818922002-11-14 19:50:14 +00001262# MRO order disagreement
1263#
1264# class C3(C1, C2):
1265# __slots__ = []
1266#
1267# class C4(C2, C1):
1268# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001269
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270def dynamics():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001271 if verbose: print("Testing class attribute propagation...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001274 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001276 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001279 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001281 vereq(E.foo, 1)
1282 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001283 # Test dynamic instances
1284 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001285 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001286 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001287 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001288 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001289 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001290 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001291 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001292 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001293 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001294 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001295 vereq(int(a), 100)
1296 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001297 verify(not hasattr(a, "spam"))
1298 def mygetattr(self, name):
1299 if name == "spam":
1300 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001301 raise AttributeError
1302 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001303 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001304 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001305 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001306 def mysetattr(self, name, value):
1307 if name == "spam":
1308 raise AttributeError
1309 return object.__setattr__(self, name, value)
1310 C.__setattr__ = mysetattr
1311 try:
1312 a.spam = "not spam"
1313 except AttributeError:
1314 pass
1315 else:
1316 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001317 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001318 class D(C):
1319 pass
1320 d = D()
1321 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001322 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323
Guido van Rossum7e35d572001-09-15 03:14:32 +00001324 # Test handling of int*seq and seq*int
1325 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001326 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001327 vereq("a"*I(2), "aa")
1328 vereq(I(2)*"a", "aa")
1329 vereq(2*I(3), 6)
1330 vereq(I(3)*2, 6)
1331 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001332
1333 # Test handling of long*seq and seq*long
Guido van Rossume2a383d2007-01-15 16:59:06 +00001334 class L(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001335 pass
Guido van Rossume2a383d2007-01-15 16:59:06 +00001336 vereq("a"*L(2), "aa")
1337 vereq(L(2)*"a", "aa")
Guido van Rossum45704552001-10-08 16:35:45 +00001338 vereq(2*L(3), 6)
1339 vereq(L(3)*2, 6)
1340 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001341
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001342 # Test comparison of classes with dynamic metaclasses
1343 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001344 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001345 class someclass(metaclass=dynamicmetaclass):
1346 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001347 verify(someclass != object)
1348
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349def errors():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001350 if verbose: print("Testing errors...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001351
1352 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001353 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354 pass
1355 except TypeError:
1356 pass
1357 else:
1358 verify(0, "inheritance from both list and dict should be illegal")
1359
1360 try:
1361 class C(object, None):
1362 pass
1363 except TypeError:
1364 pass
1365 else:
1366 verify(0, "inheritance from non-type should be illegal")
1367 class Classic:
1368 pass
1369
1370 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001371 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 pass
1373 except TypeError:
1374 pass
1375 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001376 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377
1378 try:
1379 class C(object):
1380 __slots__ = 1
1381 except TypeError:
1382 pass
1383 else:
1384 verify(0, "__slots__ = 1 should be illegal")
1385
1386 try:
1387 class C(object):
1388 __slots__ = [1]
1389 except TypeError:
1390 pass
1391 else:
1392 verify(0, "__slots__ = [1] should be illegal")
1393
Guido van Rossumd8faa362007-04-27 19:54:29 +00001394 class M1(type):
1395 pass
1396 class M2(type):
1397 pass
1398 class A1(object, metaclass=M1):
1399 pass
1400 class A2(object, metaclass=M2):
1401 pass
1402 try:
1403 class B(A1, A2):
1404 pass
1405 except TypeError:
1406 pass
1407 else:
1408 verify(0, "finding the most derived metaclass should have failed")
1409
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410def classmethods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001411 if verbose: print("Testing class methods...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 class C(object):
1413 def foo(*a): return a
1414 goo = classmethod(foo)
1415 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001416 vereq(C.goo(1), (C, 1))
1417 vereq(c.goo(1), (C, 1))
1418 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 class D(C):
1420 pass
1421 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001422 vereq(D.goo(1), (D, 1))
1423 vereq(d.goo(1), (D, 1))
1424 vereq(d.foo(1), (d, 1))
1425 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001426 # Test for a specific crash (SF bug 528132)
1427 def f(cls, arg): return (cls, arg)
1428 ff = classmethod(f)
1429 vereq(ff.__get__(0, int)(42), (int, 42))
1430 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431
Guido van Rossum155db9a2002-04-02 17:53:47 +00001432 # Test super() with classmethods (SF bug 535444)
1433 veris(C.goo.im_self, C)
1434 veris(D.goo.im_self, D)
1435 veris(super(D,D).goo.im_self, D)
1436 veris(super(D,d).goo.im_self, D)
1437 vereq(super(D,D).goo(), (D,))
1438 vereq(super(D,d).goo(), (D,))
1439
Raymond Hettingerbe971532003-06-18 01:13:41 +00001440 # Verify that argument is checked for callability (SF bug 753451)
1441 try:
1442 classmethod(1).__get__(1)
1443 except TypeError:
1444 pass
1445 else:
1446 raise TestFailed, "classmethod should check for callability"
1447
Georg Brandl6a29c322006-02-21 22:17:46 +00001448 # Verify that classmethod() doesn't allow keyword args
1449 try:
1450 classmethod(f, kw=1)
1451 except TypeError:
1452 pass
1453 else:
1454 raise TestFailed, "classmethod shouldn't accept keyword args"
1455
Fred Drakef841aa62002-03-28 15:49:54 +00001456def classmethods_in_c():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001457 if verbose: print("Testing C-based class methods...")
Fred Drakef841aa62002-03-28 15:49:54 +00001458 import xxsubtype as spam
1459 a = (1, 2, 3)
1460 d = {'abc': 123}
1461 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001462 veris(x, spam.spamlist)
1463 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001464 vereq(d, d1)
1465 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001466 veris(x, spam.spamlist)
1467 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001468 vereq(d, d1)
1469
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470def staticmethods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001471 if verbose: print("Testing static methods...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 class C(object):
1473 def foo(*a): return a
1474 goo = staticmethod(foo)
1475 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001476 vereq(C.goo(1), (1,))
1477 vereq(c.goo(1), (1,))
1478 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479 class D(C):
1480 pass
1481 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001482 vereq(D.goo(1), (1,))
1483 vereq(d.goo(1), (1,))
1484 vereq(d.foo(1), (d, 1))
1485 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486
Fred Drakef841aa62002-03-28 15:49:54 +00001487def staticmethods_in_c():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001488 if verbose: print("Testing C-based static methods...")
Fred Drakef841aa62002-03-28 15:49:54 +00001489 import xxsubtype as spam
1490 a = (1, 2, 3)
1491 d = {"abc": 123}
1492 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1493 veris(x, None)
1494 vereq(a, a1)
1495 vereq(d, d1)
1496 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1497 veris(x, None)
1498 vereq(a, a1)
1499 vereq(d, d1)
1500
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501def classic():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001502 if verbose: print("Testing classic classes...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503 class C:
1504 def foo(*a): return a
1505 goo = classmethod(foo)
1506 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001507 vereq(C.goo(1), (C, 1))
1508 vereq(c.goo(1), (C, 1))
1509 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 class D(C):
1511 pass
1512 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001513 vereq(D.goo(1), (D, 1))
1514 vereq(d.goo(1), (D, 1))
1515 vereq(d.foo(1), (d, 1))
1516 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001517 class E: # *not* subclassing from C
1518 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001519 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001520 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521
1522def compattr():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001523 if verbose: print("Testing computed attributes...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524 class C(object):
1525 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001526 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 self.__get = get
1528 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001529 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001530 def __get__(self, obj, type=None):
1531 return self.__get(obj)
1532 def __set__(self, obj, value):
1533 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001534 def __delete__(self, obj):
1535 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536 def __init__(self):
1537 self.__x = 0
1538 def __get_x(self):
1539 x = self.__x
1540 self.__x = x+1
1541 return x
1542 def __set_x(self, x):
1543 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001544 def __delete_x(self):
1545 del self.__x
1546 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001548 vereq(a.x, 0)
1549 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001551 vereq(a.x, 10)
1552 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001553 del a.x
1554 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555
1556def newslot():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001557 if verbose: print("Testing __new__ slot override...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 class C(list):
1559 def __new__(cls):
1560 self = list.__new__(cls)
1561 self.foo = 1
1562 return self
1563 def __init__(self):
1564 self.foo = self.foo + 2
1565 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001566 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 verify(a.__class__ is C)
1568 class D(C):
1569 pass
1570 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001571 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572 verify(b.__class__ is D)
1573
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574def altmro():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001575 if verbose: print("Testing mro() and overriding it...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 class A(object):
1577 def f(self): return "A"
1578 class B(A):
1579 pass
1580 class C(A):
1581 def f(self): return "C"
1582 class D(B, C):
1583 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001584 vereq(D.mro(), [D, B, C, A, object])
1585 vereq(D.__mro__, (D, B, C, A, object))
1586 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001587
Guido van Rossumd3077402001-08-12 05:24:18 +00001588 class PerverseMetaType(type):
1589 def mro(cls):
1590 L = type.mro(cls)
1591 L.reverse()
1592 return L
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001593 class X(D,B,C,A, metaclass=PerverseMetaType):
1594 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001595 vereq(X.__mro__, (object, A, C, B, D, X))
1596 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597
Armin Rigo037d1e02005-12-29 17:07:39 +00001598 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001599 class _metaclass(type):
1600 def mro(self):
1601 return [self, dict, object]
1602 class X(object, metaclass=_metaclass):
1603 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001604 except TypeError:
1605 pass
1606 else:
1607 raise TestFailed, "devious mro() return not caught"
1608
1609 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001610 class _metaclass(type):
1611 def mro(self):
1612 return [1]
1613 class X(object, metaclass=_metaclass):
1614 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001615 except TypeError:
1616 pass
1617 else:
1618 raise TestFailed, "non-class mro() return not caught"
1619
1620 try:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001621 class _metaclass(type):
1622 def mro(self):
1623 return 1
1624 class X(object, metaclass=_metaclass):
1625 pass
Armin Rigo037d1e02005-12-29 17:07:39 +00001626 except TypeError:
1627 pass
1628 else:
1629 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001630
Armin Rigo037d1e02005-12-29 17:07:39 +00001631
Tim Peters6d6c1a32001-08-02 04:15:00 +00001632def overloading():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001633 if verbose: print("Testing operator overloading...")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634
1635 class B(object):
1636 "Intermediate class because object doesn't have a __setattr__"
1637
1638 class C(B):
1639
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001640 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 if name == "foo":
1642 return ("getattr", name)
1643 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001644 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 def __setattr__(self, name, value):
1646 if name == "foo":
1647 self.setattr = (name, value)
1648 else:
1649 return B.__setattr__(self, name, value)
1650 def __delattr__(self, name):
1651 if name == "foo":
1652 self.delattr = name
1653 else:
1654 return B.__delattr__(self, name)
1655
1656 def __getitem__(self, key):
1657 return ("getitem", key)
1658 def __setitem__(self, key, value):
1659 self.setitem = (key, value)
1660 def __delitem__(self, key):
1661 self.delitem = key
1662
1663 def __getslice__(self, i, j):
1664 return ("getslice", i, j)
1665 def __setslice__(self, i, j, value):
1666 self.setslice = (i, j, value)
1667 def __delslice__(self, i, j):
1668 self.delslice = (i, j)
1669
1670 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001671 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001673 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001675 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676
Guido van Rossum45704552001-10-08 16:35:45 +00001677 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001679 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001681 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682
Guido van Rossum45704552001-10-08 16:35:45 +00001683 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001685 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001687 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001689def methods():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001690 if verbose: print("Testing methods...")
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001691 class C(object):
1692 def __init__(self, x):
1693 self.x = x
1694 def foo(self):
1695 return self.x
1696 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001697 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001698 class D(C):
1699 boo = C.foo
1700 goo = c1.foo
1701 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001702 vereq(d2.foo(), 2)
1703 vereq(d2.boo(), 2)
1704 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001705 class E(object):
1706 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001707 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001708 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001709
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001710def specials():
1711 # Test operators like __hash__ for which a built-in default exists
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001712 if verbose: print("Testing special operators...")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001713 # Test the default behavior for static classes
1714 class C(object):
1715 def __getitem__(self, i):
1716 if 0 <= i < 10: return i
1717 raise IndexError
1718 c1 = C()
1719 c2 = C()
1720 verify(not not c1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001721 verify(id(c1) != id(c2))
1722 hash(c1)
1723 hash(c2)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001724 ##vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
Guido van Rossum45704552001-10-08 16:35:45 +00001725 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001726 verify(c1 != c2)
1727 verify(not c1 != c1)
1728 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001729 # Note that the module name appears in str/repr, and that varies
1730 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001731 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001732 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001733 verify(-1 not in c1)
1734 for i in range(10):
1735 verify(i in c1)
1736 verify(10 not in c1)
1737 # Test the default behavior for dynamic classes
1738 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001739 def __getitem__(self, i):
1740 if 0 <= i < 10: return i
1741 raise IndexError
1742 d1 = D()
1743 d2 = D()
1744 verify(not not d1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001745 verify(id(d1) != id(d2))
1746 hash(d1)
1747 hash(d2)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001748 ##vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
Guido van Rossum45704552001-10-08 16:35:45 +00001749 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001750 verify(d1 != d2)
1751 verify(not d1 != d1)
1752 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001753 # Note that the module name appears in str/repr, and that varies
1754 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001755 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001756 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001757 verify(-1 not in d1)
1758 for i in range(10):
1759 verify(i in d1)
1760 verify(10 not in d1)
1761 # Test overridden behavior for static classes
1762 class Proxy(object):
1763 def __init__(self, x):
1764 self.x = x
Jack Diederich4dafcc42006-11-28 19:15:13 +00001765 def __bool__(self):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001766 return not not self.x
1767 def __hash__(self):
1768 return hash(self.x)
1769 def __eq__(self, other):
1770 return self.x == other
1771 def __ne__(self, other):
1772 return self.x != other
1773 def __cmp__(self, other):
1774 return cmp(self.x, other.x)
1775 def __str__(self):
1776 return "Proxy:%s" % self.x
1777 def __repr__(self):
1778 return "Proxy(%r)" % self.x
1779 def __contains__(self, value):
1780 return value in self.x
1781 p0 = Proxy(0)
1782 p1 = Proxy(1)
1783 p_1 = Proxy(-1)
1784 verify(not p0)
1785 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001786 vereq(hash(p0), hash(0))
1787 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001788 verify(p0 != p1)
1789 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001790 vereq(not p0, p1)
1791 vereq(cmp(p0, p1), -1)
1792 vereq(cmp(p0, p0), 0)
1793 vereq(cmp(p0, p_1), 1)
1794 vereq(str(p0), "Proxy:0")
1795 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001796 p10 = Proxy(range(10))
1797 verify(-1 not in p10)
1798 for i in range(10):
1799 verify(i in p10)
1800 verify(10 not in p10)
1801 # Test overridden behavior for dynamic classes
1802 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001803 def __init__(self, x):
1804 self.x = x
Jack Diederich4dafcc42006-11-28 19:15:13 +00001805 def __bool__(self):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001806 return not not self.x
1807 def __hash__(self):
1808 return hash(self.x)
1809 def __eq__(self, other):
1810 return self.x == other
1811 def __ne__(self, other):
1812 return self.x != other
1813 def __cmp__(self, other):
1814 return cmp(self.x, other.x)
1815 def __str__(self):
1816 return "DProxy:%s" % self.x
1817 def __repr__(self):
1818 return "DProxy(%r)" % self.x
1819 def __contains__(self, value):
1820 return value in self.x
1821 p0 = DProxy(0)
1822 p1 = DProxy(1)
1823 p_1 = DProxy(-1)
1824 verify(not p0)
1825 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001826 vereq(hash(p0), hash(0))
1827 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001828 verify(p0 != p1)
1829 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001830 vereq(not p0, p1)
1831 vereq(cmp(p0, p1), -1)
1832 vereq(cmp(p0, p0), 0)
1833 vereq(cmp(p0, p_1), 1)
1834 vereq(str(p0), "DProxy:0")
1835 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001836 p10 = DProxy(range(10))
1837 verify(-1 not in p10)
1838 for i in range(10):
1839 verify(i in p10)
1840 verify(10 not in p10)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001841## # Safety test for __cmp__
1842## def unsafecmp(a, b):
1843## try:
1844## a.__class__.__cmp__(a, b)
1845## except TypeError:
1846## pass
1847## else:
1848## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1849## a.__class__, a, b)
1850## unsafecmp(u"123", "123")
1851## unsafecmp("123", u"123")
1852## unsafecmp(1, 1.0)
1853## unsafecmp(1.0, 1)
1854## unsafecmp(1, 1L)
1855## unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001856
Neal Norwitz1a997502003-01-13 20:13:12 +00001857 class Letter(str):
1858 def __new__(cls, letter):
1859 if letter == 'EPS':
1860 return str.__new__(cls)
1861 return str.__new__(cls, letter)
1862 def __str__(self):
1863 if not self:
1864 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001865 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001866
1867 # sys.stdout needs to be the original to trigger the recursion bug
1868 import sys
1869 test_stdout = sys.stdout
1870 sys.stdout = get_original_stdout()
1871 try:
1872 # nothing should actually be printed, this should raise an exception
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001873 print(Letter('w'))
Neal Norwitz1a997502003-01-13 20:13:12 +00001874 except RuntimeError:
1875 pass
1876 else:
1877 raise TestFailed, "expected a RuntimeError for print recursion"
1878 sys.stdout = test_stdout
1879
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001880def weakrefs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001881 if verbose: print("Testing weak references...")
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001882 import weakref
1883 class C(object):
1884 pass
1885 c = C()
1886 r = weakref.ref(c)
1887 verify(r() is c)
1888 del c
1889 verify(r() is None)
1890 del r
1891 class NoWeak(object):
1892 __slots__ = ['foo']
1893 no = NoWeak()
1894 try:
1895 weakref.ref(no)
Guido van Rossumb940e112007-01-10 16:19:56 +00001896 except TypeError as msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001897 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001898 else:
1899 verify(0, "weakref.ref(no) should be illegal")
1900 class Weak(object):
1901 __slots__ = ['foo', '__weakref__']
1902 yes = Weak()
1903 r = weakref.ref(yes)
1904 verify(r() is yes)
1905 del yes
1906 verify(r() is None)
1907 del r
1908
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001909def properties():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001910 if verbose: print("Testing property...")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001911 class C(object):
1912 def getx(self):
1913 return self.__x
1914 def setx(self, value):
1915 self.__x = value
1916 def delx(self):
1917 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001918 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001919 a = C()
1920 verify(not hasattr(a, "x"))
1921 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001922 vereq(a._C__x, 42)
1923 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001924 del a.x
1925 verify(not hasattr(a, "x"))
1926 verify(not hasattr(a, "_C__x"))
1927 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001928 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001929 C.x.__delete__(a)
1930 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001931
Tim Peters66c1a522001-09-24 21:17:50 +00001932 raw = C.__dict__['x']
1933 verify(isinstance(raw, property))
1934
1935 attrs = dir(raw)
1936 verify("__doc__" in attrs)
1937 verify("fget" in attrs)
1938 verify("fset" in attrs)
1939 verify("fdel" in attrs)
1940
Guido van Rossum45704552001-10-08 16:35:45 +00001941 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001942 verify(raw.fget is C.__dict__['getx'])
1943 verify(raw.fset is C.__dict__['setx'])
1944 verify(raw.fdel is C.__dict__['delx'])
1945
1946 for attr in "__doc__", "fget", "fset", "fdel":
1947 try:
1948 setattr(raw, attr, 42)
Collin Winter42dae6a2007-03-28 21:44:53 +00001949 except AttributeError as msg:
Tim Peters66c1a522001-09-24 21:17:50 +00001950 if str(msg).find('readonly') < 0:
1951 raise TestFailed("when setting readonly attr %r on a "
Collin Winter42dae6a2007-03-28 21:44:53 +00001952 "property, got unexpected AttributeError "
Tim Peters66c1a522001-09-24 21:17:50 +00001953 "msg %r" % (attr, str(msg)))
1954 else:
Collin Winter42dae6a2007-03-28 21:44:53 +00001955 raise TestFailed("expected AttributeError from trying to set "
Tim Peters66c1a522001-09-24 21:17:50 +00001956 "readonly %r attr on a property" % attr)
1957
Neal Norwitz673cd822002-10-18 16:33:13 +00001958 class D(object):
1959 __getitem__ = property(lambda s: 1/0)
1960
1961 d = D()
1962 try:
1963 for i in d:
1964 str(i)
1965 except ZeroDivisionError:
1966 pass
1967 else:
1968 raise TestFailed, "expected ZeroDivisionError from bad property"
1969
Georg Brandl533ff6f2006-03-08 18:09:27 +00001970 class E(object):
1971 def getter(self):
1972 "getter method"
1973 return 0
1974 def setter(self, value):
1975 "setter method"
1976 pass
1977 prop = property(getter)
1978 vereq(prop.__doc__, "getter method")
1979 prop2 = property(fset=setter)
1980 vereq(prop2.__doc__, None)
1981
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001982 # this segfaulted in 2.5b2
1983 try:
1984 import _testcapi
1985 except ImportError:
1986 pass
1987 else:
1988 class X(object):
1989 p = property(_testcapi.test_with_docstring)
1990
1991
Guido van Rossumc4a18802001-08-24 16:55:27 +00001992def supers():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001993 if verbose: print("Testing super...")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001994
1995 class A(object):
1996 def meth(self, a):
1997 return "A(%r)" % a
1998
Guido van Rossum45704552001-10-08 16:35:45 +00001999 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002000
2001 class B(A):
2002 def __init__(self):
2003 self.__super = super(B, self)
2004 def meth(self, a):
2005 return "B(%r)" % a + self.__super.meth(a)
2006
Guido van Rossum45704552001-10-08 16:35:45 +00002007 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002008
2009 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002010 def meth(self, a):
2011 return "C(%r)" % a + self.__super.meth(a)
2012 C._C__super = super(C)
2013
Guido van Rossum45704552001-10-08 16:35:45 +00002014 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002015
2016 class D(C, B):
2017 def meth(self, a):
2018 return "D(%r)" % a + super(D, self).meth(a)
2019
Guido van Rossum5b443c62001-12-03 15:38:28 +00002020 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2021
2022 # Test for subclassing super
2023
2024 class mysuper(super):
2025 def __init__(self, *args):
2026 return super(mysuper, self).__init__(*args)
2027
2028 class E(D):
2029 def meth(self, a):
2030 return "E(%r)" % a + mysuper(E, self).meth(a)
2031
2032 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2033
2034 class F(E):
2035 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002036 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002037 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2038 F._F__super = mysuper(F)
2039
2040 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2041
2042 # Make sure certain errors are raised
2043
2044 try:
2045 super(D, 42)
2046 except TypeError:
2047 pass
2048 else:
2049 raise TestFailed, "shouldn't allow super(D, 42)"
2050
2051 try:
2052 super(D, C())
2053 except TypeError:
2054 pass
2055 else:
2056 raise TestFailed, "shouldn't allow super(D, C())"
2057
2058 try:
2059 super(D).__get__(12)
2060 except TypeError:
2061 pass
2062 else:
2063 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2064
2065 try:
2066 super(D).__get__(C())
2067 except TypeError:
2068 pass
2069 else:
2070 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002071
Guido van Rossuma4541a32003-04-16 20:02:22 +00002072 # Make sure data descriptors can be overridden and accessed via super
2073 # (new feature in Python 2.3)
2074
2075 class DDbase(object):
2076 def getx(self): return 42
2077 x = property(getx)
2078
2079 class DDsub(DDbase):
2080 def getx(self): return "hello"
2081 x = property(getx)
2082
2083 dd = DDsub()
2084 vereq(dd.x, "hello")
2085 vereq(super(DDsub, dd).x, 42)
2086
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002087 # Ensure that super() lookup of descriptor from classmethod
2088 # works (SF ID# 743627)
2089
2090 class Base(object):
2091 aProp = property(lambda self: "foo")
2092
2093 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002094 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002095 def test(klass):
2096 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002097
2098 veris(Sub.test(), Base.aProp)
2099
Thomas Wouters89f507f2006-12-13 04:49:30 +00002100 # Verify that super() doesn't allow keyword args
2101 try:
2102 super(Base, kw=1)
2103 except TypeError:
2104 pass
2105 else:
2106 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002107
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002108def inherits():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002109 if verbose: print("Testing inheritance from basic types...")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002110
2111 class hexint(int):
2112 def __repr__(self):
2113 return hex(self)
2114 def __add__(self, other):
2115 return hexint(int.__add__(self, other))
2116 # (Note that overriding __radd__ doesn't work,
2117 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002118 vereq(repr(hexint(7) + 9), "0x10")
2119 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002120 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002121 vereq(a, 12345)
2122 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002123 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002124 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002125 verify((+a).__class__ is int)
2126 verify((a >> 0).__class__ is int)
2127 verify((a << 0).__class__ is int)
2128 verify((hexint(0) << 12).__class__ is int)
2129 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002130
Guido van Rossume2a383d2007-01-15 16:59:06 +00002131 class octlong(int):
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002132 __slots__ = []
2133 def __str__(self):
2134 s = oct(self)
2135 if s[-1] == 'L':
2136 s = s[:-1]
2137 return s
2138 def __add__(self, other):
2139 return self.__class__(super(octlong, self).__add__(other))
2140 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002141 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002142 # (Note that overriding __radd__ here only seems to work
2143 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002144 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002145 a = octlong(12345)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002146 vereq(a, 12345)
2147 vereq(int(a), 12345)
2148 vereq(hash(a), hash(12345))
2149 verify(int(a).__class__ is int)
2150 verify((+a).__class__ is int)
2151 verify((-a).__class__ is int)
2152 verify((-octlong(0)).__class__ is int)
2153 verify((a >> 0).__class__ is int)
2154 verify((a << 0).__class__ is int)
2155 verify((a - 0).__class__ is int)
2156 verify((a * 1).__class__ is int)
2157 verify((a ** 1).__class__ is int)
2158 verify((a // 1).__class__ is int)
2159 verify((1 * a).__class__ is int)
2160 verify((a | 0).__class__ is int)
2161 verify((a ^ 0).__class__ is int)
2162 verify((a & -1).__class__ is int)
2163 verify((octlong(0) << 12).__class__ is int)
2164 verify((octlong(0) >> 12).__class__ is int)
2165 verify(abs(octlong(0)).__class__ is int)
Tim Peters69c2de32001-09-11 22:31:33 +00002166
2167 # Because octlong overrides __add__, we can't check the absence of +0
2168 # optimizations using octlong.
Guido van Rossume2a383d2007-01-15 16:59:06 +00002169 class longclone(int):
Tim Peters69c2de32001-09-11 22:31:33 +00002170 pass
2171 a = longclone(1)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002172 verify((a + 0).__class__ is int)
2173 verify((0 + a).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002174
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002175 # Check that negative clones don't segfault
2176 a = longclone(-1)
2177 vereq(a.__dict__, {})
Guido van Rossume2a383d2007-01-15 16:59:06 +00002178 vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002179
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002180 class precfloat(float):
2181 __slots__ = ['prec']
2182 def __init__(self, value=0.0, prec=12):
2183 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002184 def __repr__(self):
2185 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002186 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002187 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002188 vereq(a, 12345.0)
2189 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002190 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002191 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002192 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002193
Tim Peters2400fa42001-09-12 19:12:49 +00002194 class madcomplex(complex):
2195 def __repr__(self):
2196 return "%.17gj%+.17g" % (self.imag, self.real)
2197 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002198 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002199 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002200 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002201 vereq(a, base)
2202 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002203 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002204 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002205 vereq(repr(a), "4j-3")
2206 vereq(a, base)
2207 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002208 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002209 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002210 veris((+a).__class__, complex)
2211 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002212 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002213 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002214 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002215 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002216 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002217 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002218 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002219
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002220 class madtuple(tuple):
2221 _rev = None
2222 def rev(self):
2223 if self._rev is not None:
2224 return self._rev
2225 L = list(self)
2226 L.reverse()
2227 self._rev = self.__class__(L)
2228 return self._rev
2229 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002230 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2231 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2232 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002233 for i in range(512):
2234 t = madtuple(range(i))
2235 u = t.rev()
2236 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002237 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002238 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002239 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002240 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002241 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002242 verify(a[:].__class__ is tuple)
2243 verify((a * 1).__class__ is tuple)
2244 verify((a * 0).__class__ is tuple)
2245 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002246 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002247 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002248 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002249 verify((a + a).__class__ is tuple)
2250 verify((a * 0).__class__ is tuple)
2251 verify((a * 1).__class__ is tuple)
2252 verify((a * 2).__class__ is tuple)
2253 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002254
2255 class madstring(str):
2256 _rev = None
2257 def rev(self):
2258 if self._rev is not None:
2259 return self._rev
2260 L = list(self)
2261 L.reverse()
2262 self._rev = self.__class__("".join(L))
2263 return self._rev
2264 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002265 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2266 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2267 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002268 for i in range(256):
2269 s = madstring("".join(map(chr, range(i))))
2270 t = s.rev()
2271 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002272 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002273 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002274 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002275 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002276
Tim Peters8fa5dd02001-09-12 02:18:30 +00002277 base = "\x00" * 5
2278 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002279 vereq(s, base)
2280 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002281 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002282 vereq(hash(s), hash(base))
2283 vereq({s: 1}[base], 1)
2284 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002285 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002286 vereq(s + "", 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).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002290 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002291 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002292 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002293 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002294 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002295 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002296 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002297 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002298 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002299 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002300 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002301 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002302 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002303 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002304 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002305 identitytab = ''.join([chr(i) for i in range(256)])
2306 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002308 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002309 vereq(s.translate(identitytab, "x"), base)
2310 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002311 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002312 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002313 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002314 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002315 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002316 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002317 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002318 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002319 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002320 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002321
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002322 class madunicode(str):
Guido van Rossum91ee7982001-08-30 20:52:40 +00002323 _rev = None
2324 def rev(self):
2325 if self._rev is not None:
2326 return self._rev
2327 L = list(self)
2328 L.reverse()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002329 self._rev = self.__class__("".join(L))
Guido van Rossum91ee7982001-08-30 20:52:40 +00002330 return self._rev
2331 u = madunicode("ABCDEF")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002332 vereq(u, "ABCDEF")
2333 vereq(u.rev(), madunicode("FEDCBA"))
2334 vereq(u.rev().rev(), madunicode("ABCDEF"))
2335 base = "12345"
Tim Peters7a29bd52001-09-12 03:03:31 +00002336 u = madunicode(base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002337 vereq(str(u), base)
2338 verify(str(u).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002339 vereq(hash(u), hash(base))
2340 vereq({u: 1}[base], 1)
2341 vereq({base: 1}[u], 1)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002342 verify(u.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002343 vereq(u.strip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002344 verify(u.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002345 vereq(u.lstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002346 verify(u.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002347 vereq(u.rstrip(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002348 verify(u.replace("x", "x").__class__ is str)
2349 vereq(u.replace("x", "x"), base)
2350 verify(u.replace("xy", "xy").__class__ is str)
2351 vereq(u.replace("xy", "xy"), base)
2352 verify(u.center(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002353 vereq(u.center(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002354 verify(u.ljust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002355 vereq(u.ljust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002356 verify(u.rjust(len(u)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002357 vereq(u.rjust(len(u)), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002358 verify(u.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002359 vereq(u.lower(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002360 verify(u.upper().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002361 vereq(u.upper(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002362 verify(u.capitalize().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002363 vereq(u.capitalize(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002364 verify(u.title().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002365 vereq(u.title(), base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002366 verify((u + "").__class__ is str)
2367 vereq(u + "", base)
2368 verify(("" + u).__class__ is str)
2369 vereq("" + u, base)
2370 verify((u * 0).__class__ is str)
2371 vereq(u * 0, "")
2372 verify((u * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002373 vereq(u * 1, base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002374 verify((u * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002375 vereq(u * 2, base + base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002376 verify(u[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002377 vereq(u[:], base)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002378 verify(u[0:0].__class__ is str)
2379 vereq(u[0:0], "")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002380
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002381 class sublist(list):
2382 pass
2383 a = sublist(range(5))
Guido van Rossum805365e2007-05-07 22:24:25 +00002384 vereq(a, list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002385 a.append("hello")
Guido van Rossum805365e2007-05-07 22:24:25 +00002386 vereq(a, list(range(5)) + ["hello"])
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002387 a[5] = 5
Guido van Rossum805365e2007-05-07 22:24:25 +00002388 vereq(a, list(range(6)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002389 a.extend(range(6, 20))
Guido van Rossum805365e2007-05-07 22:24:25 +00002390 vereq(a, list(range(20)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002391 a[-5:] = []
Guido van Rossum805365e2007-05-07 22:24:25 +00002392 vereq(a, list(range(15)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002393 del a[10:15]
2394 vereq(len(a), 10)
Guido van Rossum805365e2007-05-07 22:24:25 +00002395 vereq(a, list(range(10)))
2396 vereq(list(a), list(range(10)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002397 vereq(a[0], 0)
2398 vereq(a[9], 9)
2399 vereq(a[-10], 0)
2400 vereq(a[-1], 9)
Guido van Rossum805365e2007-05-07 22:24:25 +00002401 vereq(a[:5], list(range(5)))
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002402
Tim Peters59c9a642001-09-13 05:38:56 +00002403 class CountedInput(file):
2404 """Counts lines read by self.readline().
2405
2406 self.lineno is the 0-based ordinal of the last line read, up to
2407 a maximum of one greater than the number of lines in the file.
2408
2409 self.ateof is true if and only if the final "" line has been read,
2410 at which point self.lineno stops incrementing, and further calls
2411 to readline() continue to return "".
2412 """
2413
2414 lineno = 0
2415 ateof = 0
2416 def readline(self):
2417 if self.ateof:
2418 return ""
2419 s = file.readline(self)
2420 # Next line works too.
2421 # s = super(CountedInput, self).readline()
2422 self.lineno += 1
2423 if s == "":
2424 self.ateof = 1
2425 return s
2426
Alex Martelli01c77c62006-08-24 02:58:11 +00002427 f = open(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002428 lines = ['a\n', 'b\n', 'c\n']
2429 try:
2430 f.writelines(lines)
2431 f.close()
2432 f = CountedInput(TESTFN)
Guido van Rossum805365e2007-05-07 22:24:25 +00002433 for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]):
Tim Peters59c9a642001-09-13 05:38:56 +00002434 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002435 vereq(expected, got)
2436 vereq(f.lineno, i)
2437 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002438 f.close()
2439 finally:
2440 try:
2441 f.close()
2442 except:
2443 pass
2444 try:
2445 import os
2446 os.unlink(TESTFN)
2447 except:
2448 pass
2449
Tim Peters808b94e2001-09-13 19:33:07 +00002450def keywords():
2451 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002452 print("Testing keyword args to basic type constructors ...")
Guido van Rossum45704552001-10-08 16:35:45 +00002453 vereq(int(x=1), 1)
2454 vereq(float(x=2), 2.0)
Guido van Rossume2a383d2007-01-15 16:59:06 +00002455 vereq(int(x=3), 3)
Guido van Rossum45704552001-10-08 16:35:45 +00002456 vereq(complex(imag=42, real=666), complex(666, 42))
2457 vereq(str(object=500), '500')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002458 vereq(str(string='abc', errors='strict'), 'abc')
Guido van Rossum45704552001-10-08 16:35:45 +00002459 vereq(tuple(sequence=range(3)), (0, 1, 2))
Guido van Rossum805365e2007-05-07 22:24:25 +00002460 vereq(list(sequence=(0, 1, 2)), list(range(3)))
Just van Rossuma797d812002-11-23 09:45:04 +00002461 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002462
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002463 for constructor in (int, float, int, complex, str, str,
Just van Rossuma797d812002-11-23 09:45:04 +00002464 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002465 try:
2466 constructor(bogus_keyword_arg=1)
2467 except TypeError:
2468 pass
2469 else:
2470 raise TestFailed("expected TypeError from bogus keyword "
2471 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002472
Tim Peters0ab085c2001-09-14 00:25:33 +00002473def str_subclass_as_dict_key():
2474 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002475 print("Testing a str subclass used as dict key ..")
Tim Peters0ab085c2001-09-14 00:25:33 +00002476
2477 class cistr(str):
2478 """Sublcass of str that computes __eq__ case-insensitively.
2479
2480 Also computes a hash code of the string in canonical form.
2481 """
2482
2483 def __init__(self, value):
2484 self.canonical = value.lower()
2485 self.hashcode = hash(self.canonical)
2486
2487 def __eq__(self, other):
2488 if not isinstance(other, cistr):
2489 other = cistr(other)
2490 return self.canonical == other.canonical
2491
2492 def __hash__(self):
2493 return self.hashcode
2494
Guido van Rossum45704552001-10-08 16:35:45 +00002495 vereq(cistr('ABC'), 'abc')
2496 vereq('aBc', cistr('ABC'))
2497 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002498
2499 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002500 vereq(d[cistr('one')], 1)
2501 vereq(d[cistr('tWo')], 2)
2502 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002503 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002504 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002505
Guido van Rossumab3b0342001-09-18 20:38:53 +00002506def classic_comparisons():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002507 if verbose: print("Testing classic comparisons...")
Guido van Rossum0639f592001-09-18 21:06:04 +00002508 class classic:
2509 pass
2510 for base in (classic, int, object):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002511 if verbose: print(" (base = %s)" % base)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002512 class C(base):
2513 def __init__(self, value):
2514 self.value = int(value)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002515 def __eq__(self, other):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002516 if isinstance(other, C):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002517 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002518 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002519 return self.value == other
Guido van Rossumab3b0342001-09-18 20:38:53 +00002520 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002521 def __ne__(self, other):
2522 if isinstance(other, C):
2523 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002524 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002525 return self.value != other
2526 return NotImplemented
2527 def __lt__(self, other):
2528 if isinstance(other, C):
2529 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002530 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002531 return self.value < other
2532 return NotImplemented
2533 def __le__(self, other):
2534 if isinstance(other, C):
2535 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002536 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002537 return self.value <= other
2538 return NotImplemented
2539 def __gt__(self, other):
2540 if isinstance(other, C):
2541 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002542 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002543 return self.value > other
2544 return NotImplemented
2545 def __ge__(self, other):
2546 if isinstance(other, C):
2547 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002548 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002549 return self.value >= other
2550 return NotImplemented
2551
Guido van Rossumab3b0342001-09-18 20:38:53 +00002552 c1 = C(1)
2553 c2 = C(2)
2554 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002555 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002556 c = {1: c1, 2: c2, 3: c3}
2557 for x in 1, 2, 3:
2558 for y in 1, 2, 3:
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002559 ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002560 for op in "<", "<=", "==", "!=", ">", ">=":
2561 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2562 "x=%d, y=%d" % (x, y))
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002563 ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2564 ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Guido van Rossumab3b0342001-09-18 20:38:53 +00002565
Guido van Rossum0639f592001-09-18 21:06:04 +00002566def rich_comparisons():
2567 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002568 print("Testing rich comparisons...")
Guido van Rossum22056422001-09-24 17:52:04 +00002569 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002570 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002571 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002572 vereq(z, 1+0j)
2573 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002574 class ZZ(complex):
2575 def __eq__(self, other):
2576 try:
2577 return abs(self - other) <= 1e-6
2578 except:
2579 return NotImplemented
2580 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002581 vereq(zz, 1+0j)
2582 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002583
Guido van Rossum0639f592001-09-18 21:06:04 +00002584 class classic:
2585 pass
2586 for base in (classic, int, object, list):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002587 if verbose: print(" (base = %s)" % base)
Guido van Rossum0639f592001-09-18 21:06:04 +00002588 class C(base):
2589 def __init__(self, value):
2590 self.value = int(value)
2591 def __cmp__(self, other):
2592 raise TestFailed, "shouldn't call __cmp__"
2593 def __eq__(self, other):
2594 if isinstance(other, C):
2595 return self.value == other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002596 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002597 return self.value == other
2598 return NotImplemented
2599 def __ne__(self, other):
2600 if isinstance(other, C):
2601 return self.value != other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002602 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002603 return self.value != other
2604 return NotImplemented
2605 def __lt__(self, other):
2606 if isinstance(other, C):
2607 return self.value < other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002608 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002609 return self.value < other
2610 return NotImplemented
2611 def __le__(self, other):
2612 if isinstance(other, C):
2613 return self.value <= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002614 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002615 return self.value <= other
2616 return NotImplemented
2617 def __gt__(self, other):
2618 if isinstance(other, C):
2619 return self.value > other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002620 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002621 return self.value > other
2622 return NotImplemented
2623 def __ge__(self, other):
2624 if isinstance(other, C):
2625 return self.value >= other.value
Guido van Rossume2a383d2007-01-15 16:59:06 +00002626 if isinstance(other, int) or isinstance(other, int):
Guido van Rossum0639f592001-09-18 21:06:04 +00002627 return self.value >= other
2628 return NotImplemented
2629 c1 = C(1)
2630 c2 = C(2)
2631 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002632 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002633 c = {1: c1, 2: c2, 3: c3}
2634 for x in 1, 2, 3:
2635 for y in 1, 2, 3:
2636 for op in "<", "<=", "==", "!=", ">", ">=":
2637 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2638 "x=%d, y=%d" % (x, y))
2639 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2640 "x=%d, y=%d" % (x, y))
2641 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2642 "x=%d, y=%d" % (x, y))
2643
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002644def descrdoc():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002645 if verbose: print("Testing descriptor doc strings...")
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002646 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002647 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002648 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002649 check(file.name, "file name") # member descriptor
2650
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002651def setclass():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002652 if verbose: print("Testing __class__ assignment...")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002653 class C(object): pass
2654 class D(object): pass
2655 class E(object): pass
2656 class F(D, E): pass
2657 for cls in C, D, E, F:
2658 for cls2 in C, D, E, F:
2659 x = cls()
2660 x.__class__ = cls2
2661 verify(x.__class__ is cls2)
2662 x.__class__ = cls
2663 verify(x.__class__ is cls)
2664 def cant(x, C):
2665 try:
2666 x.__class__ = C
2667 except TypeError:
2668 pass
2669 else:
2670 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002671 try:
2672 delattr(x, "__class__")
2673 except TypeError:
2674 pass
2675 else:
2676 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002677 cant(C(), list)
2678 cant(list(), C)
2679 cant(C(), 1)
2680 cant(C(), object)
2681 cant(object(), list)
2682 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002683 class Int(int): __slots__ = []
2684 cant(2, Int)
2685 cant(Int(), int)
2686 cant(True, int)
2687 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002688 o = object()
2689 cant(o, type(1))
2690 cant(o, type(None))
2691 del o
Guido van Rossumd8faa362007-04-27 19:54:29 +00002692 class G(object):
2693 __slots__ = ["a", "b"]
2694 class H(object):
2695 __slots__ = ["b", "a"]
2696 try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002697 str
Guido van Rossumd8faa362007-04-27 19:54:29 +00002698 except NameError:
2699 class I(object):
2700 __slots__ = ["a", "b"]
2701 else:
2702 class I(object):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002703 __slots__ = [str("a"), str("b")]
Guido van Rossumd8faa362007-04-27 19:54:29 +00002704 class J(object):
2705 __slots__ = ["c", "b"]
2706 class K(object):
2707 __slots__ = ["a", "b", "d"]
2708 class L(H):
2709 __slots__ = ["e"]
2710 class M(I):
2711 __slots__ = ["e"]
2712 class N(J):
2713 __slots__ = ["__weakref__"]
2714 class P(J):
2715 __slots__ = ["__dict__"]
2716 class Q(J):
2717 pass
2718 class R(J):
2719 __slots__ = ["__dict__", "__weakref__"]
2720
2721 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2722 x = cls()
2723 x.a = 1
2724 x.__class__ = cls2
2725 verify(x.__class__ is cls2,
2726 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2727 vereq(x.a, 1)
2728 x.__class__ = cls
2729 verify(x.__class__ is cls,
2730 "assigning %r as __class__ for %r silently failed" % (cls, x))
2731 vereq(x.a, 1)
2732 for cls in G, J, K, L, M, N, P, R, list, Int:
2733 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2734 if cls is cls2:
2735 continue
2736 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002737
Guido van Rossum6661be32001-10-26 04:26:12 +00002738def setdict():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002739 if verbose: print("Testing __dict__ assignment...")
Guido van Rossum6661be32001-10-26 04:26:12 +00002740 class C(object): pass
2741 a = C()
2742 a.__dict__ = {'b': 1}
2743 vereq(a.b, 1)
2744 def cant(x, dict):
2745 try:
2746 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002747 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002748 pass
2749 else:
2750 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2751 cant(a, None)
2752 cant(a, [])
2753 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002754 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum360e4b82007-05-14 22:51:27 +00002755
2756 class Base(object):
2757 pass
2758 def verify_dict_readonly(x):
2759 """
2760 x has to be an instance of a class inheriting from Base.
2761 """
2762 cant(x, {})
2763 try:
2764 del x.__dict__
2765 except (AttributeError, TypeError):
2766 pass
2767 else:
2768 raise TestFailed, "shouldn't allow del %r.__dict__" % x
2769 dict_descr = Base.__dict__["__dict__"]
2770 try:
2771 dict_descr.__set__(x, {})
2772 except (AttributeError, TypeError):
2773 pass
2774 else:
2775 raise TestFailed, "dict_descr allowed access to %r's dict" % x
2776
2777 # Classes don't allow __dict__ assignment and have readonly dicts
2778 class Meta1(type, Base):
2779 pass
2780 class Meta2(Base, type):
2781 pass
2782 class D(object):
2783 __metaclass__ = Meta1
2784 class E(object):
2785 __metaclass__ = Meta2
2786 for cls in C, D, E:
2787 verify_dict_readonly(cls)
2788 class_dict = cls.__dict__
2789 try:
2790 class_dict["spam"] = "eggs"
2791 except TypeError:
2792 pass
2793 else:
2794 raise TestFailed, "%r's __dict__ can be modified" % cls
2795
2796 # Modules also disallow __dict__ assignment
2797 class Module1(types.ModuleType, Base):
2798 pass
2799 class Module2(Base, types.ModuleType):
2800 pass
2801 for ModuleType in Module1, Module2:
2802 mod = ModuleType("spam")
2803 verify_dict_readonly(mod)
2804 mod.__dict__["spam"] = "eggs"
2805
2806 # Exception's __dict__ can be replaced, but not deleted
2807 class Exception1(Exception, Base):
2808 pass
2809 class Exception2(Base, Exception):
2810 pass
2811 for ExceptionType in Exception, Exception1, Exception2:
2812 e = ExceptionType()
2813 e.__dict__ = {"a": 1}
2814 vereq(e.a, 1)
2815 try:
2816 del e.__dict__
2817 except (TypeError, AttributeError):
2818 pass
2819 else:
2820 raise TestFaied, "%r's __dict__ can be deleted" % e
2821
Guido van Rossum6661be32001-10-26 04:26:12 +00002822
Guido van Rossum3926a632001-09-25 16:25:58 +00002823def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002824 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002825 print("Testing pickling and copying new-style classes and objects...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002826 import pickle
2827 try:
2828 import cPickle
2829 except ImportError:
2830 cPickle = None
Guido van Rossum3926a632001-09-25 16:25:58 +00002831
2832 def sorteditems(d):
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002833 return sorted(d.items())
Guido van Rossum3926a632001-09-25 16:25:58 +00002834
2835 global C
2836 class C(object):
2837 def __init__(self, a, b):
2838 super(C, self).__init__()
2839 self.a = a
2840 self.b = b
2841 def __repr__(self):
2842 return "C(%r, %r)" % (self.a, self.b)
2843
2844 global C1
2845 class C1(list):
2846 def __new__(cls, a, b):
2847 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002848 def __getnewargs__(self):
2849 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002850 def __init__(self, a, b):
2851 self.a = a
2852 self.b = b
2853 def __repr__(self):
2854 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2855
2856 global C2
2857 class C2(int):
2858 def __new__(cls, a, b, val=0):
2859 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002860 def __getnewargs__(self):
2861 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002862 def __init__(self, a, b, val=0):
2863 self.a = a
2864 self.b = b
2865 def __repr__(self):
2866 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2867
Guido van Rossum90c45142001-11-24 21:07:01 +00002868 global C3
2869 class C3(object):
2870 def __init__(self, foo):
2871 self.foo = foo
2872 def __getstate__(self):
2873 return self.foo
2874 def __setstate__(self, foo):
2875 self.foo = foo
2876
2877 global C4classic, C4
2878 class C4classic: # classic
2879 pass
2880 class C4(C4classic, object): # mixed inheritance
2881 pass
2882
Guido van Rossum3926a632001-09-25 16:25:58 +00002883 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002884 if p is None:
2885 continue # cPickle not found -- skip it
Guido van Rossum3926a632001-09-25 16:25:58 +00002886 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002887 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002888 print(p.__name__, ["text", "binary"][bin])
Guido van Rossum3926a632001-09-25 16:25:58 +00002889
2890 for cls in C, C1, C2:
2891 s = p.dumps(cls, bin)
2892 cls2 = p.loads(s)
2893 verify(cls2 is cls)
2894
2895 a = C1(1, 2); a.append(42); a.append(24)
2896 b = C2("hello", "world", 42)
2897 s = p.dumps((a, b), bin)
2898 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002899 vereq(x.__class__, a.__class__)
2900 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2901 vereq(y.__class__, b.__class__)
2902 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002903 vereq(repr(x), repr(a))
2904 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00002905 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002906 print("a = x =", a)
2907 print("b = y =", b)
Guido van Rossum90c45142001-11-24 21:07:01 +00002908 # Test for __getstate__ and __setstate__ on new style class
2909 u = C3(42)
2910 s = p.dumps(u, bin)
2911 v = p.loads(s)
2912 veris(u.__class__, v.__class__)
2913 vereq(u.foo, v.foo)
2914 # Test for picklability of hybrid class
2915 u = C4()
2916 u.foo = 42
2917 s = p.dumps(u, bin)
2918 v = p.loads(s)
2919 veris(u.__class__, v.__class__)
2920 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002921
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002922 # Testing copy.deepcopy()
2923 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002924 print("deepcopy")
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002925 import copy
2926 for cls in C, C1, C2:
2927 cls2 = copy.deepcopy(cls)
2928 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002929
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002930 a = C1(1, 2); a.append(42); a.append(24)
2931 b = C2("hello", "world", 42)
2932 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002933 vereq(x.__class__, a.__class__)
2934 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2935 vereq(y.__class__, b.__class__)
2936 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00002937 vereq(repr(x), repr(a))
2938 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002939 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002940 print("a = x =", a)
2941 print("b = y =", b)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002942
Guido van Rossum8c842552002-03-14 23:05:54 +00002943def pickleslots():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002944 if verbose: print("Testing pickling of classes with __slots__ ...")
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00002945 import pickle, pickle as cPickle
Guido van Rossum8c842552002-03-14 23:05:54 +00002946 # Pickling of classes with __slots__ but without __getstate__ should fail
2947 global B, C, D, E
2948 class B(object):
2949 pass
2950 for base in [object, B]:
2951 class C(base):
2952 __slots__ = ['a']
2953 class D(C):
2954 pass
2955 try:
2956 pickle.dumps(C())
2957 except TypeError:
2958 pass
2959 else:
2960 raise TestFailed, "should fail: pickle C instance - %s" % base
2961 try:
2962 cPickle.dumps(C())
2963 except TypeError:
2964 pass
2965 else:
2966 raise TestFailed, "should fail: cPickle C instance - %s" % base
2967 try:
2968 pickle.dumps(C())
2969 except TypeError:
2970 pass
2971 else:
2972 raise TestFailed, "should fail: pickle D instance - %s" % base
2973 try:
2974 cPickle.dumps(D())
2975 except TypeError:
2976 pass
2977 else:
2978 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002979 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002980 class C(base):
2981 __slots__ = ['a']
2982 def __getstate__(self):
2983 try:
2984 d = self.__dict__.copy()
2985 except AttributeError:
2986 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002987 for cls in self.__class__.__mro__:
2988 for sn in cls.__dict__.get('__slots__', ()):
2989 try:
2990 d[sn] = getattr(self, sn)
2991 except AttributeError:
2992 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002993 return d
2994 def __setstate__(self, d):
2995 for k, v in d.items():
2996 setattr(self, k, v)
2997 class D(C):
2998 pass
2999 # Now it should work
3000 x = C()
3001 y = pickle.loads(pickle.dumps(x))
3002 vereq(hasattr(y, 'a'), 0)
3003 y = cPickle.loads(cPickle.dumps(x))
3004 vereq(hasattr(y, 'a'), 0)
3005 x.a = 42
3006 y = pickle.loads(pickle.dumps(x))
3007 vereq(y.a, 42)
3008 y = cPickle.loads(cPickle.dumps(x))
3009 vereq(y.a, 42)
3010 x = D()
3011 x.a = 42
3012 x.b = 100
3013 y = pickle.loads(pickle.dumps(x))
3014 vereq(y.a + y.b, 142)
3015 y = cPickle.loads(cPickle.dumps(x))
3016 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003017 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003018 class E(C):
3019 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003020 x = E()
3021 x.a = 42
3022 x.b = "foo"
3023 y = pickle.loads(pickle.dumps(x))
3024 vereq(y.a, x.a)
3025 vereq(y.b, x.b)
3026 y = cPickle.loads(cPickle.dumps(x))
3027 vereq(y.a, x.a)
3028 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003029
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003030def copies():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003031 if verbose: print("Testing copy.copy() and copy.deepcopy()...")
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003032 import copy
3033 class C(object):
3034 pass
3035
3036 a = C()
3037 a.foo = 12
3038 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003039 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003040
3041 a.bar = [1,2,3]
3042 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003043 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003044 verify(c.bar is a.bar)
3045
3046 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003047 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003048 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003049 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003050
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003051def binopoverride():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003052 if verbose: print("Testing overrides of binary operations...")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003053 class I(int):
3054 def __repr__(self):
3055 return "I(%r)" % int(self)
3056 def __add__(self, other):
3057 return I(int(self) + int(other))
3058 __radd__ = __add__
3059 def __pow__(self, other, mod=None):
3060 if mod is None:
3061 return I(pow(int(self), int(other)))
3062 else:
3063 return I(pow(int(self), int(other), int(mod)))
3064 def __rpow__(self, other, mod=None):
3065 if mod is None:
3066 return I(pow(int(other), int(self), mod))
3067 else:
3068 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003069
Walter Dörwald70a6b492004-02-12 17:35:32 +00003070 vereq(repr(I(1) + I(2)), "I(3)")
3071 vereq(repr(I(1) + 2), "I(3)")
3072 vereq(repr(1 + I(2)), "I(3)")
3073 vereq(repr(I(2) ** I(3)), "I(8)")
3074 vereq(repr(2 ** I(3)), "I(8)")
3075 vereq(repr(I(2) ** 3), "I(8)")
3076 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003077 class S(str):
3078 def __eq__(self, other):
3079 return self.lower() == other.lower()
3080
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003081def subclasspropagation():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003082 if verbose: print("Testing propagation of slot functions to subclasses...")
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003083 class A(object):
3084 pass
3085 class B(A):
3086 pass
3087 class C(A):
3088 pass
3089 class D(B, C):
3090 pass
3091 d = D()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003092 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003093 A.__hash__ = lambda self: 42
3094 vereq(hash(d), 42)
3095 C.__hash__ = lambda self: 314
3096 vereq(hash(d), 314)
3097 B.__hash__ = lambda self: 144
3098 vereq(hash(d), 144)
3099 D.__hash__ = lambda self: 100
3100 vereq(hash(d), 100)
3101 del D.__hash__
3102 vereq(hash(d), 144)
3103 del B.__hash__
3104 vereq(hash(d), 314)
3105 del C.__hash__
3106 vereq(hash(d), 42)
3107 del A.__hash__
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003108 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003109 d.foo = 42
3110 d.bar = 42
3111 vereq(d.foo, 42)
3112 vereq(d.bar, 42)
3113 def __getattribute__(self, name):
3114 if name == "foo":
3115 return 24
3116 return object.__getattribute__(self, name)
3117 A.__getattribute__ = __getattribute__
3118 vereq(d.foo, 24)
3119 vereq(d.bar, 42)
3120 def __getattr__(self, name):
3121 if name in ("spam", "foo", "bar"):
3122 return "hello"
3123 raise AttributeError, name
3124 B.__getattr__ = __getattr__
3125 vereq(d.spam, "hello")
3126 vereq(d.foo, 24)
3127 vereq(d.bar, 42)
3128 del A.__getattribute__
3129 vereq(d.foo, 42)
3130 del d.foo
3131 vereq(d.foo, "hello")
3132 vereq(d.bar, 42)
3133 del B.__getattr__
3134 try:
3135 d.foo
3136 except AttributeError:
3137 pass
3138 else:
3139 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003140
Guido van Rossume7f3e242002-06-14 02:35:45 +00003141 # Test a nasty bug in recurse_down_subclasses()
3142 import gc
3143 class A(object):
3144 pass
3145 class B(A):
3146 pass
3147 del B
3148 gc.collect()
3149 A.__setitem__ = lambda *a: None # crash
3150
Tim Petersfc57ccb2001-10-12 02:38:24 +00003151def buffer_inherit():
3152 import binascii
3153 # SF bug [#470040] ParseTuple t# vs subclasses.
3154 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003155 print("Testing that buffer interface is inherited ...")
Tim Petersfc57ccb2001-10-12 02:38:24 +00003156
3157 class MyStr(str):
3158 pass
3159 base = 'abc'
3160 m = MyStr(base)
3161 # b2a_hex uses the buffer interface to get its argument's value, via
3162 # PyArg_ParseTuple 't#' code.
3163 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3164
3165 # It's not clear that unicode will continue to support the character
3166 # buffer interface, and this test will fail if that's taken away.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003167 class MyUni(str):
Tim Petersfc57ccb2001-10-12 02:38:24 +00003168 pass
Guido van Rossumef87d6e2007-05-02 19:09:54 +00003169 base = 'abc'
Tim Petersfc57ccb2001-10-12 02:38:24 +00003170 m = MyUni(base)
3171 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3172
3173 class MyInt(int):
3174 pass
3175 m = MyInt(42)
3176 try:
3177 binascii.b2a_hex(m)
3178 raise TestFailed('subclass of int should not have a buffer interface')
3179 except TypeError:
3180 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003181
Tim Petersc9933152001-10-16 20:18:24 +00003182def str_of_str_subclass():
3183 import binascii
3184 import cStringIO
3185
3186 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003187 print("Testing __str__ defined in subclass of str ...")
Tim Petersc9933152001-10-16 20:18:24 +00003188
3189 class octetstring(str):
3190 def __str__(self):
3191 return binascii.b2a_hex(self)
3192 def __repr__(self):
3193 return self + " repr"
3194
3195 o = octetstring('A')
3196 vereq(type(o), octetstring)
3197 vereq(type(str(o)), str)
3198 vereq(type(repr(o)), str)
3199 vereq(ord(o), 0x41)
3200 vereq(str(o), '41')
3201 vereq(repr(o), 'A repr')
3202 vereq(o.__str__(), '41')
3203 vereq(o.__repr__(), 'A repr')
3204
3205 capture = cStringIO.StringIO()
3206 # Calling str() or not exercises different internal paths.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003207 print(o, file=capture)
3208 print(str(o), file=capture)
Tim Petersc9933152001-10-16 20:18:24 +00003209 vereq(capture.getvalue(), '41\n41\n')
3210 capture.close()
3211
Guido van Rossumc8e56452001-10-22 00:43:43 +00003212def kwdargs():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003213 if verbose: print("Testing keyword arguments to __init__, __call__...")
Guido van Rossumc8e56452001-10-22 00:43:43 +00003214 def f(a): return a
3215 vereq(f.__call__(a=42), 42)
3216 a = []
3217 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003218 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003219
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003220def recursive__call__():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003221 if verbose: print(("Testing recursive __call__() by setting to instance of "
3222 "class ..."))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003223 class A(object):
3224 pass
3225
3226 A.__call__ = A()
3227 try:
3228 A()()
3229 except RuntimeError:
3230 pass
3231 else:
3232 raise TestFailed("Recursion limit should have been reached for "
3233 "__call__()")
3234
Guido van Rossumed87ad82001-10-30 02:33:02 +00003235def delhook():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003236 if verbose: print("Testing __del__ hook...")
Guido van Rossumed87ad82001-10-30 02:33:02 +00003237 log = []
3238 class C(object):
3239 def __del__(self):
3240 log.append(1)
3241 c = C()
3242 vereq(log, [])
3243 del c
3244 vereq(log, [1])
3245
Guido van Rossum29d26062001-12-11 04:37:34 +00003246 class D(object): pass
3247 d = D()
3248 try: del d[0]
3249 except TypeError: pass
3250 else: raise TestFailed, "invalid del() didn't raise TypeError"
3251
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003252def hashinherit():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003253 if verbose: print("Testing hash of mutable subclasses...")
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003254
3255 class mydict(dict):
3256 pass
3257 d = mydict()
3258 try:
3259 hash(d)
3260 except TypeError:
3261 pass
3262 else:
3263 raise TestFailed, "hash() of dict subclass should fail"
3264
3265 class mylist(list):
3266 pass
3267 d = mylist()
3268 try:
3269 hash(d)
3270 except TypeError:
3271 pass
3272 else:
3273 raise TestFailed, "hash() of list subclass should fail"
3274
Guido van Rossum29d26062001-12-11 04:37:34 +00003275def strops():
3276 try: 'a' + 5
3277 except TypeError: pass
3278 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3279
3280 try: ''.split('')
3281 except ValueError: pass
3282 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3283
3284 try: ''.join([0])
3285 except TypeError: pass
3286 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3287
3288 try: ''.rindex('5')
3289 except ValueError: pass
3290 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3291
Guido van Rossum29d26062001-12-11 04:37:34 +00003292 try: '%(n)s' % None
3293 except TypeError: pass
3294 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3295
3296 try: '%(n' % {}
3297 except ValueError: pass
3298 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3299
3300 try: '%*s' % ('abc')
3301 except TypeError: pass
3302 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3303
3304 try: '%*.*s' % ('abc', 5)
3305 except TypeError: pass
3306 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3307
3308 try: '%s' % (1, 2)
3309 except TypeError: pass
3310 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3311
3312 try: '%' % None
3313 except ValueError: pass
3314 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3315
3316 vereq('534253'.isdigit(), 1)
3317 vereq('534253x'.isdigit(), 0)
3318 vereq('%c' % 5, '\x05')
3319 vereq('%c' % '5', '5')
3320
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003321def deepcopyrecursive():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003322 if verbose: print("Testing deepcopy of recursive objects...")
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003323 class Node:
3324 pass
3325 a = Node()
3326 b = Node()
3327 a.b = b
3328 b.a = a
3329 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003330
Guido van Rossumd7035672002-03-12 20:43:31 +00003331def modules():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003332 if verbose: print("Testing uninitialized module objects...")
Guido van Rossumd7035672002-03-12 20:43:31 +00003333 from types import ModuleType as M
3334 m = M.__new__(M)
3335 str(m)
3336 vereq(hasattr(m, "__name__"), 0)
3337 vereq(hasattr(m, "__file__"), 0)
3338 vereq(hasattr(m, "foo"), 0)
3339 vereq(m.__dict__, None)
3340 m.foo = 1
3341 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003342
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003343def dictproxyiterkeys():
3344 class C(object):
3345 def meth(self):
3346 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003347 if verbose: print("Testing dict-proxy iterkeys...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003348 keys = [ key for key in C.__dict__.keys() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003349 keys.sort()
3350 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3351
3352def dictproxyitervalues():
3353 class C(object):
3354 def meth(self):
3355 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003356 if verbose: print("Testing dict-proxy itervalues...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003357 values = [ values for values in C.__dict__.values() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003358 vereq(len(values), 5)
3359
3360def dictproxyiteritems():
3361 class C(object):
3362 def meth(self):
3363 pass
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003364 if verbose: print("Testing dict-proxy iteritems...")
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003365 keys = [ key for (key, value) in C.__dict__.items() ]
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003366 keys.sort()
3367 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3368
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003369def funnynew():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003370 if verbose: print("Testing __new__ returning something unexpected...")
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003371 class C(object):
3372 def __new__(cls, arg):
3373 if isinstance(arg, str): return [1, 2, 3]
3374 elif isinstance(arg, int): return object.__new__(D)
3375 else: return object.__new__(cls)
3376 class D(C):
3377 def __init__(self, arg):
3378 self.foo = arg
3379 vereq(C("1"), [1, 2, 3])
3380 vereq(D("1"), [1, 2, 3])
3381 d = D(None)
3382 veris(d.foo, None)
3383 d = C(1)
3384 vereq(isinstance(d, D), True)
3385 vereq(d.foo, 1)
3386 d = D(1)
3387 vereq(isinstance(d, D), True)
3388 vereq(d.foo, 1)
3389
Guido van Rossume8fc6402002-04-16 16:44:51 +00003390def imulbug():
3391 # SF bug 544647
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003392 if verbose: print("Testing for __imul__ problems...")
Guido van Rossume8fc6402002-04-16 16:44:51 +00003393 class C(object):
3394 def __imul__(self, other):
3395 return (self, other)
3396 x = C()
3397 y = x
3398 y *= 1.0
3399 vereq(y, (x, 1.0))
3400 y = x
3401 y *= 2
3402 vereq(y, (x, 2))
3403 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003404 y *= 3
3405 vereq(y, (x, 3))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003406 y = x
Guido van Rossume2a383d2007-01-15 16:59:06 +00003407 y *= 1<<100
3408 vereq(y, (x, 1<<100))
Guido van Rossume8fc6402002-04-16 16:44:51 +00003409 y = x
3410 y *= None
3411 vereq(y, (x, None))
3412 y = x
3413 y *= "foo"
3414 vereq(y, (x, "foo"))
3415
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003416def docdescriptor():
3417 # SF bug 542984
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003418 if verbose: print("Testing __doc__ descriptor...")
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003419 class DocDescr(object):
3420 def __get__(self, object, otype):
3421 if object:
3422 object = object.__class__.__name__ + ' instance'
3423 if otype:
3424 otype = otype.__name__
3425 return 'object=%s; type=%s' % (object, otype)
3426 class OldClass:
3427 __doc__ = DocDescr()
3428 class NewClass(object):
3429 __doc__ = DocDescr()
3430 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3431 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3432 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3433 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3434
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003435def copy_setstate():
3436 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003437 print("Testing that copy.*copy() correctly uses __setstate__...")
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003438 import copy
3439 class C(object):
3440 def __init__(self, foo=None):
3441 self.foo = foo
3442 self.__foo = foo
3443 def setfoo(self, foo=None):
3444 self.foo = foo
3445 def getfoo(self):
3446 return self.__foo
3447 def __getstate__(self):
3448 return [self.foo]
3449 def __setstate__(self, lst):
3450 assert len(lst) == 1
3451 self.__foo = self.foo = lst[0]
3452 a = C(42)
3453 a.setfoo(24)
3454 vereq(a.foo, 24)
3455 vereq(a.getfoo(), 42)
3456 b = copy.copy(a)
3457 vereq(b.foo, 24)
3458 vereq(b.getfoo(), 24)
3459 b = copy.deepcopy(a)
3460 vereq(b.foo, 24)
3461 vereq(b.getfoo(), 24)
3462
Guido van Rossum09638c12002-06-13 19:17:46 +00003463def slices():
3464 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003465 print("Testing cases with slices and overridden __getitem__ ...")
Guido van Rossum09638c12002-06-13 19:17:46 +00003466 # Strings
3467 vereq("hello"[:4], "hell")
3468 vereq("hello"[slice(4)], "hell")
3469 vereq(str.__getitem__("hello", slice(4)), "hell")
3470 class S(str):
3471 def __getitem__(self, x):
3472 return str.__getitem__(self, x)
3473 vereq(S("hello")[:4], "hell")
3474 vereq(S("hello")[slice(4)], "hell")
3475 vereq(S("hello").__getitem__(slice(4)), "hell")
3476 # Tuples
3477 vereq((1,2,3)[:2], (1,2))
3478 vereq((1,2,3)[slice(2)], (1,2))
3479 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3480 class T(tuple):
3481 def __getitem__(self, x):
3482 return tuple.__getitem__(self, x)
3483 vereq(T((1,2,3))[:2], (1,2))
3484 vereq(T((1,2,3))[slice(2)], (1,2))
3485 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3486 # Lists
3487 vereq([1,2,3][:2], [1,2])
3488 vereq([1,2,3][slice(2)], [1,2])
3489 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3490 class L(list):
3491 def __getitem__(self, x):
3492 return list.__getitem__(self, x)
3493 vereq(L([1,2,3])[:2], [1,2])
3494 vereq(L([1,2,3])[slice(2)], [1,2])
3495 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3496 # Now do lists and __setitem__
3497 a = L([1,2,3])
3498 a[slice(1, 3)] = [3,2]
3499 vereq(a, [1,3,2])
3500 a[slice(0, 2, 1)] = [3,1]
3501 vereq(a, [3,1,2])
3502 a.__setitem__(slice(1, 3), [2,1])
3503 vereq(a, [3,2,1])
3504 a.__setitem__(slice(0, 2, 1), [2,3])
3505 vereq(a, [2,3,1])
3506
Tim Peters2484aae2002-07-11 06:56:07 +00003507def subtype_resurrection():
3508 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003509 print("Testing resurrection of new-style instance...")
Tim Peters2484aae2002-07-11 06:56:07 +00003510
3511 class C(object):
3512 container = []
3513
3514 def __del__(self):
3515 # resurrect the instance
3516 C.container.append(self)
3517
3518 c = C()
3519 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003520 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003521 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003522 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003523
3524 # If that didn't blow up, it's also interesting to see whether clearing
3525 # the last container slot works: that will attempt to delete c again,
3526 # which will cause c to get appended back to the container again "during"
3527 # the del.
3528 del C.container[-1]
3529 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003530 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003531
Tim Peters14cb1e12002-07-11 18:26:21 +00003532 # Make c mortal again, so that the test framework with -l doesn't report
3533 # it as a leak.
3534 del C.__del__
3535
Guido van Rossum2d702462002-08-06 21:28:28 +00003536def slottrash():
3537 # Deallocating deeply nested slotted trash caused stack overflows
3538 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003539 print("Testing slot trash...")
Guido van Rossum2d702462002-08-06 21:28:28 +00003540 class trash(object):
3541 __slots__ = ['x']
3542 def __init__(self, x):
3543 self.x = x
3544 o = None
Guido van Rossum805365e2007-05-07 22:24:25 +00003545 for i in range(50000):
Guido van Rossum2d702462002-08-06 21:28:28 +00003546 o = trash(o)
3547 del o
3548
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003549def slotmultipleinheritance():
3550 # SF bug 575229, multiple inheritance w/ slots dumps core
3551 class A(object):
3552 __slots__=()
3553 class B(object):
3554 pass
3555 class C(A,B) :
3556 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003557 vereq(C.__basicsize__, B.__basicsize__)
3558 verify(hasattr(C, '__dict__'))
3559 verify(hasattr(C, '__weakref__'))
3560 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003561
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003562def testrmul():
3563 # SF patch 592646
3564 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003565 print("Testing correct invocation of __rmul__...")
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003566 class C(object):
3567 def __mul__(self, other):
3568 return "mul"
3569 def __rmul__(self, other):
3570 return "rmul"
3571 a = C()
3572 vereq(a*2, "mul")
3573 vereq(a*2.2, "mul")
3574 vereq(2*a, "rmul")
3575 vereq(2.2*a, "rmul")
3576
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003577def testipow():
3578 # [SF bug 620179]
3579 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003580 print("Testing correct invocation of __ipow__...")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003581 class C(object):
3582 def __ipow__(self, other):
3583 pass
3584 a = C()
3585 a **= 2
3586
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003587def do_this_first():
3588 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003589 print("Testing SF bug 551412 ...")
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003590 # This dumps core when SF bug 551412 isn't fixed --
3591 # but only when test_descr.py is run separately.
3592 # (That can't be helped -- as soon as PyType_Ready()
3593 # is called for PyLong_Type, the bug is gone.)
3594 class UserLong(object):
3595 def __pow__(self, *args):
3596 pass
3597 try:
Guido van Rossume2a383d2007-01-15 16:59:06 +00003598 pow(0, UserLong(), 0)
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003599 except:
3600 pass
3601
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003602 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003603 print("Testing SF bug 570483...")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003604 # Another segfault only when run early
3605 # (before PyType_Ready(tuple) is called)
3606 type.mro(tuple)
3607
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003608def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003609 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003610 print("Testing mutable bases...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003611 # stuff that should work:
3612 class C(object):
3613 pass
3614 class C2(object):
3615 def __getattribute__(self, attr):
3616 if attr == 'a':
3617 return 2
3618 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003619 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003620 def meth(self):
3621 return 1
3622 class D(C):
3623 pass
3624 class E(D):
3625 pass
3626 d = D()
3627 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003628 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003629 D.__bases__ = (C2,)
3630 vereq(d.meth(), 1)
3631 vereq(e.meth(), 1)
3632 vereq(d.a, 2)
3633 vereq(e.a, 2)
3634 vereq(C2.__subclasses__(), [D])
3635
3636 # stuff that shouldn't:
3637 class L(list):
3638 pass
3639
3640 try:
3641 L.__bases__ = (dict,)
3642 except TypeError:
3643 pass
3644 else:
3645 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3646
3647 try:
3648 list.__bases__ = (dict,)
3649 except TypeError:
3650 pass
3651 else:
3652 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3653
3654 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00003655 D.__bases__ = (C2, list)
3656 except TypeError:
3657 pass
3658 else:
3659 assert 0, "best_base calculation found wanting"
3660
3661 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003662 del D.__bases__
3663 except TypeError:
3664 pass
3665 else:
3666 raise TestFailed, "shouldn't be able to delete .__bases__"
3667
3668 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003669 D.__bases__ = ()
Guido van Rossumb940e112007-01-10 16:19:56 +00003670 except TypeError as msg:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003671 if str(msg) == "a new-style class can't have only classic bases":
3672 raise TestFailed, "wrong error message for .__bases__ = ()"
3673 else:
3674 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3675
3676 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003677 D.__bases__ = (D,)
3678 except TypeError:
3679 pass
3680 else:
3681 # actually, we'll have crashed by here...
3682 raise TestFailed, "shouldn't be able to create inheritance cycles"
3683
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003684 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003685 D.__bases__ = (C, C)
3686 except TypeError:
3687 pass
3688 else:
3689 raise TestFailed, "didn't detect repeated base classes"
3690
3691 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003692 D.__bases__ = (E,)
3693 except TypeError:
3694 pass
3695 else:
3696 raise TestFailed, "shouldn't be able to create inheritance cycles"
3697
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003698def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003699 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003700 print("Testing mutable bases with failing mro...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003701 class WorkOnce(type):
3702 def __new__(self, name, bases, ns):
3703 self.flag = 0
3704 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3705 def mro(self):
3706 if self.flag > 0:
3707 raise RuntimeError, "bozo"
3708 else:
3709 self.flag += 1
3710 return type.mro(self)
3711
3712 class WorkAlways(type):
3713 def mro(self):
3714 # this is here to make sure that .mro()s aren't called
3715 # with an exception set (which was possible at one point).
3716 # An error message will be printed in a debug build.
3717 # What's a good way to test for this?
3718 return type.mro(self)
3719
3720 class C(object):
3721 pass
3722
3723 class C2(object):
3724 pass
3725
3726 class D(C):
3727 pass
3728
3729 class E(D):
3730 pass
3731
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003732 class F(D, metaclass=WorkOnce):
3733 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003734
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003735 class G(D, metaclass=WorkAlways):
3736 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003737
3738 # Immediate subclasses have their mro's adjusted in alphabetical
3739 # order, so E's will get adjusted before adjusting F's fails. We
3740 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003741
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003742 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003743 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003744
3745 try:
3746 D.__bases__ = (C2,)
3747 except RuntimeError:
3748 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003749 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003750 else:
3751 raise TestFailed, "exception not propagated"
3752
3753def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003754 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003755 print("Testing mutable bases catch mro conflict...")
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003756 class A(object):
3757 pass
3758
3759 class B(object):
3760 pass
3761
3762 class C(A, B):
3763 pass
3764
3765 class D(A, B):
3766 pass
3767
3768 class E(C, D):
3769 pass
3770
3771 try:
3772 C.__bases__ = (B, A)
3773 except TypeError:
3774 pass
3775 else:
3776 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003777
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003778def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003779 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003780 print("Testing mutable names...")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003781 class C(object):
3782 pass
3783
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003784 # C.__module__ could be 'test_descr' or '__main__'
3785 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003786
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +00003787 C.__name__ = 'D'
3788 vereq((C.__module__, C.__name__), (mod, 'D'))
3789
3790 C.__name__ = 'D.E'
3791 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003792
Guido van Rossum613f24f2003-01-06 23:00:59 +00003793def subclass_right_op():
3794 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003795 print("Testing correct dispatch of subclass overloading __r<op>__...")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003796
3797 # This code tests various cases where right-dispatch of a subclass
3798 # should be preferred over left-dispatch of a base class.
3799
3800 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3801
3802 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003803 def __floordiv__(self, other):
3804 return "B.__floordiv__"
3805 def __rfloordiv__(self, other):
3806 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003807
Guido van Rossumf389c772003-02-27 20:04:19 +00003808 vereq(B(1) // 1, "B.__floordiv__")
3809 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003810
3811 # Case 2: subclass of object; this is just the baseline for case 3
3812
3813 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003814 def __floordiv__(self, other):
3815 return "C.__floordiv__"
3816 def __rfloordiv__(self, other):
3817 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003818
Guido van Rossumf389c772003-02-27 20:04:19 +00003819 vereq(C() // 1, "C.__floordiv__")
3820 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003821
3822 # Case 3: subclass of new-style class; here it gets interesting
3823
3824 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003825 def __floordiv__(self, other):
3826 return "D.__floordiv__"
3827 def __rfloordiv__(self, other):
3828 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003829
Guido van Rossumf389c772003-02-27 20:04:19 +00003830 vereq(D() // C(), "D.__floordiv__")
3831 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003832
3833 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3834
3835 class E(C):
3836 pass
3837
Guido van Rossumf389c772003-02-27 20:04:19 +00003838 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003839
Guido van Rossumf389c772003-02-27 20:04:19 +00003840 vereq(E() // 1, "C.__floordiv__")
3841 vereq(1 // E(), "C.__rfloordiv__")
3842 vereq(E() // C(), "C.__floordiv__")
3843 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003844
Guido van Rossum373c7412003-01-07 13:41:37 +00003845def dict_type_with_metaclass():
3846 if verbose:
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003847 print("Testing type of __dict__ when metaclass set...")
Guido van Rossum373c7412003-01-07 13:41:37 +00003848
3849 class B(object):
3850 pass
3851 class M(type):
3852 pass
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003853 class C(metaclass=M):
Guido van Rossum373c7412003-01-07 13:41:37 +00003854 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003855 pass
Guido van Rossum373c7412003-01-07 13:41:37 +00003856 veris(type(C.__dict__), type(B.__dict__))
3857
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003858def meth_class_get():
3859 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003860 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003861 print("Testing __get__ method of METH_CLASS C methods...")
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003862 # Baseline
3863 arg = [1, 2, 3]
3864 res = {1: None, 2: None, 3: None}
3865 vereq(dict.fromkeys(arg), res)
3866 vereq({}.fromkeys(arg), res)
3867 # Now get the descriptor
3868 descr = dict.__dict__["fromkeys"]
3869 # More baseline using the descriptor directly
3870 vereq(descr.__get__(None, dict)(arg), res)
3871 vereq(descr.__get__({})(arg), res)
3872 # Now check various error cases
3873 try:
3874 descr.__get__(None, None)
3875 except TypeError:
3876 pass
3877 else:
3878 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3879 try:
3880 descr.__get__(42)
3881 except TypeError:
3882 pass
3883 else:
3884 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3885 try:
3886 descr.__get__(None, 42)
3887 except TypeError:
3888 pass
3889 else:
3890 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3891 try:
3892 descr.__get__(None, int)
3893 except TypeError:
3894 pass
3895 else:
3896 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3897
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003898def isinst_isclass():
3899 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003900 print("Testing proxy isinstance() and isclass()...")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003901 class Proxy(object):
3902 def __init__(self, obj):
3903 self.__obj = obj
3904 def __getattribute__(self, name):
3905 if name.startswith("_Proxy__"):
3906 return object.__getattribute__(self, name)
3907 else:
3908 return getattr(self.__obj, name)
3909 # Test with a classic class
3910 class C:
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 classic 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
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003923 # Test with a new-style class
3924 class C(object):
3925 pass
3926 a = C()
3927 pa = Proxy(a)
3928 verify(isinstance(a, C)) # Baseline
3929 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003930 # Test with a new-style subclass
3931 class D(C):
3932 pass
3933 a = D()
3934 pa = Proxy(a)
3935 verify(isinstance(a, C)) # Baseline
3936 verify(isinstance(pa, C)) # Test
3937
3938def proxysuper():
3939 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003940 print("Testing super() for a proxy object...")
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003941 class Proxy(object):
3942 def __init__(self, obj):
3943 self.__obj = obj
3944 def __getattribute__(self, name):
3945 if name.startswith("_Proxy__"):
3946 return object.__getattribute__(self, name)
3947 else:
3948 return getattr(self.__obj, name)
3949
3950 class B(object):
3951 def f(self):
3952 return "B.f"
3953
3954 class C(B):
3955 def f(self):
3956 return super(C, self).f() + "->C.f"
3957
3958 obj = C()
3959 p = Proxy(obj)
3960 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003961
Guido van Rossum52b27052003-04-15 20:05:10 +00003962def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003963 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003964 print("Testing prohibition of Carlo Verre's hack...")
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003965 try:
3966 object.__setattr__(str, "foo", 42)
3967 except TypeError:
3968 pass
3969 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003970 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003971 try:
3972 object.__delattr__(str, "lower")
3973 except TypeError:
3974 pass
3975 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00003976 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003977
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003978def weakref_segfault():
3979 # SF 742911
3980 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00003981 print("Testing weakref segfault...")
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003982
3983 import weakref
3984
3985 class Provoker:
3986 def __init__(self, referrent):
3987 self.ref = weakref.ref(referrent)
3988
3989 def __del__(self):
3990 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00003991
3992 class Oops(object):
3993 pass
3994
3995 o = Oops()
3996 o.whatever = Provoker(o)
3997 del o
3998
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003999def wrapper_segfault():
4000 # SF 927248: deeply nested wrappers could cause stack overflow
4001 f = lambda:None
Guido van Rossum805365e2007-05-07 22:24:25 +00004002 for i in range(1000000):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004003 f = f.__call__
4004 f = None
4005
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004006# Fix SF #762455, segfault when sys.stdout is changed in getattr
4007def filefault():
4008 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004009 print("Testing sys.stdout is changed in getattr...")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004010 import sys
4011 class StdoutGuard:
4012 def __getattr__(self, attr):
4013 sys.stdout = sys.__stdout__
4014 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4015 sys.stdout = StdoutGuard()
4016 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004017 print("Oops!")
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004018 except RuntimeError:
4019 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004020
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004021def vicious_descriptor_nonsense():
4022 # A potential segfault spotted by Thomas Wouters in mail to
4023 # python-dev 2003-04-17, turned into an example & fixed by Michael
4024 # Hudson just less than four months later...
4025 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004026 print("Testing vicious_descriptor_nonsense...")
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004027
4028 class Evil(object):
4029 def __hash__(self):
4030 return hash('attr')
4031 def __eq__(self, other):
4032 del C.attr
4033 return 0
4034
4035 class Descr(object):
4036 def __get__(self, ob, type=None):
4037 return 1
4038
4039 class C(object):
4040 attr = Descr()
4041
4042 c = C()
4043 c.__dict__[Evil()] = 0
4044
4045 vereq(c.attr, 1)
4046 # this makes a crash more likely:
4047 import gc; gc.collect()
4048 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004049
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004050def test_init():
4051 # SF 1155938
4052 class Foo(object):
4053 def __init__(self):
4054 return 10
4055 try:
4056 Foo()
4057 except TypeError:
4058 pass
4059 else:
4060 raise TestFailed, "did not test __init__() for None return"
4061
Armin Rigoc6686b72005-11-07 08:38:00 +00004062def methodwrapper():
4063 # <type 'method-wrapper'> did not support any reflection before 2.5
4064 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004065 print("Testing method-wrapper objects...")
Armin Rigoc6686b72005-11-07 08:38:00 +00004066
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004067 return # XXX should methods really support __eq__?
4068
Armin Rigoc6686b72005-11-07 08:38:00 +00004069 l = []
4070 vereq(l.__add__, l.__add__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004071 vereq(l.__add__, [].__add__)
4072 verify(l.__add__ != [5].__add__)
4073 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004074 verify(l.__add__.__name__ == '__add__')
4075 verify(l.__add__.__self__ is l)
4076 verify(l.__add__.__objclass__ is list)
4077 vereq(l.__add__.__doc__, list.__add__.__doc__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004078 try:
4079 hash(l.__add__)
4080 except TypeError:
4081 pass
4082 else:
4083 raise TestFailed("no TypeError from hash([].__add__)")
4084
4085 t = ()
4086 t += (7,)
4087 vereq(t.__add__, (7,).__add__)
4088 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004089
Armin Rigofd163f92005-12-29 15:59:19 +00004090def notimplemented():
4091 # all binary methods should be able to return a NotImplemented
4092 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004093 print("Testing NotImplemented...")
Armin Rigofd163f92005-12-29 15:59:19 +00004094
4095 import sys
4096 import types
4097 import operator
4098
4099 def specialmethod(self, other):
4100 return NotImplemented
4101
4102 def check(expr, x, y):
4103 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +00004104 exec(expr, {'x': x, 'y': y, 'operator': operator})
Armin Rigofd163f92005-12-29 15:59:19 +00004105 except TypeError:
4106 pass
4107 else:
4108 raise TestFailed("no TypeError from %r" % (expr,))
4109
Guido van Rossume2a383d2007-01-15 16:59:06 +00004110 N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004111 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4112 # ValueErrors instead of TypeErrors
Guido van Rossum13257902007-06-07 23:15:56 +00004113 if 1:
4114 metaclass = type
Armin Rigofd163f92005-12-29 15:59:19 +00004115 for name, expr, iexpr in [
4116 ('__add__', 'x + y', 'x += y'),
4117 ('__sub__', 'x - y', 'x -= y'),
4118 ('__mul__', 'x * y', 'x *= y'),
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004119 ('__truediv__', 'x / y', None),
4120 ('__floordiv__', 'x // y', None),
Armin Rigofd163f92005-12-29 15:59:19 +00004121 ('__mod__', 'x % y', 'x %= y'),
4122 ('__divmod__', 'divmod(x, y)', None),
4123 ('__pow__', 'x ** y', 'x **= y'),
4124 ('__lshift__', 'x << y', 'x <<= y'),
4125 ('__rshift__', 'x >> y', 'x >>= y'),
4126 ('__and__', 'x & y', 'x &= y'),
4127 ('__or__', 'x | y', 'x |= y'),
4128 ('__xor__', 'x ^ y', 'x ^= y'),
Neal Norwitz4886cc32006-08-21 17:06:07 +00004129 ]:
4130 rname = '__r' + name[2:]
Armin Rigofd163f92005-12-29 15:59:19 +00004131 A = metaclass('A', (), {name: specialmethod})
4132 B = metaclass('B', (), {rname: specialmethod})
4133 a = A()
4134 b = B()
4135 check(expr, a, a)
4136 check(expr, a, b)
4137 check(expr, b, a)
4138 check(expr, b, b)
4139 check(expr, a, N1)
4140 check(expr, a, N2)
4141 check(expr, N1, b)
4142 check(expr, N2, b)
4143 if iexpr:
4144 check(iexpr, a, a)
4145 check(iexpr, a, b)
4146 check(iexpr, b, a)
4147 check(iexpr, b, b)
4148 check(iexpr, a, N1)
4149 check(iexpr, a, N2)
4150 iname = '__i' + name[2:]
4151 C = metaclass('C', (), {iname: specialmethod})
4152 c = C()
4153 check(iexpr, c, a)
4154 check(iexpr, c, b)
4155 check(iexpr, c, N1)
4156 check(iexpr, c, N2)
4157
Guido van Rossumd8faa362007-04-27 19:54:29 +00004158def test_assign_slice():
4159 # ceval.c's assign_slice used to check for
4160 # tp->tp_as_sequence->sq_slice instead of
4161 # tp->tp_as_sequence->sq_ass_slice
4162
4163 class C(object):
4164 def __setslice__(self, start, stop, value):
4165 self.value = value
4166
4167 c = C()
4168 c[1:2] = 3
4169 vereq(c.value, 3)
4170
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004171def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004172 weakref_segfault() # Must be first, somehow
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004173 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004174 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004175 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176 lists()
4177 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004178 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004179 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004180 ints()
4181 longs()
4182 floats()
4183 complexes()
4184 spamlists()
4185 spamdicts()
4186 pydicts()
4187 pylists()
4188 metaclass()
4189 pymods()
4190 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004191 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004193 ex5()
4194 monotonicity()
4195 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004196 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004198 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004199 dynamics()
4200 errors()
4201 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004202 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004204 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 classic()
4206 compattr()
4207 newslot()
4208 altmro()
4209 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004210 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004211 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004212 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004213 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004214 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004215 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004216 keywords()
Tim Peters0ab085c2001-09-14 00:25:33 +00004217 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004218 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004219 rich_comparisons()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004220 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004221 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004222 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004223 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004224 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004225 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004226 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004227 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004228 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004229 kwdargs()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004230 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004231 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004232 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004233 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004234 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004235 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004236 dictproxyiterkeys()
4237 dictproxyitervalues()
4238 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004239 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004240 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004241 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004242 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004243 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004244 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004245 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004246 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004247 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004248 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004249 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004250 test_mutable_bases()
4251 test_mutable_bases_with_failing_mro()
4252 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004253 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004254 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004255 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004256 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004257 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004258 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004259 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004260 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004261 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004262 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004263 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004264 notimplemented()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004265 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004266
Guido van Rossumbe19ed72007-02-09 05:37:30 +00004267 if verbose: print("All OK")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004268
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004269if __name__ == "__main__":
4270 test_main()