blob: 2129a7b7c812f7577b63e303c43ba33ee4fe3f02 [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
Tim Petersc2fe6182001-10-30 23:20:46 +00003from test_support import verify, vereq, verbose, TestFailed, TESTFN
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
Tim Peters4d9b4662002-04-16 01:59:17 +00005import warnings
6
7warnings.filterwarnings("ignore",
8 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +00009 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Guido van Rossum875eeaa2001-10-11 18:33:53 +000011def veris(a, b):
12 if a is not b:
13 raise TestFailed, "%r is %r" % (a, b)
14
Tim Peters6d6c1a32001-08-02 04:15:00 +000015def testunop(a, res, expr="len(a)", meth="__len__"):
16 if verbose: print "checking", expr
17 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000018 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000019 t = type(a)
20 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000021 while meth not in t.__dict__:
22 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000023 vereq(m, t.__dict__[meth])
24 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000025 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000026 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000027
28def testbinop(a, b, res, expr="a+b", meth="__add__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000031
32 # XXX Hack so this passes before 2.3 when -Qnew is specified.
33 if meth == "__div__" and 1/2 == 0.5:
34 meth = "__truediv__"
35
Guido van Rossum45704552001-10-08 16:35:45 +000036 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000037 t = type(a)
38 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000039 while meth not in t.__dict__:
40 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000041 vereq(m, t.__dict__[meth])
42 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000043 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000044 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000045
46def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
47 if verbose: print "checking", expr
48 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000049 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000050 t = type(a)
51 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000052 while meth not in t.__dict__:
53 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000054 vereq(m, t.__dict__[meth])
55 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000056 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000057 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000058
59def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
60 if verbose: print "checking", stmt
61 dict = {'a': deepcopy(a), 'b': b}
62 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000063 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000064 t = type(a)
65 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000066 while meth not in t.__dict__:
67 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000068 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000069 dict['a'] = deepcopy(a)
70 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000071 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000072 dict['a'] = deepcopy(a)
73 bm = getattr(dict['a'], meth)
74 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000075 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076
77def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
78 if verbose: print "checking", stmt
79 dict = {'a': deepcopy(a), 'b': b, 'c': c}
80 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000081 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000082 t = type(a)
83 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000084 while meth not in t.__dict__:
85 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000086 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 dict['a'] = deepcopy(a)
88 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000089 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000090 dict['a'] = deepcopy(a)
91 bm = getattr(dict['a'], meth)
92 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000093 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000094
95def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
96 if verbose: print "checking", stmt
97 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
98 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000099 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000101 while meth not in t.__dict__:
102 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +0000103 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000104 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000105 dict['a'] = deepcopy(a)
106 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000107 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108 dict['a'] = deepcopy(a)
109 bm = getattr(dict['a'], meth)
110 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000111 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000112
Tim Peters2f93e282001-10-04 05:27:00 +0000113def class_docstrings():
114 class Classic:
115 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000116 vereq(Classic.__doc__, "A classic docstring.")
117 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000118
119 class Classic2:
120 pass
121 verify(Classic2.__doc__ is None)
122
Tim Peters4fb1fe82001-10-04 05:48:13 +0000123 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000124 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000125 vereq(NewStatic.__doc__, "Another docstring.")
126 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000127
Tim Peters4fb1fe82001-10-04 05:48:13 +0000128 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000129 pass
130 verify(NewStatic2.__doc__ is None)
131
Tim Peters4fb1fe82001-10-04 05:48:13 +0000132 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000133 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000134 vereq(NewDynamic.__doc__, "Another docstring.")
135 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000136
Tim Peters4fb1fe82001-10-04 05:48:13 +0000137 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000138 pass
139 verify(NewDynamic2.__doc__ is None)
140
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141def lists():
142 if verbose: print "Testing list operations..."
143 testbinop([1], [2], [1,2], "a+b", "__add__")
144 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
145 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
146 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
147 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
148 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
149 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
150 testunop([1,2,3], 3, "len(a)", "__len__")
151 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
152 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
153 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
154 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
155
156def dicts():
157 if verbose: print "Testing dict operations..."
158 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
159 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
160 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
161 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
162 d = {1:2,3:4}
163 l1 = []
164 for i in d.keys(): l1.append(i)
165 l = []
166 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000167 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000168 l = []
169 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000170 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000172 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000173 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 d = {1:2, 3:4}
175 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000176 vereq(eval(repr(d), {}), d)
177 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
179
Tim Peters25786c02001-09-02 08:22:48 +0000180def dict_constructor():
181 if verbose:
Tim Petersa427a2b2001-10-29 22:25:45 +0000182 print "Testing dict constructor ..."
183 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000184 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000185 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000186 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000187 d = dict(items={})
Guido van Rossum45704552001-10-08 16:35:45 +0000188 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000189 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000190 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000191 vereq(d, dict(d.items()))
192 vereq(d, dict(items=d.iteritems()))
Tim Peters25786c02001-09-02 08:22:48 +0000193 for badarg in 0, 0L, 0j, "0", [0], (0,):
194 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000195 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000196 except TypeError:
197 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000198 except ValueError:
199 if badarg == "0":
200 # It's a sequence, and its elements are also sequences (gotta
201 # love strings <wink>), but they aren't of length 2, so this
202 # one seemed better as a ValueError than a TypeError.
203 pass
204 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000205 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000206 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 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000209 dict(senseless={})
Tim Peters25786c02001-09-02 08:22:48 +0000210 except TypeError:
211 pass
212 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000213 raise TestFailed("no TypeError from dict(senseless={})")
Tim Peters25786c02001-09-02 08:22:48 +0000214
215 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000216 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000217 except TypeError:
218 pass
219 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000220 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000221
222 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000223 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000224 dict = {1:2, 3:4, 'a':1j}
225
Tim Peters25786c02001-09-02 08:22:48 +0000226 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000227 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000228 except TypeError:
229 pass
230 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000231 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000232
233 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000234 Mapping.__getitem__ = lambda self, i: self.dict[i]
Tim Petersa427a2b2001-10-29 22:25:45 +0000235 d = dict(items=Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000236 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000237
Tim Peters1fc240e2001-10-26 05:06:50 +0000238 # Init from sequence of iterable objects, each producing a 2-sequence.
239 class AddressBookEntry:
240 def __init__(self, first, last):
241 self.first = first
242 self.last = last
243 def __iter__(self):
244 return iter([self.first, self.last])
245
Tim Petersa427a2b2001-10-29 22:25:45 +0000246 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000247 AddressBookEntry('Barry', 'Peters'),
248 AddressBookEntry('Tim', 'Peters'),
249 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000250 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
251
Tim Petersa427a2b2001-10-29 22:25:45 +0000252 d = dict(zip(range(4), range(1, 5)))
253 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000254
255 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000256 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000257 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000258 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000259 except ValueError:
260 pass
261 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000262 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000263
Tim Peters5d2b77c2001-09-03 05:47:38 +0000264def test_dir():
265 if verbose:
266 print "Testing dir() ..."
267 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000268 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000269 del junk
270
271 # Just make sure these don't blow up!
272 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
273 dir(arg)
274
Tim Peters37a309d2001-09-04 01:20:04 +0000275 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000276 class C:
277 Cdata = 1
278 def Cmethod(self): pass
279
280 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
Guido van Rossum45704552001-10-08 16:35:45 +0000281 vereq(dir(C), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000282 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000283
284 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
Guido van Rossum45704552001-10-08 16:35:45 +0000285 vereq(dir(c), cstuff)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000286
287 c.cdata = 2
288 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000289 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000290 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000291
292 class A(C):
293 Adata = 1
294 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000295
Tim Peters37a309d2001-09-04 01:20:04 +0000296 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000297 vereq(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(dir(a), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000301 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000302 a.adata = 42
303 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000304 vereq(dir(a), astuff + ['adata', 'amethod'])
Tim Peters37a309d2001-09-04 01:20:04 +0000305
306 # The same, but with new-style classes. Since these have object as a
307 # base class, a lot more gets sucked in.
308 def interesting(strings):
309 return [s for s in strings if not s.startswith('_')]
310
Tim Peters5d2b77c2001-09-03 05:47:38 +0000311 class C(object):
312 Cdata = 1
313 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000314
315 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000316 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000317
318 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000319 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000320 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000321
322 c.cdata = 2
323 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000324 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000325 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000326
Tim Peters5d2b77c2001-09-03 05:47:38 +0000327 class A(C):
328 Adata = 1
329 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000330
331 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000332 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000333 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000334 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000335 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000336 a.adata = 42
337 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000338 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000339 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000340
Tim Peterscaaff8d2001-09-10 23:12:14 +0000341 # Try a module subclass.
342 import sys
343 class M(type(sys)):
344 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000345 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000346 minstance.b = 2
347 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000348 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
349 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000350
351 class M2(M):
352 def getdict(self):
353 return "Not a dict!"
354 __dict__ = property(getdict)
355
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000356 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000357 m2instance.b = 2
358 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000359 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000360 try:
361 dir(m2instance)
362 except TypeError:
363 pass
364
Tim Peters9e6a3992001-10-30 05:45:26 +0000365 # Two essentially featureless objects, just inheriting stuff from
366 # object.
367 vereq(dir(None), dir(Ellipsis))
368
Guido van Rossum44022412002-05-13 18:29:46 +0000369 # Nasty test case for proxied objects
370 class Wrapper(object):
371 def __init__(self, obj):
372 self.__obj = obj
373 def __repr__(self):
374 return "Wrapper(%s)" % repr(self.__obj)
375 def __getitem__(self, key):
376 return Wrapper(self.__obj[key])
377 def __len__(self):
378 return len(self.__obj)
379 def __getattr__(self, name):
380 return Wrapper(getattr(self.__obj, name))
381
382 class C(object):
383 def __getclass(self):
384 return Wrapper(type(self))
385 __class__ = property(__getclass)
386
387 dir(C()) # This used to segfault
388
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389binops = {
390 'add': '+',
391 'sub': '-',
392 'mul': '*',
393 'div': '/',
394 'mod': '%',
395 'divmod': 'divmod',
396 'pow': '**',
397 'lshift': '<<',
398 'rshift': '>>',
399 'and': '&',
400 'xor': '^',
401 'or': '|',
402 'cmp': 'cmp',
403 'lt': '<',
404 'le': '<=',
405 'eq': '==',
406 'ne': '!=',
407 'gt': '>',
408 'ge': '>=',
409 }
410
411for name, expr in binops.items():
412 if expr.islower():
413 expr = expr + "(a, b)"
414 else:
415 expr = 'a %s b' % expr
416 binops[name] = expr
417
418unops = {
419 'pos': '+',
420 'neg': '-',
421 'abs': 'abs',
422 'invert': '~',
423 'int': 'int',
424 'long': 'long',
425 'float': 'float',
426 'oct': 'oct',
427 'hex': 'hex',
428 }
429
430for name, expr in unops.items():
431 if expr.islower():
432 expr = expr + "(a)"
433 else:
434 expr = '%s a' % expr
435 unops[name] = expr
436
437def numops(a, b, skip=[]):
438 dict = {'a': a, 'b': b}
439 for name, expr in binops.items():
440 if name not in skip:
441 name = "__%s__" % name
442 if hasattr(a, name):
443 res = eval(expr, dict)
444 testbinop(a, b, res, expr, name)
445 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000446 if name not in skip:
447 name = "__%s__" % name
448 if hasattr(a, name):
449 res = eval(expr, dict)
450 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452def ints():
453 if verbose: print "Testing int operations..."
454 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000455 # The following crashes in Python 2.2
456 vereq((1).__nonzero__(), 1)
457 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000458 # This returns 'NotImplemented' in Python 2.2
459 class C(int):
460 def __add__(self, other):
461 return NotImplemented
462 try:
463 C() + ""
464 except TypeError:
465 pass
466 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000467 raise TestFailed, "NotImplemented should have caused TypeError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468
469def longs():
470 if verbose: print "Testing long operations..."
471 numops(100L, 3L)
472
473def floats():
474 if verbose: print "Testing float operations..."
475 numops(100.0, 3.0)
476
477def complexes():
478 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000479 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000480 class Number(complex):
481 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000482 def __new__(cls, *args, **kwds):
483 result = complex.__new__(cls, *args)
484 result.prec = kwds.get('prec', 12)
485 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000486 def __repr__(self):
487 prec = self.prec
488 if self.imag == 0.0:
489 return "%.*g" % (prec, self.real)
490 if self.real == 0.0:
491 return "%.*gj" % (prec, self.imag)
492 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
493 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000494
Tim Peters6d6c1a32001-08-02 04:15:00 +0000495 a = Number(3.14, prec=6)
Guido van Rossum45704552001-10-08 16:35:45 +0000496 vereq(`a`, "3.14")
497 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000498
Tim Peters3f996e72001-09-13 19:18:27 +0000499 a = Number(a, prec=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000500 vereq(`a`, "3.1")
501 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000502
503 a = Number(234.5)
Guido van Rossum45704552001-10-08 16:35:45 +0000504 vereq(`a`, "234.5")
505 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000506
Tim Peters6d6c1a32001-08-02 04:15:00 +0000507def spamlists():
508 if verbose: print "Testing spamlist operations..."
509 import copy, xxsubtype as spam
510 def spamlist(l, memo=None):
511 import xxsubtype as spam
512 return spam.spamlist(l)
513 # This is an ugly hack:
514 copy._deepcopy_dispatch[spam.spamlist] = spamlist
515
516 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
517 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
518 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
519 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
520 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
521 "a[b:c]", "__getslice__")
522 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
523 "a+=b", "__iadd__")
524 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
525 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
526 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
527 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
528 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
529 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
530 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
531 # Test subclassing
532 class C(spam.spamlist):
533 def foo(self): return 1
534 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000535 vereq(a, [])
536 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000537 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000538 vereq(a, [100])
539 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000540 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000541 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000542
543def spamdicts():
544 if verbose: print "Testing spamdict operations..."
545 import copy, xxsubtype as spam
546 def spamdict(d, memo=None):
547 import xxsubtype as spam
548 sd = spam.spamdict()
549 for k, v in d.items(): sd[k] = v
550 return sd
551 # This is an ugly hack:
552 copy._deepcopy_dispatch[spam.spamdict] = spamdict
553
554 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
555 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
556 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
557 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
558 d = spamdict({1:2,3:4})
559 l1 = []
560 for i in d.keys(): l1.append(i)
561 l = []
562 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000563 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564 l = []
565 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000566 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000567 l = []
568 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000569 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000570 straightd = {1:2, 3:4}
571 spamd = spamdict(straightd)
572 testunop(spamd, 2, "len(a)", "__len__")
573 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
574 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
575 "a[b]=c", "__setitem__")
576 # Test subclassing
577 class C(spam.spamdict):
578 def foo(self): return 1
579 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000580 vereq(a.items(), [])
581 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000583 vereq(a.items(), [('foo', 'bar')])
584 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000586 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
588def pydicts():
589 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000590 verify(issubclass(dict, dict))
591 verify(isinstance({}, dict))
592 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000593 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000594 verify(d.__class__ is dict)
595 verify(isinstance(d, dict))
596 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597 state = -1
598 def __init__(self, *a, **kw):
599 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000600 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000601 self.state = a[0]
602 if kw:
603 for k, v in kw.items(): self[v] = k
604 def __getitem__(self, key):
605 return self.get(key, 0)
606 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000607 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000608 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609 def setstate(self, state):
610 self.state = state
611 def getstate(self):
612 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000613 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000614 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000615 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000617 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000619 vereq(a.state, -1)
620 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000622 vereq(a.state, 0)
623 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000625 vereq(a.state, 10)
626 vereq(a.getstate(), 10)
627 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000629 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630 if verbose: print "pydict stress test ..."
631 N = 50
632 for i in range(N):
633 a[i] = C()
634 for j in range(N):
635 a[i][j] = i*j
636 for i in range(N):
637 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000638 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639
640def pylists():
641 if verbose: print "Testing Python subclass of list..."
642 class C(list):
643 def __getitem__(self, i):
644 return list.__getitem__(self, i) + 100
645 def __getslice__(self, i, j):
646 return (i, j)
647 a = C()
648 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000649 vereq(a[0], 100)
650 vereq(a[1], 101)
651 vereq(a[2], 102)
652 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000653
654def metaclass():
655 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656 class C:
657 __metaclass__ = type
658 def __init__(self):
659 self.__state = 0
660 def getstate(self):
661 return self.__state
662 def setstate(self, state):
663 self.__state = state
664 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000665 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000666 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000667 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668 class D:
669 class __metaclass__(type):
670 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000671 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000672 d = D()
673 verify(d.__class__ is D)
674 class M1(type):
675 def __new__(cls, name, bases, dict):
676 dict['__spam__'] = 1
677 return type.__new__(cls, name, bases, dict)
678 class C:
679 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000680 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000681 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000682 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000683
Guido van Rossum309b5662001-08-17 11:43:17 +0000684 class _instance(object):
685 pass
686 class M2(object):
687 def __new__(cls, name, bases, dict):
688 self = object.__new__(cls)
689 self.name = name
690 self.bases = bases
691 self.dict = dict
692 return self
693 __new__ = staticmethod(__new__)
694 def __call__(self):
695 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000696 # Early binding of methods
697 for key in self.dict:
698 if key.startswith("__"):
699 continue
700 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000701 return it
702 class C:
703 __metaclass__ = M2
704 def spam(self):
705 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000706 vereq(C.name, 'C')
707 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000708 verify('spam' in C.dict)
709 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000710 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711
Guido van Rossum91ee7982001-08-30 20:52:40 +0000712 # More metaclass examples
713
714 class autosuper(type):
715 # Automatically add __super to the class
716 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000717 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000718 cls = super(autosuper, metaclass).__new__(metaclass,
719 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000720 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000721 while name[:1] == "_":
722 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000723 if name:
724 name = "_%s__super" % name
725 else:
726 name = "__super"
727 setattr(cls, name, super(cls))
728 return cls
729 class A:
730 __metaclass__ = autosuper
731 def meth(self):
732 return "A"
733 class B(A):
734 def meth(self):
735 return "B" + self.__super.meth()
736 class C(A):
737 def meth(self):
738 return "C" + self.__super.meth()
739 class D(C, B):
740 def meth(self):
741 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000742 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000743 class E(B, C):
744 def meth(self):
745 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000746 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000747
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000748 class autoproperty(type):
749 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000750 # named _get_x and/or _set_x are found
751 def __new__(metaclass, name, bases, dict):
752 hits = {}
753 for key, val in dict.iteritems():
754 if key.startswith("_get_"):
755 key = key[5:]
756 get, set = hits.get(key, (None, None))
757 get = val
758 hits[key] = get, set
759 elif key.startswith("_set_"):
760 key = key[5:]
761 get, set = hits.get(key, (None, None))
762 set = val
763 hits[key] = get, set
764 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000765 dict[key] = property(get, set)
766 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000767 name, bases, dict)
768 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000769 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000770 def _get_x(self):
771 return -self.__x
772 def _set_x(self, x):
773 self.__x = -x
774 a = A()
775 verify(not hasattr(a, "x"))
776 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000777 vereq(a.x, 12)
778 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000779
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000780 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000781 # Merge of multiple cooperating metaclasses
782 pass
783 class A:
784 __metaclass__ = multimetaclass
785 def _get_x(self):
786 return "A"
787 class B(A):
788 def _get_x(self):
789 return "B" + self.__super._get_x()
790 class C(A):
791 def _get_x(self):
792 return "C" + self.__super._get_x()
793 class D(C, B):
794 def _get_x(self):
795 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000796 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000797
Guido van Rossumf76de622001-10-18 15:49:21 +0000798 # Make sure type(x) doesn't call x.__class__.__init__
799 class T(type):
800 counter = 0
801 def __init__(self, *args):
802 T.counter += 1
803 class C:
804 __metaclass__ = T
805 vereq(T.counter, 1)
806 a = C()
807 vereq(type(a), C)
808 vereq(T.counter, 1)
809
Guido van Rossum29d26062001-12-11 04:37:34 +0000810 class C(object): pass
811 c = C()
812 try: c()
813 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000814 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000815
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816def pymods():
817 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000819 import sys
820 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000822 def __init__(self, name):
823 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000824 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000826 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 def __setattr__(self, name, value):
828 log.append(("setattr", name, value))
829 MT.__setattr__(self, name, value)
830 def __delattr__(self, name):
831 log.append(("delattr", name))
832 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000833 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 a.foo = 12
835 x = a.foo
836 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000837 vereq(log, [("setattr", "foo", 12),
838 ("getattr", "foo"),
839 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840
841def multi():
842 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843 class C(object):
844 def __init__(self):
845 self.__state = 0
846 def getstate(self):
847 return self.__state
848 def setstate(self, state):
849 self.__state = state
850 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000851 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000853 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000854 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 def __init__(self):
856 type({}).__init__(self)
857 C.__init__(self)
858 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000859 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000860 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000861 vereq(d.items(), [("hello", "world")])
862 vereq(d["hello"], "world")
863 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000865 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000866 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867
Guido van Rossume45763a2001-08-10 21:28:46 +0000868 # SF bug #442833
869 class Node(object):
870 def __int__(self):
871 return int(self.foo())
872 def foo(self):
873 return "23"
874 class Frag(Node, list):
875 def foo(self):
876 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000877 vereq(Node().__int__(), 23)
878 vereq(int(Node()), 23)
879 vereq(Frag().__int__(), 42)
880 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000881
Tim Petersa91e9642001-11-14 23:32:33 +0000882 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000883
884 class A:
885 x = 1
886
887 class B(A):
888 pass
889
890 class C(A):
891 x = 2
892
893 class D(B, C):
894 pass
895 vereq(D.x, 1)
896
897 # Classic MRO is preserved for a classic base class.
898 class E(D, object):
899 pass
900 vereq(E.__mro__, (E, D, B, A, C, object))
901 vereq(E.x, 1)
902
903 # But with a mix of classic bases, their MROs are combined using
904 # new-style MRO.
905 class F(B, C, object):
906 pass
907 vereq(F.__mro__, (F, B, C, A, object))
908 vereq(F.x, 2)
909
910 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000911 class C:
912 def cmethod(self):
913 return "C a"
914 def all_method(self):
915 return "C b"
916
917 class M1(C, object):
918 def m1method(self):
919 return "M1 a"
920 def all_method(self):
921 return "M1 b"
922
923 vereq(M1.__mro__, (M1, C, object))
924 m = M1()
925 vereq(m.cmethod(), "C a")
926 vereq(m.m1method(), "M1 a")
927 vereq(m.all_method(), "M1 b")
928
929 class D(C):
930 def dmethod(self):
931 return "D a"
932 def all_method(self):
933 return "D b"
934
935 class M2(object, D):
936 def m2method(self):
937 return "M2 a"
938 def all_method(self):
939 return "M2 b"
940
941 vereq(M2.__mro__, (M2, object, D, C))
942 m = M2()
943 vereq(m.cmethod(), "C a")
944 vereq(m.dmethod(), "D a")
945 vereq(m.m2method(), "M2 a")
946 vereq(m.all_method(), "M2 b")
947
948 class M3(M1, object, M2):
949 def m3method(self):
950 return "M3 a"
951 def all_method(self):
952 return "M3 b"
953 # XXX Expected this (the commented-out result):
954 # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
955 vereq(M3.__mro__, (M3, M1, M2, D, C, object)) # XXX ?
Tim Peters144b98d2001-11-14 23:56:45 +0000956 m = M3()
957 vereq(m.cmethod(), "C a")
958 vereq(m.dmethod(), "D a")
959 vereq(m.m1method(), "M1 a")
960 vereq(m.m2method(), "M2 a")
961 vereq(m.m3method(), "M3 a")
962 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000963
Guido van Rossume54616c2001-12-14 04:19:56 +0000964 class Classic:
965 pass
966 try:
967 class New(Classic):
968 __metaclass__ = type
969 except TypeError:
970 pass
971 else:
972 raise TestFailed, "new class with only classic bases - shouldn't be"
973
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974def diamond():
975 if verbose: print "Testing multiple inheritance special cases..."
976 class A(object):
977 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000978 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979 class B(A):
980 def boo(self): return "B"
981 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000982 vereq(B().spam(), "B")
983 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984 class C(A):
985 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000986 vereq(C().spam(), "A")
987 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000988 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000989 vereq(D().spam(), "B")
990 vereq(D().boo(), "B")
991 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000992 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000993 vereq(E().spam(), "B")
994 vereq(E().boo(), "C")
995 vereq(E.__mro__, (E, C, B, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000996 class F(D, E): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000997 vereq(F().spam(), "B")
998 vereq(F().boo(), "B")
999 vereq(F.__mro__, (F, D, E, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 class G(E, D): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001001 vereq(G().spam(), "B")
1002 vereq(G().boo(), "C")
1003 vereq(G.__mro__, (G, E, D, C, B, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004
Guido van Rossum37202612001-08-09 19:45:21 +00001005def objects():
1006 if verbose: print "Testing object class..."
1007 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001008 vereq(a.__class__, object)
1009 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001010 b = object()
1011 verify(a is not b)
1012 verify(not hasattr(a, "foo"))
1013 try:
1014 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001015 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001016 pass
1017 else:
1018 verify(0, "object() should not allow setting a foo attribute")
1019 verify(not hasattr(object(), "__dict__"))
1020
1021 class Cdict(object):
1022 pass
1023 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001024 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001025 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001026 vereq(x.foo, 1)
1027 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001028
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029def slots():
1030 if verbose: print "Testing __slots__..."
1031 class C0(object):
1032 __slots__ = []
1033 x = C0()
1034 verify(not hasattr(x, "__dict__"))
1035 verify(not hasattr(x, "foo"))
1036
1037 class C1(object):
1038 __slots__ = ['a']
1039 x = C1()
1040 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001041 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001043 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001044 x.a = None
1045 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001047 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001048
1049 class C3(object):
1050 __slots__ = ['a', 'b', 'c']
1051 x = C3()
1052 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001053 verify(not hasattr(x, 'a'))
1054 verify(not hasattr(x, 'b'))
1055 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 x.a = 1
1057 x.b = 2
1058 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001059 vereq(x.a, 1)
1060 vereq(x.b, 2)
1061 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001063 # Make sure slot names are proper identifiers
1064 try:
1065 class C(object):
1066 __slots__ = [None]
1067 except TypeError:
1068 pass
1069 else:
1070 raise TestFailed, "[None] slots not caught"
1071 try:
1072 class C(object):
1073 __slots__ = ["foo bar"]
1074 except TypeError:
1075 pass
1076 else:
1077 raise TestFailed, "['foo bar'] slots not caught"
1078 try:
1079 class C(object):
1080 __slots__ = ["foo\0bar"]
1081 except TypeError:
1082 pass
1083 else:
1084 raise TestFailed, "['foo\\0bar'] slots not caught"
1085 try:
1086 class C(object):
1087 __slots__ = ["1"]
1088 except TypeError:
1089 pass
1090 else:
1091 raise TestFailed, "['1'] slots not caught"
1092 try:
1093 class C(object):
1094 __slots__ = [""]
1095 except TypeError:
1096 pass
1097 else:
1098 raise TestFailed, "[''] slots not caught"
1099 class C(object):
1100 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1101
Guido van Rossum33bab012001-12-05 22:45:48 +00001102 # Test leaks
1103 class Counted(object):
1104 counter = 0 # counts the number of instances alive
1105 def __init__(self):
1106 Counted.counter += 1
1107 def __del__(self):
1108 Counted.counter -= 1
1109 class C(object):
1110 __slots__ = ['a', 'b', 'c']
1111 x = C()
1112 x.a = Counted()
1113 x.b = Counted()
1114 x.c = Counted()
1115 vereq(Counted.counter, 3)
1116 del x
1117 vereq(Counted.counter, 0)
1118 class D(C):
1119 pass
1120 x = D()
1121 x.a = Counted()
1122 x.z = Counted()
1123 vereq(Counted.counter, 2)
1124 del x
1125 vereq(Counted.counter, 0)
1126 class E(D):
1127 __slots__ = ['e']
1128 x = E()
1129 x.a = Counted()
1130 x.z = Counted()
1131 x.e = Counted()
1132 vereq(Counted.counter, 3)
1133 del x
1134 vereq(Counted.counter, 0)
1135
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001136 # Test cyclical leaks [SF bug 519621]
1137 class F(object):
1138 __slots__ = ['a', 'b']
1139 log = []
1140 s = F()
1141 s.a = [Counted(), s]
1142 vereq(Counted.counter, 1)
1143 s = None
1144 import gc
1145 gc.collect()
1146 vereq(Counted.counter, 0)
1147
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001149 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001152 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001154 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001157 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001158 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001159 vereq(E.foo, 1)
1160 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001161 # Test dynamic instances
1162 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001163 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001164 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001165 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001166 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001167 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001168 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001169 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001170 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001171 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001172 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001173 vereq(int(a), 100)
1174 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001175 verify(not hasattr(a, "spam"))
1176 def mygetattr(self, name):
1177 if name == "spam":
1178 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001179 raise AttributeError
1180 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001181 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001182 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001183 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001184 def mysetattr(self, name, value):
1185 if name == "spam":
1186 raise AttributeError
1187 return object.__setattr__(self, name, value)
1188 C.__setattr__ = mysetattr
1189 try:
1190 a.spam = "not spam"
1191 except AttributeError:
1192 pass
1193 else:
1194 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001195 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001196 class D(C):
1197 pass
1198 d = D()
1199 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001200 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201
Guido van Rossum7e35d572001-09-15 03:14:32 +00001202 # Test handling of int*seq and seq*int
1203 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001204 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001205 vereq("a"*I(2), "aa")
1206 vereq(I(2)*"a", "aa")
1207 vereq(2*I(3), 6)
1208 vereq(I(3)*2, 6)
1209 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001210
1211 # Test handling of long*seq and seq*long
1212 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001213 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001214 vereq("a"*L(2L), "aa")
1215 vereq(L(2L)*"a", "aa")
1216 vereq(2*L(3), 6)
1217 vereq(L(3)*2, 6)
1218 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001219
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001220 # Test comparison of classes with dynamic metaclasses
1221 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001222 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001223 class someclass:
1224 __metaclass__ = dynamicmetaclass
1225 verify(someclass != object)
1226
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227def errors():
1228 if verbose: print "Testing errors..."
1229
1230 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001231 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 pass
1233 except TypeError:
1234 pass
1235 else:
1236 verify(0, "inheritance from both list and dict should be illegal")
1237
1238 try:
1239 class C(object, None):
1240 pass
1241 except TypeError:
1242 pass
1243 else:
1244 verify(0, "inheritance from non-type should be illegal")
1245 class Classic:
1246 pass
1247
1248 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001249 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 pass
1251 except TypeError:
1252 pass
1253 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001254 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255
1256 try:
1257 class C(object):
1258 __slots__ = 1
1259 except TypeError:
1260 pass
1261 else:
1262 verify(0, "__slots__ = 1 should be illegal")
1263
1264 try:
1265 class C(object):
1266 __slots__ = [1]
1267 except TypeError:
1268 pass
1269 else:
1270 verify(0, "__slots__ = [1] should be illegal")
1271
1272def classmethods():
1273 if verbose: print "Testing class methods..."
1274 class C(object):
1275 def foo(*a): return a
1276 goo = classmethod(foo)
1277 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001278 vereq(C.goo(1), (C, 1))
1279 vereq(c.goo(1), (C, 1))
1280 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281 class D(C):
1282 pass
1283 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001284 vereq(D.goo(1), (D, 1))
1285 vereq(d.goo(1), (D, 1))
1286 vereq(d.foo(1), (d, 1))
1287 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001288 # Test for a specific crash (SF bug 528132)
1289 def f(cls, arg): return (cls, arg)
1290 ff = classmethod(f)
1291 vereq(ff.__get__(0, int)(42), (int, 42))
1292 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293
Guido van Rossum155db9a2002-04-02 17:53:47 +00001294 # Test super() with classmethods (SF bug 535444)
1295 veris(C.goo.im_self, C)
1296 veris(D.goo.im_self, D)
1297 veris(super(D,D).goo.im_self, D)
1298 veris(super(D,d).goo.im_self, D)
1299 vereq(super(D,D).goo(), (D,))
1300 vereq(super(D,d).goo(), (D,))
1301
Fred Drakef841aa62002-03-28 15:49:54 +00001302def classmethods_in_c():
1303 if verbose: print "Testing C-based class methods..."
1304 import xxsubtype as spam
1305 a = (1, 2, 3)
1306 d = {'abc': 123}
1307 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1308 veris(x, None)
1309 vereq((spam.spamlist,) + a, a1)
1310 vereq(d, d1)
1311 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1312 veris(x, None)
1313 vereq((spam.spamlist,) + a, a1)
1314 vereq(d, d1)
1315
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316def staticmethods():
1317 if verbose: print "Testing static methods..."
1318 class C(object):
1319 def foo(*a): return a
1320 goo = staticmethod(foo)
1321 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001322 vereq(C.goo(1), (1,))
1323 vereq(c.goo(1), (1,))
1324 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 class D(C):
1326 pass
1327 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001328 vereq(D.goo(1), (1,))
1329 vereq(d.goo(1), (1,))
1330 vereq(d.foo(1), (d, 1))
1331 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332
Fred Drakef841aa62002-03-28 15:49:54 +00001333def staticmethods_in_c():
1334 if verbose: print "Testing C-based static methods..."
1335 import xxsubtype as spam
1336 a = (1, 2, 3)
1337 d = {"abc": 123}
1338 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1339 veris(x, None)
1340 vereq(a, a1)
1341 vereq(d, d1)
1342 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1343 veris(x, None)
1344 vereq(a, a1)
1345 vereq(d, d1)
1346
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347def classic():
1348 if verbose: print "Testing classic classes..."
1349 class C:
1350 def foo(*a): return a
1351 goo = classmethod(foo)
1352 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001353 vereq(C.goo(1), (C, 1))
1354 vereq(c.goo(1), (C, 1))
1355 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 class D(C):
1357 pass
1358 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001359 vereq(D.goo(1), (D, 1))
1360 vereq(d.goo(1), (D, 1))
1361 vereq(d.foo(1), (d, 1))
1362 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001363 class E: # *not* subclassing from C
1364 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001365 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001366 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
1368def compattr():
1369 if verbose: print "Testing computed attributes..."
1370 class C(object):
1371 class computed_attribute(object):
1372 def __init__(self, get, set=None):
1373 self.__get = get
1374 self.__set = set
1375 def __get__(self, obj, type=None):
1376 return self.__get(obj)
1377 def __set__(self, obj, value):
1378 return self.__set(obj, value)
1379 def __init__(self):
1380 self.__x = 0
1381 def __get_x(self):
1382 x = self.__x
1383 self.__x = x+1
1384 return x
1385 def __set_x(self, x):
1386 self.__x = x
1387 x = computed_attribute(__get_x, __set_x)
1388 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001389 vereq(a.x, 0)
1390 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001392 vereq(a.x, 10)
1393 vereq(a.x, 11)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394
1395def newslot():
1396 if verbose: print "Testing __new__ slot override..."
1397 class C(list):
1398 def __new__(cls):
1399 self = list.__new__(cls)
1400 self.foo = 1
1401 return self
1402 def __init__(self):
1403 self.foo = self.foo + 2
1404 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001405 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 verify(a.__class__ is C)
1407 class D(C):
1408 pass
1409 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001410 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411 verify(b.__class__ is D)
1412
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413def altmro():
1414 if verbose: print "Testing mro() and overriding it..."
1415 class A(object):
1416 def f(self): return "A"
1417 class B(A):
1418 pass
1419 class C(A):
1420 def f(self): return "C"
1421 class D(B, C):
1422 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001423 vereq(D.mro(), [D, B, C, A, object])
1424 vereq(D.__mro__, (D, B, C, A, object))
1425 vereq(D().f(), "C")
Guido van Rossumd3077402001-08-12 05:24:18 +00001426 class PerverseMetaType(type):
1427 def mro(cls):
1428 L = type.mro(cls)
1429 L.reverse()
1430 return L
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431 class X(A,B,C,D):
1432 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001433 vereq(X.__mro__, (object, A, C, B, D, X))
1434 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435
1436def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001437 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438
1439 class B(object):
1440 "Intermediate class because object doesn't have a __setattr__"
1441
1442 class C(B):
1443
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001444 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 if name == "foo":
1446 return ("getattr", name)
1447 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001448 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 def __setattr__(self, name, value):
1450 if name == "foo":
1451 self.setattr = (name, value)
1452 else:
1453 return B.__setattr__(self, name, value)
1454 def __delattr__(self, name):
1455 if name == "foo":
1456 self.delattr = name
1457 else:
1458 return B.__delattr__(self, name)
1459
1460 def __getitem__(self, key):
1461 return ("getitem", key)
1462 def __setitem__(self, key, value):
1463 self.setitem = (key, value)
1464 def __delitem__(self, key):
1465 self.delitem = key
1466
1467 def __getslice__(self, i, j):
1468 return ("getslice", i, j)
1469 def __setslice__(self, i, j, value):
1470 self.setslice = (i, j, value)
1471 def __delslice__(self, i, j):
1472 self.delslice = (i, j)
1473
1474 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001475 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001477 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001479 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480
Guido van Rossum45704552001-10-08 16:35:45 +00001481 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001483 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001485 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486
Guido van Rossum45704552001-10-08 16:35:45 +00001487 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001489 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001491 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001493def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001494 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001495 class C(object):
1496 def __init__(self, x):
1497 self.x = x
1498 def foo(self):
1499 return self.x
1500 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001501 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001502 class D(C):
1503 boo = C.foo
1504 goo = c1.foo
1505 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001506 vereq(d2.foo(), 2)
1507 vereq(d2.boo(), 2)
1508 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001509 class E(object):
1510 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001511 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001512 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001513
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001514def specials():
1515 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001516 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001517 # Test the default behavior for static classes
1518 class C(object):
1519 def __getitem__(self, i):
1520 if 0 <= i < 10: return i
1521 raise IndexError
1522 c1 = C()
1523 c2 = C()
1524 verify(not not c1)
Guido van Rossum45704552001-10-08 16:35:45 +00001525 vereq(hash(c1), id(c1))
1526 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1527 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001528 verify(c1 != c2)
1529 verify(not c1 != c1)
1530 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001531 # Note that the module name appears in str/repr, and that varies
1532 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001533 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001534 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001535 verify(-1 not in c1)
1536 for i in range(10):
1537 verify(i in c1)
1538 verify(10 not in c1)
1539 # Test the default behavior for dynamic classes
1540 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001541 def __getitem__(self, i):
1542 if 0 <= i < 10: return i
1543 raise IndexError
1544 d1 = D()
1545 d2 = D()
1546 verify(not not d1)
Guido van Rossum45704552001-10-08 16:35:45 +00001547 vereq(hash(d1), id(d1))
1548 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1549 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001550 verify(d1 != d2)
1551 verify(not d1 != d1)
1552 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001553 # Note that the module name appears in str/repr, and that varies
1554 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001555 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001556 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001557 verify(-1 not in d1)
1558 for i in range(10):
1559 verify(i in d1)
1560 verify(10 not in d1)
1561 # Test overridden behavior for static classes
1562 class Proxy(object):
1563 def __init__(self, x):
1564 self.x = x
1565 def __nonzero__(self):
1566 return not not self.x
1567 def __hash__(self):
1568 return hash(self.x)
1569 def __eq__(self, other):
1570 return self.x == other
1571 def __ne__(self, other):
1572 return self.x != other
1573 def __cmp__(self, other):
1574 return cmp(self.x, other.x)
1575 def __str__(self):
1576 return "Proxy:%s" % self.x
1577 def __repr__(self):
1578 return "Proxy(%r)" % self.x
1579 def __contains__(self, value):
1580 return value in self.x
1581 p0 = Proxy(0)
1582 p1 = Proxy(1)
1583 p_1 = Proxy(-1)
1584 verify(not p0)
1585 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001586 vereq(hash(p0), hash(0))
1587 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001588 verify(p0 != p1)
1589 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001590 vereq(not p0, p1)
1591 vereq(cmp(p0, p1), -1)
1592 vereq(cmp(p0, p0), 0)
1593 vereq(cmp(p0, p_1), 1)
1594 vereq(str(p0), "Proxy:0")
1595 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001596 p10 = Proxy(range(10))
1597 verify(-1 not in p10)
1598 for i in range(10):
1599 verify(i in p10)
1600 verify(10 not in p10)
1601 # Test overridden behavior for dynamic classes
1602 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001603 def __init__(self, x):
1604 self.x = x
1605 def __nonzero__(self):
1606 return not not self.x
1607 def __hash__(self):
1608 return hash(self.x)
1609 def __eq__(self, other):
1610 return self.x == other
1611 def __ne__(self, other):
1612 return self.x != other
1613 def __cmp__(self, other):
1614 return cmp(self.x, other.x)
1615 def __str__(self):
1616 return "DProxy:%s" % self.x
1617 def __repr__(self):
1618 return "DProxy(%r)" % self.x
1619 def __contains__(self, value):
1620 return value in self.x
1621 p0 = DProxy(0)
1622 p1 = DProxy(1)
1623 p_1 = DProxy(-1)
1624 verify(not p0)
1625 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001626 vereq(hash(p0), hash(0))
1627 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001628 verify(p0 != p1)
1629 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001630 vereq(not p0, p1)
1631 vereq(cmp(p0, p1), -1)
1632 vereq(cmp(p0, p0), 0)
1633 vereq(cmp(p0, p_1), 1)
1634 vereq(str(p0), "DProxy:0")
1635 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001636 p10 = DProxy(range(10))
1637 verify(-1 not in p10)
1638 for i in range(10):
1639 verify(i in p10)
1640 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001641 # Safety test for __cmp__
1642 def unsafecmp(a, b):
1643 try:
1644 a.__class__.__cmp__(a, b)
1645 except TypeError:
1646 pass
1647 else:
1648 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1649 a.__class__, a, b)
1650 unsafecmp(u"123", "123")
1651 unsafecmp("123", u"123")
1652 unsafecmp(1, 1.0)
1653 unsafecmp(1.0, 1)
1654 unsafecmp(1, 1L)
1655 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001656
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001657def weakrefs():
1658 if verbose: print "Testing weak references..."
1659 import weakref
1660 class C(object):
1661 pass
1662 c = C()
1663 r = weakref.ref(c)
1664 verify(r() is c)
1665 del c
1666 verify(r() is None)
1667 del r
1668 class NoWeak(object):
1669 __slots__ = ['foo']
1670 no = NoWeak()
1671 try:
1672 weakref.ref(no)
1673 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001674 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001675 else:
1676 verify(0, "weakref.ref(no) should be illegal")
1677 class Weak(object):
1678 __slots__ = ['foo', '__weakref__']
1679 yes = Weak()
1680 r = weakref.ref(yes)
1681 verify(r() is yes)
1682 del yes
1683 verify(r() is None)
1684 del r
1685
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001686def properties():
1687 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001688 class C(object):
1689 def getx(self):
1690 return self.__x
1691 def setx(self, value):
1692 self.__x = value
1693 def delx(self):
1694 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001695 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001696 a = C()
1697 verify(not hasattr(a, "x"))
1698 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001699 vereq(a._C__x, 42)
1700 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001701 del a.x
1702 verify(not hasattr(a, "x"))
1703 verify(not hasattr(a, "_C__x"))
1704 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001705 vereq(C.x.__get__(a), 100)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001706## C.x.__set__(a)
1707## verify(not hasattr(a, "x"))
1708
Tim Peters66c1a522001-09-24 21:17:50 +00001709 raw = C.__dict__['x']
1710 verify(isinstance(raw, property))
1711
1712 attrs = dir(raw)
1713 verify("__doc__" in attrs)
1714 verify("fget" in attrs)
1715 verify("fset" in attrs)
1716 verify("fdel" in attrs)
1717
Guido van Rossum45704552001-10-08 16:35:45 +00001718 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001719 verify(raw.fget is C.__dict__['getx'])
1720 verify(raw.fset is C.__dict__['setx'])
1721 verify(raw.fdel is C.__dict__['delx'])
1722
1723 for attr in "__doc__", "fget", "fset", "fdel":
1724 try:
1725 setattr(raw, attr, 42)
1726 except TypeError, msg:
1727 if str(msg).find('readonly') < 0:
1728 raise TestFailed("when setting readonly attr %r on a "
1729 "property, got unexpected TypeError "
1730 "msg %r" % (attr, str(msg)))
1731 else:
1732 raise TestFailed("expected TypeError from trying to set "
1733 "readonly %r attr on a property" % attr)
1734
Guido van Rossumc4a18802001-08-24 16:55:27 +00001735def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001736 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001737
1738 class A(object):
1739 def meth(self, a):
1740 return "A(%r)" % a
1741
Guido van Rossum45704552001-10-08 16:35:45 +00001742 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001743
1744 class B(A):
1745 def __init__(self):
1746 self.__super = super(B, self)
1747 def meth(self, a):
1748 return "B(%r)" % a + self.__super.meth(a)
1749
Guido van Rossum45704552001-10-08 16:35:45 +00001750 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001751
1752 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00001753 def meth(self, a):
1754 return "C(%r)" % a + self.__super.meth(a)
1755 C._C__super = super(C)
1756
Guido van Rossum45704552001-10-08 16:35:45 +00001757 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001758
1759 class D(C, B):
1760 def meth(self, a):
1761 return "D(%r)" % a + super(D, self).meth(a)
1762
Guido van Rossum5b443c62001-12-03 15:38:28 +00001763 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1764
1765 # Test for subclassing super
1766
1767 class mysuper(super):
1768 def __init__(self, *args):
1769 return super(mysuper, self).__init__(*args)
1770
1771 class E(D):
1772 def meth(self, a):
1773 return "E(%r)" % a + mysuper(E, self).meth(a)
1774
1775 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1776
1777 class F(E):
1778 def meth(self, a):
1779 s = self.__super
1780 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1781 F._F__super = mysuper(F)
1782
1783 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1784
1785 # Make sure certain errors are raised
1786
1787 try:
1788 super(D, 42)
1789 except TypeError:
1790 pass
1791 else:
1792 raise TestFailed, "shouldn't allow super(D, 42)"
1793
1794 try:
1795 super(D, C())
1796 except TypeError:
1797 pass
1798 else:
1799 raise TestFailed, "shouldn't allow super(D, C())"
1800
1801 try:
1802 super(D).__get__(12)
1803 except TypeError:
1804 pass
1805 else:
1806 raise TestFailed, "shouldn't allow super(D).__get__(12)"
1807
1808 try:
1809 super(D).__get__(C())
1810 except TypeError:
1811 pass
1812 else:
1813 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00001814
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001815def inherits():
1816 if verbose: print "Testing inheritance from basic types..."
1817
1818 class hexint(int):
1819 def __repr__(self):
1820 return hex(self)
1821 def __add__(self, other):
1822 return hexint(int.__add__(self, other))
1823 # (Note that overriding __radd__ doesn't work,
1824 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00001825 vereq(repr(hexint(7) + 9), "0x10")
1826 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00001827 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00001828 vereq(a, 12345)
1829 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00001830 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00001831 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00001832 verify((+a).__class__ is int)
1833 verify((a >> 0).__class__ is int)
1834 verify((a << 0).__class__ is int)
1835 verify((hexint(0) << 12).__class__ is int)
1836 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001837
1838 class octlong(long):
1839 __slots__ = []
1840 def __str__(self):
1841 s = oct(self)
1842 if s[-1] == 'L':
1843 s = s[:-1]
1844 return s
1845 def __add__(self, other):
1846 return self.__class__(super(octlong, self).__add__(other))
1847 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00001848 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001849 # (Note that overriding __radd__ here only seems to work
1850 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00001851 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00001852 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00001853 vereq(a, 12345L)
1854 vereq(long(a), 12345L)
1855 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00001856 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00001857 verify((+a).__class__ is long)
1858 verify((-a).__class__ is long)
1859 verify((-octlong(0)).__class__ is long)
1860 verify((a >> 0).__class__ is long)
1861 verify((a << 0).__class__ is long)
1862 verify((a - 0).__class__ is long)
1863 verify((a * 1).__class__ is long)
1864 verify((a ** 1).__class__ is long)
1865 verify((a // 1).__class__ is long)
1866 verify((1 * a).__class__ is long)
1867 verify((a | 0).__class__ is long)
1868 verify((a ^ 0).__class__ is long)
1869 verify((a & -1L).__class__ is long)
1870 verify((octlong(0) << 12).__class__ is long)
1871 verify((octlong(0) >> 12).__class__ is long)
1872 verify(abs(octlong(0)).__class__ is long)
1873
1874 # Because octlong overrides __add__, we can't check the absence of +0
1875 # optimizations using octlong.
1876 class longclone(long):
1877 pass
1878 a = longclone(1)
1879 verify((a + 0).__class__ is long)
1880 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001881
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001882 # Check that negative clones don't segfault
1883 a = longclone(-1)
1884 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00001885 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001886
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001887 class precfloat(float):
1888 __slots__ = ['prec']
1889 def __init__(self, value=0.0, prec=12):
1890 self.prec = int(prec)
1891 float.__init__(value)
1892 def __repr__(self):
1893 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00001894 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00001895 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00001896 vereq(a, 12345.0)
1897 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00001898 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00001899 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00001900 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001901
Tim Peters2400fa42001-09-12 19:12:49 +00001902 class madcomplex(complex):
1903 def __repr__(self):
1904 return "%.17gj%+.17g" % (self.imag, self.real)
1905 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00001906 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00001907 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001908 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00001909 vereq(a, base)
1910 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001911 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00001912 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00001913 vereq(repr(a), "4j-3")
1914 vereq(a, base)
1915 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001916 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00001917 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001918 veris((+a).__class__, complex)
1919 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00001920 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001921 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00001922 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001923 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00001924 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001925 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00001926 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00001927
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001928 class madtuple(tuple):
1929 _rev = None
1930 def rev(self):
1931 if self._rev is not None:
1932 return self._rev
1933 L = list(self)
1934 L.reverse()
1935 self._rev = self.__class__(L)
1936 return self._rev
1937 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00001938 vereq(a, (1,2,3,4,5,6,7,8,9,0))
1939 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
1940 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001941 for i in range(512):
1942 t = madtuple(range(i))
1943 u = t.rev()
1944 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00001945 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00001946 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00001947 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00001948 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00001949 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00001950 verify(a[:].__class__ is tuple)
1951 verify((a * 1).__class__ is tuple)
1952 verify((a * 0).__class__ is tuple)
1953 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00001954 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00001955 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00001956 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00001957 verify((a + a).__class__ is tuple)
1958 verify((a * 0).__class__ is tuple)
1959 verify((a * 1).__class__ is tuple)
1960 verify((a * 2).__class__ is tuple)
1961 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001962
1963 class madstring(str):
1964 _rev = None
1965 def rev(self):
1966 if self._rev is not None:
1967 return self._rev
1968 L = list(self)
1969 L.reverse()
1970 self._rev = self.__class__("".join(L))
1971 return self._rev
1972 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00001973 vereq(s, "abcdefghijklmnopqrstuvwxyz")
1974 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
1975 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001976 for i in range(256):
1977 s = madstring("".join(map(chr, range(i))))
1978 t = s.rev()
1979 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00001980 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00001981 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00001982 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00001983 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00001984
Tim Peters8fa5dd02001-09-12 02:18:30 +00001985 base = "\x00" * 5
1986 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00001987 vereq(s, base)
1988 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00001989 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00001990 vereq(hash(s), hash(base))
1991 vereq({s: 1}[base], 1)
1992 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001993 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00001994 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001995 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00001996 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00001997 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00001998 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00001999 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002000 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002001 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002002 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002003 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002004 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002005 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002006 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002007 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002008 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002009 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002010 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002011 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002012 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002013 identitytab = ''.join([chr(i) for i in range(256)])
2014 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002015 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002016 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002017 vereq(s.translate(identitytab, "x"), base)
2018 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002019 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002020 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002021 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002022 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002023 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002024 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002025 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002026 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002027 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002028 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002029
Tim Peters111f6092001-09-12 07:54:51 +00002030 s = madstring("x y")
Guido van Rossum45704552001-10-08 16:35:45 +00002031 vereq(s, "x y")
Tim Peters111f6092001-09-12 07:54:51 +00002032 verify(intern(s).__class__ is str)
2033 verify(intern(s) is intern("x y"))
Guido van Rossum45704552001-10-08 16:35:45 +00002034 vereq(intern(s), "x y")
Tim Peters111f6092001-09-12 07:54:51 +00002035
2036 i = intern("y x")
2037 s = madstring("y x")
Guido van Rossum45704552001-10-08 16:35:45 +00002038 vereq(s, i)
Tim Peters111f6092001-09-12 07:54:51 +00002039 verify(intern(s).__class__ is str)
2040 verify(intern(s) is i)
2041
2042 s = madstring(i)
2043 verify(intern(s).__class__ is str)
2044 verify(intern(s) is i)
2045
Guido van Rossum91ee7982001-08-30 20:52:40 +00002046 class madunicode(unicode):
2047 _rev = None
2048 def rev(self):
2049 if self._rev is not None:
2050 return self._rev
2051 L = list(self)
2052 L.reverse()
2053 self._rev = self.__class__(u"".join(L))
2054 return self._rev
2055 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002056 vereq(u, u"ABCDEF")
2057 vereq(u.rev(), madunicode(u"FEDCBA"))
2058 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002059 base = u"12345"
2060 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002061 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002062 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002063 vereq(hash(u), hash(base))
2064 vereq({u: 1}[base], 1)
2065 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002066 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002067 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002068 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002069 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002070 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002071 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002072 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002073 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002074 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002075 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002076 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002077 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002078 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002079 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002080 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002081 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002082 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002083 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002084 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002085 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002086 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002087 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002088 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002089 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002090 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002091 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002092 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002093 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002094 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002095 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002096 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002097 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002098 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002099 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002100 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002101 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002102 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002103 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002104
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002105 class sublist(list):
2106 pass
2107 a = sublist(range(5))
2108 vereq(a, range(5))
2109 a.append("hello")
2110 vereq(a, range(5) + ["hello"])
2111 a[5] = 5
2112 vereq(a, range(6))
2113 a.extend(range(6, 20))
2114 vereq(a, range(20))
2115 a[-5:] = []
2116 vereq(a, range(15))
2117 del a[10:15]
2118 vereq(len(a), 10)
2119 vereq(a, range(10))
2120 vereq(list(a), range(10))
2121 vereq(a[0], 0)
2122 vereq(a[9], 9)
2123 vereq(a[-10], 0)
2124 vereq(a[-1], 9)
2125 vereq(a[:5], range(5))
2126
Tim Peters59c9a642001-09-13 05:38:56 +00002127 class CountedInput(file):
2128 """Counts lines read by self.readline().
2129
2130 self.lineno is the 0-based ordinal of the last line read, up to
2131 a maximum of one greater than the number of lines in the file.
2132
2133 self.ateof is true if and only if the final "" line has been read,
2134 at which point self.lineno stops incrementing, and further calls
2135 to readline() continue to return "".
2136 """
2137
2138 lineno = 0
2139 ateof = 0
2140 def readline(self):
2141 if self.ateof:
2142 return ""
2143 s = file.readline(self)
2144 # Next line works too.
2145 # s = super(CountedInput, self).readline()
2146 self.lineno += 1
2147 if s == "":
2148 self.ateof = 1
2149 return s
2150
Tim Peters561f8992001-09-13 19:36:36 +00002151 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002152 lines = ['a\n', 'b\n', 'c\n']
2153 try:
2154 f.writelines(lines)
2155 f.close()
2156 f = CountedInput(TESTFN)
2157 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2158 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002159 vereq(expected, got)
2160 vereq(f.lineno, i)
2161 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002162 f.close()
2163 finally:
2164 try:
2165 f.close()
2166 except:
2167 pass
2168 try:
2169 import os
2170 os.unlink(TESTFN)
2171 except:
2172 pass
2173
Tim Peters808b94e2001-09-13 19:33:07 +00002174def keywords():
2175 if verbose:
2176 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002177 vereq(int(x=1), 1)
2178 vereq(float(x=2), 2.0)
2179 vereq(long(x=3), 3L)
2180 vereq(complex(imag=42, real=666), complex(666, 42))
2181 vereq(str(object=500), '500')
2182 vereq(unicode(string='abc', errors='strict'), u'abc')
2183 vereq(tuple(sequence=range(3)), (0, 1, 2))
2184 vereq(list(sequence=(0, 1, 2)), range(3))
Tim Petersa427a2b2001-10-29 22:25:45 +00002185 vereq(dict(items={1: 2}), {1: 2})
Tim Peters808b94e2001-09-13 19:33:07 +00002186
2187 for constructor in (int, float, long, complex, str, unicode,
Tim Petersa427a2b2001-10-29 22:25:45 +00002188 tuple, list, dict, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002189 try:
2190 constructor(bogus_keyword_arg=1)
2191 except TypeError:
2192 pass
2193 else:
2194 raise TestFailed("expected TypeError from bogus keyword "
2195 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002196
Tim Peters8fa45672001-09-13 21:01:29 +00002197def restricted():
2198 import rexec
2199 if verbose:
2200 print "Testing interaction with restricted execution ..."
2201
2202 sandbox = rexec.RExec()
2203
2204 code1 = """f = open(%r, 'w')""" % TESTFN
2205 code2 = """f = file(%r, 'w')""" % TESTFN
2206 code3 = """\
2207f = open(%r)
2208t = type(f) # a sneaky way to get the file() constructor
2209f.close()
2210f = t(%r, 'w') # rexec can't catch this by itself
2211""" % (TESTFN, TESTFN)
2212
2213 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2214 f.close()
2215
2216 try:
2217 for code in code1, code2, code3:
2218 try:
2219 sandbox.r_exec(code)
2220 except IOError, msg:
2221 if str(msg).find("restricted") >= 0:
2222 outcome = "OK"
2223 else:
2224 outcome = "got an exception, but not an expected one"
2225 else:
2226 outcome = "expected a restricted-execution exception"
2227
2228 if outcome != "OK":
2229 raise TestFailed("%s, in %r" % (outcome, code))
2230
2231 finally:
2232 try:
2233 import os
2234 os.unlink(TESTFN)
2235 except:
2236 pass
2237
Tim Peters0ab085c2001-09-14 00:25:33 +00002238def str_subclass_as_dict_key():
2239 if verbose:
2240 print "Testing a str subclass used as dict key .."
2241
2242 class cistr(str):
2243 """Sublcass of str that computes __eq__ case-insensitively.
2244
2245 Also computes a hash code of the string in canonical form.
2246 """
2247
2248 def __init__(self, value):
2249 self.canonical = value.lower()
2250 self.hashcode = hash(self.canonical)
2251
2252 def __eq__(self, other):
2253 if not isinstance(other, cistr):
2254 other = cistr(other)
2255 return self.canonical == other.canonical
2256
2257 def __hash__(self):
2258 return self.hashcode
2259
Guido van Rossum45704552001-10-08 16:35:45 +00002260 vereq(cistr('ABC'), 'abc')
2261 vereq('aBc', cistr('ABC'))
2262 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002263
2264 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002265 vereq(d[cistr('one')], 1)
2266 vereq(d[cistr('tWo')], 2)
2267 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002268 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002269 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002270
Guido van Rossumab3b0342001-09-18 20:38:53 +00002271def classic_comparisons():
2272 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002273 class classic:
2274 pass
2275 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002276 if verbose: print " (base = %s)" % base
2277 class C(base):
2278 def __init__(self, value):
2279 self.value = int(value)
2280 def __cmp__(self, other):
2281 if isinstance(other, C):
2282 return cmp(self.value, other.value)
2283 if isinstance(other, int) or isinstance(other, long):
2284 return cmp(self.value, other)
2285 return NotImplemented
2286 c1 = C(1)
2287 c2 = C(2)
2288 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002289 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002290 c = {1: c1, 2: c2, 3: c3}
2291 for x in 1, 2, 3:
2292 for y in 1, 2, 3:
2293 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2294 for op in "<", "<=", "==", "!=", ">", ">=":
2295 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2296 "x=%d, y=%d" % (x, y))
2297 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2298 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2299
Guido van Rossum0639f592001-09-18 21:06:04 +00002300def rich_comparisons():
2301 if verbose:
2302 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002303 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002304 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002305 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002306 vereq(z, 1+0j)
2307 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002308 class ZZ(complex):
2309 def __eq__(self, other):
2310 try:
2311 return abs(self - other) <= 1e-6
2312 except:
2313 return NotImplemented
2314 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002315 vereq(zz, 1+0j)
2316 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002317
Guido van Rossum0639f592001-09-18 21:06:04 +00002318 class classic:
2319 pass
2320 for base in (classic, int, object, list):
2321 if verbose: print " (base = %s)" % base
2322 class C(base):
2323 def __init__(self, value):
2324 self.value = int(value)
2325 def __cmp__(self, other):
2326 raise TestFailed, "shouldn't call __cmp__"
2327 def __eq__(self, other):
2328 if isinstance(other, C):
2329 return self.value == other.value
2330 if isinstance(other, int) or isinstance(other, long):
2331 return self.value == other
2332 return NotImplemented
2333 def __ne__(self, other):
2334 if isinstance(other, C):
2335 return self.value != other.value
2336 if isinstance(other, int) or isinstance(other, long):
2337 return self.value != other
2338 return NotImplemented
2339 def __lt__(self, other):
2340 if isinstance(other, C):
2341 return self.value < other.value
2342 if isinstance(other, int) or isinstance(other, long):
2343 return self.value < other
2344 return NotImplemented
2345 def __le__(self, other):
2346 if isinstance(other, C):
2347 return self.value <= other.value
2348 if isinstance(other, int) or isinstance(other, long):
2349 return self.value <= other
2350 return NotImplemented
2351 def __gt__(self, other):
2352 if isinstance(other, C):
2353 return self.value > other.value
2354 if isinstance(other, int) or isinstance(other, long):
2355 return self.value > other
2356 return NotImplemented
2357 def __ge__(self, other):
2358 if isinstance(other, C):
2359 return self.value >= other.value
2360 if isinstance(other, int) or isinstance(other, long):
2361 return self.value >= other
2362 return NotImplemented
2363 c1 = C(1)
2364 c2 = C(2)
2365 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002366 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002367 c = {1: c1, 2: c2, 3: c3}
2368 for x in 1, 2, 3:
2369 for y in 1, 2, 3:
2370 for op in "<", "<=", "==", "!=", ">", ">=":
2371 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2372 "x=%d, y=%d" % (x, y))
2373 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2374 "x=%d, y=%d" % (x, y))
2375 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2376 "x=%d, y=%d" % (x, y))
2377
Guido van Rossum1952e382001-09-19 01:25:16 +00002378def coercions():
2379 if verbose: print "Testing coercions..."
2380 class I(int): pass
2381 coerce(I(0), 0)
2382 coerce(0, I(0))
2383 class L(long): pass
2384 coerce(L(0), 0)
2385 coerce(L(0), 0L)
2386 coerce(0, L(0))
2387 coerce(0L, L(0))
2388 class F(float): pass
2389 coerce(F(0), 0)
2390 coerce(F(0), 0L)
2391 coerce(F(0), 0.)
2392 coerce(0, F(0))
2393 coerce(0L, F(0))
2394 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002395 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002396 coerce(C(0), 0)
2397 coerce(C(0), 0L)
2398 coerce(C(0), 0.)
2399 coerce(C(0), 0j)
2400 coerce(0, C(0))
2401 coerce(0L, C(0))
2402 coerce(0., C(0))
2403 coerce(0j, C(0))
2404
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002405def descrdoc():
2406 if verbose: print "Testing descriptor doc strings..."
2407 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002408 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002409 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002410 check(file.name, "file name") # member descriptor
2411
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002412def setclass():
2413 if verbose: print "Testing __class__ assignment..."
2414 class C(object): pass
2415 class D(object): pass
2416 class E(object): pass
2417 class F(D, E): pass
2418 for cls in C, D, E, F:
2419 for cls2 in C, D, E, F:
2420 x = cls()
2421 x.__class__ = cls2
2422 verify(x.__class__ is cls2)
2423 x.__class__ = cls
2424 verify(x.__class__ is cls)
2425 def cant(x, C):
2426 try:
2427 x.__class__ = C
2428 except TypeError:
2429 pass
2430 else:
2431 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002432 try:
2433 delattr(x, "__class__")
2434 except TypeError:
2435 pass
2436 else:
2437 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002438 cant(C(), list)
2439 cant(list(), C)
2440 cant(C(), 1)
2441 cant(C(), object)
2442 cant(object(), list)
2443 cant(list(), object)
2444
Guido van Rossum6661be32001-10-26 04:26:12 +00002445def setdict():
2446 if verbose: print "Testing __dict__ assignment..."
2447 class C(object): pass
2448 a = C()
2449 a.__dict__ = {'b': 1}
2450 vereq(a.b, 1)
2451 def cant(x, dict):
2452 try:
2453 x.__dict__ = dict
2454 except TypeError:
2455 pass
2456 else:
2457 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2458 cant(a, None)
2459 cant(a, [])
2460 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002461 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002462 # Classes don't allow __dict__ assignment
2463 cant(C, {})
2464
Guido van Rossum3926a632001-09-25 16:25:58 +00002465def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002466 if verbose:
2467 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002468 import pickle, cPickle
2469
2470 def sorteditems(d):
2471 L = d.items()
2472 L.sort()
2473 return L
2474
2475 global C
2476 class C(object):
2477 def __init__(self, a, b):
2478 super(C, self).__init__()
2479 self.a = a
2480 self.b = b
2481 def __repr__(self):
2482 return "C(%r, %r)" % (self.a, self.b)
2483
2484 global C1
2485 class C1(list):
2486 def __new__(cls, a, b):
2487 return super(C1, cls).__new__(cls)
2488 def __init__(self, a, b):
2489 self.a = a
2490 self.b = b
2491 def __repr__(self):
2492 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2493
2494 global C2
2495 class C2(int):
2496 def __new__(cls, a, b, val=0):
2497 return super(C2, cls).__new__(cls, val)
2498 def __init__(self, a, b, val=0):
2499 self.a = a
2500 self.b = b
2501 def __repr__(self):
2502 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2503
Guido van Rossum90c45142001-11-24 21:07:01 +00002504 global C3
2505 class C3(object):
2506 def __init__(self, foo):
2507 self.foo = foo
2508 def __getstate__(self):
2509 return self.foo
2510 def __setstate__(self, foo):
2511 self.foo = foo
2512
2513 global C4classic, C4
2514 class C4classic: # classic
2515 pass
2516 class C4(C4classic, object): # mixed inheritance
2517 pass
2518
Guido van Rossum3926a632001-09-25 16:25:58 +00002519 for p in pickle, cPickle:
2520 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002521 if verbose:
2522 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002523
2524 for cls in C, C1, C2:
2525 s = p.dumps(cls, bin)
2526 cls2 = p.loads(s)
2527 verify(cls2 is cls)
2528
2529 a = C1(1, 2); a.append(42); a.append(24)
2530 b = C2("hello", "world", 42)
2531 s = p.dumps((a, b), bin)
2532 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002533 vereq(x.__class__, a.__class__)
2534 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2535 vereq(y.__class__, b.__class__)
2536 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2537 vereq(`x`, `a`)
2538 vereq(`y`, `b`)
Guido van Rossum3926a632001-09-25 16:25:58 +00002539 if verbose:
2540 print "a = x =", a
2541 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002542 # Test for __getstate__ and __setstate__ on new style class
2543 u = C3(42)
2544 s = p.dumps(u, bin)
2545 v = p.loads(s)
2546 veris(u.__class__, v.__class__)
2547 vereq(u.foo, v.foo)
2548 # Test for picklability of hybrid class
2549 u = C4()
2550 u.foo = 42
2551 s = p.dumps(u, bin)
2552 v = p.loads(s)
2553 veris(u.__class__, v.__class__)
2554 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002555
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002556 # Testing copy.deepcopy()
2557 if verbose:
2558 print "deepcopy"
2559 import copy
2560 for cls in C, C1, C2:
2561 cls2 = copy.deepcopy(cls)
2562 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002563
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002564 a = C1(1, 2); a.append(42); a.append(24)
2565 b = C2("hello", "world", 42)
2566 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002567 vereq(x.__class__, a.__class__)
2568 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2569 vereq(y.__class__, b.__class__)
2570 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2571 vereq(`x`, `a`)
2572 vereq(`y`, `b`)
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002573 if verbose:
2574 print "a = x =", a
2575 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002576
Guido van Rossum8c842552002-03-14 23:05:54 +00002577def pickleslots():
2578 if verbose: print "Testing pickling of classes with __slots__ ..."
2579 import pickle, cPickle
2580 # Pickling of classes with __slots__ but without __getstate__ should fail
2581 global B, C, D, E
2582 class B(object):
2583 pass
2584 for base in [object, B]:
2585 class C(base):
2586 __slots__ = ['a']
2587 class D(C):
2588 pass
2589 try:
2590 pickle.dumps(C())
2591 except TypeError:
2592 pass
2593 else:
2594 raise TestFailed, "should fail: pickle C instance - %s" % base
2595 try:
2596 cPickle.dumps(C())
2597 except TypeError:
2598 pass
2599 else:
2600 raise TestFailed, "should fail: cPickle C instance - %s" % base
2601 try:
2602 pickle.dumps(C())
2603 except TypeError:
2604 pass
2605 else:
2606 raise TestFailed, "should fail: pickle D instance - %s" % base
2607 try:
2608 cPickle.dumps(D())
2609 except TypeError:
2610 pass
2611 else:
2612 raise TestFailed, "should fail: cPickle D instance - %s" % base
2613 # Give C a __getstate__ and __setstate__
2614 class C(base):
2615 __slots__ = ['a']
2616 def __getstate__(self):
2617 try:
2618 d = self.__dict__.copy()
2619 except AttributeError:
2620 d = {}
2621 try:
2622 d['a'] = self.a
2623 except AttributeError:
2624 pass
2625 return d
2626 def __setstate__(self, d):
2627 for k, v in d.items():
2628 setattr(self, k, v)
2629 class D(C):
2630 pass
2631 # Now it should work
2632 x = C()
2633 y = pickle.loads(pickle.dumps(x))
2634 vereq(hasattr(y, 'a'), 0)
2635 y = cPickle.loads(cPickle.dumps(x))
2636 vereq(hasattr(y, 'a'), 0)
2637 x.a = 42
2638 y = pickle.loads(pickle.dumps(x))
2639 vereq(y.a, 42)
2640 y = cPickle.loads(cPickle.dumps(x))
2641 vereq(y.a, 42)
2642 x = D()
2643 x.a = 42
2644 x.b = 100
2645 y = pickle.loads(pickle.dumps(x))
2646 vereq(y.a + y.b, 142)
2647 y = cPickle.loads(cPickle.dumps(x))
2648 vereq(y.a + y.b, 142)
2649 # But a subclass that adds a slot should not work
2650 class E(C):
2651 __slots__ = ['b']
2652 try:
2653 pickle.dumps(E())
2654 except TypeError:
2655 pass
2656 else:
2657 raise TestFailed, "should fail: pickle E instance - %s" % base
2658 try:
2659 cPickle.dumps(E())
2660 except TypeError:
2661 pass
2662 else:
2663 raise TestFailed, "should fail: cPickle E instance - %s" % base
2664
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002665def copies():
2666 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2667 import copy
2668 class C(object):
2669 pass
2670
2671 a = C()
2672 a.foo = 12
2673 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002674 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002675
2676 a.bar = [1,2,3]
2677 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002678 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002679 verify(c.bar is a.bar)
2680
2681 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002682 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002683 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002684 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002685
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002686def binopoverride():
2687 if verbose: print "Testing overrides of binary operations..."
2688 class I(int):
2689 def __repr__(self):
2690 return "I(%r)" % int(self)
2691 def __add__(self, other):
2692 return I(int(self) + int(other))
2693 __radd__ = __add__
2694 def __pow__(self, other, mod=None):
2695 if mod is None:
2696 return I(pow(int(self), int(other)))
2697 else:
2698 return I(pow(int(self), int(other), int(mod)))
2699 def __rpow__(self, other, mod=None):
2700 if mod is None:
2701 return I(pow(int(other), int(self), mod))
2702 else:
2703 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00002704
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002705 vereq(`I(1) + I(2)`, "I(3)")
2706 vereq(`I(1) + 2`, "I(3)")
2707 vereq(`1 + I(2)`, "I(3)")
2708 vereq(`I(2) ** I(3)`, "I(8)")
2709 vereq(`2 ** I(3)`, "I(8)")
2710 vereq(`I(2) ** 3`, "I(8)")
2711 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2712 class S(str):
2713 def __eq__(self, other):
2714 return self.lower() == other.lower()
2715
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002716def subclasspropagation():
2717 if verbose: print "Testing propagation of slot functions to subclasses..."
2718 class A(object):
2719 pass
2720 class B(A):
2721 pass
2722 class C(A):
2723 pass
2724 class D(B, C):
2725 pass
2726 d = D()
2727 vereq(hash(d), id(d))
2728 A.__hash__ = lambda self: 42
2729 vereq(hash(d), 42)
2730 C.__hash__ = lambda self: 314
2731 vereq(hash(d), 314)
2732 B.__hash__ = lambda self: 144
2733 vereq(hash(d), 144)
2734 D.__hash__ = lambda self: 100
2735 vereq(hash(d), 100)
2736 del D.__hash__
2737 vereq(hash(d), 144)
2738 del B.__hash__
2739 vereq(hash(d), 314)
2740 del C.__hash__
2741 vereq(hash(d), 42)
2742 del A.__hash__
2743 vereq(hash(d), id(d))
2744 d.foo = 42
2745 d.bar = 42
2746 vereq(d.foo, 42)
2747 vereq(d.bar, 42)
2748 def __getattribute__(self, name):
2749 if name == "foo":
2750 return 24
2751 return object.__getattribute__(self, name)
2752 A.__getattribute__ = __getattribute__
2753 vereq(d.foo, 24)
2754 vereq(d.bar, 42)
2755 def __getattr__(self, name):
2756 if name in ("spam", "foo", "bar"):
2757 return "hello"
2758 raise AttributeError, name
2759 B.__getattr__ = __getattr__
2760 vereq(d.spam, "hello")
2761 vereq(d.foo, 24)
2762 vereq(d.bar, 42)
2763 del A.__getattribute__
2764 vereq(d.foo, 42)
2765 del d.foo
2766 vereq(d.foo, "hello")
2767 vereq(d.bar, 42)
2768 del B.__getattr__
2769 try:
2770 d.foo
2771 except AttributeError:
2772 pass
2773 else:
2774 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00002775
Guido van Rossume7f3e242002-06-14 02:35:45 +00002776 # Test a nasty bug in recurse_down_subclasses()
2777 import gc
2778 class A(object):
2779 pass
2780 class B(A):
2781 pass
2782 del B
2783 gc.collect()
2784 A.__setitem__ = lambda *a: None # crash
2785
Tim Petersfc57ccb2001-10-12 02:38:24 +00002786def buffer_inherit():
2787 import binascii
2788 # SF bug [#470040] ParseTuple t# vs subclasses.
2789 if verbose:
2790 print "Testing that buffer interface is inherited ..."
2791
2792 class MyStr(str):
2793 pass
2794 base = 'abc'
2795 m = MyStr(base)
2796 # b2a_hex uses the buffer interface to get its argument's value, via
2797 # PyArg_ParseTuple 't#' code.
2798 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2799
2800 # It's not clear that unicode will continue to support the character
2801 # buffer interface, and this test will fail if that's taken away.
2802 class MyUni(unicode):
2803 pass
2804 base = u'abc'
2805 m = MyUni(base)
2806 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2807
2808 class MyInt(int):
2809 pass
2810 m = MyInt(42)
2811 try:
2812 binascii.b2a_hex(m)
2813 raise TestFailed('subclass of int should not have a buffer interface')
2814 except TypeError:
2815 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00002816
Tim Petersc9933152001-10-16 20:18:24 +00002817def str_of_str_subclass():
2818 import binascii
2819 import cStringIO
2820
2821 if verbose:
2822 print "Testing __str__ defined in subclass of str ..."
2823
2824 class octetstring(str):
2825 def __str__(self):
2826 return binascii.b2a_hex(self)
2827 def __repr__(self):
2828 return self + " repr"
2829
2830 o = octetstring('A')
2831 vereq(type(o), octetstring)
2832 vereq(type(str(o)), str)
2833 vereq(type(repr(o)), str)
2834 vereq(ord(o), 0x41)
2835 vereq(str(o), '41')
2836 vereq(repr(o), 'A repr')
2837 vereq(o.__str__(), '41')
2838 vereq(o.__repr__(), 'A repr')
2839
2840 capture = cStringIO.StringIO()
2841 # Calling str() or not exercises different internal paths.
2842 print >> capture, o
2843 print >> capture, str(o)
2844 vereq(capture.getvalue(), '41\n41\n')
2845 capture.close()
2846
Guido van Rossumc8e56452001-10-22 00:43:43 +00002847def kwdargs():
2848 if verbose: print "Testing keyword arguments to __init__, __call__..."
2849 def f(a): return a
2850 vereq(f.__call__(a=42), 42)
2851 a = []
2852 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00002853 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00002854
Guido van Rossumed87ad82001-10-30 02:33:02 +00002855def delhook():
2856 if verbose: print "Testing __del__ hook..."
2857 log = []
2858 class C(object):
2859 def __del__(self):
2860 log.append(1)
2861 c = C()
2862 vereq(log, [])
2863 del c
2864 vereq(log, [1])
2865
Guido van Rossum29d26062001-12-11 04:37:34 +00002866 class D(object): pass
2867 d = D()
2868 try: del d[0]
2869 except TypeError: pass
2870 else: raise TestFailed, "invalid del() didn't raise TypeError"
2871
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002872def hashinherit():
2873 if verbose: print "Testing hash of mutable subclasses..."
2874
2875 class mydict(dict):
2876 pass
2877 d = mydict()
2878 try:
2879 hash(d)
2880 except TypeError:
2881 pass
2882 else:
2883 raise TestFailed, "hash() of dict subclass should fail"
2884
2885 class mylist(list):
2886 pass
2887 d = mylist()
2888 try:
2889 hash(d)
2890 except TypeError:
2891 pass
2892 else:
2893 raise TestFailed, "hash() of list subclass should fail"
2894
Guido van Rossum29d26062001-12-11 04:37:34 +00002895def strops():
2896 try: 'a' + 5
2897 except TypeError: pass
2898 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
2899
2900 try: ''.split('')
2901 except ValueError: pass
2902 else: raise TestFailed, "''.split('') doesn't raise ValueError"
2903
2904 try: ''.join([0])
2905 except TypeError: pass
2906 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
2907
2908 try: ''.rindex('5')
2909 except ValueError: pass
2910 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
2911
2912 try: ''.replace('', '')
2913 except ValueError: pass
2914 else: raise TestFailed, "''.replace('', '') doesn't raise ValueError"
2915
2916 try: '%(n)s' % None
2917 except TypeError: pass
2918 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
2919
2920 try: '%(n' % {}
2921 except ValueError: pass
2922 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
2923
2924 try: '%*s' % ('abc')
2925 except TypeError: pass
2926 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
2927
2928 try: '%*.*s' % ('abc', 5)
2929 except TypeError: pass
2930 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
2931
2932 try: '%s' % (1, 2)
2933 except TypeError: pass
2934 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
2935
2936 try: '%' % None
2937 except ValueError: pass
2938 else: raise TestFailed, "'%' % None doesn't raise ValueError"
2939
2940 vereq('534253'.isdigit(), 1)
2941 vereq('534253x'.isdigit(), 0)
2942 vereq('%c' % 5, '\x05')
2943 vereq('%c' % '5', '5')
2944
Guido van Rossum2764a3a2001-12-28 21:39:03 +00002945def deepcopyrecursive():
2946 if verbose: print "Testing deepcopy of recursive objects..."
2947 class Node:
2948 pass
2949 a = Node()
2950 b = Node()
2951 a.b = b
2952 b.a = a
2953 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00002954
Guido van Rossumd7035672002-03-12 20:43:31 +00002955def modules():
2956 if verbose: print "Testing uninitialized module objects..."
2957 from types import ModuleType as M
2958 m = M.__new__(M)
2959 str(m)
2960 vereq(hasattr(m, "__name__"), 0)
2961 vereq(hasattr(m, "__file__"), 0)
2962 vereq(hasattr(m, "foo"), 0)
2963 vereq(m.__dict__, None)
2964 m.foo = 1
2965 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00002966
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002967def dictproxyiterkeys():
2968 class C(object):
2969 def meth(self):
2970 pass
2971 if verbose: print "Testing dict-proxy iterkeys..."
2972 keys = [ key for key in C.__dict__.iterkeys() ]
2973 keys.sort()
2974 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
2975
2976def dictproxyitervalues():
2977 class C(object):
2978 def meth(self):
2979 pass
2980 if verbose: print "Testing dict-proxy itervalues..."
2981 values = [ values for values in C.__dict__.itervalues() ]
2982 vereq(len(values), 5)
2983
2984def dictproxyiteritems():
2985 class C(object):
2986 def meth(self):
2987 pass
2988 if verbose: print "Testing dict-proxy iteritems..."
2989 keys = [ key for (key, value) in C.__dict__.iteritems() ]
2990 keys.sort()
2991 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
2992
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002993def funnynew():
2994 if verbose: print "Testing __new__ returning something unexpected..."
2995 class C(object):
2996 def __new__(cls, arg):
2997 if isinstance(arg, str): return [1, 2, 3]
2998 elif isinstance(arg, int): return object.__new__(D)
2999 else: return object.__new__(cls)
3000 class D(C):
3001 def __init__(self, arg):
3002 self.foo = arg
3003 vereq(C("1"), [1, 2, 3])
3004 vereq(D("1"), [1, 2, 3])
3005 d = D(None)
3006 veris(d.foo, None)
3007 d = C(1)
3008 vereq(isinstance(d, D), True)
3009 vereq(d.foo, 1)
3010 d = D(1)
3011 vereq(isinstance(d, D), True)
3012 vereq(d.foo, 1)
3013
Guido van Rossume8fc6402002-04-16 16:44:51 +00003014def imulbug():
3015 # SF bug 544647
3016 if verbose: print "Testing for __imul__ problems..."
3017 class C(object):
3018 def __imul__(self, other):
3019 return (self, other)
3020 x = C()
3021 y = x
3022 y *= 1.0
3023 vereq(y, (x, 1.0))
3024 y = x
3025 y *= 2
3026 vereq(y, (x, 2))
3027 y = x
3028 y *= 3L
3029 vereq(y, (x, 3L))
3030 y = x
3031 y *= 1L<<100
3032 vereq(y, (x, 1L<<100))
3033 y = x
3034 y *= None
3035 vereq(y, (x, None))
3036 y = x
3037 y *= "foo"
3038 vereq(y, (x, "foo"))
3039
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003040def docdescriptor():
3041 # SF bug 542984
3042 if verbose: print "Testing __doc__ descriptor..."
3043 class DocDescr(object):
3044 def __get__(self, object, otype):
3045 if object:
3046 object = object.__class__.__name__ + ' instance'
3047 if otype:
3048 otype = otype.__name__
3049 return 'object=%s; type=%s' % (object, otype)
3050 class OldClass:
3051 __doc__ = DocDescr()
3052 class NewClass(object):
3053 __doc__ = DocDescr()
3054 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3055 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3056 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3057 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3058
Tim Petersafb2c802002-04-18 18:06:20 +00003059def string_exceptions():
3060 if verbose:
3061 print "Testing string exceptions ..."
3062
3063 # Ensure builtin strings work OK as exceptions.
3064 astring = "An exception string."
3065 try:
3066 raise astring
3067 except astring:
3068 pass
3069 else:
3070 raise TestFailed, "builtin string not usable as exception"
3071
3072 # Ensure string subclass instances do not.
3073 class MyStr(str):
3074 pass
3075
3076 newstring = MyStr("oops -- shouldn't work")
3077 try:
3078 raise newstring
3079 except TypeError:
3080 pass
3081 except:
3082 raise TestFailed, "string subclass allowed as exception"
3083
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003084def copy_setstate():
3085 if verbose:
3086 print "Testing that copy.*copy() correctly uses __setstate__..."
3087 import copy
3088 class C(object):
3089 def __init__(self, foo=None):
3090 self.foo = foo
3091 self.__foo = foo
3092 def setfoo(self, foo=None):
3093 self.foo = foo
3094 def getfoo(self):
3095 return self.__foo
3096 def __getstate__(self):
3097 return [self.foo]
3098 def __setstate__(self, lst):
3099 assert len(lst) == 1
3100 self.__foo = self.foo = lst[0]
3101 a = C(42)
3102 a.setfoo(24)
3103 vereq(a.foo, 24)
3104 vereq(a.getfoo(), 42)
3105 b = copy.copy(a)
3106 vereq(b.foo, 24)
3107 vereq(b.getfoo(), 24)
3108 b = copy.deepcopy(a)
3109 vereq(b.foo, 24)
3110 vereq(b.getfoo(), 24)
3111
Guido van Rossum09638c12002-06-13 19:17:46 +00003112def slices():
3113 if verbose:
3114 print "Testing cases with slices and overridden __getitem__ ..."
3115 # Strings
3116 vereq("hello"[:4], "hell")
3117 vereq("hello"[slice(4)], "hell")
3118 vereq(str.__getitem__("hello", slice(4)), "hell")
3119 class S(str):
3120 def __getitem__(self, x):
3121 return str.__getitem__(self, x)
3122 vereq(S("hello")[:4], "hell")
3123 vereq(S("hello")[slice(4)], "hell")
3124 vereq(S("hello").__getitem__(slice(4)), "hell")
3125 # Tuples
3126 vereq((1,2,3)[:2], (1,2))
3127 vereq((1,2,3)[slice(2)], (1,2))
3128 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3129 class T(tuple):
3130 def __getitem__(self, x):
3131 return tuple.__getitem__(self, x)
3132 vereq(T((1,2,3))[:2], (1,2))
3133 vereq(T((1,2,3))[slice(2)], (1,2))
3134 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3135 # Lists
3136 vereq([1,2,3][:2], [1,2])
3137 vereq([1,2,3][slice(2)], [1,2])
3138 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3139 class L(list):
3140 def __getitem__(self, x):
3141 return list.__getitem__(self, x)
3142 vereq(L([1,2,3])[:2], [1,2])
3143 vereq(L([1,2,3])[slice(2)], [1,2])
3144 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3145 # Now do lists and __setitem__
3146 a = L([1,2,3])
3147 a[slice(1, 3)] = [3,2]
3148 vereq(a, [1,3,2])
3149 a[slice(0, 2, 1)] = [3,1]
3150 vereq(a, [3,1,2])
3151 a.__setitem__(slice(1, 3), [2,1])
3152 vereq(a, [3,2,1])
3153 a.__setitem__(slice(0, 2, 1), [2,3])
3154 vereq(a, [2,3,1])
3155
3156
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003157def do_this_first():
3158 if verbose:
3159 print "Testing SF bug 551412 ..."
3160 # This dumps core when SF bug 551412 isn't fixed --
3161 # but only when test_descr.py is run separately.
3162 # (That can't be helped -- as soon as PyType_Ready()
3163 # is called for PyLong_Type, the bug is gone.)
3164 class UserLong(object):
3165 def __pow__(self, *args):
3166 pass
3167 try:
3168 pow(0L, UserLong(), 0L)
3169 except:
3170 pass
3171
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003172 if verbose:
3173 print "Testing SF bug 570483..."
3174 # Another segfault only when run early
3175 # (before PyType_Ready(tuple) is called)
3176 type.mro(tuple)
3177
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003178def test_main():
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003179 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00003180 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181 lists()
3182 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00003183 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00003184 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 ints()
3186 longs()
3187 floats()
3188 complexes()
3189 spamlists()
3190 spamdicts()
3191 pydicts()
3192 pylists()
3193 metaclass()
3194 pymods()
3195 multi()
3196 diamond()
Guido van Rossum37202612001-08-09 19:45:21 +00003197 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198 slots()
3199 dynamics()
3200 errors()
3201 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003202 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003204 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 classic()
3206 compattr()
3207 newslot()
3208 altmro()
3209 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00003210 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00003211 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00003212 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00003213 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00003214 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00003215 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00003216 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00003217 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00003218 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00003219 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00003220 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00003221 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00003222 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003223 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00003224 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00003225 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003226 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003227 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003228 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00003229 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00003230 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00003231 kwdargs()
Guido van Rossumed87ad82001-10-30 02:33:02 +00003232 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003233 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00003234 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003235 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00003236 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003237 dictproxyiterkeys()
3238 dictproxyitervalues()
3239 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00003240 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003241 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00003242 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003243 docdescriptor()
Tim Petersafb2c802002-04-18 18:06:20 +00003244 string_exceptions()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003245 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00003246 slices()
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003247 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003249if __name__ == "__main__":
3250 test_main()