blob: eda96a6bd9991eead57f1794c6e5fd434d474956 [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
Jeremy Hyltonfa955692007-02-27 18:29:45 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, run_doctest
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({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000188 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000189 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000190 vereq(d, dict(d.iteritems()))
191 d = dict({'one':1, 'two':2})
192 vereq(d, dict(one=1, two=2))
193 vereq(d, dict(**d))
194 vereq(d, dict({"one": 1}, two=2))
195 vereq(d, dict([("two", 2)], one=1))
196 vereq(d, dict([("one", 100), ("two", 200)], **d))
197 verify(d is not dict(**d))
Tim Peters25786c02001-09-02 08:22:48 +0000198 for badarg in 0, 0L, 0j, "0", [0], (0,):
199 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000200 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000201 except TypeError:
202 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000203 except ValueError:
204 if badarg == "0":
205 # It's a sequence, and its elements are also sequences (gotta
206 # love strings <wink>), but they aren't of length 2, so this
207 # one seemed better as a ValueError than a TypeError.
208 pass
209 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000210 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000211 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000212 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000213
214 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000215 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000216 except TypeError:
217 pass
218 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000219 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000220
221 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000222 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000223 dict = {1:2, 3:4, 'a':1j}
224
Tim Peters25786c02001-09-02 08:22:48 +0000225 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000226 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000227 except TypeError:
228 pass
229 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000230 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000231
232 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000233 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000234 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000235 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000236
Tim Peters1fc240e2001-10-26 05:06:50 +0000237 # Init from sequence of iterable objects, each producing a 2-sequence.
238 class AddressBookEntry:
239 def __init__(self, first, last):
240 self.first = first
241 self.last = last
242 def __iter__(self):
243 return iter([self.first, self.last])
244
Tim Petersa427a2b2001-10-29 22:25:45 +0000245 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000246 AddressBookEntry('Barry', 'Peters'),
247 AddressBookEntry('Tim', 'Peters'),
248 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000249 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
250
Tim Petersa427a2b2001-10-29 22:25:45 +0000251 d = dict(zip(range(4), range(1, 5)))
252 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000253
254 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000255 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000256 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000257 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000258 except ValueError:
259 pass
260 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000261 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000262
Tim Peters5d2b77c2001-09-03 05:47:38 +0000263def test_dir():
264 if verbose:
265 print "Testing dir() ..."
266 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000267 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000268 del junk
269
270 # Just make sure these don't blow up!
271 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
272 dir(arg)
273
Tim Peters37a309d2001-09-04 01:20:04 +0000274 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275 class C:
276 Cdata = 1
277 def Cmethod(self): pass
278
279 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
Guido van Rossum45704552001-10-08 16:35:45 +0000280 vereq(dir(C), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000281 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000282
283 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
Guido van Rossum45704552001-10-08 16:35:45 +0000284 vereq(dir(c), cstuff)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000285
286 c.cdata = 2
287 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000288 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000289 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000290
291 class A(C):
292 Adata = 1
293 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000294
Tim Peters37a309d2001-09-04 01:20:04 +0000295 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000296 vereq(dir(A), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000297 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000298 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000299 vereq(dir(a), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000300 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000301 a.adata = 42
302 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000303 vereq(dir(a), astuff + ['adata', 'amethod'])
Tim Peters37a309d2001-09-04 01:20:04 +0000304
305 # The same, but with new-style classes. Since these have object as a
306 # base class, a lot more gets sucked in.
307 def interesting(strings):
308 return [s for s in strings if not s.startswith('_')]
309
Tim Peters5d2b77c2001-09-03 05:47:38 +0000310 class C(object):
311 Cdata = 1
312 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000313
314 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000315 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000316
317 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000318 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000319 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000320
321 c.cdata = 2
322 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000323 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000324 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000325
Tim Peters5d2b77c2001-09-03 05:47:38 +0000326 class A(C):
327 Adata = 1
328 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000329
330 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000331 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000332 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000333 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000334 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000335 a.adata = 42
336 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000337 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000338 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000339
Tim Peterscaaff8d2001-09-10 23:12:14 +0000340 # Try a module subclass.
341 import sys
342 class M(type(sys)):
343 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000344 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000345 minstance.b = 2
346 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000347 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
348 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000349
350 class M2(M):
351 def getdict(self):
352 return "Not a dict!"
353 __dict__ = property(getdict)
354
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000355 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000356 m2instance.b = 2
357 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000358 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000359 try:
360 dir(m2instance)
361 except TypeError:
362 pass
363
Tim Peters9e6a3992001-10-30 05:45:26 +0000364 # Two essentially featureless objects, just inheriting stuff from
365 # object.
366 vereq(dir(None), dir(Ellipsis))
367
Guido van Rossum44022412002-05-13 18:29:46 +0000368 # Nasty test case for proxied objects
369 class Wrapper(object):
370 def __init__(self, obj):
371 self.__obj = obj
372 def __repr__(self):
373 return "Wrapper(%s)" % repr(self.__obj)
374 def __getitem__(self, key):
375 return Wrapper(self.__obj[key])
376 def __len__(self):
377 return len(self.__obj)
378 def __getattr__(self, name):
379 return Wrapper(getattr(self.__obj, name))
380
381 class C(object):
382 def __getclass(self):
383 return Wrapper(type(self))
384 __class__ = property(__getclass)
385
386 dir(C()) # This used to segfault
387
Tim Peters6d6c1a32001-08-02 04:15:00 +0000388binops = {
389 'add': '+',
390 'sub': '-',
391 'mul': '*',
392 'div': '/',
393 'mod': '%',
394 'divmod': 'divmod',
395 'pow': '**',
396 'lshift': '<<',
397 'rshift': '>>',
398 'and': '&',
399 'xor': '^',
400 'or': '|',
401 'cmp': 'cmp',
402 'lt': '<',
403 'le': '<=',
404 'eq': '==',
405 'ne': '!=',
406 'gt': '>',
407 'ge': '>=',
408 }
409
410for name, expr in binops.items():
411 if expr.islower():
412 expr = expr + "(a, b)"
413 else:
414 expr = 'a %s b' % expr
415 binops[name] = expr
416
417unops = {
418 'pos': '+',
419 'neg': '-',
420 'abs': 'abs',
421 'invert': '~',
422 'int': 'int',
423 'long': 'long',
424 'float': 'float',
425 'oct': 'oct',
426 'hex': 'hex',
427 }
428
429for name, expr in unops.items():
430 if expr.islower():
431 expr = expr + "(a)"
432 else:
433 expr = '%s a' % expr
434 unops[name] = expr
435
436def numops(a, b, skip=[]):
437 dict = {'a': a, 'b': b}
438 for name, expr in binops.items():
439 if name not in skip:
440 name = "__%s__" % name
441 if hasattr(a, name):
442 res = eval(expr, dict)
443 testbinop(a, b, res, expr, name)
444 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000445 if name not in skip:
446 name = "__%s__" % name
447 if hasattr(a, name):
448 res = eval(expr, dict)
449 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450
451def ints():
452 if verbose: print "Testing int operations..."
453 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000454 # The following crashes in Python 2.2
455 vereq((1).__nonzero__(), 1)
456 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000457 # This returns 'NotImplemented' in Python 2.2
458 class C(int):
459 def __add__(self, other):
460 return NotImplemented
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000461 vereq(C(5L), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000462 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"
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000468 import sys
469 try:
470 C(sys.maxint+1)
471 except OverflowError:
472 pass
473 else:
474 raise TestFailed, "should have raised OverflowError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000475
476def longs():
477 if verbose: print "Testing long operations..."
478 numops(100L, 3L)
479
480def floats():
481 if verbose: print "Testing float operations..."
482 numops(100.0, 3.0)
483
484def complexes():
485 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000486 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000487 class Number(complex):
488 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000489 def __new__(cls, *args, **kwds):
490 result = complex.__new__(cls, *args)
491 result.prec = kwds.get('prec', 12)
492 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 def __repr__(self):
494 prec = self.prec
495 if self.imag == 0.0:
496 return "%.*g" % (prec, self.real)
497 if self.real == 0.0:
498 return "%.*gj" % (prec, self.imag)
499 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
500 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000501
Tim Peters6d6c1a32001-08-02 04:15:00 +0000502 a = Number(3.14, prec=6)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000503 vereq(repr(a), "3.14")
Guido van Rossum45704552001-10-08 16:35:45 +0000504 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000505
Tim Peters3f996e72001-09-13 19:18:27 +0000506 a = Number(a, prec=2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000507 vereq(repr(a), "3.1")
Guido van Rossum45704552001-10-08 16:35:45 +0000508 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000509
510 a = Number(234.5)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000511 vereq(repr(a), "234.5")
Guido van Rossum45704552001-10-08 16:35:45 +0000512 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000513
Tim Peters6d6c1a32001-08-02 04:15:00 +0000514def spamlists():
515 if verbose: print "Testing spamlist operations..."
516 import copy, xxsubtype as spam
517 def spamlist(l, memo=None):
518 import xxsubtype as spam
519 return spam.spamlist(l)
520 # This is an ugly hack:
521 copy._deepcopy_dispatch[spam.spamlist] = spamlist
522
523 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
524 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
525 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
526 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
527 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
528 "a[b:c]", "__getslice__")
529 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
530 "a+=b", "__iadd__")
531 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
532 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
533 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
535 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
536 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
537 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
538 # Test subclassing
539 class C(spam.spamlist):
540 def foo(self): return 1
541 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000542 vereq(a, [])
543 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000544 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000545 vereq(a, [100])
546 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000548 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000549
550def spamdicts():
551 if verbose: print "Testing spamdict operations..."
552 import copy, xxsubtype as spam
553 def spamdict(d, memo=None):
554 import xxsubtype as spam
555 sd = spam.spamdict()
556 for k, v in d.items(): sd[k] = v
557 return sd
558 # This is an ugly hack:
559 copy._deepcopy_dispatch[spam.spamdict] = spamdict
560
561 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
562 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
563 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
564 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
565 d = spamdict({1:2,3:4})
566 l1 = []
567 for i in d.keys(): l1.append(i)
568 l = []
569 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000570 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000571 l = []
572 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000573 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000574 l = []
575 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000576 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577 straightd = {1:2, 3:4}
578 spamd = spamdict(straightd)
579 testunop(spamd, 2, "len(a)", "__len__")
580 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
581 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
582 "a[b]=c", "__setitem__")
583 # Test subclassing
584 class C(spam.spamdict):
585 def foo(self): return 1
586 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000587 vereq(a.items(), [])
588 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000590 vereq(a.items(), [('foo', 'bar')])
591 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000593 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
595def pydicts():
596 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000597 verify(issubclass(dict, dict))
598 verify(isinstance({}, dict))
599 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000600 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000601 verify(d.__class__ is dict)
602 verify(isinstance(d, dict))
603 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604 state = -1
605 def __init__(self, *a, **kw):
606 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000607 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000608 self.state = a[0]
609 if kw:
610 for k, v in kw.items(): self[v] = k
611 def __getitem__(self, key):
612 return self.get(key, 0)
613 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000614 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000615 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616 def setstate(self, state):
617 self.state = state
618 def getstate(self):
619 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000620 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000622 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000624 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000626 vereq(a.state, -1)
627 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000629 vereq(a.state, 0)
630 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000632 vereq(a.state, 10)
633 vereq(a.getstate(), 10)
634 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000636 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000637 if verbose: print "pydict stress test ..."
638 N = 50
639 for i in range(N):
640 a[i] = C()
641 for j in range(N):
642 a[i][j] = i*j
643 for i in range(N):
644 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000645 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646
647def pylists():
648 if verbose: print "Testing Python subclass of list..."
649 class C(list):
650 def __getitem__(self, i):
651 return list.__getitem__(self, i) + 100
652 def __getslice__(self, i, j):
653 return (i, j)
654 a = C()
655 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000656 vereq(a[0], 100)
657 vereq(a[1], 101)
658 vereq(a[2], 102)
659 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660
661def metaclass():
662 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 class C:
664 __metaclass__ = type
665 def __init__(self):
666 self.__state = 0
667 def getstate(self):
668 return self.__state
669 def setstate(self, state):
670 self.__state = state
671 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000672 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000674 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675 class D:
676 class __metaclass__(type):
677 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000678 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000679 d = D()
680 verify(d.__class__ is D)
681 class M1(type):
682 def __new__(cls, name, bases, dict):
683 dict['__spam__'] = 1
684 return type.__new__(cls, name, bases, dict)
685 class C:
686 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000687 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000688 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000689 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000690
Guido van Rossum309b5662001-08-17 11:43:17 +0000691 class _instance(object):
692 pass
693 class M2(object):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000694 @staticmethod
Guido van Rossum309b5662001-08-17 11:43:17 +0000695 def __new__(cls, name, bases, dict):
696 self = object.__new__(cls)
697 self.name = name
698 self.bases = bases
699 self.dict = dict
700 return self
Guido van Rossum309b5662001-08-17 11:43:17 +0000701 def __call__(self):
702 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000703 # Early binding of methods
704 for key in self.dict:
705 if key.startswith("__"):
706 continue
707 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000708 return it
709 class C:
710 __metaclass__ = M2
711 def spam(self):
712 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000713 vereq(C.name, 'C')
714 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000715 verify('spam' in C.dict)
716 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000717 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
Guido van Rossum91ee7982001-08-30 20:52:40 +0000719 # More metaclass examples
720
721 class autosuper(type):
722 # Automatically add __super to the class
723 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000724 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000725 cls = super(autosuper, metaclass).__new__(metaclass,
726 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000727 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000728 while name[:1] == "_":
729 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000730 if name:
731 name = "_%s__super" % name
732 else:
733 name = "__super"
734 setattr(cls, name, super(cls))
735 return cls
736 class A:
737 __metaclass__ = autosuper
738 def meth(self):
739 return "A"
740 class B(A):
741 def meth(self):
742 return "B" + self.__super.meth()
743 class C(A):
744 def meth(self):
745 return "C" + self.__super.meth()
746 class D(C, B):
747 def meth(self):
748 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000749 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000750 class E(B, C):
751 def meth(self):
752 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000753 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000754
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000755 class autoproperty(type):
756 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000757 # named _get_x and/or _set_x are found
758 def __new__(metaclass, name, bases, dict):
759 hits = {}
760 for key, val in dict.iteritems():
761 if key.startswith("_get_"):
762 key = key[5:]
763 get, set = hits.get(key, (None, None))
764 get = val
765 hits[key] = get, set
766 elif key.startswith("_set_"):
767 key = key[5:]
768 get, set = hits.get(key, (None, None))
769 set = val
770 hits[key] = get, set
771 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000772 dict[key] = property(get, set)
773 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000774 name, bases, dict)
775 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000776 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000777 def _get_x(self):
778 return -self.__x
779 def _set_x(self, x):
780 self.__x = -x
781 a = A()
782 verify(not hasattr(a, "x"))
783 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000784 vereq(a.x, 12)
785 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000786
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000787 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000788 # Merge of multiple cooperating metaclasses
789 pass
790 class A:
791 __metaclass__ = multimetaclass
792 def _get_x(self):
793 return "A"
794 class B(A):
795 def _get_x(self):
796 return "B" + self.__super._get_x()
797 class C(A):
798 def _get_x(self):
799 return "C" + self.__super._get_x()
800 class D(C, B):
801 def _get_x(self):
802 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000803 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000804
Guido van Rossumf76de622001-10-18 15:49:21 +0000805 # Make sure type(x) doesn't call x.__class__.__init__
806 class T(type):
807 counter = 0
808 def __init__(self, *args):
809 T.counter += 1
810 class C:
811 __metaclass__ = T
812 vereq(T.counter, 1)
813 a = C()
814 vereq(type(a), C)
815 vereq(T.counter, 1)
816
Guido van Rossum29d26062001-12-11 04:37:34 +0000817 class C(object): pass
818 c = C()
819 try: c()
820 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000821 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000822
Jeremy Hyltonfa955692007-02-27 18:29:45 +0000823 # Testing code to find most derived baseclass
824 class A(type):
825 def __new__(*args, **kwargs):
826 return type.__new__(*args, **kwargs)
827
828 class B(object):
829 pass
830
831 class C(object):
832 __metaclass__ = A
833
834 # The most derived metaclass of D is A rather than type.
835 class D(B, C):
836 pass
837
838
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839def pymods():
840 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000842 import sys
843 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000845 def __init__(self, name):
846 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000847 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000848 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000849 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 def __setattr__(self, name, value):
851 log.append(("setattr", name, value))
852 MT.__setattr__(self, name, value)
853 def __delattr__(self, name):
854 log.append(("delattr", name))
855 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000856 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 a.foo = 12
858 x = a.foo
859 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000860 vereq(log, [("setattr", "foo", 12),
861 ("getattr", "foo"),
862 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863
864def multi():
865 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 class C(object):
867 def __init__(self):
868 self.__state = 0
869 def getstate(self):
870 return self.__state
871 def setstate(self, state):
872 self.__state = state
873 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000874 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000876 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000877 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878 def __init__(self):
879 type({}).__init__(self)
880 C.__init__(self)
881 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000882 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000884 vereq(d.items(), [("hello", "world")])
885 vereq(d["hello"], "world")
886 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000888 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000889 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000890
Guido van Rossume45763a2001-08-10 21:28:46 +0000891 # SF bug #442833
892 class Node(object):
893 def __int__(self):
894 return int(self.foo())
895 def foo(self):
896 return "23"
897 class Frag(Node, list):
898 def foo(self):
899 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000900 vereq(Node().__int__(), 23)
901 vereq(int(Node()), 23)
902 vereq(Frag().__int__(), 42)
903 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000904
Tim Petersa91e9642001-11-14 23:32:33 +0000905 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000906
907 class A:
908 x = 1
909
910 class B(A):
911 pass
912
913 class C(A):
914 x = 2
915
916 class D(B, C):
917 pass
918 vereq(D.x, 1)
919
920 # Classic MRO is preserved for a classic base class.
921 class E(D, object):
922 pass
923 vereq(E.__mro__, (E, D, B, A, C, object))
924 vereq(E.x, 1)
925
926 # But with a mix of classic bases, their MROs are combined using
927 # new-style MRO.
928 class F(B, C, object):
929 pass
930 vereq(F.__mro__, (F, B, C, A, object))
931 vereq(F.x, 2)
932
933 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000934 class C:
935 def cmethod(self):
936 return "C a"
937 def all_method(self):
938 return "C b"
939
940 class M1(C, object):
941 def m1method(self):
942 return "M1 a"
943 def all_method(self):
944 return "M1 b"
945
946 vereq(M1.__mro__, (M1, C, object))
947 m = M1()
948 vereq(m.cmethod(), "C a")
949 vereq(m.m1method(), "M1 a")
950 vereq(m.all_method(), "M1 b")
951
952 class D(C):
953 def dmethod(self):
954 return "D a"
955 def all_method(self):
956 return "D b"
957
Guido van Rossum9a818922002-11-14 19:50:14 +0000958 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000959 def m2method(self):
960 return "M2 a"
961 def all_method(self):
962 return "M2 b"
963
Guido van Rossum9a818922002-11-14 19:50:14 +0000964 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000965 m = M2()
966 vereq(m.cmethod(), "C a")
967 vereq(m.dmethod(), "D a")
968 vereq(m.m2method(), "M2 a")
969 vereq(m.all_method(), "M2 b")
970
Guido van Rossum9a818922002-11-14 19:50:14 +0000971 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000972 def m3method(self):
973 return "M3 a"
974 def all_method(self):
975 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000976 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000977 m = M3()
978 vereq(m.cmethod(), "C a")
979 vereq(m.dmethod(), "D a")
980 vereq(m.m1method(), "M1 a")
981 vereq(m.m2method(), "M2 a")
982 vereq(m.m3method(), "M3 a")
983 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000984
Guido van Rossume54616c2001-12-14 04:19:56 +0000985 class Classic:
986 pass
987 try:
988 class New(Classic):
989 __metaclass__ = type
990 except TypeError:
991 pass
992 else:
993 raise TestFailed, "new class with only classic bases - shouldn't be"
994
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995def diamond():
996 if verbose: print "Testing multiple inheritance special cases..."
997 class A(object):
998 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000999 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 class B(A):
1001 def boo(self): return "B"
1002 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +00001003 vereq(B().spam(), "B")
1004 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 class C(A):
1006 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +00001007 vereq(C().spam(), "A")
1008 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001010 vereq(D().spam(), "B")
1011 vereq(D().boo(), "B")
1012 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +00001014 vereq(E().spam(), "B")
1015 vereq(E().boo(), "C")
1016 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +00001017 # MRO order disagreement
1018 try:
1019 class F(D, E): pass
1020 except TypeError:
1021 pass
1022 else:
1023 raise TestFailed, "expected MRO order disagreement (F)"
1024 try:
1025 class G(E, D): pass
1026 except TypeError:
1027 pass
1028 else:
1029 raise TestFailed, "expected MRO order disagreement (G)"
1030
1031
1032# see thread python-dev/2002-October/029035.html
1033def ex5():
1034 if verbose: print "Testing ex5 from C3 switch discussion..."
1035 class A(object): pass
1036 class B(object): pass
1037 class C(object): pass
1038 class X(A): pass
1039 class Y(A): pass
1040 class Z(X,B,Y,C): pass
1041 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1042
1043# see "A Monotonic Superclass Linearization for Dylan",
1044# by Kim Barrett et al. (OOPSLA 1996)
1045def monotonicity():
1046 if verbose: print "Testing MRO monotonicity..."
1047 class Boat(object): pass
1048 class DayBoat(Boat): pass
1049 class WheelBoat(Boat): pass
1050 class EngineLess(DayBoat): pass
1051 class SmallMultihull(DayBoat): pass
1052 class PedalWheelBoat(EngineLess,WheelBoat): pass
1053 class SmallCatamaran(SmallMultihull): pass
1054 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1055
1056 vereq(PedalWheelBoat.__mro__,
1057 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1058 object))
1059 vereq(SmallCatamaran.__mro__,
1060 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1061
1062 vereq(Pedalo.__mro__,
1063 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1064 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1065
1066# see "A Monotonic Superclass Linearization for Dylan",
1067# by Kim Barrett et al. (OOPSLA 1996)
1068def consistency_with_epg():
1069 if verbose: print "Testing consistentcy with EPG..."
1070 class Pane(object): pass
1071 class ScrollingMixin(object): pass
1072 class EditingMixin(object): pass
1073 class ScrollablePane(Pane,ScrollingMixin): pass
1074 class EditablePane(Pane,EditingMixin): pass
1075 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1076
1077 vereq(EditableScrollablePane.__mro__,
1078 (EditableScrollablePane, ScrollablePane, EditablePane,
1079 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
Raymond Hettingerf394df42003-04-06 19:13:41 +00001081mro_err_msg = """Cannot create a consistent method resolution
1082order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +00001083
Guido van Rossumd32047f2002-11-25 21:38:52 +00001084def mro_disagreement():
1085 if verbose: print "Testing error messages for MRO disagreement..."
1086 def raises(exc, expected, callable, *args):
1087 try:
1088 callable(*args)
1089 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001090 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001091 raise TestFailed, "Message %r, expected %r" % (str(msg),
1092 expected)
1093 else:
1094 raise TestFailed, "Expected %s" % exc
1095 class A(object): pass
1096 class B(A): pass
1097 class C(object): pass
1098 # Test some very simple errors
1099 raises(TypeError, "duplicate base class A",
1100 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001101 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001102 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001103 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001104 type, "X", (A, C, B), {})
1105 # Test a slightly more complex error
1106 class GridLayout(object): pass
1107 class HorizontalGrid(GridLayout): pass
1108 class VerticalGrid(GridLayout): pass
1109 class HVGrid(HorizontalGrid, VerticalGrid): pass
1110 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +00001111 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001112 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1113
Guido van Rossum37202612001-08-09 19:45:21 +00001114def objects():
1115 if verbose: print "Testing object class..."
1116 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001117 vereq(a.__class__, object)
1118 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001119 b = object()
1120 verify(a is not b)
1121 verify(not hasattr(a, "foo"))
1122 try:
1123 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001124 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001125 pass
1126 else:
1127 verify(0, "object() should not allow setting a foo attribute")
1128 verify(not hasattr(object(), "__dict__"))
1129
1130 class Cdict(object):
1131 pass
1132 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001133 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001134 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001135 vereq(x.foo, 1)
1136 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001137
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138def slots():
1139 if verbose: print "Testing __slots__..."
1140 class C0(object):
1141 __slots__ = []
1142 x = C0()
1143 verify(not hasattr(x, "__dict__"))
1144 verify(not hasattr(x, "foo"))
1145
1146 class C1(object):
1147 __slots__ = ['a']
1148 x = C1()
1149 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001150 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001152 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001153 x.a = None
1154 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001156 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157
1158 class C3(object):
1159 __slots__ = ['a', 'b', 'c']
1160 x = C3()
1161 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001162 verify(not hasattr(x, 'a'))
1163 verify(not hasattr(x, 'b'))
1164 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 x.a = 1
1166 x.b = 2
1167 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001168 vereq(x.a, 1)
1169 vereq(x.b, 2)
1170 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001172 class C4(object):
1173 """Validate name mangling"""
1174 __slots__ = ['__a']
1175 def __init__(self, value):
1176 self.__a = value
1177 def get(self):
1178 return self.__a
1179 x = C4(5)
1180 verify(not hasattr(x, '__dict__'))
1181 verify(not hasattr(x, '__a'))
1182 vereq(x.get(), 5)
1183 try:
1184 x.__a = 6
1185 except AttributeError:
1186 pass
1187 else:
1188 raise TestFailed, "Double underscored names not mangled"
1189
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001190 # Make sure slot names are proper identifiers
1191 try:
1192 class C(object):
1193 __slots__ = [None]
1194 except TypeError:
1195 pass
1196 else:
1197 raise TestFailed, "[None] slots not caught"
1198 try:
1199 class C(object):
1200 __slots__ = ["foo bar"]
1201 except TypeError:
1202 pass
1203 else:
1204 raise TestFailed, "['foo bar'] slots not caught"
1205 try:
1206 class C(object):
1207 __slots__ = ["foo\0bar"]
1208 except TypeError:
1209 pass
1210 else:
1211 raise TestFailed, "['foo\\0bar'] slots not caught"
1212 try:
1213 class C(object):
1214 __slots__ = ["1"]
1215 except TypeError:
1216 pass
1217 else:
1218 raise TestFailed, "['1'] slots not caught"
1219 try:
1220 class C(object):
1221 __slots__ = [""]
1222 except TypeError:
1223 pass
1224 else:
1225 raise TestFailed, "[''] slots not caught"
1226 class C(object):
1227 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001228 # XXX(nnorwitz): was there supposed to be something tested
1229 # from the class above?
1230
1231 # Test a single string is not expanded as a sequence.
1232 class C(object):
1233 __slots__ = "abc"
1234 c = C()
1235 c.abc = 5
1236 vereq(c.abc, 5)
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001237
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001238 # Test unicode slot names
1239 try:
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001240 unicode
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001241 except NameError:
1242 pass
1243 else:
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001244 # Test a single unicode string is not expanded as a sequence.
1245 class C(object):
1246 __slots__ = unicode("abc")
1247 c = C()
1248 c.abc = 5
1249 vereq(c.abc, 5)
1250
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001251 # _unicode_to_string used to modify slots in certain circumstances
1252 slots = (unicode("foo"), unicode("bar"))
1253 class C(object):
1254 __slots__ = slots
1255 x = C()
1256 x.foo = 5
1257 vereq(x.foo, 5)
1258 veris(type(slots[0]), unicode)
1259 # this used to leak references
1260 try:
1261 class C(object):
1262 __slots__ = [unichr(128)]
1263 except (TypeError, UnicodeEncodeError):
1264 pass
1265 else:
1266 raise TestFailed, "[unichr(128)] slots not caught"
1267
Guido van Rossum33bab012001-12-05 22:45:48 +00001268 # Test leaks
1269 class Counted(object):
1270 counter = 0 # counts the number of instances alive
1271 def __init__(self):
1272 Counted.counter += 1
1273 def __del__(self):
1274 Counted.counter -= 1
1275 class C(object):
1276 __slots__ = ['a', 'b', 'c']
1277 x = C()
1278 x.a = Counted()
1279 x.b = Counted()
1280 x.c = Counted()
1281 vereq(Counted.counter, 3)
1282 del x
1283 vereq(Counted.counter, 0)
1284 class D(C):
1285 pass
1286 x = D()
1287 x.a = Counted()
1288 x.z = Counted()
1289 vereq(Counted.counter, 2)
1290 del x
1291 vereq(Counted.counter, 0)
1292 class E(D):
1293 __slots__ = ['e']
1294 x = E()
1295 x.a = Counted()
1296 x.z = Counted()
1297 x.e = Counted()
1298 vereq(Counted.counter, 3)
1299 del x
1300 vereq(Counted.counter, 0)
1301
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001302 # Test cyclical leaks [SF bug 519621]
1303 class F(object):
1304 __slots__ = ['a', 'b']
1305 log = []
1306 s = F()
1307 s.a = [Counted(), s]
1308 vereq(Counted.counter, 1)
1309 s = None
1310 import gc
1311 gc.collect()
1312 vereq(Counted.counter, 0)
1313
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001314 # Test lookup leaks [SF bug 572567]
1315 import sys,gc
1316 class G(object):
1317 def __cmp__(self, other):
1318 return 0
1319 g = G()
1320 orig_objects = len(gc.get_objects())
1321 for i in xrange(10):
1322 g==g
1323 new_objects = len(gc.get_objects())
1324 vereq(orig_objects, new_objects)
Neal Norwitz98a379e2003-06-16 22:51:22 +00001325 class H(object):
1326 __slots__ = ['a', 'b']
1327 def __init__(self):
1328 self.a = 1
1329 self.b = 2
1330 def __del__(self):
1331 assert self.a == 1
1332 assert self.b == 2
1333
1334 save_stderr = sys.stderr
1335 sys.stderr = sys.stdout
1336 h = H()
1337 try:
1338 del h
1339 finally:
1340 sys.stderr = save_stderr
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001341
Guido van Rossum8b056da2002-08-13 18:26:26 +00001342def slotspecials():
1343 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1344
1345 class D(object):
1346 __slots__ = ["__dict__"]
1347 a = D()
1348 verify(hasattr(a, "__dict__"))
1349 verify(not hasattr(a, "__weakref__"))
1350 a.foo = 42
1351 vereq(a.__dict__, {"foo": 42})
1352
1353 class W(object):
1354 __slots__ = ["__weakref__"]
1355 a = W()
1356 verify(hasattr(a, "__weakref__"))
1357 verify(not hasattr(a, "__dict__"))
1358 try:
1359 a.foo = 42
1360 except AttributeError:
1361 pass
1362 else:
1363 raise TestFailed, "shouldn't be allowed to set a.foo"
1364
1365 class C1(W, D):
1366 __slots__ = []
1367 a = C1()
1368 verify(hasattr(a, "__dict__"))
1369 verify(hasattr(a, "__weakref__"))
1370 a.foo = 42
1371 vereq(a.__dict__, {"foo": 42})
1372
1373 class C2(D, W):
1374 __slots__ = []
1375 a = C2()
1376 verify(hasattr(a, "__dict__"))
1377 verify(hasattr(a, "__weakref__"))
1378 a.foo = 42
1379 vereq(a.__dict__, {"foo": 42})
1380
Guido van Rossum9a818922002-11-14 19:50:14 +00001381# MRO order disagreement
1382#
1383# class C3(C1, C2):
1384# __slots__ = []
1385#
1386# class C4(C2, C1):
1387# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001388
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001390 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001393 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001395 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001396 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001398 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001400 vereq(E.foo, 1)
1401 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001402 # Test dynamic instances
1403 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001404 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001405 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001406 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001407 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001408 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001409 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001410 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001411 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001412 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001413 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001414 vereq(int(a), 100)
1415 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001416 verify(not hasattr(a, "spam"))
1417 def mygetattr(self, name):
1418 if name == "spam":
1419 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001420 raise AttributeError
1421 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001422 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001423 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001424 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001425 def mysetattr(self, name, value):
1426 if name == "spam":
1427 raise AttributeError
1428 return object.__setattr__(self, name, value)
1429 C.__setattr__ = mysetattr
1430 try:
1431 a.spam = "not spam"
1432 except AttributeError:
1433 pass
1434 else:
1435 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001436 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001437 class D(C):
1438 pass
1439 d = D()
1440 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001441 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442
Guido van Rossum7e35d572001-09-15 03:14:32 +00001443 # Test handling of int*seq and seq*int
1444 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001445 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001446 vereq("a"*I(2), "aa")
1447 vereq(I(2)*"a", "aa")
1448 vereq(2*I(3), 6)
1449 vereq(I(3)*2, 6)
1450 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001451
1452 # Test handling of long*seq and seq*long
1453 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001454 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001455 vereq("a"*L(2L), "aa")
1456 vereq(L(2L)*"a", "aa")
1457 vereq(2*L(3), 6)
1458 vereq(L(3)*2, 6)
1459 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001460
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001461 # Test comparison of classes with dynamic metaclasses
1462 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001463 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001464 class someclass:
1465 __metaclass__ = dynamicmetaclass
1466 verify(someclass != object)
1467
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468def errors():
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001469 """Test that type can't be placed after an instance of type in bases.
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001471 >>> class C(list, dict):
1472 ... pass
1473 Traceback (most recent call last):
1474 TypeError: Error when calling the metaclass bases
1475 multiple bases have instance lay-out conflict
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001477 >>> class C(object, None):
1478 ... pass
1479 Traceback (most recent call last):
1480 TypeError: Error when calling the metaclass bases
1481 bases must be types
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001483 >>> class C(type(len)):
1484 ... pass
1485 Traceback (most recent call last):
1486 TypeError: Error when calling the metaclass bases
1487 type 'builtin_function_or_method' is not an acceptable base type
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001489 >>> class Classic:
1490 ... def __init__(*args): pass
1491 >>> class C(object):
1492 ... __metaclass__ = Classic
Tim Peters6d6c1a32001-08-02 04:15:00 +00001493
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001494 >>> class C(object):
1495 ... __slots__ = 1
1496 Traceback (most recent call last):
1497 TypeError: Error when calling the metaclass bases
1498 'int' object is not iterable
1499
1500 >>> class C(object):
1501 ... __slots__ = [1]
1502 Traceback (most recent call last):
1503 TypeError: Error when calling the metaclass bases
1504 __slots__ items must be strings, not 'int'
1505
1506 >>> class A(object):
1507 ... pass
Tim Petersea5962f2007-03-12 18:07:52 +00001508
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001509 >>> class B(A, type):
1510 ... pass
1511 Traceback (most recent call last):
1512 TypeError: Error when calling the metaclass bases
1513 metaclass conflict: type must occur in bases before other non-classic base classes
1514
1515 Create two different metaclasses in order to setup an error where
1516 there is no inheritance relationship between the metaclass of a class
1517 and the metaclass of its bases.
1518
1519 >>> class M1(type):
1520 ... pass
1521 >>> class M2(type):
1522 ... pass
1523 >>> class A1(object):
1524 ... __metaclass__ = M1
1525 >>> class A2(object):
1526 ... __metaclass__ = M2
1527 >>> class B(A1, A2):
1528 ... pass
1529 Traceback (most recent call last):
1530 TypeError: Error when calling the metaclass bases
1531 metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1532 >>> class B(A1):
1533 ... pass
1534
1535 Also check that assignment to bases is safe.
Tim Petersea5962f2007-03-12 18:07:52 +00001536
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001537 >>> B.__bases__ = A1, A2
1538 Traceback (most recent call last):
1539 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1540 >>> B.__bases__ = A2,
1541 Traceback (most recent call last):
1542 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
1543
1544 >>> class M3(M1):
1545 ... pass
1546 >>> class C(object):
1547 ... __metaclass__ = M3
1548 >>> B.__bases__ = C,
1549 Traceback (most recent call last):
1550 TypeError: assignment to __bases__ may not change metatype
1551 """
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552
1553def classmethods():
1554 if verbose: print "Testing class methods..."
1555 class C(object):
1556 def foo(*a): return a
1557 goo = classmethod(foo)
1558 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001559 vereq(C.goo(1), (C, 1))
1560 vereq(c.goo(1), (C, 1))
1561 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562 class D(C):
1563 pass
1564 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001565 vereq(D.goo(1), (D, 1))
1566 vereq(d.goo(1), (D, 1))
1567 vereq(d.foo(1), (d, 1))
1568 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001569 # Test for a specific crash (SF bug 528132)
1570 def f(cls, arg): return (cls, arg)
1571 ff = classmethod(f)
1572 vereq(ff.__get__(0, int)(42), (int, 42))
1573 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574
Guido van Rossum155db9a2002-04-02 17:53:47 +00001575 # Test super() with classmethods (SF bug 535444)
1576 veris(C.goo.im_self, C)
1577 veris(D.goo.im_self, D)
1578 veris(super(D,D).goo.im_self, D)
1579 veris(super(D,d).goo.im_self, D)
1580 vereq(super(D,D).goo(), (D,))
1581 vereq(super(D,d).goo(), (D,))
1582
Raymond Hettingerbe971532003-06-18 01:13:41 +00001583 # Verify that argument is checked for callability (SF bug 753451)
1584 try:
1585 classmethod(1).__get__(1)
1586 except TypeError:
1587 pass
1588 else:
1589 raise TestFailed, "classmethod should check for callability"
1590
Georg Brandl6a29c322006-02-21 22:17:46 +00001591 # Verify that classmethod() doesn't allow keyword args
1592 try:
1593 classmethod(f, kw=1)
1594 except TypeError:
1595 pass
1596 else:
1597 raise TestFailed, "classmethod shouldn't accept keyword args"
1598
Fred Drakef841aa62002-03-28 15:49:54 +00001599def classmethods_in_c():
1600 if verbose: print "Testing C-based class methods..."
1601 import xxsubtype as spam
1602 a = (1, 2, 3)
1603 d = {'abc': 123}
1604 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001605 veris(x, spam.spamlist)
1606 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001607 vereq(d, d1)
1608 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001609 veris(x, spam.spamlist)
1610 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001611 vereq(d, d1)
1612
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613def staticmethods():
1614 if verbose: print "Testing static methods..."
1615 class C(object):
1616 def foo(*a): return a
1617 goo = staticmethod(foo)
1618 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001619 vereq(C.goo(1), (1,))
1620 vereq(c.goo(1), (1,))
1621 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622 class D(C):
1623 pass
1624 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001625 vereq(D.goo(1), (1,))
1626 vereq(d.goo(1), (1,))
1627 vereq(d.foo(1), (d, 1))
1628 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629
Fred Drakef841aa62002-03-28 15:49:54 +00001630def staticmethods_in_c():
1631 if verbose: print "Testing C-based static methods..."
1632 import xxsubtype as spam
1633 a = (1, 2, 3)
1634 d = {"abc": 123}
1635 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1636 veris(x, None)
1637 vereq(a, a1)
1638 vereq(d, d1)
1639 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1640 veris(x, None)
1641 vereq(a, a1)
1642 vereq(d, d1)
1643
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644def classic():
1645 if verbose: print "Testing classic classes..."
1646 class C:
1647 def foo(*a): return a
1648 goo = classmethod(foo)
1649 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001650 vereq(C.goo(1), (C, 1))
1651 vereq(c.goo(1), (C, 1))
1652 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 class D(C):
1654 pass
1655 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001656 vereq(D.goo(1), (D, 1))
1657 vereq(d.goo(1), (D, 1))
1658 vereq(d.foo(1), (d, 1))
1659 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001660 class E: # *not* subclassing from C
1661 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001662 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001663 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664
1665def compattr():
1666 if verbose: print "Testing computed attributes..."
1667 class C(object):
1668 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001669 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001670 self.__get = get
1671 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001672 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 def __get__(self, obj, type=None):
1674 return self.__get(obj)
1675 def __set__(self, obj, value):
1676 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001677 def __delete__(self, obj):
1678 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 def __init__(self):
1680 self.__x = 0
1681 def __get_x(self):
1682 x = self.__x
1683 self.__x = x+1
1684 return x
1685 def __set_x(self, x):
1686 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001687 def __delete_x(self):
1688 del self.__x
1689 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001691 vereq(a.x, 0)
1692 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001694 vereq(a.x, 10)
1695 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001696 del a.x
1697 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698
1699def newslot():
1700 if verbose: print "Testing __new__ slot override..."
1701 class C(list):
1702 def __new__(cls):
1703 self = list.__new__(cls)
1704 self.foo = 1
1705 return self
1706 def __init__(self):
1707 self.foo = self.foo + 2
1708 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001709 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 verify(a.__class__ is C)
1711 class D(C):
1712 pass
1713 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001714 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 verify(b.__class__ is D)
1716
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717def altmro():
1718 if verbose: print "Testing mro() and overriding it..."
1719 class A(object):
1720 def f(self): return "A"
1721 class B(A):
1722 pass
1723 class C(A):
1724 def f(self): return "C"
1725 class D(B, C):
1726 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001727 vereq(D.mro(), [D, B, C, A, object])
1728 vereq(D.__mro__, (D, B, C, A, object))
1729 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001730
Guido van Rossumd3077402001-08-12 05:24:18 +00001731 class PerverseMetaType(type):
1732 def mro(cls):
1733 L = type.mro(cls)
1734 L.reverse()
1735 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001736 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001738 vereq(X.__mro__, (object, A, C, B, D, X))
1739 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001740
Armin Rigo037d1e02005-12-29 17:07:39 +00001741 try:
1742 class X(object):
1743 class __metaclass__(type):
1744 def mro(self):
1745 return [self, dict, object]
1746 except TypeError:
1747 pass
1748 else:
1749 raise TestFailed, "devious mro() return not caught"
1750
1751 try:
1752 class X(object):
1753 class __metaclass__(type):
1754 def mro(self):
1755 return [1]
1756 except TypeError:
1757 pass
1758 else:
1759 raise TestFailed, "non-class mro() return not caught"
1760
1761 try:
1762 class X(object):
1763 class __metaclass__(type):
1764 def mro(self):
1765 return 1
1766 except TypeError:
1767 pass
1768 else:
1769 raise TestFailed, "non-sequence mro() return not caught"
Tim Peters1b27f862005-12-30 18:42:42 +00001770
Armin Rigo037d1e02005-12-29 17:07:39 +00001771
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001773 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774
1775 class B(object):
1776 "Intermediate class because object doesn't have a __setattr__"
1777
1778 class C(B):
1779
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001780 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 if name == "foo":
1782 return ("getattr", name)
1783 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001784 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785 def __setattr__(self, name, value):
1786 if name == "foo":
1787 self.setattr = (name, value)
1788 else:
1789 return B.__setattr__(self, name, value)
1790 def __delattr__(self, name):
1791 if name == "foo":
1792 self.delattr = name
1793 else:
1794 return B.__delattr__(self, name)
1795
1796 def __getitem__(self, key):
1797 return ("getitem", key)
1798 def __setitem__(self, key, value):
1799 self.setitem = (key, value)
1800 def __delitem__(self, key):
1801 self.delitem = key
1802
1803 def __getslice__(self, i, j):
1804 return ("getslice", i, j)
1805 def __setslice__(self, i, j, value):
1806 self.setslice = (i, j, value)
1807 def __delslice__(self, i, j):
1808 self.delslice = (i, j)
1809
1810 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001811 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001813 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001815 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816
Guido van Rossum45704552001-10-08 16:35:45 +00001817 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001818 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001819 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001821 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822
Guido van Rossum45704552001-10-08 16:35:45 +00001823 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001825 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001827 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001829def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001830 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001831 class C(object):
1832 def __init__(self, x):
1833 self.x = x
1834 def foo(self):
1835 return self.x
1836 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001837 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001838 class D(C):
1839 boo = C.foo
1840 goo = c1.foo
1841 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001842 vereq(d2.foo(), 2)
1843 vereq(d2.boo(), 2)
1844 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001845 class E(object):
1846 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001847 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001848 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001849
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001850def specials():
1851 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001852 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001853 # Test the default behavior for static classes
1854 class C(object):
1855 def __getitem__(self, i):
1856 if 0 <= i < 10: return i
1857 raise IndexError
1858 c1 = C()
1859 c2 = C()
1860 verify(not not c1)
Tim Peters85b362f2006-04-11 01:21:00 +00001861 verify(id(c1) != id(c2))
1862 hash(c1)
1863 hash(c2)
Guido van Rossum45704552001-10-08 16:35:45 +00001864 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1865 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001866 verify(c1 != c2)
1867 verify(not c1 != c1)
1868 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001869 # Note that the module name appears in str/repr, and that varies
1870 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001871 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001872 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001873 verify(-1 not in c1)
1874 for i in range(10):
1875 verify(i in c1)
1876 verify(10 not in c1)
1877 # Test the default behavior for dynamic classes
1878 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001879 def __getitem__(self, i):
1880 if 0 <= i < 10: return i
1881 raise IndexError
1882 d1 = D()
1883 d2 = D()
1884 verify(not not d1)
Tim Peters85b362f2006-04-11 01:21:00 +00001885 verify(id(d1) != id(d2))
1886 hash(d1)
1887 hash(d2)
Guido van Rossum45704552001-10-08 16:35:45 +00001888 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1889 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001890 verify(d1 != d2)
1891 verify(not d1 != d1)
1892 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001893 # Note that the module name appears in str/repr, and that varies
1894 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001895 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001896 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001897 verify(-1 not in d1)
1898 for i in range(10):
1899 verify(i in d1)
1900 verify(10 not in d1)
1901 # Test overridden behavior for static classes
1902 class Proxy(object):
1903 def __init__(self, x):
1904 self.x = x
1905 def __nonzero__(self):
1906 return not not self.x
1907 def __hash__(self):
1908 return hash(self.x)
1909 def __eq__(self, other):
1910 return self.x == other
1911 def __ne__(self, other):
1912 return self.x != other
1913 def __cmp__(self, other):
1914 return cmp(self.x, other.x)
1915 def __str__(self):
1916 return "Proxy:%s" % self.x
1917 def __repr__(self):
1918 return "Proxy(%r)" % self.x
1919 def __contains__(self, value):
1920 return value in self.x
1921 p0 = Proxy(0)
1922 p1 = Proxy(1)
1923 p_1 = Proxy(-1)
1924 verify(not p0)
1925 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001926 vereq(hash(p0), hash(0))
1927 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001928 verify(p0 != p1)
1929 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001930 vereq(not p0, p1)
1931 vereq(cmp(p0, p1), -1)
1932 vereq(cmp(p0, p0), 0)
1933 vereq(cmp(p0, p_1), 1)
1934 vereq(str(p0), "Proxy:0")
1935 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001936 p10 = Proxy(range(10))
1937 verify(-1 not in p10)
1938 for i in range(10):
1939 verify(i in p10)
1940 verify(10 not in p10)
1941 # Test overridden behavior for dynamic classes
1942 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001943 def __init__(self, x):
1944 self.x = x
1945 def __nonzero__(self):
1946 return not not self.x
1947 def __hash__(self):
1948 return hash(self.x)
1949 def __eq__(self, other):
1950 return self.x == other
1951 def __ne__(self, other):
1952 return self.x != other
1953 def __cmp__(self, other):
1954 return cmp(self.x, other.x)
1955 def __str__(self):
1956 return "DProxy:%s" % self.x
1957 def __repr__(self):
1958 return "DProxy(%r)" % self.x
1959 def __contains__(self, value):
1960 return value in self.x
1961 p0 = DProxy(0)
1962 p1 = DProxy(1)
1963 p_1 = DProxy(-1)
1964 verify(not p0)
1965 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001966 vereq(hash(p0), hash(0))
1967 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001968 verify(p0 != p1)
1969 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001970 vereq(not p0, p1)
1971 vereq(cmp(p0, p1), -1)
1972 vereq(cmp(p0, p0), 0)
1973 vereq(cmp(p0, p_1), 1)
1974 vereq(str(p0), "DProxy:0")
1975 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001976 p10 = DProxy(range(10))
1977 verify(-1 not in p10)
1978 for i in range(10):
1979 verify(i in p10)
1980 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001981 # Safety test for __cmp__
1982 def unsafecmp(a, b):
1983 try:
1984 a.__class__.__cmp__(a, b)
1985 except TypeError:
1986 pass
1987 else:
1988 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1989 a.__class__, a, b)
1990 unsafecmp(u"123", "123")
1991 unsafecmp("123", u"123")
1992 unsafecmp(1, 1.0)
1993 unsafecmp(1.0, 1)
1994 unsafecmp(1, 1L)
1995 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001996
Neal Norwitz1a997502003-01-13 20:13:12 +00001997 class Letter(str):
1998 def __new__(cls, letter):
1999 if letter == 'EPS':
2000 return str.__new__(cls)
2001 return str.__new__(cls, letter)
2002 def __str__(self):
2003 if not self:
2004 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00002005 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00002006
2007 # sys.stdout needs to be the original to trigger the recursion bug
2008 import sys
2009 test_stdout = sys.stdout
2010 sys.stdout = get_original_stdout()
2011 try:
2012 # nothing should actually be printed, this should raise an exception
2013 print Letter('w')
2014 except RuntimeError:
2015 pass
2016 else:
2017 raise TestFailed, "expected a RuntimeError for print recursion"
2018 sys.stdout = test_stdout
2019
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002020def weakrefs():
2021 if verbose: print "Testing weak references..."
2022 import weakref
2023 class C(object):
2024 pass
2025 c = C()
2026 r = weakref.ref(c)
2027 verify(r() is c)
2028 del c
2029 verify(r() is None)
2030 del r
2031 class NoWeak(object):
2032 __slots__ = ['foo']
2033 no = NoWeak()
2034 try:
2035 weakref.ref(no)
2036 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00002037 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00002038 else:
2039 verify(0, "weakref.ref(no) should be illegal")
2040 class Weak(object):
2041 __slots__ = ['foo', '__weakref__']
2042 yes = Weak()
2043 r = weakref.ref(yes)
2044 verify(r() is yes)
2045 del yes
2046 verify(r() is None)
2047 del r
2048
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00002049def properties():
2050 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002051 class C(object):
2052 def getx(self):
2053 return self.__x
2054 def setx(self, value):
2055 self.__x = value
2056 def delx(self):
2057 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00002058 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002059 a = C()
2060 verify(not hasattr(a, "x"))
2061 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00002062 vereq(a._C__x, 42)
2063 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002064 del a.x
2065 verify(not hasattr(a, "x"))
2066 verify(not hasattr(a, "_C__x"))
2067 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00002068 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002069 C.x.__delete__(a)
2070 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00002071
Tim Peters66c1a522001-09-24 21:17:50 +00002072 raw = C.__dict__['x']
2073 verify(isinstance(raw, property))
2074
2075 attrs = dir(raw)
2076 verify("__doc__" in attrs)
2077 verify("fget" in attrs)
2078 verify("fset" in attrs)
2079 verify("fdel" in attrs)
2080
Guido van Rossum45704552001-10-08 16:35:45 +00002081 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00002082 verify(raw.fget is C.__dict__['getx'])
2083 verify(raw.fset is C.__dict__['setx'])
2084 verify(raw.fdel is C.__dict__['delx'])
2085
2086 for attr in "__doc__", "fget", "fset", "fdel":
2087 try:
2088 setattr(raw, attr, 42)
2089 except TypeError, msg:
2090 if str(msg).find('readonly') < 0:
2091 raise TestFailed("when setting readonly attr %r on a "
2092 "property, got unexpected TypeError "
2093 "msg %r" % (attr, str(msg)))
2094 else:
2095 raise TestFailed("expected TypeError from trying to set "
2096 "readonly %r attr on a property" % attr)
2097
Neal Norwitz673cd822002-10-18 16:33:13 +00002098 class D(object):
2099 __getitem__ = property(lambda s: 1/0)
2100
2101 d = D()
2102 try:
2103 for i in d:
2104 str(i)
2105 except ZeroDivisionError:
2106 pass
2107 else:
2108 raise TestFailed, "expected ZeroDivisionError from bad property"
2109
Georg Brandl533ff6f2006-03-08 18:09:27 +00002110 class E(object):
2111 def getter(self):
2112 "getter method"
2113 return 0
2114 def setter(self, value):
2115 "setter method"
2116 pass
2117 prop = property(getter)
2118 vereq(prop.__doc__, "getter method")
2119 prop2 = property(fset=setter)
2120 vereq(prop2.__doc__, None)
2121
Georg Brandle9462c72006-08-04 18:03:37 +00002122 # this segfaulted in 2.5b2
2123 try:
2124 import _testcapi
2125 except ImportError:
2126 pass
2127 else:
2128 class X(object):
2129 p = property(_testcapi.test_with_docstring)
2130
2131
Guido van Rossumc4a18802001-08-24 16:55:27 +00002132def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00002133 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00002134
2135 class A(object):
2136 def meth(self, a):
2137 return "A(%r)" % a
2138
Guido van Rossum45704552001-10-08 16:35:45 +00002139 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002140
2141 class B(A):
2142 def __init__(self):
2143 self.__super = super(B, self)
2144 def meth(self, a):
2145 return "B(%r)" % a + self.__super.meth(a)
2146
Guido van Rossum45704552001-10-08 16:35:45 +00002147 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002148
2149 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00002150 def meth(self, a):
2151 return "C(%r)" % a + self.__super.meth(a)
2152 C._C__super = super(C)
2153
Guido van Rossum45704552001-10-08 16:35:45 +00002154 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00002155
2156 class D(C, B):
2157 def meth(self, a):
2158 return "D(%r)" % a + super(D, self).meth(a)
2159
Guido van Rossum5b443c62001-12-03 15:38:28 +00002160 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2161
2162 # Test for subclassing super
2163
2164 class mysuper(super):
2165 def __init__(self, *args):
2166 return super(mysuper, self).__init__(*args)
2167
2168 class E(D):
2169 def meth(self, a):
2170 return "E(%r)" % a + mysuper(E, self).meth(a)
2171
2172 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2173
2174 class F(E):
2175 def meth(self, a):
Guido van Rossuma4541a32003-04-16 20:02:22 +00002176 s = self.__super # == mysuper(F, self)
Guido van Rossum5b443c62001-12-03 15:38:28 +00002177 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2178 F._F__super = mysuper(F)
2179
2180 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2181
2182 # Make sure certain errors are raised
2183
2184 try:
2185 super(D, 42)
2186 except TypeError:
2187 pass
2188 else:
2189 raise TestFailed, "shouldn't allow super(D, 42)"
2190
2191 try:
2192 super(D, C())
2193 except TypeError:
2194 pass
2195 else:
2196 raise TestFailed, "shouldn't allow super(D, C())"
2197
2198 try:
2199 super(D).__get__(12)
2200 except TypeError:
2201 pass
2202 else:
2203 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2204
2205 try:
2206 super(D).__get__(C())
2207 except TypeError:
2208 pass
2209 else:
2210 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002211
Guido van Rossuma4541a32003-04-16 20:02:22 +00002212 # Make sure data descriptors can be overridden and accessed via super
2213 # (new feature in Python 2.3)
2214
2215 class DDbase(object):
2216 def getx(self): return 42
2217 x = property(getx)
2218
2219 class DDsub(DDbase):
2220 def getx(self): return "hello"
2221 x = property(getx)
2222
2223 dd = DDsub()
2224 vereq(dd.x, "hello")
2225 vereq(super(DDsub, dd).x, 42)
2226
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002227 # Ensure that super() lookup of descriptor from classmethod
2228 # works (SF ID# 743627)
2229
2230 class Base(object):
2231 aProp = property(lambda self: "foo")
2232
2233 class Sub(Base):
Guido van Rossum5a8a0372005-01-16 00:25:31 +00002234 @classmethod
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002235 def test(klass):
2236 return super(Sub,klass).aProp
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002237
2238 veris(Sub.test(), Base.aProp)
2239
Georg Brandl5d59c092006-09-30 08:43:30 +00002240 # Verify that super() doesn't allow keyword args
2241 try:
2242 super(Base, kw=1)
2243 except TypeError:
2244 pass
2245 else:
2246 raise TestFailed, "super shouldn't accept keyword args"
Phillip J. Eby91a968a2004-03-25 02:19:34 +00002247
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002248def inherits():
2249 if verbose: print "Testing inheritance from basic types..."
2250
2251 class hexint(int):
2252 def __repr__(self):
2253 return hex(self)
2254 def __add__(self, other):
2255 return hexint(int.__add__(self, other))
2256 # (Note that overriding __radd__ doesn't work,
2257 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002258 vereq(repr(hexint(7) + 9), "0x10")
2259 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002260 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002261 vereq(a, 12345)
2262 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002263 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002264 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002265 verify((+a).__class__ is int)
2266 verify((a >> 0).__class__ is int)
2267 verify((a << 0).__class__ is int)
2268 verify((hexint(0) << 12).__class__ is int)
2269 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002270
2271 class octlong(long):
2272 __slots__ = []
2273 def __str__(self):
2274 s = oct(self)
2275 if s[-1] == 'L':
2276 s = s[:-1]
2277 return s
2278 def __add__(self, other):
2279 return self.__class__(super(octlong, self).__add__(other))
2280 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002281 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002282 # (Note that overriding __radd__ here only seems to work
2283 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002284 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002285 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002286 vereq(a, 12345L)
2287 vereq(long(a), 12345L)
2288 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002289 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002290 verify((+a).__class__ is long)
2291 verify((-a).__class__ is long)
2292 verify((-octlong(0)).__class__ is long)
2293 verify((a >> 0).__class__ is long)
2294 verify((a << 0).__class__ is long)
2295 verify((a - 0).__class__ is long)
2296 verify((a * 1).__class__ is long)
2297 verify((a ** 1).__class__ is long)
2298 verify((a // 1).__class__ is long)
2299 verify((1 * a).__class__ is long)
2300 verify((a | 0).__class__ is long)
2301 verify((a ^ 0).__class__ is long)
2302 verify((a & -1L).__class__ is long)
2303 verify((octlong(0) << 12).__class__ is long)
2304 verify((octlong(0) >> 12).__class__ is long)
2305 verify(abs(octlong(0)).__class__ is long)
2306
2307 # Because octlong overrides __add__, we can't check the absence of +0
2308 # optimizations using octlong.
2309 class longclone(long):
2310 pass
2311 a = longclone(1)
2312 verify((a + 0).__class__ is long)
2313 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002314
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002315 # Check that negative clones don't segfault
2316 a = longclone(-1)
2317 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002318 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002319
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002320 class precfloat(float):
2321 __slots__ = ['prec']
2322 def __init__(self, value=0.0, prec=12):
2323 self.prec = int(prec)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002324 def __repr__(self):
2325 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002326 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002327 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002328 vereq(a, 12345.0)
2329 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002330 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002331 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002332 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002333
Tim Peters2400fa42001-09-12 19:12:49 +00002334 class madcomplex(complex):
2335 def __repr__(self):
2336 return "%.17gj%+.17g" % (self.imag, self.real)
2337 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002338 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002339 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002340 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002341 vereq(a, base)
2342 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002343 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002344 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002345 vereq(repr(a), "4j-3")
2346 vereq(a, base)
2347 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002348 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002349 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002350 veris((+a).__class__, complex)
2351 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002352 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002353 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002354 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002355 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002356 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002357 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002358 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002359
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002360 class madtuple(tuple):
2361 _rev = None
2362 def rev(self):
2363 if self._rev is not None:
2364 return self._rev
2365 L = list(self)
2366 L.reverse()
2367 self._rev = self.__class__(L)
2368 return self._rev
2369 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002370 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2371 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2372 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002373 for i in range(512):
2374 t = madtuple(range(i))
2375 u = t.rev()
2376 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002377 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002378 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002379 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002380 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002381 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002382 verify(a[:].__class__ is tuple)
2383 verify((a * 1).__class__ is tuple)
2384 verify((a * 0).__class__ is tuple)
2385 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002386 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002387 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002388 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002389 verify((a + a).__class__ is tuple)
2390 verify((a * 0).__class__ is tuple)
2391 verify((a * 1).__class__ is tuple)
2392 verify((a * 2).__class__ is tuple)
2393 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002394
2395 class madstring(str):
2396 _rev = None
2397 def rev(self):
2398 if self._rev is not None:
2399 return self._rev
2400 L = list(self)
2401 L.reverse()
2402 self._rev = self.__class__("".join(L))
2403 return self._rev
2404 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002405 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2406 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2407 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002408 for i in range(256):
2409 s = madstring("".join(map(chr, range(i))))
2410 t = s.rev()
2411 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002412 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002413 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002414 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002415 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002416
Tim Peters8fa5dd02001-09-12 02:18:30 +00002417 base = "\x00" * 5
2418 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002419 vereq(s, base)
2420 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002421 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002422 vereq(hash(s), hash(base))
2423 vereq({s: 1}[base], 1)
2424 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002425 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002426 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002427 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002428 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002429 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002430 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002431 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002432 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002433 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002434 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002435 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002436 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002437 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002438 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002439 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002440 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002441 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002442 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002443 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002444 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002445 identitytab = ''.join([chr(i) for i in range(256)])
2446 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002447 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002448 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002449 vereq(s.translate(identitytab, "x"), base)
2450 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002451 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002452 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002453 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002454 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002455 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002456 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002457 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002458 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002459 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002460 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002461
Guido van Rossum91ee7982001-08-30 20:52:40 +00002462 class madunicode(unicode):
2463 _rev = None
2464 def rev(self):
2465 if self._rev is not None:
2466 return self._rev
2467 L = list(self)
2468 L.reverse()
2469 self._rev = self.__class__(u"".join(L))
2470 return self._rev
2471 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002472 vereq(u, u"ABCDEF")
2473 vereq(u.rev(), madunicode(u"FEDCBA"))
2474 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002475 base = u"12345"
2476 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002477 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002478 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002479 vereq(hash(u), hash(base))
2480 vereq({u: 1}[base], 1)
2481 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002482 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002483 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002484 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002485 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002486 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002487 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002488 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002489 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002490 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002491 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002492 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002493 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002494 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002495 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002496 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002497 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002498 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002499 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002500 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002501 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002502 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002503 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002504 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002505 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002506 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002507 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002508 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002509 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002510 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002511 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002512 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002513 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002514 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002515 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002516 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002517 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002518 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002519 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002520
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002521 class sublist(list):
2522 pass
2523 a = sublist(range(5))
2524 vereq(a, range(5))
2525 a.append("hello")
2526 vereq(a, range(5) + ["hello"])
2527 a[5] = 5
2528 vereq(a, range(6))
2529 a.extend(range(6, 20))
2530 vereq(a, range(20))
2531 a[-5:] = []
2532 vereq(a, range(15))
2533 del a[10:15]
2534 vereq(len(a), 10)
2535 vereq(a, range(10))
2536 vereq(list(a), range(10))
2537 vereq(a[0], 0)
2538 vereq(a[9], 9)
2539 vereq(a[-10], 0)
2540 vereq(a[-1], 9)
2541 vereq(a[:5], range(5))
2542
Tim Peters59c9a642001-09-13 05:38:56 +00002543 class CountedInput(file):
2544 """Counts lines read by self.readline().
2545
2546 self.lineno is the 0-based ordinal of the last line read, up to
2547 a maximum of one greater than the number of lines in the file.
2548
2549 self.ateof is true if and only if the final "" line has been read,
2550 at which point self.lineno stops incrementing, and further calls
2551 to readline() continue to return "".
2552 """
2553
2554 lineno = 0
2555 ateof = 0
2556 def readline(self):
2557 if self.ateof:
2558 return ""
2559 s = file.readline(self)
2560 # Next line works too.
2561 # s = super(CountedInput, self).readline()
2562 self.lineno += 1
2563 if s == "":
2564 self.ateof = 1
2565 return s
2566
Tim Peters561f8992001-09-13 19:36:36 +00002567 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002568 lines = ['a\n', 'b\n', 'c\n']
2569 try:
2570 f.writelines(lines)
2571 f.close()
2572 f = CountedInput(TESTFN)
2573 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2574 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002575 vereq(expected, got)
2576 vereq(f.lineno, i)
2577 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002578 f.close()
2579 finally:
2580 try:
2581 f.close()
2582 except:
2583 pass
2584 try:
2585 import os
2586 os.unlink(TESTFN)
2587 except:
2588 pass
2589
Tim Peters808b94e2001-09-13 19:33:07 +00002590def keywords():
2591 if verbose:
2592 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002593 vereq(int(x=1), 1)
2594 vereq(float(x=2), 2.0)
2595 vereq(long(x=3), 3L)
2596 vereq(complex(imag=42, real=666), complex(666, 42))
2597 vereq(str(object=500), '500')
2598 vereq(unicode(string='abc', errors='strict'), u'abc')
2599 vereq(tuple(sequence=range(3)), (0, 1, 2))
2600 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002601 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002602
2603 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002604 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002605 try:
2606 constructor(bogus_keyword_arg=1)
2607 except TypeError:
2608 pass
2609 else:
2610 raise TestFailed("expected TypeError from bogus keyword "
2611 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002612
Tim Peters8fa45672001-09-13 21:01:29 +00002613def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002614 # XXX This test is disabled because rexec is not deemed safe
2615 return
Tim Peters8fa45672001-09-13 21:01:29 +00002616 import rexec
2617 if verbose:
2618 print "Testing interaction with restricted execution ..."
2619
2620 sandbox = rexec.RExec()
2621
2622 code1 = """f = open(%r, 'w')""" % TESTFN
2623 code2 = """f = file(%r, 'w')""" % TESTFN
2624 code3 = """\
2625f = open(%r)
2626t = type(f) # a sneaky way to get the file() constructor
2627f.close()
2628f = t(%r, 'w') # rexec can't catch this by itself
2629""" % (TESTFN, TESTFN)
2630
2631 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2632 f.close()
2633
2634 try:
2635 for code in code1, code2, code3:
2636 try:
2637 sandbox.r_exec(code)
2638 except IOError, msg:
2639 if str(msg).find("restricted") >= 0:
2640 outcome = "OK"
2641 else:
2642 outcome = "got an exception, but not an expected one"
2643 else:
2644 outcome = "expected a restricted-execution exception"
2645
2646 if outcome != "OK":
2647 raise TestFailed("%s, in %r" % (outcome, code))
2648
2649 finally:
2650 try:
2651 import os
2652 os.unlink(TESTFN)
2653 except:
2654 pass
2655
Tim Peters0ab085c2001-09-14 00:25:33 +00002656def str_subclass_as_dict_key():
2657 if verbose:
2658 print "Testing a str subclass used as dict key .."
2659
2660 class cistr(str):
2661 """Sublcass of str that computes __eq__ case-insensitively.
2662
2663 Also computes a hash code of the string in canonical form.
2664 """
2665
2666 def __init__(self, value):
2667 self.canonical = value.lower()
2668 self.hashcode = hash(self.canonical)
2669
2670 def __eq__(self, other):
2671 if not isinstance(other, cistr):
2672 other = cistr(other)
2673 return self.canonical == other.canonical
2674
2675 def __hash__(self):
2676 return self.hashcode
2677
Guido van Rossum45704552001-10-08 16:35:45 +00002678 vereq(cistr('ABC'), 'abc')
2679 vereq('aBc', cistr('ABC'))
2680 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002681
2682 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002683 vereq(d[cistr('one')], 1)
2684 vereq(d[cistr('tWo')], 2)
2685 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002686 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002687 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002688
Guido van Rossumab3b0342001-09-18 20:38:53 +00002689def classic_comparisons():
2690 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002691 class classic:
2692 pass
2693 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002694 if verbose: print " (base = %s)" % base
2695 class C(base):
2696 def __init__(self, value):
2697 self.value = int(value)
2698 def __cmp__(self, other):
2699 if isinstance(other, C):
2700 return cmp(self.value, other.value)
2701 if isinstance(other, int) or isinstance(other, long):
2702 return cmp(self.value, other)
2703 return NotImplemented
2704 c1 = C(1)
2705 c2 = C(2)
2706 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002707 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002708 c = {1: c1, 2: c2, 3: c3}
2709 for x in 1, 2, 3:
2710 for y in 1, 2, 3:
2711 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2712 for op in "<", "<=", "==", "!=", ">", ">=":
2713 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2714 "x=%d, y=%d" % (x, y))
2715 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2716 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2717
Guido van Rossum0639f592001-09-18 21:06:04 +00002718def rich_comparisons():
2719 if verbose:
2720 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002721 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002722 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002723 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002724 vereq(z, 1+0j)
2725 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002726 class ZZ(complex):
2727 def __eq__(self, other):
2728 try:
2729 return abs(self - other) <= 1e-6
2730 except:
2731 return NotImplemented
2732 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002733 vereq(zz, 1+0j)
2734 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002735
Guido van Rossum0639f592001-09-18 21:06:04 +00002736 class classic:
2737 pass
2738 for base in (classic, int, object, list):
2739 if verbose: print " (base = %s)" % base
2740 class C(base):
2741 def __init__(self, value):
2742 self.value = int(value)
2743 def __cmp__(self, other):
2744 raise TestFailed, "shouldn't call __cmp__"
2745 def __eq__(self, other):
2746 if isinstance(other, C):
2747 return self.value == other.value
2748 if isinstance(other, int) or isinstance(other, long):
2749 return self.value == other
2750 return NotImplemented
2751 def __ne__(self, other):
2752 if isinstance(other, C):
2753 return self.value != other.value
2754 if isinstance(other, int) or isinstance(other, long):
2755 return self.value != other
2756 return NotImplemented
2757 def __lt__(self, other):
2758 if isinstance(other, C):
2759 return self.value < other.value
2760 if isinstance(other, int) or isinstance(other, long):
2761 return self.value < other
2762 return NotImplemented
2763 def __le__(self, other):
2764 if isinstance(other, C):
2765 return self.value <= other.value
2766 if isinstance(other, int) or isinstance(other, long):
2767 return self.value <= other
2768 return NotImplemented
2769 def __gt__(self, other):
2770 if isinstance(other, C):
2771 return self.value > other.value
2772 if isinstance(other, int) or isinstance(other, long):
2773 return self.value > other
2774 return NotImplemented
2775 def __ge__(self, other):
2776 if isinstance(other, C):
2777 return self.value >= other.value
2778 if isinstance(other, int) or isinstance(other, long):
2779 return self.value >= other
2780 return NotImplemented
2781 c1 = C(1)
2782 c2 = C(2)
2783 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002784 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002785 c = {1: c1, 2: c2, 3: c3}
2786 for x in 1, 2, 3:
2787 for y in 1, 2, 3:
2788 for op in "<", "<=", "==", "!=", ">", ">=":
2789 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2790 "x=%d, y=%d" % (x, y))
2791 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2792 "x=%d, y=%d" % (x, y))
2793 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2794 "x=%d, y=%d" % (x, y))
2795
Guido van Rossum1952e382001-09-19 01:25:16 +00002796def coercions():
2797 if verbose: print "Testing coercions..."
2798 class I(int): pass
2799 coerce(I(0), 0)
2800 coerce(0, I(0))
2801 class L(long): pass
2802 coerce(L(0), 0)
2803 coerce(L(0), 0L)
2804 coerce(0, L(0))
2805 coerce(0L, L(0))
2806 class F(float): pass
2807 coerce(F(0), 0)
2808 coerce(F(0), 0L)
2809 coerce(F(0), 0.)
2810 coerce(0, F(0))
2811 coerce(0L, F(0))
2812 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002813 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002814 coerce(C(0), 0)
2815 coerce(C(0), 0L)
2816 coerce(C(0), 0.)
2817 coerce(C(0), 0j)
2818 coerce(0, C(0))
2819 coerce(0L, C(0))
2820 coerce(0., C(0))
2821 coerce(0j, C(0))
2822
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002823def descrdoc():
2824 if verbose: print "Testing descriptor doc strings..."
2825 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002826 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002827 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002828 check(file.name, "file name") # member descriptor
2829
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002830def setclass():
2831 if verbose: print "Testing __class__ assignment..."
2832 class C(object): pass
2833 class D(object): pass
2834 class E(object): pass
2835 class F(D, E): pass
2836 for cls in C, D, E, F:
2837 for cls2 in C, D, E, F:
2838 x = cls()
2839 x.__class__ = cls2
2840 verify(x.__class__ is cls2)
2841 x.__class__ = cls
2842 verify(x.__class__ is cls)
2843 def cant(x, C):
2844 try:
2845 x.__class__ = C
2846 except TypeError:
2847 pass
2848 else:
2849 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002850 try:
2851 delattr(x, "__class__")
2852 except TypeError:
2853 pass
2854 else:
2855 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002856 cant(C(), list)
2857 cant(list(), C)
2858 cant(C(), 1)
2859 cant(C(), object)
2860 cant(object(), list)
2861 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002862 class Int(int): __slots__ = []
2863 cant(2, Int)
2864 cant(Int(), int)
2865 cant(True, int)
2866 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002867 o = object()
2868 cant(o, type(1))
2869 cant(o, type(None))
2870 del o
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002871 class G(object):
2872 __slots__ = ["a", "b"]
2873 class H(object):
2874 __slots__ = ["b", "a"]
2875 try:
2876 unicode
2877 except NameError:
2878 class I(object):
2879 __slots__ = ["a", "b"]
2880 else:
2881 class I(object):
2882 __slots__ = [unicode("a"), unicode("b")]
2883 class J(object):
2884 __slots__ = ["c", "b"]
2885 class K(object):
2886 __slots__ = ["a", "b", "d"]
2887 class L(H):
2888 __slots__ = ["e"]
2889 class M(I):
2890 __slots__ = ["e"]
2891 class N(J):
2892 __slots__ = ["__weakref__"]
2893 class P(J):
2894 __slots__ = ["__dict__"]
2895 class Q(J):
2896 pass
2897 class R(J):
2898 __slots__ = ["__dict__", "__weakref__"]
2899
2900 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2901 x = cls()
2902 x.a = 1
2903 x.__class__ = cls2
2904 verify(x.__class__ is cls2,
2905 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2906 vereq(x.a, 1)
2907 x.__class__ = cls
2908 verify(x.__class__ is cls,
2909 "assigning %r as __class__ for %r silently failed" % (cls, x))
2910 vereq(x.a, 1)
2911 for cls in G, J, K, L, M, N, P, R, list, Int:
2912 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2913 if cls is cls2:
2914 continue
2915 cant(cls(), cls2)
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002916
Guido van Rossum6661be32001-10-26 04:26:12 +00002917def setdict():
2918 if verbose: print "Testing __dict__ assignment..."
2919 class C(object): pass
2920 a = C()
2921 a.__dict__ = {'b': 1}
2922 vereq(a.b, 1)
2923 def cant(x, dict):
2924 try:
2925 x.__dict__ = dict
Barry Warsawb180c062005-04-20 19:41:36 +00002926 except (AttributeError, TypeError):
Guido van Rossum6661be32001-10-26 04:26:12 +00002927 pass
2928 else:
2929 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2930 cant(a, None)
2931 cant(a, [])
2932 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002933 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002934 # Classes don't allow __dict__ assignment
2935 cant(C, {})
2936
Guido van Rossum3926a632001-09-25 16:25:58 +00002937def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002938 if verbose:
2939 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002940 import pickle, cPickle
2941
2942 def sorteditems(d):
2943 L = d.items()
2944 L.sort()
2945 return L
2946
2947 global C
2948 class C(object):
2949 def __init__(self, a, b):
2950 super(C, self).__init__()
2951 self.a = a
2952 self.b = b
2953 def __repr__(self):
2954 return "C(%r, %r)" % (self.a, self.b)
2955
2956 global C1
2957 class C1(list):
2958 def __new__(cls, a, b):
2959 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002960 def __getnewargs__(self):
2961 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002962 def __init__(self, a, b):
2963 self.a = a
2964 self.b = b
2965 def __repr__(self):
2966 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2967
2968 global C2
2969 class C2(int):
2970 def __new__(cls, a, b, val=0):
2971 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002972 def __getnewargs__(self):
2973 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002974 def __init__(self, a, b, val=0):
2975 self.a = a
2976 self.b = b
2977 def __repr__(self):
2978 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2979
Guido van Rossum90c45142001-11-24 21:07:01 +00002980 global C3
2981 class C3(object):
2982 def __init__(self, foo):
2983 self.foo = foo
2984 def __getstate__(self):
2985 return self.foo
2986 def __setstate__(self, foo):
2987 self.foo = foo
2988
2989 global C4classic, C4
2990 class C4classic: # classic
2991 pass
2992 class C4(C4classic, object): # mixed inheritance
2993 pass
2994
Guido van Rossum3926a632001-09-25 16:25:58 +00002995 for p in pickle, cPickle:
2996 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002997 if verbose:
2998 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002999
3000 for cls in C, C1, C2:
3001 s = p.dumps(cls, bin)
3002 cls2 = p.loads(s)
3003 verify(cls2 is cls)
3004
3005 a = C1(1, 2); a.append(42); a.append(24)
3006 b = C2("hello", "world", 42)
3007 s = p.dumps((a, b), bin)
3008 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00003009 vereq(x.__class__, a.__class__)
3010 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
3011 vereq(y.__class__, b.__class__)
3012 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00003013 vereq(repr(x), repr(a))
3014 vereq(repr(y), repr(b))
Guido van Rossum3926a632001-09-25 16:25:58 +00003015 if verbose:
3016 print "a = x =", a
3017 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00003018 # Test for __getstate__ and __setstate__ on new style class
3019 u = C3(42)
3020 s = p.dumps(u, bin)
3021 v = p.loads(s)
3022 veris(u.__class__, v.__class__)
3023 vereq(u.foo, v.foo)
3024 # Test for picklability of hybrid class
3025 u = C4()
3026 u.foo = 42
3027 s = p.dumps(u, bin)
3028 v = p.loads(s)
3029 veris(u.__class__, v.__class__)
3030 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003031
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003032 # Testing copy.deepcopy()
3033 if verbose:
3034 print "deepcopy"
3035 import copy
3036 for cls in C, C1, C2:
3037 cls2 = copy.deepcopy(cls)
3038 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003039
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003040 a = C1(1, 2); a.append(42); a.append(24)
3041 b = C2("hello", "world", 42)
3042 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003043 vereq(x.__class__, a.__class__)
3044 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
3045 vereq(y.__class__, b.__class__)
3046 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
Walter Dörwald70a6b492004-02-12 17:35:32 +00003047 vereq(repr(x), repr(a))
3048 vereq(repr(y), repr(b))
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00003049 if verbose:
3050 print "a = x =", a
3051 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003052
Guido van Rossum8c842552002-03-14 23:05:54 +00003053def pickleslots():
3054 if verbose: print "Testing pickling of classes with __slots__ ..."
3055 import pickle, cPickle
3056 # Pickling of classes with __slots__ but without __getstate__ should fail
3057 global B, C, D, E
3058 class B(object):
3059 pass
3060 for base in [object, B]:
3061 class C(base):
3062 __slots__ = ['a']
3063 class D(C):
3064 pass
3065 try:
3066 pickle.dumps(C())
3067 except TypeError:
3068 pass
3069 else:
3070 raise TestFailed, "should fail: pickle C instance - %s" % base
3071 try:
3072 cPickle.dumps(C())
3073 except TypeError:
3074 pass
3075 else:
3076 raise TestFailed, "should fail: cPickle C instance - %s" % base
3077 try:
3078 pickle.dumps(C())
3079 except TypeError:
3080 pass
3081 else:
3082 raise TestFailed, "should fail: pickle D instance - %s" % base
3083 try:
3084 cPickle.dumps(D())
3085 except TypeError:
3086 pass
3087 else:
3088 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003089 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00003090 class C(base):
3091 __slots__ = ['a']
3092 def __getstate__(self):
3093 try:
3094 d = self.__dict__.copy()
3095 except AttributeError:
3096 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003097 for cls in self.__class__.__mro__:
3098 for sn in cls.__dict__.get('__slots__', ()):
3099 try:
3100 d[sn] = getattr(self, sn)
3101 except AttributeError:
3102 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00003103 return d
3104 def __setstate__(self, d):
3105 for k, v in d.items():
3106 setattr(self, k, v)
3107 class D(C):
3108 pass
3109 # Now it should work
3110 x = C()
3111 y = pickle.loads(pickle.dumps(x))
3112 vereq(hasattr(y, 'a'), 0)
3113 y = cPickle.loads(cPickle.dumps(x))
3114 vereq(hasattr(y, 'a'), 0)
3115 x.a = 42
3116 y = pickle.loads(pickle.dumps(x))
3117 vereq(y.a, 42)
3118 y = cPickle.loads(cPickle.dumps(x))
3119 vereq(y.a, 42)
3120 x = D()
3121 x.a = 42
3122 x.b = 100
3123 y = pickle.loads(pickle.dumps(x))
3124 vereq(y.a + y.b, 142)
3125 y = cPickle.loads(cPickle.dumps(x))
3126 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003127 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00003128 class E(C):
3129 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00003130 x = E()
3131 x.a = 42
3132 x.b = "foo"
3133 y = pickle.loads(pickle.dumps(x))
3134 vereq(y.a, x.a)
3135 vereq(y.b, x.b)
3136 y = cPickle.loads(cPickle.dumps(x))
3137 vereq(y.a, x.a)
3138 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00003139
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003140def copies():
3141 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
3142 import copy
3143 class C(object):
3144 pass
3145
3146 a = C()
3147 a.foo = 12
3148 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003149 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003150
3151 a.bar = [1,2,3]
3152 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003153 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003154 verify(c.bar is a.bar)
3155
3156 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00003157 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003158 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00003159 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003160
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003161def binopoverride():
3162 if verbose: print "Testing overrides of binary operations..."
3163 class I(int):
3164 def __repr__(self):
3165 return "I(%r)" % int(self)
3166 def __add__(self, other):
3167 return I(int(self) + int(other))
3168 __radd__ = __add__
3169 def __pow__(self, other, mod=None):
3170 if mod is None:
3171 return I(pow(int(self), int(other)))
3172 else:
3173 return I(pow(int(self), int(other), int(mod)))
3174 def __rpow__(self, other, mod=None):
3175 if mod is None:
3176 return I(pow(int(other), int(self), mod))
3177 else:
3178 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00003179
Walter Dörwald70a6b492004-02-12 17:35:32 +00003180 vereq(repr(I(1) + I(2)), "I(3)")
3181 vereq(repr(I(1) + 2), "I(3)")
3182 vereq(repr(1 + I(2)), "I(3)")
3183 vereq(repr(I(2) ** I(3)), "I(8)")
3184 vereq(repr(2 ** I(3)), "I(8)")
3185 vereq(repr(I(2) ** 3), "I(8)")
3186 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003187 class S(str):
3188 def __eq__(self, other):
3189 return self.lower() == other.lower()
3190
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003191def subclasspropagation():
3192 if verbose: print "Testing propagation of slot functions to subclasses..."
3193 class A(object):
3194 pass
3195 class B(A):
3196 pass
3197 class C(A):
3198 pass
3199 class D(B, C):
3200 pass
3201 d = D()
Tim Peters171b8682006-04-11 01:59:34 +00003202 orig_hash = hash(d) # related to id(d) in platform-dependent ways
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003203 A.__hash__ = lambda self: 42
3204 vereq(hash(d), 42)
3205 C.__hash__ = lambda self: 314
3206 vereq(hash(d), 314)
3207 B.__hash__ = lambda self: 144
3208 vereq(hash(d), 144)
3209 D.__hash__ = lambda self: 100
3210 vereq(hash(d), 100)
3211 del D.__hash__
3212 vereq(hash(d), 144)
3213 del B.__hash__
3214 vereq(hash(d), 314)
3215 del C.__hash__
3216 vereq(hash(d), 42)
3217 del A.__hash__
Tim Peters171b8682006-04-11 01:59:34 +00003218 vereq(hash(d), orig_hash)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003219 d.foo = 42
3220 d.bar = 42
3221 vereq(d.foo, 42)
3222 vereq(d.bar, 42)
3223 def __getattribute__(self, name):
3224 if name == "foo":
3225 return 24
3226 return object.__getattribute__(self, name)
3227 A.__getattribute__ = __getattribute__
3228 vereq(d.foo, 24)
3229 vereq(d.bar, 42)
3230 def __getattr__(self, name):
3231 if name in ("spam", "foo", "bar"):
3232 return "hello"
3233 raise AttributeError, name
3234 B.__getattr__ = __getattr__
3235 vereq(d.spam, "hello")
3236 vereq(d.foo, 24)
3237 vereq(d.bar, 42)
3238 del A.__getattribute__
3239 vereq(d.foo, 42)
3240 del d.foo
3241 vereq(d.foo, "hello")
3242 vereq(d.bar, 42)
3243 del B.__getattr__
3244 try:
3245 d.foo
3246 except AttributeError:
3247 pass
3248 else:
3249 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003250
Guido van Rossume7f3e242002-06-14 02:35:45 +00003251 # Test a nasty bug in recurse_down_subclasses()
3252 import gc
3253 class A(object):
3254 pass
3255 class B(A):
3256 pass
3257 del B
3258 gc.collect()
3259 A.__setitem__ = lambda *a: None # crash
3260
Tim Petersfc57ccb2001-10-12 02:38:24 +00003261def buffer_inherit():
3262 import binascii
3263 # SF bug [#470040] ParseTuple t# vs subclasses.
3264 if verbose:
3265 print "Testing that buffer interface is inherited ..."
3266
3267 class MyStr(str):
3268 pass
3269 base = 'abc'
3270 m = MyStr(base)
3271 # b2a_hex uses the buffer interface to get its argument's value, via
3272 # PyArg_ParseTuple 't#' code.
3273 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3274
3275 # It's not clear that unicode will continue to support the character
3276 # buffer interface, and this test will fail if that's taken away.
3277 class MyUni(unicode):
3278 pass
3279 base = u'abc'
3280 m = MyUni(base)
3281 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3282
3283 class MyInt(int):
3284 pass
3285 m = MyInt(42)
3286 try:
3287 binascii.b2a_hex(m)
3288 raise TestFailed('subclass of int should not have a buffer interface')
3289 except TypeError:
3290 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003291
Tim Petersc9933152001-10-16 20:18:24 +00003292def str_of_str_subclass():
3293 import binascii
3294 import cStringIO
3295
3296 if verbose:
3297 print "Testing __str__ defined in subclass of str ..."
3298
3299 class octetstring(str):
3300 def __str__(self):
3301 return binascii.b2a_hex(self)
3302 def __repr__(self):
3303 return self + " repr"
3304
3305 o = octetstring('A')
3306 vereq(type(o), octetstring)
3307 vereq(type(str(o)), str)
3308 vereq(type(repr(o)), str)
3309 vereq(ord(o), 0x41)
3310 vereq(str(o), '41')
3311 vereq(repr(o), 'A repr')
3312 vereq(o.__str__(), '41')
3313 vereq(o.__repr__(), 'A repr')
3314
3315 capture = cStringIO.StringIO()
3316 # Calling str() or not exercises different internal paths.
3317 print >> capture, o
3318 print >> capture, str(o)
3319 vereq(capture.getvalue(), '41\n41\n')
3320 capture.close()
3321
Guido van Rossumc8e56452001-10-22 00:43:43 +00003322def kwdargs():
3323 if verbose: print "Testing keyword arguments to __init__, __call__..."
3324 def f(a): return a
3325 vereq(f.__call__(a=42), 42)
3326 a = []
3327 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003328 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003329
Brett Cannon22565aa2006-06-09 22:31:23 +00003330def recursive__call__():
3331 if verbose: print ("Testing recursive __call__() by setting to instance of "
3332 "class ...")
3333 class A(object):
3334 pass
3335
3336 A.__call__ = A()
3337 try:
3338 A()()
3339 except RuntimeError:
3340 pass
3341 else:
3342 raise TestFailed("Recursion limit should have been reached for "
3343 "__call__()")
3344
Guido van Rossumed87ad82001-10-30 02:33:02 +00003345def delhook():
3346 if verbose: print "Testing __del__ hook..."
3347 log = []
3348 class C(object):
3349 def __del__(self):
3350 log.append(1)
3351 c = C()
3352 vereq(log, [])
3353 del c
3354 vereq(log, [1])
3355
Guido van Rossum29d26062001-12-11 04:37:34 +00003356 class D(object): pass
3357 d = D()
3358 try: del d[0]
3359 except TypeError: pass
3360 else: raise TestFailed, "invalid del() didn't raise TypeError"
3361
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003362def hashinherit():
3363 if verbose: print "Testing hash of mutable subclasses..."
3364
3365 class mydict(dict):
3366 pass
3367 d = mydict()
3368 try:
3369 hash(d)
3370 except TypeError:
3371 pass
3372 else:
3373 raise TestFailed, "hash() of dict subclass should fail"
3374
3375 class mylist(list):
3376 pass
3377 d = mylist()
3378 try:
3379 hash(d)
3380 except TypeError:
3381 pass
3382 else:
3383 raise TestFailed, "hash() of list subclass should fail"
3384
Guido van Rossum29d26062001-12-11 04:37:34 +00003385def strops():
3386 try: 'a' + 5
3387 except TypeError: pass
3388 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3389
3390 try: ''.split('')
3391 except ValueError: pass
3392 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3393
3394 try: ''.join([0])
3395 except TypeError: pass
3396 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3397
3398 try: ''.rindex('5')
3399 except ValueError: pass
3400 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3401
Guido van Rossum29d26062001-12-11 04:37:34 +00003402 try: '%(n)s' % None
3403 except TypeError: pass
3404 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3405
3406 try: '%(n' % {}
3407 except ValueError: pass
3408 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3409
3410 try: '%*s' % ('abc')
3411 except TypeError: pass
3412 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3413
3414 try: '%*.*s' % ('abc', 5)
3415 except TypeError: pass
3416 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3417
3418 try: '%s' % (1, 2)
3419 except TypeError: pass
3420 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3421
3422 try: '%' % None
3423 except ValueError: pass
3424 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3425
3426 vereq('534253'.isdigit(), 1)
3427 vereq('534253x'.isdigit(), 0)
3428 vereq('%c' % 5, '\x05')
3429 vereq('%c' % '5', '5')
3430
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003431def deepcopyrecursive():
3432 if verbose: print "Testing deepcopy of recursive objects..."
3433 class Node:
3434 pass
3435 a = Node()
3436 b = Node()
3437 a.b = b
3438 b.a = a
3439 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003440
Guido van Rossumd7035672002-03-12 20:43:31 +00003441def modules():
3442 if verbose: print "Testing uninitialized module objects..."
3443 from types import ModuleType as M
3444 m = M.__new__(M)
3445 str(m)
3446 vereq(hasattr(m, "__name__"), 0)
3447 vereq(hasattr(m, "__file__"), 0)
3448 vereq(hasattr(m, "foo"), 0)
3449 vereq(m.__dict__, None)
3450 m.foo = 1
3451 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003452
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003453def dictproxyiterkeys():
3454 class C(object):
3455 def meth(self):
3456 pass
3457 if verbose: print "Testing dict-proxy iterkeys..."
3458 keys = [ key for key in C.__dict__.iterkeys() ]
3459 keys.sort()
3460 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3461
3462def dictproxyitervalues():
3463 class C(object):
3464 def meth(self):
3465 pass
3466 if verbose: print "Testing dict-proxy itervalues..."
3467 values = [ values for values in C.__dict__.itervalues() ]
3468 vereq(len(values), 5)
3469
3470def dictproxyiteritems():
3471 class C(object):
3472 def meth(self):
3473 pass
3474 if verbose: print "Testing dict-proxy iteritems..."
3475 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3476 keys.sort()
3477 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3478
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003479def funnynew():
3480 if verbose: print "Testing __new__ returning something unexpected..."
3481 class C(object):
3482 def __new__(cls, arg):
3483 if isinstance(arg, str): return [1, 2, 3]
3484 elif isinstance(arg, int): return object.__new__(D)
3485 else: return object.__new__(cls)
3486 class D(C):
3487 def __init__(self, arg):
3488 self.foo = arg
3489 vereq(C("1"), [1, 2, 3])
3490 vereq(D("1"), [1, 2, 3])
3491 d = D(None)
3492 veris(d.foo, None)
3493 d = C(1)
3494 vereq(isinstance(d, D), True)
3495 vereq(d.foo, 1)
3496 d = D(1)
3497 vereq(isinstance(d, D), True)
3498 vereq(d.foo, 1)
3499
Guido van Rossume8fc6402002-04-16 16:44:51 +00003500def imulbug():
3501 # SF bug 544647
3502 if verbose: print "Testing for __imul__ problems..."
3503 class C(object):
3504 def __imul__(self, other):
3505 return (self, other)
3506 x = C()
3507 y = x
3508 y *= 1.0
3509 vereq(y, (x, 1.0))
3510 y = x
3511 y *= 2
3512 vereq(y, (x, 2))
3513 y = x
3514 y *= 3L
3515 vereq(y, (x, 3L))
3516 y = x
3517 y *= 1L<<100
3518 vereq(y, (x, 1L<<100))
3519 y = x
3520 y *= None
3521 vereq(y, (x, None))
3522 y = x
3523 y *= "foo"
3524 vereq(y, (x, "foo"))
3525
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003526def docdescriptor():
3527 # SF bug 542984
3528 if verbose: print "Testing __doc__ descriptor..."
3529 class DocDescr(object):
3530 def __get__(self, object, otype):
3531 if object:
3532 object = object.__class__.__name__ + ' instance'
3533 if otype:
3534 otype = otype.__name__
3535 return 'object=%s; type=%s' % (object, otype)
3536 class OldClass:
3537 __doc__ = DocDescr()
3538 class NewClass(object):
3539 __doc__ = DocDescr()
3540 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3541 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3542 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3543 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3544
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003545def copy_setstate():
3546 if verbose:
3547 print "Testing that copy.*copy() correctly uses __setstate__..."
3548 import copy
3549 class C(object):
3550 def __init__(self, foo=None):
3551 self.foo = foo
3552 self.__foo = foo
3553 def setfoo(self, foo=None):
3554 self.foo = foo
3555 def getfoo(self):
3556 return self.__foo
3557 def __getstate__(self):
3558 return [self.foo]
3559 def __setstate__(self, lst):
3560 assert len(lst) == 1
3561 self.__foo = self.foo = lst[0]
3562 a = C(42)
3563 a.setfoo(24)
3564 vereq(a.foo, 24)
3565 vereq(a.getfoo(), 42)
3566 b = copy.copy(a)
3567 vereq(b.foo, 24)
3568 vereq(b.getfoo(), 24)
3569 b = copy.deepcopy(a)
3570 vereq(b.foo, 24)
3571 vereq(b.getfoo(), 24)
3572
Guido van Rossum09638c12002-06-13 19:17:46 +00003573def slices():
3574 if verbose:
3575 print "Testing cases with slices and overridden __getitem__ ..."
3576 # Strings
3577 vereq("hello"[:4], "hell")
3578 vereq("hello"[slice(4)], "hell")
3579 vereq(str.__getitem__("hello", slice(4)), "hell")
3580 class S(str):
3581 def __getitem__(self, x):
3582 return str.__getitem__(self, x)
3583 vereq(S("hello")[:4], "hell")
3584 vereq(S("hello")[slice(4)], "hell")
3585 vereq(S("hello").__getitem__(slice(4)), "hell")
3586 # Tuples
3587 vereq((1,2,3)[:2], (1,2))
3588 vereq((1,2,3)[slice(2)], (1,2))
3589 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3590 class T(tuple):
3591 def __getitem__(self, x):
3592 return tuple.__getitem__(self, x)
3593 vereq(T((1,2,3))[:2], (1,2))
3594 vereq(T((1,2,3))[slice(2)], (1,2))
3595 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3596 # Lists
3597 vereq([1,2,3][:2], [1,2])
3598 vereq([1,2,3][slice(2)], [1,2])
3599 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3600 class L(list):
3601 def __getitem__(self, x):
3602 return list.__getitem__(self, x)
3603 vereq(L([1,2,3])[:2], [1,2])
3604 vereq(L([1,2,3])[slice(2)], [1,2])
3605 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3606 # Now do lists and __setitem__
3607 a = L([1,2,3])
3608 a[slice(1, 3)] = [3,2]
3609 vereq(a, [1,3,2])
3610 a[slice(0, 2, 1)] = [3,1]
3611 vereq(a, [3,1,2])
3612 a.__setitem__(slice(1, 3), [2,1])
3613 vereq(a, [3,2,1])
3614 a.__setitem__(slice(0, 2, 1), [2,3])
3615 vereq(a, [2,3,1])
3616
Tim Peters2484aae2002-07-11 06:56:07 +00003617def subtype_resurrection():
3618 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003619 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003620
3621 class C(object):
3622 container = []
3623
3624 def __del__(self):
3625 # resurrect the instance
3626 C.container.append(self)
3627
3628 c = C()
3629 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003630 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003631 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003632 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003633
3634 # If that didn't blow up, it's also interesting to see whether clearing
3635 # the last container slot works: that will attempt to delete c again,
3636 # which will cause c to get appended back to the container again "during"
3637 # the del.
3638 del C.container[-1]
3639 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003640 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003641
Tim Peters14cb1e12002-07-11 18:26:21 +00003642 # Make c mortal again, so that the test framework with -l doesn't report
3643 # it as a leak.
3644 del C.__del__
3645
Guido van Rossum2d702462002-08-06 21:28:28 +00003646def slottrash():
3647 # Deallocating deeply nested slotted trash caused stack overflows
3648 if verbose:
3649 print "Testing slot trash..."
3650 class trash(object):
3651 __slots__ = ['x']
3652 def __init__(self, x):
3653 self.x = x
3654 o = None
3655 for i in xrange(50000):
3656 o = trash(o)
3657 del o
3658
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003659def slotmultipleinheritance():
3660 # SF bug 575229, multiple inheritance w/ slots dumps core
3661 class A(object):
3662 __slots__=()
3663 class B(object):
3664 pass
3665 class C(A,B) :
3666 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003667 vereq(C.__basicsize__, B.__basicsize__)
3668 verify(hasattr(C, '__dict__'))
3669 verify(hasattr(C, '__weakref__'))
3670 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003671
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003672def testrmul():
3673 # SF patch 592646
3674 if verbose:
3675 print "Testing correct invocation of __rmul__..."
3676 class C(object):
3677 def __mul__(self, other):
3678 return "mul"
3679 def __rmul__(self, other):
3680 return "rmul"
3681 a = C()
3682 vereq(a*2, "mul")
3683 vereq(a*2.2, "mul")
3684 vereq(2*a, "rmul")
3685 vereq(2.2*a, "rmul")
3686
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003687def testipow():
3688 # [SF bug 620179]
3689 if verbose:
3690 print "Testing correct invocation of __ipow__..."
3691 class C(object):
3692 def __ipow__(self, other):
3693 pass
3694 a = C()
3695 a **= 2
3696
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003697def do_this_first():
3698 if verbose:
3699 print "Testing SF bug 551412 ..."
3700 # This dumps core when SF bug 551412 isn't fixed --
3701 # but only when test_descr.py is run separately.
3702 # (That can't be helped -- as soon as PyType_Ready()
3703 # is called for PyLong_Type, the bug is gone.)
3704 class UserLong(object):
3705 def __pow__(self, *args):
3706 pass
3707 try:
3708 pow(0L, UserLong(), 0L)
3709 except:
3710 pass
3711
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003712 if verbose:
3713 print "Testing SF bug 570483..."
3714 # Another segfault only when run early
3715 # (before PyType_Ready(tuple) is called)
3716 type.mro(tuple)
3717
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003718def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003719 if verbose:
3720 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003721 # stuff that should work:
3722 class C(object):
3723 pass
3724 class C2(object):
3725 def __getattribute__(self, attr):
3726 if attr == 'a':
3727 return 2
3728 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003729 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003730 def meth(self):
3731 return 1
3732 class D(C):
3733 pass
3734 class E(D):
3735 pass
3736 d = D()
3737 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003738 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003739 D.__bases__ = (C2,)
3740 vereq(d.meth(), 1)
3741 vereq(e.meth(), 1)
3742 vereq(d.a, 2)
3743 vereq(e.a, 2)
3744 vereq(C2.__subclasses__(), [D])
3745
3746 # stuff that shouldn't:
3747 class L(list):
3748 pass
3749
3750 try:
3751 L.__bases__ = (dict,)
3752 except TypeError:
3753 pass
3754 else:
3755 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3756
3757 try:
3758 list.__bases__ = (dict,)
3759 except TypeError:
3760 pass
3761 else:
3762 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3763
3764 try:
Michael W. Hudsonf3904422006-11-23 13:54:04 +00003765 D.__bases__ = (C2, list)
3766 except TypeError:
3767 pass
3768 else:
3769 assert 0, "best_base calculation found wanting"
3770
3771 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003772 del D.__bases__
3773 except TypeError:
3774 pass
3775 else:
3776 raise TestFailed, "shouldn't be able to delete .__bases__"
3777
3778 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003779 D.__bases__ = ()
3780 except TypeError, msg:
3781 if str(msg) == "a new-style class can't have only classic bases":
3782 raise TestFailed, "wrong error message for .__bases__ = ()"
3783 else:
3784 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3785
3786 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003787 D.__bases__ = (D,)
3788 except TypeError:
3789 pass
3790 else:
3791 # actually, we'll have crashed by here...
3792 raise TestFailed, "shouldn't be able to create inheritance cycles"
3793
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003794 try:
Michael W. Hudsone723e452003-08-07 14:58:10 +00003795 D.__bases__ = (C, C)
3796 except TypeError:
3797 pass
3798 else:
3799 raise TestFailed, "didn't detect repeated base classes"
3800
3801 try:
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003802 D.__bases__ = (E,)
3803 except TypeError:
3804 pass
3805 else:
3806 raise TestFailed, "shouldn't be able to create inheritance cycles"
3807
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003808 # let's throw a classic class into the mix:
3809 class Classic:
3810 def meth2(self):
3811 return 3
3812
3813 D.__bases__ = (C, Classic)
3814
3815 vereq(d.meth2(), 3)
3816 vereq(e.meth2(), 3)
3817 try:
3818 d.a
3819 except AttributeError:
3820 pass
3821 else:
3822 raise TestFailed, "attribute should have vanished"
3823
3824 try:
3825 D.__bases__ = (Classic,)
3826 except TypeError:
3827 pass
3828 else:
3829 raise TestFailed, "new-style class must have a new-style base"
3830
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003831def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003832 if verbose:
3833 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003834 class WorkOnce(type):
3835 def __new__(self, name, bases, ns):
3836 self.flag = 0
3837 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3838 def mro(self):
3839 if self.flag > 0:
3840 raise RuntimeError, "bozo"
3841 else:
3842 self.flag += 1
3843 return type.mro(self)
3844
3845 class WorkAlways(type):
3846 def mro(self):
3847 # this is here to make sure that .mro()s aren't called
3848 # with an exception set (which was possible at one point).
3849 # An error message will be printed in a debug build.
3850 # What's a good way to test for this?
3851 return type.mro(self)
3852
3853 class C(object):
3854 pass
3855
3856 class C2(object):
3857 pass
3858
3859 class D(C):
3860 pass
3861
3862 class E(D):
3863 pass
3864
3865 class F(D):
3866 __metaclass__ = WorkOnce
3867
3868 class G(D):
3869 __metaclass__ = WorkAlways
3870
3871 # Immediate subclasses have their mro's adjusted in alphabetical
3872 # order, so E's will get adjusted before adjusting F's fails. We
3873 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003874
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003875 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003876 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003877
3878 try:
3879 D.__bases__ = (C2,)
3880 except RuntimeError:
3881 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003882 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003883 else:
3884 raise TestFailed, "exception not propagated"
3885
3886def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003887 if verbose:
3888 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003889 class A(object):
3890 pass
3891
3892 class B(object):
3893 pass
3894
3895 class C(A, B):
3896 pass
3897
3898 class D(A, B):
3899 pass
3900
3901 class E(C, D):
3902 pass
3903
3904 try:
3905 C.__bases__ = (B, A)
3906 except TypeError:
3907 pass
3908 else:
3909 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003910
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003911def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003912 if verbose:
3913 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003914 class C(object):
3915 pass
3916
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003917 # C.__module__ could be 'test_descr' or '__main__'
3918 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003919
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003920 C.__name__ = 'D'
3921 vereq((C.__module__, C.__name__), (mod, 'D'))
3922
3923 C.__name__ = 'D.E'
3924 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003925
Guido van Rossum613f24f2003-01-06 23:00:59 +00003926def subclass_right_op():
3927 if verbose:
3928 print "Testing correct dispatch of subclass overloading __r<op>__..."
3929
3930 # This code tests various cases where right-dispatch of a subclass
3931 # should be preferred over left-dispatch of a base class.
3932
3933 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3934
3935 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003936 def __floordiv__(self, other):
3937 return "B.__floordiv__"
3938 def __rfloordiv__(self, other):
3939 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003940
Guido van Rossumf389c772003-02-27 20:04:19 +00003941 vereq(B(1) // 1, "B.__floordiv__")
3942 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003943
3944 # Case 2: subclass of object; this is just the baseline for case 3
3945
3946 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003947 def __floordiv__(self, other):
3948 return "C.__floordiv__"
3949 def __rfloordiv__(self, other):
3950 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003951
Guido van Rossumf389c772003-02-27 20:04:19 +00003952 vereq(C() // 1, "C.__floordiv__")
3953 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003954
3955 # Case 3: subclass of new-style class; here it gets interesting
3956
3957 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003958 def __floordiv__(self, other):
3959 return "D.__floordiv__"
3960 def __rfloordiv__(self, other):
3961 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003962
Guido van Rossumf389c772003-02-27 20:04:19 +00003963 vereq(D() // C(), "D.__floordiv__")
3964 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003965
3966 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3967
3968 class E(C):
3969 pass
3970
Guido van Rossumf389c772003-02-27 20:04:19 +00003971 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003972
Guido van Rossumf389c772003-02-27 20:04:19 +00003973 vereq(E() // 1, "C.__floordiv__")
3974 vereq(1 // E(), "C.__rfloordiv__")
3975 vereq(E() // C(), "C.__floordiv__")
3976 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003977
Guido van Rossum373c7412003-01-07 13:41:37 +00003978def dict_type_with_metaclass():
3979 if verbose:
3980 print "Testing type of __dict__ when __metaclass__ set..."
3981
3982 class B(object):
3983 pass
3984 class M(type):
3985 pass
3986 class C:
3987 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3988 __metaclass__ = M
3989 veris(type(C.__dict__), type(B.__dict__))
3990
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003991def meth_class_get():
3992 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003993 if verbose:
3994 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003995 # Baseline
3996 arg = [1, 2, 3]
3997 res = {1: None, 2: None, 3: None}
3998 vereq(dict.fromkeys(arg), res)
3999 vereq({}.fromkeys(arg), res)
4000 # Now get the descriptor
4001 descr = dict.__dict__["fromkeys"]
4002 # More baseline using the descriptor directly
4003 vereq(descr.__get__(None, dict)(arg), res)
4004 vereq(descr.__get__({})(arg), res)
4005 # Now check various error cases
4006 try:
4007 descr.__get__(None, None)
4008 except TypeError:
4009 pass
4010 else:
4011 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
4012 try:
4013 descr.__get__(42)
4014 except TypeError:
4015 pass
4016 else:
4017 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
4018 try:
4019 descr.__get__(None, 42)
4020 except TypeError:
4021 pass
4022 else:
4023 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
4024 try:
4025 descr.__get__(None, int)
4026 except TypeError:
4027 pass
4028 else:
4029 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
4030
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004031def isinst_isclass():
4032 if verbose:
4033 print "Testing proxy isinstance() and isclass()..."
4034 class Proxy(object):
4035 def __init__(self, obj):
4036 self.__obj = obj
4037 def __getattribute__(self, name):
4038 if name.startswith("_Proxy__"):
4039 return object.__getattribute__(self, name)
4040 else:
4041 return getattr(self.__obj, name)
4042 # Test with a classic class
4043 class C:
4044 pass
4045 a = C()
4046 pa = Proxy(a)
4047 verify(isinstance(a, C)) # Baseline
4048 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004049 # Test with a classic subclass
4050 class D(C):
4051 pass
4052 a = D()
4053 pa = Proxy(a)
4054 verify(isinstance(a, C)) # Baseline
4055 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004056 # Test with a new-style class
4057 class C(object):
4058 pass
4059 a = C()
4060 pa = Proxy(a)
4061 verify(isinstance(a, C)) # Baseline
4062 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004063 # Test with a new-style subclass
4064 class D(C):
4065 pass
4066 a = D()
4067 pa = Proxy(a)
4068 verify(isinstance(a, C)) # Baseline
4069 verify(isinstance(pa, C)) # Test
4070
4071def proxysuper():
4072 if verbose:
4073 print "Testing super() for a proxy object..."
4074 class Proxy(object):
4075 def __init__(self, obj):
4076 self.__obj = obj
4077 def __getattribute__(self, name):
4078 if name.startswith("_Proxy__"):
4079 return object.__getattribute__(self, name)
4080 else:
4081 return getattr(self.__obj, name)
4082
4083 class B(object):
4084 def f(self):
4085 return "B.f"
4086
4087 class C(B):
4088 def f(self):
4089 return super(C, self).f() + "->C.f"
4090
4091 obj = C()
4092 p = Proxy(obj)
4093 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004094
Guido van Rossum52b27052003-04-15 20:05:10 +00004095def carloverre():
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004096 if verbose:
Guido van Rossum52b27052003-04-15 20:05:10 +00004097 print "Testing prohibition of Carlo Verre's hack..."
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004098 try:
4099 object.__setattr__(str, "foo", 42)
4100 except TypeError:
4101 pass
4102 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004103 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004104 try:
4105 object.__delattr__(str, "lower")
4106 except TypeError:
4107 pass
4108 else:
Guido van Rossum52b27052003-04-15 20:05:10 +00004109 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004110
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004111def weakref_segfault():
4112 # SF 742911
4113 if verbose:
4114 print "Testing weakref segfault..."
4115
4116 import weakref
4117
4118 class Provoker:
4119 def __init__(self, referrent):
4120 self.ref = weakref.ref(referrent)
4121
4122 def __del__(self):
4123 x = self.ref()
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004124
4125 class Oops(object):
4126 pass
4127
4128 o = Oops()
4129 o.whatever = Provoker(o)
4130 del o
4131
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004132def wrapper_segfault():
4133 # SF 927248: deeply nested wrappers could cause stack overflow
4134 f = lambda:None
4135 for i in xrange(1000000):
4136 f = f.__call__
4137 f = None
4138
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004139# Fix SF #762455, segfault when sys.stdout is changed in getattr
4140def filefault():
4141 if verbose:
4142 print "Testing sys.stdout is changed in getattr..."
4143 import sys
4144 class StdoutGuard:
4145 def __getattr__(self, attr):
4146 sys.stdout = sys.__stdout__
4147 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4148 sys.stdout = StdoutGuard()
4149 try:
4150 print "Oops!"
4151 except RuntimeError:
4152 pass
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004153
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004154def vicious_descriptor_nonsense():
4155 # A potential segfault spotted by Thomas Wouters in mail to
4156 # python-dev 2003-04-17, turned into an example & fixed by Michael
4157 # Hudson just less than four months later...
4158 if verbose:
4159 print "Testing vicious_descriptor_nonsense..."
4160
4161 class Evil(object):
4162 def __hash__(self):
4163 return hash('attr')
4164 def __eq__(self, other):
4165 del C.attr
4166 return 0
4167
4168 class Descr(object):
4169 def __get__(self, ob, type=None):
4170 return 1
4171
4172 class C(object):
4173 attr = Descr()
4174
4175 c = C()
4176 c.__dict__[Evil()] = 0
4177
4178 vereq(c.attr, 1)
4179 # this makes a crash more likely:
4180 import gc; gc.collect()
4181 vereq(hasattr(c, 'attr'), False)
Tim Peters58eb11c2004-01-18 20:29:55 +00004182
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004183def test_init():
4184 # SF 1155938
4185 class Foo(object):
4186 def __init__(self):
4187 return 10
4188 try:
4189 Foo()
4190 except TypeError:
4191 pass
4192 else:
4193 raise TestFailed, "did not test __init__() for None return"
4194
Armin Rigoc6686b72005-11-07 08:38:00 +00004195def methodwrapper():
4196 # <type 'method-wrapper'> did not support any reflection before 2.5
4197 if verbose:
4198 print "Testing method-wrapper objects..."
4199
4200 l = []
4201 vereq(l.__add__, l.__add__)
Armin Rigofd01d792006-06-08 10:56:24 +00004202 vereq(l.__add__, [].__add__)
4203 verify(l.__add__ != [5].__add__)
4204 verify(l.__add__ != l.__mul__)
Armin Rigoc6686b72005-11-07 08:38:00 +00004205 verify(l.__add__.__name__ == '__add__')
4206 verify(l.__add__.__self__ is l)
4207 verify(l.__add__.__objclass__ is list)
4208 vereq(l.__add__.__doc__, list.__add__.__doc__)
Armin Rigofd01d792006-06-08 10:56:24 +00004209 try:
4210 hash(l.__add__)
4211 except TypeError:
4212 pass
4213 else:
4214 raise TestFailed("no TypeError from hash([].__add__)")
4215
4216 t = ()
4217 t += (7,)
4218 vereq(t.__add__, (7,).__add__)
4219 vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004220
Armin Rigofd163f92005-12-29 15:59:19 +00004221def notimplemented():
4222 # all binary methods should be able to return a NotImplemented
4223 if verbose:
4224 print "Testing NotImplemented..."
4225
4226 import sys
4227 import types
4228 import operator
4229
4230 def specialmethod(self, other):
4231 return NotImplemented
4232
4233 def check(expr, x, y):
4234 try:
4235 exec expr in {'x': x, 'y': y, 'operator': operator}
4236 except TypeError:
4237 pass
4238 else:
4239 raise TestFailed("no TypeError from %r" % (expr,))
4240
4241 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4242 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4243 # ValueErrors instead of TypeErrors
4244 for metaclass in [type, types.ClassType]:
4245 for name, expr, iexpr in [
4246 ('__add__', 'x + y', 'x += y'),
4247 ('__sub__', 'x - y', 'x -= y'),
4248 ('__mul__', 'x * y', 'x *= y'),
4249 ('__truediv__', 'operator.truediv(x, y)', None),
4250 ('__floordiv__', 'operator.floordiv(x, y)', None),
4251 ('__div__', 'x / y', 'x /= y'),
4252 ('__mod__', 'x % y', 'x %= y'),
4253 ('__divmod__', 'divmod(x, y)', None),
4254 ('__pow__', 'x ** y', 'x **= y'),
4255 ('__lshift__', 'x << y', 'x <<= y'),
4256 ('__rshift__', 'x >> y', 'x >>= y'),
4257 ('__and__', 'x & y', 'x &= y'),
4258 ('__or__', 'x | y', 'x |= y'),
4259 ('__xor__', 'x ^ y', 'x ^= y'),
4260 ('__coerce__', 'coerce(x, y)', None)]:
4261 if name == '__coerce__':
4262 rname = name
4263 else:
4264 rname = '__r' + name[2:]
4265 A = metaclass('A', (), {name: specialmethod})
4266 B = metaclass('B', (), {rname: specialmethod})
4267 a = A()
4268 b = B()
4269 check(expr, a, a)
4270 check(expr, a, b)
4271 check(expr, b, a)
4272 check(expr, b, b)
4273 check(expr, a, N1)
4274 check(expr, a, N2)
4275 check(expr, N1, b)
4276 check(expr, N2, b)
4277 if iexpr:
4278 check(iexpr, a, a)
4279 check(iexpr, a, b)
4280 check(iexpr, b, a)
4281 check(iexpr, b, b)
4282 check(iexpr, a, N1)
4283 check(iexpr, a, N2)
4284 iname = '__i' + name[2:]
4285 C = metaclass('C', (), {iname: specialmethod})
4286 c = C()
4287 check(iexpr, c, a)
4288 check(iexpr, c, b)
4289 check(iexpr, c, N1)
4290 check(iexpr, c, N2)
4291
Georg Brandl0fca97a2007-03-05 22:28:08 +00004292def test_assign_slice():
4293 # ceval.c's assign_slice used to check for
4294 # tp->tp_as_sequence->sq_slice instead of
4295 # tp->tp_as_sequence->sq_ass_slice
4296
4297 class C(object):
4298 def __setslice__(self, start, stop, value):
4299 self.value = value
4300
4301 c = C()
4302 c[1:2] = 3
4303 vereq(c.value, 3)
4304
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004305def test_main():
Guido van Rossumaabe0b32003-05-29 14:26:57 +00004306 weakref_segfault() # Must be first, somehow
Martin v. Löwisd5cfa542006-07-03 13:47:40 +00004307 wrapper_segfault()
Guido van Rossum9fc8a292002-05-24 21:40:08 +00004308 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00004309 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310 lists()
4311 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00004312 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00004313 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314 ints()
4315 longs()
4316 floats()
4317 complexes()
4318 spamlists()
4319 spamdicts()
4320 pydicts()
4321 pylists()
4322 metaclass()
4323 pymods()
4324 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00004325 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004326 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00004327 ex5()
4328 monotonicity()
4329 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00004330 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00004332 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333 dynamics()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004335 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00004337 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338 classic()
4339 compattr()
4340 newslot()
4341 altmro()
4342 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00004343 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00004344 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00004345 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00004346 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00004347 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00004348 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00004349 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00004350 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00004351 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00004352 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00004353 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00004354 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00004355 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00004356 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00004357 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00004358 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00004359 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00004360 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004361 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00004362 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00004363 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00004364 kwdargs()
Brett Cannon22565aa2006-06-09 22:31:23 +00004365 recursive__call__()
Guido van Rossumed87ad82001-10-30 02:33:02 +00004366 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00004367 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00004368 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00004369 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00004370 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00004371 dictproxyiterkeys()
4372 dictproxyitervalues()
4373 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00004374 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00004375 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00004376 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00004377 docdescriptor()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00004378 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00004379 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00004380 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00004381 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00004382 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00004383 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004384 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004385 test_mutable_bases()
4386 test_mutable_bases_with_failing_mro()
4387 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004388 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00004389 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00004390 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00004391 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00004392 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00004393 proxysuper()
Guido van Rossum52b27052003-04-15 20:05:10 +00004394 carloverre()
Raymond Hettinger2b6220d2003-06-29 15:44:07 +00004395 filefault()
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00004396 vicious_descriptor_nonsense()
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004397 test_init()
Armin Rigoc6686b72005-11-07 08:38:00 +00004398 methodwrapper()
Armin Rigofd163f92005-12-29 15:59:19 +00004399 notimplemented()
Georg Brandl0fca97a2007-03-05 22:28:08 +00004400 test_assign_slice()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004401
Jeremy Hyltonfa955692007-02-27 18:29:45 +00004402 from test import test_descr
4403 run_doctest(test_descr, verbosity=True)
4404
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004405 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004407if __name__ == "__main__":
4408 test_main()