blob: f3c216a39cc7d081bfe2f8acc2ccf881361474ed [file] [log] [blame]
Benjamin Petersond4d400c2009-04-18 20:12:47 +00001import __builtin__
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00002import sys
Armin Rigo9790a272007-05-02 19:23:31 +00003import types
Georg Brandl48545522008-02-02 10:12:36 +00004import unittest
5import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00006
Georg Brandl48545522008-02-02 10:12:36 +00007from copy import deepcopy
8from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +00009
Guido van Rossum875eeaa2001-10-11 18:33:53 +000010
Georg Brandl48545522008-02-02 10:12:36 +000011class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000012
Georg Brandl48545522008-02-02 10:12:36 +000013 def __init__(self, *args, **kwargs):
14 unittest.TestCase.__init__(self, *args, **kwargs)
15 self.binops = {
16 'add': '+',
17 'sub': '-',
18 'mul': '*',
19 'div': '/',
20 'divmod': 'divmod',
21 'pow': '**',
22 'lshift': '<<',
23 'rshift': '>>',
24 'and': '&',
25 'xor': '^',
26 'or': '|',
27 'cmp': 'cmp',
28 'lt': '<',
29 'le': '<=',
30 'eq': '==',
31 'ne': '!=',
32 'gt': '>',
33 'ge': '>=',
34 }
Tim Peters3caca232001-12-06 06:23:26 +000035
Georg Brandl48545522008-02-02 10:12:36 +000036 for name, expr in self.binops.items():
37 if expr.islower():
38 expr = expr + "(a, b)"
39 else:
40 expr = 'a %s b' % expr
41 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000042
Georg Brandl48545522008-02-02 10:12:36 +000043 self.unops = {
44 'pos': '+',
45 'neg': '-',
46 'abs': 'abs',
47 'invert': '~',
48 'int': 'int',
49 'long': 'long',
50 'float': 'float',
51 'oct': 'oct',
52 'hex': 'hex',
53 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000054
Georg Brandl48545522008-02-02 10:12:36 +000055 for name, expr in self.unops.items():
56 if expr.islower():
57 expr = expr + "(a)"
58 else:
59 expr = '%s a' % expr
60 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000061
Georg Brandl48545522008-02-02 10:12:36 +000062 def setUp(self):
63 self.original_filters = warnings.filters[:]
64 warnings.filterwarnings("ignore",
65 r'complex divmod\(\), // and % are deprecated$',
66 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000067
Georg Brandl48545522008-02-02 10:12:36 +000068 def tearDown(self):
69 warnings.filters = self.original_filters
Tim Peters6d6c1a32001-08-02 04:15:00 +000070
Georg Brandl48545522008-02-02 10:12:36 +000071 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
72 d = {'a': a}
73 self.assertEqual(eval(expr, d), res)
74 t = type(a)
75 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076
Georg Brandl48545522008-02-02 10:12:36 +000077 # Find method in parent class
78 while meth not in t.__dict__:
79 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000080 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
81 # method object; the getattr() below obtains its underlying function.
82 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000083 self.assertEqual(m(a), res)
84 bm = getattr(a, meth)
85 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000086
Georg Brandl48545522008-02-02 10:12:36 +000087 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
88 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000089
Georg Brandl48545522008-02-02 10:12:36 +000090 # XXX Hack so this passes before 2.3 when -Qnew is specified.
91 if meth == "__div__" and 1/2 == 0.5:
92 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000093
Georg Brandl48545522008-02-02 10:12:36 +000094 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000095
Georg Brandl48545522008-02-02 10:12:36 +000096 self.assertEqual(eval(expr, d), res)
97 t = type(a)
98 m = getattr(t, meth)
99 while meth not in t.__dict__:
100 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000101 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
102 # method object; the getattr() below obtains its underlying function.
103 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000104 self.assertEqual(m(a, b), res)
105 bm = getattr(a, meth)
106 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000107
Georg Brandl48545522008-02-02 10:12:36 +0000108 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
109 d = {'a': a, 'b': b, 'c': c}
110 self.assertEqual(eval(expr, d), res)
111 t = type(a)
112 m = getattr(t, meth)
113 while meth not in t.__dict__:
114 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000115 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
116 # method object; the getattr() below obtains its underlying function.
117 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000118 self.assertEqual(m(a, b, c), res)
119 bm = getattr(a, meth)
120 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000121
Georg Brandl48545522008-02-02 10:12:36 +0000122 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
123 d = {'a': deepcopy(a), 'b': b}
124 exec stmt in d
125 self.assertEqual(d['a'], res)
126 t = type(a)
127 m = getattr(t, meth)
128 while meth not in t.__dict__:
129 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000130 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
131 # method object; the getattr() below obtains its underlying function.
132 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000133 d['a'] = deepcopy(a)
134 m(d['a'], b)
135 self.assertEqual(d['a'], res)
136 d['a'] = deepcopy(a)
137 bm = getattr(d['a'], meth)
138 bm(b)
139 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000140
Georg Brandl48545522008-02-02 10:12:36 +0000141 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
142 d = {'a': deepcopy(a), 'b': b, 'c': c}
143 exec stmt in d
144 self.assertEqual(d['a'], res)
145 t = type(a)
146 m = getattr(t, meth)
147 while meth not in t.__dict__:
148 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000149 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
150 # method object; the getattr() below obtains its underlying function.
151 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000152 d['a'] = deepcopy(a)
153 m(d['a'], b, c)
154 self.assertEqual(d['a'], res)
155 d['a'] = deepcopy(a)
156 bm = getattr(d['a'], meth)
157 bm(b, c)
158 self.assertEqual(d['a'], res)
159
160 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
161 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
162 exec stmt in dictionary
163 self.assertEqual(dictionary['a'], res)
164 t = type(a)
165 while meth not in t.__dict__:
166 t = t.__bases__[0]
167 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000168 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
169 # method object; the getattr() below obtains its underlying function.
170 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000171 dictionary['a'] = deepcopy(a)
172 m(dictionary['a'], b, c, d)
173 self.assertEqual(dictionary['a'], res)
174 dictionary['a'] = deepcopy(a)
175 bm = getattr(dictionary['a'], meth)
176 bm(b, c, d)
177 self.assertEqual(dictionary['a'], res)
178
179 def test_lists(self):
180 # Testing list operations...
181 # Asserts are within individual test methods
182 self.binop_test([1], [2], [1,2], "a+b", "__add__")
183 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
184 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
185 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
186 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
187 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
188 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
189 self.unop_test([1,2,3], 3, "len(a)", "__len__")
190 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
191 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
192 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
193 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
194 "__setslice__")
195
196 def test_dicts(self):
197 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000198 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
199 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
200 else:
201 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000202 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
203 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
204 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
205
206 d = {1:2, 3:4}
207 l1 = []
208 for i in d.keys():
209 l1.append(i)
210 l = []
211 for i in iter(d):
212 l.append(i)
213 self.assertEqual(l, l1)
214 l = []
215 for i in d.__iter__():
216 l.append(i)
217 self.assertEqual(l, l1)
218 l = []
219 for i in dict.__iter__(d):
220 l.append(i)
221 self.assertEqual(l, l1)
222 d = {1:2, 3:4}
223 self.unop_test(d, 2, "len(a)", "__len__")
224 self.assertEqual(eval(repr(d), {}), d)
225 self.assertEqual(eval(d.__repr__(), {}), d)
226 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
227 "__setitem__")
228
229 # Tests for unary and binary operators
230 def number_operators(self, a, b, skip=[]):
231 dict = {'a': a, 'b': b}
232
233 for name, expr in self.binops.items():
234 if name not in skip:
235 name = "__%s__" % name
236 if hasattr(a, name):
237 res = eval(expr, dict)
238 self.binop_test(a, b, res, expr, name)
239
240 for name, expr in self.unops.items():
241 if name not in skip:
242 name = "__%s__" % name
243 if hasattr(a, name):
244 res = eval(expr, dict)
245 self.unop_test(a, res, expr, name)
246
247 def test_ints(self):
248 # Testing int operations...
249 self.number_operators(100, 3)
250 # The following crashes in Python 2.2
251 self.assertEqual((1).__nonzero__(), 1)
252 self.assertEqual((0).__nonzero__(), 0)
253 # This returns 'NotImplemented' in Python 2.2
254 class C(int):
255 def __add__(self, other):
256 return NotImplemented
257 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000258 try:
Georg Brandl48545522008-02-02 10:12:36 +0000259 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000260 except TypeError:
261 pass
262 else:
Georg Brandl48545522008-02-02 10:12:36 +0000263 self.fail("NotImplemented should have caused TypeError")
264 import sys
Tim Peters1fc240e2001-10-26 05:06:50 +0000265 try:
Georg Brandl48545522008-02-02 10:12:36 +0000266 C(sys.maxint+1)
267 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000268 pass
269 else:
Georg Brandl48545522008-02-02 10:12:36 +0000270 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000271
Georg Brandl48545522008-02-02 10:12:36 +0000272 def test_longs(self):
273 # Testing long operations...
274 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275
Georg Brandl48545522008-02-02 10:12:36 +0000276 def test_floats(self):
277 # Testing float operations...
278 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000279
Georg Brandl48545522008-02-02 10:12:36 +0000280 def test_complexes(self):
281 # Testing complex operations...
282 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
283 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000284
Georg Brandl48545522008-02-02 10:12:36 +0000285 class Number(complex):
286 __slots__ = ['prec']
287 def __new__(cls, *args, **kwds):
288 result = complex.__new__(cls, *args)
289 result.prec = kwds.get('prec', 12)
290 return result
291 def __repr__(self):
292 prec = self.prec
293 if self.imag == 0.0:
294 return "%.*g" % (prec, self.real)
295 if self.real == 0.0:
296 return "%.*gj" % (prec, self.imag)
297 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
298 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000299
Georg Brandl48545522008-02-02 10:12:36 +0000300 a = Number(3.14, prec=6)
301 self.assertEqual(repr(a), "3.14")
302 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000303
Georg Brandl48545522008-02-02 10:12:36 +0000304 a = Number(a, prec=2)
305 self.assertEqual(repr(a), "3.1")
306 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000307
Georg Brandl48545522008-02-02 10:12:36 +0000308 a = Number(234.5)
309 self.assertEqual(repr(a), "234.5")
310 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000311
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000312 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000313 def test_spam_lists(self):
314 # Testing spamlist operations...
315 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000316
Georg Brandl48545522008-02-02 10:12:36 +0000317 def spamlist(l, memo=None):
318 import xxsubtype as spam
319 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000320
Georg Brandl48545522008-02-02 10:12:36 +0000321 # This is an ugly hack:
322 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000323
Georg Brandl48545522008-02-02 10:12:36 +0000324 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
325 "__add__")
326 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
327 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
328 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
329 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
330 "__getslice__")
331 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
332 "__iadd__")
333 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
334 "__imul__")
335 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
336 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
337 "__mul__")
338 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
339 "__rmul__")
340 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
341 "__setitem__")
342 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
343 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
344 # Test subclassing
345 class C(spam.spamlist):
346 def foo(self): return 1
347 a = C()
348 self.assertEqual(a, [])
349 self.assertEqual(a.foo(), 1)
350 a.append(100)
351 self.assertEqual(a, [100])
352 self.assertEqual(a.getstate(), 0)
353 a.setstate(42)
354 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000355
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000356 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000357 def test_spam_dicts(self):
358 # Testing spamdict operations...
359 import copy, xxsubtype as spam
360 def spamdict(d, memo=None):
361 import xxsubtype as spam
362 sd = spam.spamdict()
363 for k, v in d.items():
364 sd[k] = v
365 return sd
366 # This is an ugly hack:
367 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000368
Georg Brandl48545522008-02-02 10:12:36 +0000369 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
370 "__cmp__")
371 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
372 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
373 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
374 d = spamdict({1:2,3:4})
375 l1 = []
376 for i in d.keys():
377 l1.append(i)
378 l = []
379 for i in iter(d):
380 l.append(i)
381 self.assertEqual(l, l1)
382 l = []
383 for i in d.__iter__():
384 l.append(i)
385 self.assertEqual(l, l1)
386 l = []
387 for i in type(spamdict({})).__iter__(d):
388 l.append(i)
389 self.assertEqual(l, l1)
390 straightd = {1:2, 3:4}
391 spamd = spamdict(straightd)
392 self.unop_test(spamd, 2, "len(a)", "__len__")
393 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
394 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
395 "a[b]=c", "__setitem__")
396 # Test subclassing
397 class C(spam.spamdict):
398 def foo(self): return 1
399 a = C()
400 self.assertEqual(a.items(), [])
401 self.assertEqual(a.foo(), 1)
402 a['foo'] = 'bar'
403 self.assertEqual(a.items(), [('foo', 'bar')])
404 self.assertEqual(a.getstate(), 0)
405 a.setstate(100)
406 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000407
Georg Brandl48545522008-02-02 10:12:36 +0000408class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000409
Georg Brandl48545522008-02-02 10:12:36 +0000410 def test_python_dicts(self):
411 # Testing Python subclass of dict...
412 self.assert_(issubclass(dict, dict))
413 self.assert_(isinstance({}, dict))
414 d = dict()
415 self.assertEqual(d, {})
416 self.assert_(d.__class__ is dict)
417 self.assert_(isinstance(d, dict))
418 class C(dict):
419 state = -1
420 def __init__(self_local, *a, **kw):
421 if a:
422 self.assertEqual(len(a), 1)
423 self_local.state = a[0]
424 if kw:
425 for k, v in kw.items():
426 self_local[v] = k
427 def __getitem__(self, key):
428 return self.get(key, 0)
429 def __setitem__(self_local, key, value):
430 self.assert_(isinstance(key, type(0)))
431 dict.__setitem__(self_local, key, value)
432 def setstate(self, state):
433 self.state = state
434 def getstate(self):
435 return self.state
436 self.assert_(issubclass(C, dict))
437 a1 = C(12)
438 self.assertEqual(a1.state, 12)
439 a2 = C(foo=1, bar=2)
440 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
441 a = C()
442 self.assertEqual(a.state, -1)
443 self.assertEqual(a.getstate(), -1)
444 a.setstate(0)
445 self.assertEqual(a.state, 0)
446 self.assertEqual(a.getstate(), 0)
447 a.setstate(10)
448 self.assertEqual(a.state, 10)
449 self.assertEqual(a.getstate(), 10)
450 self.assertEqual(a[42], 0)
451 a[42] = 24
452 self.assertEqual(a[42], 24)
453 N = 50
454 for i in range(N):
455 a[i] = C()
456 for j in range(N):
457 a[i][j] = i*j
458 for i in range(N):
459 for j in range(N):
460 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000461
Georg Brandl48545522008-02-02 10:12:36 +0000462 def test_python_lists(self):
463 # Testing Python subclass of list...
464 class C(list):
465 def __getitem__(self, i):
466 return list.__getitem__(self, i) + 100
467 def __getslice__(self, i, j):
468 return (i, j)
469 a = C()
470 a.extend([0,1,2])
471 self.assertEqual(a[0], 100)
472 self.assertEqual(a[1], 101)
473 self.assertEqual(a[2], 102)
474 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000475
Georg Brandl48545522008-02-02 10:12:36 +0000476 def test_metaclass(self):
477 # Testing __metaclass__...
478 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000479 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000480 def __init__(self):
481 self.__state = 0
482 def getstate(self):
483 return self.__state
484 def setstate(self, state):
485 self.__state = state
486 a = C()
487 self.assertEqual(a.getstate(), 0)
488 a.setstate(10)
489 self.assertEqual(a.getstate(), 10)
490 class D:
491 class __metaclass__(type):
492 def myself(cls): return cls
493 self.assertEqual(D.myself(), D)
494 d = D()
495 self.assertEqual(d.__class__, D)
496 class M1(type):
497 def __new__(cls, name, bases, dict):
498 dict['__spam__'] = 1
499 return type.__new__(cls, name, bases, dict)
500 class C:
501 __metaclass__ = M1
502 self.assertEqual(C.__spam__, 1)
503 c = C()
504 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000505
Georg Brandl48545522008-02-02 10:12:36 +0000506 class _instance(object):
507 pass
508 class M2(object):
509 @staticmethod
510 def __new__(cls, name, bases, dict):
511 self = object.__new__(cls)
512 self.name = name
513 self.bases = bases
514 self.dict = dict
515 return self
516 def __call__(self):
517 it = _instance()
518 # Early binding of methods
519 for key in self.dict:
520 if key.startswith("__"):
521 continue
522 setattr(it, key, self.dict[key].__get__(it, self))
523 return it
524 class C:
525 __metaclass__ = M2
526 def spam(self):
527 return 42
528 self.assertEqual(C.name, 'C')
529 self.assertEqual(C.bases, ())
530 self.assert_('spam' in C.dict)
531 c = C()
532 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000533
Georg Brandl48545522008-02-02 10:12:36 +0000534 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000535
Georg Brandl48545522008-02-02 10:12:36 +0000536 class autosuper(type):
537 # Automatically add __super to the class
538 # This trick only works for dynamic classes
539 def __new__(metaclass, name, bases, dict):
540 cls = super(autosuper, metaclass).__new__(metaclass,
541 name, bases, dict)
542 # Name mangling for __super removes leading underscores
543 while name[:1] == "_":
544 name = name[1:]
545 if name:
546 name = "_%s__super" % name
547 else:
548 name = "__super"
549 setattr(cls, name, super(cls))
550 return cls
551 class A:
552 __metaclass__ = autosuper
553 def meth(self):
554 return "A"
555 class B(A):
556 def meth(self):
557 return "B" + self.__super.meth()
558 class C(A):
559 def meth(self):
560 return "C" + self.__super.meth()
561 class D(C, B):
562 def meth(self):
563 return "D" + self.__super.meth()
564 self.assertEqual(D().meth(), "DCBA")
565 class E(B, C):
566 def meth(self):
567 return "E" + self.__super.meth()
568 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000569
Georg Brandl48545522008-02-02 10:12:36 +0000570 class autoproperty(type):
571 # Automatically create property attributes when methods
572 # named _get_x and/or _set_x are found
573 def __new__(metaclass, name, bases, dict):
574 hits = {}
575 for key, val in dict.iteritems():
576 if key.startswith("_get_"):
577 key = key[5:]
578 get, set = hits.get(key, (None, None))
579 get = val
580 hits[key] = get, set
581 elif key.startswith("_set_"):
582 key = key[5:]
583 get, set = hits.get(key, (None, None))
584 set = val
585 hits[key] = get, set
586 for key, (get, set) in hits.iteritems():
587 dict[key] = property(get, set)
588 return super(autoproperty, metaclass).__new__(metaclass,
589 name, bases, dict)
590 class A:
591 __metaclass__ = autoproperty
592 def _get_x(self):
593 return -self.__x
594 def _set_x(self, x):
595 self.__x = -x
596 a = A()
597 self.assert_(not hasattr(a, "x"))
598 a.x = 12
599 self.assertEqual(a.x, 12)
600 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000601
Georg Brandl48545522008-02-02 10:12:36 +0000602 class multimetaclass(autoproperty, autosuper):
603 # Merge of multiple cooperating metaclasses
604 pass
605 class A:
606 __metaclass__ = multimetaclass
607 def _get_x(self):
608 return "A"
609 class B(A):
610 def _get_x(self):
611 return "B" + self.__super._get_x()
612 class C(A):
613 def _get_x(self):
614 return "C" + self.__super._get_x()
615 class D(C, B):
616 def _get_x(self):
617 return "D" + self.__super._get_x()
618 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000619
Georg Brandl48545522008-02-02 10:12:36 +0000620 # Make sure type(x) doesn't call x.__class__.__init__
621 class T(type):
622 counter = 0
623 def __init__(self, *args):
624 T.counter += 1
625 class C:
626 __metaclass__ = T
627 self.assertEqual(T.counter, 1)
628 a = C()
629 self.assertEqual(type(a), C)
630 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000631
Georg Brandl48545522008-02-02 10:12:36 +0000632 class C(object): pass
633 c = C()
634 try: c()
635 except TypeError: pass
636 else: self.fail("calling object w/o call method should raise "
637 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000638
Georg Brandl48545522008-02-02 10:12:36 +0000639 # Testing code to find most derived baseclass
640 class A(type):
641 def __new__(*args, **kwargs):
642 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000643
Georg Brandl48545522008-02-02 10:12:36 +0000644 class B(object):
645 pass
646
647 class C(object):
648 __metaclass__ = A
649
650 # The most derived metaclass of D is A rather than type.
651 class D(B, C):
652 pass
653
654 def test_module_subclasses(self):
655 # Testing Python subclass of module...
656 log = []
657 import types, sys
658 MT = type(sys)
659 class MM(MT):
660 def __init__(self, name):
661 MT.__init__(self, name)
662 def __getattribute__(self, name):
663 log.append(("getattr", name))
664 return MT.__getattribute__(self, name)
665 def __setattr__(self, name, value):
666 log.append(("setattr", name, value))
667 MT.__setattr__(self, name, value)
668 def __delattr__(self, name):
669 log.append(("delattr", name))
670 MT.__delattr__(self, name)
671 a = MM("a")
672 a.foo = 12
673 x = a.foo
674 del a.foo
675 self.assertEqual(log, [("setattr", "foo", 12),
676 ("getattr", "foo"),
677 ("delattr", "foo")])
678
679 # http://python.org/sf/1174712
680 try:
681 class Module(types.ModuleType, str):
682 pass
683 except TypeError:
684 pass
685 else:
686 self.fail("inheriting from ModuleType and str at the same time "
687 "should fail")
688
689 def test_multiple_inheritence(self):
690 # Testing multiple inheritance...
691 class C(object):
692 def __init__(self):
693 self.__state = 0
694 def getstate(self):
695 return self.__state
696 def setstate(self, state):
697 self.__state = state
698 a = C()
699 self.assertEqual(a.getstate(), 0)
700 a.setstate(10)
701 self.assertEqual(a.getstate(), 10)
702 class D(dict, C):
703 def __init__(self):
704 type({}).__init__(self)
705 C.__init__(self)
706 d = D()
707 self.assertEqual(d.keys(), [])
708 d["hello"] = "world"
709 self.assertEqual(d.items(), [("hello", "world")])
710 self.assertEqual(d["hello"], "world")
711 self.assertEqual(d.getstate(), 0)
712 d.setstate(10)
713 self.assertEqual(d.getstate(), 10)
714 self.assertEqual(D.__mro__, (D, dict, C, object))
715
716 # SF bug #442833
717 class Node(object):
718 def __int__(self):
719 return int(self.foo())
720 def foo(self):
721 return "23"
722 class Frag(Node, list):
723 def foo(self):
724 return "42"
725 self.assertEqual(Node().__int__(), 23)
726 self.assertEqual(int(Node()), 23)
727 self.assertEqual(Frag().__int__(), 42)
728 self.assertEqual(int(Frag()), 42)
729
730 # MI mixing classic and new-style classes.
731
732 class A:
733 x = 1
734
735 class B(A):
736 pass
737
738 class C(A):
739 x = 2
740
741 class D(B, C):
742 pass
743 self.assertEqual(D.x, 1)
744
745 # Classic MRO is preserved for a classic base class.
746 class E(D, object):
747 pass
748 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
749 self.assertEqual(E.x, 1)
750
751 # But with a mix of classic bases, their MROs are combined using
752 # new-style MRO.
753 class F(B, C, object):
754 pass
755 self.assertEqual(F.__mro__, (F, B, C, A, object))
756 self.assertEqual(F.x, 2)
757
758 # Try something else.
759 class C:
760 def cmethod(self):
761 return "C a"
762 def all_method(self):
763 return "C b"
764
765 class M1(C, object):
766 def m1method(self):
767 return "M1 a"
768 def all_method(self):
769 return "M1 b"
770
771 self.assertEqual(M1.__mro__, (M1, C, object))
772 m = M1()
773 self.assertEqual(m.cmethod(), "C a")
774 self.assertEqual(m.m1method(), "M1 a")
775 self.assertEqual(m.all_method(), "M1 b")
776
777 class D(C):
778 def dmethod(self):
779 return "D a"
780 def all_method(self):
781 return "D b"
782
783 class M2(D, object):
784 def m2method(self):
785 return "M2 a"
786 def all_method(self):
787 return "M2 b"
788
789 self.assertEqual(M2.__mro__, (M2, D, C, object))
790 m = M2()
791 self.assertEqual(m.cmethod(), "C a")
792 self.assertEqual(m.dmethod(), "D a")
793 self.assertEqual(m.m2method(), "M2 a")
794 self.assertEqual(m.all_method(), "M2 b")
795
796 class M3(M1, M2, object):
797 def m3method(self):
798 return "M3 a"
799 def all_method(self):
800 return "M3 b"
801 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
802 m = M3()
803 self.assertEqual(m.cmethod(), "C a")
804 self.assertEqual(m.dmethod(), "D a")
805 self.assertEqual(m.m1method(), "M1 a")
806 self.assertEqual(m.m2method(), "M2 a")
807 self.assertEqual(m.m3method(), "M3 a")
808 self.assertEqual(m.all_method(), "M3 b")
809
810 class Classic:
811 pass
812 try:
813 class New(Classic):
814 __metaclass__ = type
815 except TypeError:
816 pass
817 else:
818 self.fail("new class with only classic bases - shouldn't be")
819
820 def test_diamond_inheritence(self):
821 # Testing multiple inheritance special cases...
822 class A(object):
823 def spam(self): return "A"
824 self.assertEqual(A().spam(), "A")
825 class B(A):
826 def boo(self): return "B"
827 def spam(self): return "B"
828 self.assertEqual(B().spam(), "B")
829 self.assertEqual(B().boo(), "B")
830 class C(A):
831 def boo(self): return "C"
832 self.assertEqual(C().spam(), "A")
833 self.assertEqual(C().boo(), "C")
834 class D(B, C): pass
835 self.assertEqual(D().spam(), "B")
836 self.assertEqual(D().boo(), "B")
837 self.assertEqual(D.__mro__, (D, B, C, A, object))
838 class E(C, B): pass
839 self.assertEqual(E().spam(), "B")
840 self.assertEqual(E().boo(), "C")
841 self.assertEqual(E.__mro__, (E, C, B, A, object))
842 # MRO order disagreement
843 try:
844 class F(D, E): pass
845 except TypeError:
846 pass
847 else:
848 self.fail("expected MRO order disagreement (F)")
849 try:
850 class G(E, D): pass
851 except TypeError:
852 pass
853 else:
854 self.fail("expected MRO order disagreement (G)")
855
856 # see thread python-dev/2002-October/029035.html
857 def test_ex5_from_c3_switch(self):
858 # Testing ex5 from C3 switch discussion...
859 class A(object): pass
860 class B(object): pass
861 class C(object): pass
862 class X(A): pass
863 class Y(A): pass
864 class Z(X,B,Y,C): pass
865 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
866
867 # see "A Monotonic Superclass Linearization for Dylan",
868 # by Kim Barrett et al. (OOPSLA 1996)
869 def test_monotonicity(self):
870 # Testing MRO monotonicity...
871 class Boat(object): pass
872 class DayBoat(Boat): pass
873 class WheelBoat(Boat): pass
874 class EngineLess(DayBoat): pass
875 class SmallMultihull(DayBoat): pass
876 class PedalWheelBoat(EngineLess,WheelBoat): pass
877 class SmallCatamaran(SmallMultihull): pass
878 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
879
880 self.assertEqual(PedalWheelBoat.__mro__,
881 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
882 self.assertEqual(SmallCatamaran.__mro__,
883 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
884 self.assertEqual(Pedalo.__mro__,
885 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
886 SmallMultihull, DayBoat, WheelBoat, Boat, object))
887
888 # see "A Monotonic Superclass Linearization for Dylan",
889 # by Kim Barrett et al. (OOPSLA 1996)
890 def test_consistency_with_epg(self):
891 # Testing consistentcy with EPG...
892 class Pane(object): pass
893 class ScrollingMixin(object): pass
894 class EditingMixin(object): pass
895 class ScrollablePane(Pane,ScrollingMixin): pass
896 class EditablePane(Pane,EditingMixin): pass
897 class EditableScrollablePane(ScrollablePane,EditablePane): pass
898
899 self.assertEqual(EditableScrollablePane.__mro__,
900 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
901 ScrollingMixin, EditingMixin, object))
902
903 def test_mro_disagreement(self):
904 # Testing error messages for MRO disagreement...
905 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000906order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000907
Georg Brandl48545522008-02-02 10:12:36 +0000908 def raises(exc, expected, callable, *args):
909 try:
910 callable(*args)
911 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000912 # the exact msg is generally considered an impl detail
913 if test_support.check_impl_detail():
914 if not str(msg).startswith(expected):
915 self.fail("Message %r, expected %r" %
916 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000917 else:
918 self.fail("Expected %s" % exc)
919
920 class A(object): pass
921 class B(A): pass
922 class C(object): pass
923
924 # Test some very simple errors
925 raises(TypeError, "duplicate base class A",
926 type, "X", (A, A), {})
927 raises(TypeError, mro_err_msg,
928 type, "X", (A, B), {})
929 raises(TypeError, mro_err_msg,
930 type, "X", (A, C, B), {})
931 # Test a slightly more complex error
932 class GridLayout(object): pass
933 class HorizontalGrid(GridLayout): pass
934 class VerticalGrid(GridLayout): pass
935 class HVGrid(HorizontalGrid, VerticalGrid): pass
936 class VHGrid(VerticalGrid, HorizontalGrid): pass
937 raises(TypeError, mro_err_msg,
938 type, "ConfusedGrid", (HVGrid, VHGrid), {})
939
940 def test_object_class(self):
941 # Testing object class...
942 a = object()
943 self.assertEqual(a.__class__, object)
944 self.assertEqual(type(a), object)
945 b = object()
946 self.assertNotEqual(a, b)
947 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000948 try:
Georg Brandl48545522008-02-02 10:12:36 +0000949 a.foo = 12
950 except (AttributeError, TypeError):
951 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000952 else:
Georg Brandl48545522008-02-02 10:12:36 +0000953 self.fail("object() should not allow setting a foo attribute")
954 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000955
Georg Brandl48545522008-02-02 10:12:36 +0000956 class Cdict(object):
957 pass
958 x = Cdict()
959 self.assertEqual(x.__dict__, {})
960 x.foo = 1
961 self.assertEqual(x.foo, 1)
962 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000963
Georg Brandl48545522008-02-02 10:12:36 +0000964 def test_slots(self):
965 # Testing __slots__...
966 class C0(object):
967 __slots__ = []
968 x = C0()
969 self.assertFalse(hasattr(x, "__dict__"))
970 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000971
Georg Brandl48545522008-02-02 10:12:36 +0000972 class C1(object):
973 __slots__ = ['a']
974 x = C1()
975 self.assertFalse(hasattr(x, "__dict__"))
976 self.assertFalse(hasattr(x, "a"))
977 x.a = 1
978 self.assertEqual(x.a, 1)
979 x.a = None
980 self.assertEqual(x.a, None)
981 del x.a
982 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983
Georg Brandl48545522008-02-02 10:12:36 +0000984 class C3(object):
985 __slots__ = ['a', 'b', 'c']
986 x = C3()
987 self.assertFalse(hasattr(x, "__dict__"))
988 self.assertFalse(hasattr(x, 'a'))
989 self.assertFalse(hasattr(x, 'b'))
990 self.assertFalse(hasattr(x, 'c'))
991 x.a = 1
992 x.b = 2
993 x.c = 3
994 self.assertEqual(x.a, 1)
995 self.assertEqual(x.b, 2)
996 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997
Georg Brandl48545522008-02-02 10:12:36 +0000998 class C4(object):
999 """Validate name mangling"""
1000 __slots__ = ['__a']
1001 def __init__(self, value):
1002 self.__a = value
1003 def get(self):
1004 return self.__a
1005 x = C4(5)
1006 self.assertFalse(hasattr(x, '__dict__'))
1007 self.assertFalse(hasattr(x, '__a'))
1008 self.assertEqual(x.get(), 5)
1009 try:
1010 x.__a = 6
1011 except AttributeError:
1012 pass
1013 else:
1014 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015
Georg Brandl48545522008-02-02 10:12:36 +00001016 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001017 try:
1018 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001019 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001020 except TypeError:
1021 pass
1022 else:
Georg Brandl48545522008-02-02 10:12:36 +00001023 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001024 try:
Georg Brandl48545522008-02-02 10:12:36 +00001025 class C(object):
1026 __slots__ = ["foo bar"]
1027 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001028 pass
Georg Brandl48545522008-02-02 10:12:36 +00001029 else:
1030 self.fail("['foo bar'] slots not caught")
1031 try:
1032 class C(object):
1033 __slots__ = ["foo\0bar"]
1034 except TypeError:
1035 pass
1036 else:
1037 self.fail("['foo\\0bar'] slots not caught")
1038 try:
1039 class C(object):
1040 __slots__ = ["1"]
1041 except TypeError:
1042 pass
1043 else:
1044 self.fail("['1'] slots not caught")
1045 try:
1046 class C(object):
1047 __slots__ = [""]
1048 except TypeError:
1049 pass
1050 else:
1051 self.fail("[''] slots not caught")
1052 class C(object):
1053 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1054 # XXX(nnorwitz): was there supposed to be something tested
1055 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001056
Georg Brandl48545522008-02-02 10:12:36 +00001057 # Test a single string is not expanded as a sequence.
1058 class C(object):
1059 __slots__ = "abc"
1060 c = C()
1061 c.abc = 5
1062 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001063
Georg Brandl48545522008-02-02 10:12:36 +00001064 # Test unicode slot names
1065 try:
1066 unicode
1067 except NameError:
1068 pass
1069 else:
1070 # Test a single unicode string is not expanded as a sequence.
1071 class C(object):
1072 __slots__ = unicode("abc")
1073 c = C()
1074 c.abc = 5
1075 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001076
Georg Brandl48545522008-02-02 10:12:36 +00001077 # _unicode_to_string used to modify slots in certain circumstances
1078 slots = (unicode("foo"), unicode("bar"))
1079 class C(object):
1080 __slots__ = slots
1081 x = C()
1082 x.foo = 5
1083 self.assertEqual(x.foo, 5)
1084 self.assertEqual(type(slots[0]), unicode)
1085 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001086 try:
Georg Brandl48545522008-02-02 10:12:36 +00001087 class C(object):
1088 __slots__ = [unichr(128)]
1089 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001090 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001091 else:
Georg Brandl48545522008-02-02 10:12:36 +00001092 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001093
Georg Brandl48545522008-02-02 10:12:36 +00001094 # Test leaks
1095 class Counted(object):
1096 counter = 0 # counts the number of instances alive
1097 def __init__(self):
1098 Counted.counter += 1
1099 def __del__(self):
1100 Counted.counter -= 1
1101 class C(object):
1102 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001103 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001104 x.a = Counted()
1105 x.b = Counted()
1106 x.c = Counted()
1107 self.assertEqual(Counted.counter, 3)
1108 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001109 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001110 self.assertEqual(Counted.counter, 0)
1111 class D(C):
1112 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001113 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001114 x.a = Counted()
1115 x.z = Counted()
1116 self.assertEqual(Counted.counter, 2)
1117 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001118 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001119 self.assertEqual(Counted.counter, 0)
1120 class E(D):
1121 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001122 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001123 x.a = Counted()
1124 x.z = Counted()
1125 x.e = Counted()
1126 self.assertEqual(Counted.counter, 3)
1127 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001128 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001129 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001130
Georg Brandl48545522008-02-02 10:12:36 +00001131 # Test cyclical leaks [SF bug 519621]
1132 class F(object):
1133 __slots__ = ['a', 'b']
1134 log = []
1135 s = F()
1136 s.a = [Counted(), s]
1137 self.assertEqual(Counted.counter, 1)
1138 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001139 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001140 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001141
Georg Brandl48545522008-02-02 10:12:36 +00001142 # Test lookup leaks [SF bug 572567]
1143 import sys,gc
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001144 if hasattr(gc, 'get_objects'):
1145 class G(object):
1146 def __cmp__(self, other):
1147 return 0
1148 __hash__ = None # Silence Py3k warning
1149 g = G()
1150 orig_objects = len(gc.get_objects())
1151 for i in xrange(10):
1152 g==g
1153 new_objects = len(gc.get_objects())
1154 self.assertEqual(orig_objects, new_objects)
1155
Georg Brandl48545522008-02-02 10:12:36 +00001156 class H(object):
1157 __slots__ = ['a', 'b']
1158 def __init__(self):
1159 self.a = 1
1160 self.b = 2
1161 def __del__(self_):
1162 self.assertEqual(self_.a, 1)
1163 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001164 with test_support.captured_output('stderr') as s:
1165 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001166 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001167 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001168
Georg Brandl48545522008-02-02 10:12:36 +00001169 def test_slots_special(self):
1170 # Testing __dict__ and __weakref__ in __slots__...
1171 class D(object):
1172 __slots__ = ["__dict__"]
1173 a = D()
1174 self.assert_(hasattr(a, "__dict__"))
1175 self.assertFalse(hasattr(a, "__weakref__"))
1176 a.foo = 42
1177 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001178
Georg Brandl48545522008-02-02 10:12:36 +00001179 class W(object):
1180 __slots__ = ["__weakref__"]
1181 a = W()
1182 self.assert_(hasattr(a, "__weakref__"))
1183 self.assertFalse(hasattr(a, "__dict__"))
1184 try:
1185 a.foo = 42
1186 except AttributeError:
1187 pass
1188 else:
1189 self.fail("shouldn't be allowed to set a.foo")
1190
1191 class C1(W, D):
1192 __slots__ = []
1193 a = C1()
1194 self.assert_(hasattr(a, "__dict__"))
1195 self.assert_(hasattr(a, "__weakref__"))
1196 a.foo = 42
1197 self.assertEqual(a.__dict__, {"foo": 42})
1198
1199 class C2(D, W):
1200 __slots__ = []
1201 a = C2()
1202 self.assert_(hasattr(a, "__dict__"))
1203 self.assert_(hasattr(a, "__weakref__"))
1204 a.foo = 42
1205 self.assertEqual(a.__dict__, {"foo": 42})
1206
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001207 def test_slots_descriptor(self):
1208 # Issue2115: slot descriptors did not correctly check
1209 # the type of the given object
1210 import abc
1211 class MyABC:
1212 __metaclass__ = abc.ABCMeta
1213 __slots__ = "a"
1214
1215 class Unrelated(object):
1216 pass
1217 MyABC.register(Unrelated)
1218
1219 u = Unrelated()
1220 self.assert_(isinstance(u, MyABC))
1221
1222 # This used to crash
1223 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1224
Georg Brandl48545522008-02-02 10:12:36 +00001225 def test_dynamics(self):
1226 # Testing class attribute propagation...
1227 class D(object):
1228 pass
1229 class E(D):
1230 pass
1231 class F(D):
1232 pass
1233 D.foo = 1
1234 self.assertEqual(D.foo, 1)
1235 # Test that dynamic attributes are inherited
1236 self.assertEqual(E.foo, 1)
1237 self.assertEqual(F.foo, 1)
1238 # Test dynamic instances
1239 class C(object):
1240 pass
1241 a = C()
1242 self.assertFalse(hasattr(a, "foobar"))
1243 C.foobar = 2
1244 self.assertEqual(a.foobar, 2)
1245 C.method = lambda self: 42
1246 self.assertEqual(a.method(), 42)
1247 C.__repr__ = lambda self: "C()"
1248 self.assertEqual(repr(a), "C()")
1249 C.__int__ = lambda self: 100
1250 self.assertEqual(int(a), 100)
1251 self.assertEqual(a.foobar, 2)
1252 self.assertFalse(hasattr(a, "spam"))
1253 def mygetattr(self, name):
1254 if name == "spam":
1255 return "spam"
1256 raise AttributeError
1257 C.__getattr__ = mygetattr
1258 self.assertEqual(a.spam, "spam")
1259 a.new = 12
1260 self.assertEqual(a.new, 12)
1261 def mysetattr(self, name, value):
1262 if name == "spam":
1263 raise AttributeError
1264 return object.__setattr__(self, name, value)
1265 C.__setattr__ = mysetattr
1266 try:
1267 a.spam = "not spam"
1268 except AttributeError:
1269 pass
1270 else:
1271 self.fail("expected AttributeError")
1272 self.assertEqual(a.spam, "spam")
1273 class D(C):
1274 pass
1275 d = D()
1276 d.foo = 1
1277 self.assertEqual(d.foo, 1)
1278
1279 # Test handling of int*seq and seq*int
1280 class I(int):
1281 pass
1282 self.assertEqual("a"*I(2), "aa")
1283 self.assertEqual(I(2)*"a", "aa")
1284 self.assertEqual(2*I(3), 6)
1285 self.assertEqual(I(3)*2, 6)
1286 self.assertEqual(I(3)*I(2), 6)
1287
1288 # Test handling of long*seq and seq*long
1289 class L(long):
1290 pass
1291 self.assertEqual("a"*L(2L), "aa")
1292 self.assertEqual(L(2L)*"a", "aa")
1293 self.assertEqual(2*L(3), 6)
1294 self.assertEqual(L(3)*2, 6)
1295 self.assertEqual(L(3)*L(2), 6)
1296
1297 # Test comparison of classes with dynamic metaclasses
1298 class dynamicmetaclass(type):
1299 pass
1300 class someclass:
1301 __metaclass__ = dynamicmetaclass
1302 self.assertNotEqual(someclass, object)
1303
1304 def test_errors(self):
1305 # Testing errors...
1306 try:
1307 class C(list, dict):
1308 pass
1309 except TypeError:
1310 pass
1311 else:
1312 self.fail("inheritance from both list and dict should be illegal")
1313
1314 try:
1315 class C(object, None):
1316 pass
1317 except TypeError:
1318 pass
1319 else:
1320 self.fail("inheritance from non-type should be illegal")
1321 class Classic:
1322 pass
1323
1324 try:
1325 class C(type(len)):
1326 pass
1327 except TypeError:
1328 pass
1329 else:
1330 self.fail("inheritance from CFunction should be illegal")
1331
1332 try:
1333 class C(object):
1334 __slots__ = 1
1335 except TypeError:
1336 pass
1337 else:
1338 self.fail("__slots__ = 1 should be illegal")
1339
1340 try:
1341 class C(object):
1342 __slots__ = [1]
1343 except TypeError:
1344 pass
1345 else:
1346 self.fail("__slots__ = [1] should be illegal")
1347
1348 class M1(type):
1349 pass
1350 class M2(type):
1351 pass
1352 class A1(object):
1353 __metaclass__ = M1
1354 class A2(object):
1355 __metaclass__ = M2
1356 try:
1357 class B(A1, A2):
1358 pass
1359 except TypeError:
1360 pass
1361 else:
1362 self.fail("finding the most derived metaclass should have failed")
1363
1364 def test_classmethods(self):
1365 # Testing class methods...
1366 class C(object):
1367 def foo(*a): return a
1368 goo = classmethod(foo)
1369 c = C()
1370 self.assertEqual(C.goo(1), (C, 1))
1371 self.assertEqual(c.goo(1), (C, 1))
1372 self.assertEqual(c.foo(1), (c, 1))
1373 class D(C):
1374 pass
1375 d = D()
1376 self.assertEqual(D.goo(1), (D, 1))
1377 self.assertEqual(d.goo(1), (D, 1))
1378 self.assertEqual(d.foo(1), (d, 1))
1379 self.assertEqual(D.foo(d, 1), (d, 1))
1380 # Test for a specific crash (SF bug 528132)
1381 def f(cls, arg): return (cls, arg)
1382 ff = classmethod(f)
1383 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1384 self.assertEqual(ff.__get__(0)(42), (int, 42))
1385
1386 # Test super() with classmethods (SF bug 535444)
1387 self.assertEqual(C.goo.im_self, C)
1388 self.assertEqual(D.goo.im_self, D)
1389 self.assertEqual(super(D,D).goo.im_self, D)
1390 self.assertEqual(super(D,d).goo.im_self, D)
1391 self.assertEqual(super(D,D).goo(), (D,))
1392 self.assertEqual(super(D,d).goo(), (D,))
1393
1394 # Verify that argument is checked for callability (SF bug 753451)
1395 try:
1396 classmethod(1).__get__(1)
1397 except TypeError:
1398 pass
1399 else:
1400 self.fail("classmethod should check for callability")
1401
1402 # Verify that classmethod() doesn't allow keyword args
1403 try:
1404 classmethod(f, kw=1)
1405 except TypeError:
1406 pass
1407 else:
1408 self.fail("classmethod shouldn't accept keyword args")
1409
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001410 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001411 def test_classmethods_in_c(self):
1412 # Testing C-based class methods...
1413 import xxsubtype as spam
1414 a = (1, 2, 3)
1415 d = {'abc': 123}
1416 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1417 self.assertEqual(x, spam.spamlist)
1418 self.assertEqual(a, a1)
1419 self.assertEqual(d, d1)
1420 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1421 self.assertEqual(x, spam.spamlist)
1422 self.assertEqual(a, a1)
1423 self.assertEqual(d, d1)
1424
1425 def test_staticmethods(self):
1426 # Testing static methods...
1427 class C(object):
1428 def foo(*a): return a
1429 goo = staticmethod(foo)
1430 c = C()
1431 self.assertEqual(C.goo(1), (1,))
1432 self.assertEqual(c.goo(1), (1,))
1433 self.assertEqual(c.foo(1), (c, 1,))
1434 class D(C):
1435 pass
1436 d = D()
1437 self.assertEqual(D.goo(1), (1,))
1438 self.assertEqual(d.goo(1), (1,))
1439 self.assertEqual(d.foo(1), (d, 1))
1440 self.assertEqual(D.foo(d, 1), (d, 1))
1441
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001442 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001443 def test_staticmethods_in_c(self):
1444 # Testing C-based static methods...
1445 import xxsubtype as spam
1446 a = (1, 2, 3)
1447 d = {"abc": 123}
1448 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1449 self.assertEqual(x, None)
1450 self.assertEqual(a, a1)
1451 self.assertEqual(d, d1)
1452 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1453 self.assertEqual(x, None)
1454 self.assertEqual(a, a1)
1455 self.assertEqual(d, d1)
1456
1457 def test_classic(self):
1458 # Testing classic classes...
1459 class C:
1460 def foo(*a): return a
1461 goo = classmethod(foo)
1462 c = C()
1463 self.assertEqual(C.goo(1), (C, 1))
1464 self.assertEqual(c.goo(1), (C, 1))
1465 self.assertEqual(c.foo(1), (c, 1))
1466 class D(C):
1467 pass
1468 d = D()
1469 self.assertEqual(D.goo(1), (D, 1))
1470 self.assertEqual(d.goo(1), (D, 1))
1471 self.assertEqual(d.foo(1), (d, 1))
1472 self.assertEqual(D.foo(d, 1), (d, 1))
1473 class E: # *not* subclassing from C
1474 foo = C.foo
1475 self.assertEqual(E().foo, C.foo) # i.e., unbound
1476 self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
1477
1478 def test_compattr(self):
1479 # Testing computed attributes...
1480 class C(object):
1481 class computed_attribute(object):
1482 def __init__(self, get, set=None, delete=None):
1483 self.__get = get
1484 self.__set = set
1485 self.__delete = delete
1486 def __get__(self, obj, type=None):
1487 return self.__get(obj)
1488 def __set__(self, obj, value):
1489 return self.__set(obj, value)
1490 def __delete__(self, obj):
1491 return self.__delete(obj)
1492 def __init__(self):
1493 self.__x = 0
1494 def __get_x(self):
1495 x = self.__x
1496 self.__x = x+1
1497 return x
1498 def __set_x(self, x):
1499 self.__x = x
1500 def __delete_x(self):
1501 del self.__x
1502 x = computed_attribute(__get_x, __set_x, __delete_x)
1503 a = C()
1504 self.assertEqual(a.x, 0)
1505 self.assertEqual(a.x, 1)
1506 a.x = 10
1507 self.assertEqual(a.x, 10)
1508 self.assertEqual(a.x, 11)
1509 del a.x
1510 self.assertEqual(hasattr(a, 'x'), 0)
1511
1512 def test_newslots(self):
1513 # Testing __new__ slot override...
1514 class C(list):
1515 def __new__(cls):
1516 self = list.__new__(cls)
1517 self.foo = 1
1518 return self
1519 def __init__(self):
1520 self.foo = self.foo + 2
1521 a = C()
1522 self.assertEqual(a.foo, 3)
1523 self.assertEqual(a.__class__, C)
1524 class D(C):
1525 pass
1526 b = D()
1527 self.assertEqual(b.foo, 3)
1528 self.assertEqual(b.__class__, D)
1529
1530 def test_altmro(self):
1531 # Testing mro() and overriding it...
1532 class A(object):
1533 def f(self): return "A"
1534 class B(A):
1535 pass
1536 class C(A):
1537 def f(self): return "C"
1538 class D(B, C):
1539 pass
1540 self.assertEqual(D.mro(), [D, B, C, A, object])
1541 self.assertEqual(D.__mro__, (D, B, C, A, object))
1542 self.assertEqual(D().f(), "C")
1543
1544 class PerverseMetaType(type):
1545 def mro(cls):
1546 L = type.mro(cls)
1547 L.reverse()
1548 return L
1549 class X(D,B,C,A):
1550 __metaclass__ = PerverseMetaType
1551 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1552 self.assertEqual(X().f(), "A")
1553
1554 try:
1555 class X(object):
1556 class __metaclass__(type):
1557 def mro(self):
1558 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001559 # In CPython, the class creation above already raises
1560 # TypeError, as a protection against the fact that
1561 # instances of X would segfault it. In other Python
1562 # implementations it would be ok to let the class X
1563 # be created, but instead get a clean TypeError on the
1564 # __setitem__ below.
1565 x = object.__new__(X)
1566 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001567 except TypeError:
1568 pass
1569 else:
1570 self.fail("devious mro() return not caught")
1571
1572 try:
1573 class X(object):
1574 class __metaclass__(type):
1575 def mro(self):
1576 return [1]
1577 except TypeError:
1578 pass
1579 else:
1580 self.fail("non-class mro() return not caught")
1581
1582 try:
1583 class X(object):
1584 class __metaclass__(type):
1585 def mro(self):
1586 return 1
1587 except TypeError:
1588 pass
1589 else:
1590 self.fail("non-sequence mro() return not caught")
1591
1592 def test_overloading(self):
1593 # Testing operator overloading...
1594
1595 class B(object):
1596 "Intermediate class because object doesn't have a __setattr__"
1597
1598 class C(B):
1599 def __getattr__(self, name):
1600 if name == "foo":
1601 return ("getattr", name)
1602 else:
1603 raise AttributeError
1604 def __setattr__(self, name, value):
1605 if name == "foo":
1606 self.setattr = (name, value)
1607 else:
1608 return B.__setattr__(self, name, value)
1609 def __delattr__(self, name):
1610 if name == "foo":
1611 self.delattr = name
1612 else:
1613 return B.__delattr__(self, name)
1614
1615 def __getitem__(self, key):
1616 return ("getitem", key)
1617 def __setitem__(self, key, value):
1618 self.setitem = (key, value)
1619 def __delitem__(self, key):
1620 self.delitem = key
1621
1622 def __getslice__(self, i, j):
1623 return ("getslice", i, j)
1624 def __setslice__(self, i, j, value):
1625 self.setslice = (i, j, value)
1626 def __delslice__(self, i, j):
1627 self.delslice = (i, j)
1628
1629 a = C()
1630 self.assertEqual(a.foo, ("getattr", "foo"))
1631 a.foo = 12
1632 self.assertEqual(a.setattr, ("foo", 12))
1633 del a.foo
1634 self.assertEqual(a.delattr, "foo")
1635
1636 self.assertEqual(a[12], ("getitem", 12))
1637 a[12] = 21
1638 self.assertEqual(a.setitem, (12, 21))
1639 del a[12]
1640 self.assertEqual(a.delitem, 12)
1641
1642 self.assertEqual(a[0:10], ("getslice", 0, 10))
1643 a[0:10] = "foo"
1644 self.assertEqual(a.setslice, (0, 10, "foo"))
1645 del a[0:10]
1646 self.assertEqual(a.delslice, (0, 10))
1647
1648 def test_methods(self):
1649 # Testing methods...
1650 class C(object):
1651 def __init__(self, x):
1652 self.x = x
1653 def foo(self):
1654 return self.x
1655 c1 = C(1)
1656 self.assertEqual(c1.foo(), 1)
1657 class D(C):
1658 boo = C.foo
1659 goo = c1.foo
1660 d2 = D(2)
1661 self.assertEqual(d2.foo(), 2)
1662 self.assertEqual(d2.boo(), 2)
1663 self.assertEqual(d2.goo(), 1)
1664 class E(object):
1665 foo = C.foo
1666 self.assertEqual(E().foo, C.foo) # i.e., unbound
1667 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1668
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001669 def test_special_method_lookup(self):
1670 # The lookup of special methods bypasses __getattr__ and
1671 # __getattribute__, but they still can be descriptors.
1672
1673 def run_context(manager):
1674 with manager:
1675 pass
1676 def iden(self):
1677 return self
1678 def hello(self):
1679 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001680 def empty_seq(self):
1681 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001682 def zero(self):
1683 return 0
1684 def stop(self):
1685 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001686 def return_true(self, thing=None):
1687 return True
1688 def do_isinstance(obj):
1689 return isinstance(int, obj)
1690 def do_issubclass(obj):
1691 return issubclass(int, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001692
1693 # It would be nice to have every special method tested here, but I'm
1694 # only listing the ones I can remember outside of typeobject.c, since it
1695 # does it right.
1696 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001697 ("__unicode__", unicode, hello, set(), {}),
1698 ("__reversed__", reversed, empty_seq, set(), {}),
1699 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001700 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001701 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1702 ("__instancecheck__", do_isinstance, return_true, set(), {}),
1703 ("__subclasscheck__", do_issubclass, return_true,
1704 set(("__bases__",)), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001705 # These two fail because the compiler generates LOAD_ATTR to look
1706 # them up. We'd have to add a new opcode to fix this, and it's
1707 # probably not worth it.
1708 # ("__enter__", run_context, iden),
1709 # ("__exit__", run_context, iden),
1710 ]
1711
1712 class Checker(object):
1713 def __getattr__(self, attr, test=self):
1714 test.fail("__getattr__ called with {0}".format(attr))
1715 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001716 if attr not in ok:
1717 test.fail("__getattribute__ called with {0}".format(attr))
1718 return object.__getattribute__(attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001719 class SpecialDescr(object):
1720 def __init__(self, impl):
1721 self.impl = impl
1722 def __get__(self, obj, owner):
1723 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001724 return self.impl.__get__(obj, owner)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001725
1726
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001727 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001728 class X(Checker):
1729 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001730 for attr, obj in env.iteritems():
1731 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001732 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001733 runner(X())
1734
1735 record = []
1736 class X(Checker):
1737 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001738 for attr, obj in env.iteritems():
1739 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001740 setattr(X, name, SpecialDescr(meth_impl))
1741 runner(X())
1742 self.assertEqual(record, [1], name)
1743
Georg Brandl48545522008-02-02 10:12:36 +00001744 def test_specials(self):
1745 # Testing special operators...
1746 # Test operators like __hash__ for which a built-in default exists
1747
1748 # Test the default behavior for static classes
1749 class C(object):
1750 def __getitem__(self, i):
1751 if 0 <= i < 10: return i
1752 raise IndexError
1753 c1 = C()
1754 c2 = C()
1755 self.assert_(not not c1) # What?
1756 self.assertNotEqual(id(c1), id(c2))
1757 hash(c1)
1758 hash(c2)
1759 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1760 self.assertEqual(c1, c1)
1761 self.assert_(c1 != c2)
1762 self.assert_(not c1 != c1)
1763 self.assert_(not c1 == c2)
1764 # Note that the module name appears in str/repr, and that varies
1765 # depending on whether this test is run standalone or from a framework.
1766 self.assert_(str(c1).find('C object at ') >= 0)
1767 self.assertEqual(str(c1), repr(c1))
1768 self.assert_(-1 not in c1)
1769 for i in range(10):
1770 self.assert_(i in c1)
1771 self.assertFalse(10 in c1)
1772 # Test the default behavior for dynamic classes
1773 class D(object):
1774 def __getitem__(self, i):
1775 if 0 <= i < 10: return i
1776 raise IndexError
1777 d1 = D()
1778 d2 = D()
1779 self.assert_(not not d1)
1780 self.assertNotEqual(id(d1), id(d2))
1781 hash(d1)
1782 hash(d2)
1783 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1784 self.assertEqual(d1, d1)
1785 self.assertNotEqual(d1, d2)
1786 self.assert_(not d1 != d1)
1787 self.assert_(not d1 == d2)
1788 # Note that the module name appears in str/repr, and that varies
1789 # depending on whether this test is run standalone or from a framework.
1790 self.assert_(str(d1).find('D object at ') >= 0)
1791 self.assertEqual(str(d1), repr(d1))
1792 self.assert_(-1 not in d1)
1793 for i in range(10):
1794 self.assert_(i in d1)
1795 self.assertFalse(10 in d1)
1796 # Test overridden behavior for static classes
1797 class Proxy(object):
1798 def __init__(self, x):
1799 self.x = x
1800 def __nonzero__(self):
1801 return not not self.x
1802 def __hash__(self):
1803 return hash(self.x)
1804 def __eq__(self, other):
1805 return self.x == other
1806 def __ne__(self, other):
1807 return self.x != other
1808 def __cmp__(self, other):
1809 return cmp(self.x, other.x)
1810 def __str__(self):
1811 return "Proxy:%s" % self.x
1812 def __repr__(self):
1813 return "Proxy(%r)" % self.x
1814 def __contains__(self, value):
1815 return value in self.x
1816 p0 = Proxy(0)
1817 p1 = Proxy(1)
1818 p_1 = Proxy(-1)
1819 self.assertFalse(p0)
1820 self.assert_(not not p1)
1821 self.assertEqual(hash(p0), hash(0))
1822 self.assertEqual(p0, p0)
1823 self.assertNotEqual(p0, p1)
1824 self.assert_(not p0 != p0)
1825 self.assertEqual(not p0, p1)
1826 self.assertEqual(cmp(p0, p1), -1)
1827 self.assertEqual(cmp(p0, p0), 0)
1828 self.assertEqual(cmp(p0, p_1), 1)
1829 self.assertEqual(str(p0), "Proxy:0")
1830 self.assertEqual(repr(p0), "Proxy(0)")
1831 p10 = Proxy(range(10))
1832 self.assertFalse(-1 in p10)
1833 for i in range(10):
1834 self.assert_(i in p10)
1835 self.assertFalse(10 in p10)
1836 # Test overridden behavior for dynamic classes
1837 class DProxy(object):
1838 def __init__(self, x):
1839 self.x = x
1840 def __nonzero__(self):
1841 return not not self.x
1842 def __hash__(self):
1843 return hash(self.x)
1844 def __eq__(self, other):
1845 return self.x == other
1846 def __ne__(self, other):
1847 return self.x != other
1848 def __cmp__(self, other):
1849 return cmp(self.x, other.x)
1850 def __str__(self):
1851 return "DProxy:%s" % self.x
1852 def __repr__(self):
1853 return "DProxy(%r)" % self.x
1854 def __contains__(self, value):
1855 return value in self.x
1856 p0 = DProxy(0)
1857 p1 = DProxy(1)
1858 p_1 = DProxy(-1)
1859 self.assertFalse(p0)
1860 self.assert_(not not p1)
1861 self.assertEqual(hash(p0), hash(0))
1862 self.assertEqual(p0, p0)
1863 self.assertNotEqual(p0, p1)
1864 self.assertNotEqual(not p0, p0)
1865 self.assertEqual(not p0, p1)
1866 self.assertEqual(cmp(p0, p1), -1)
1867 self.assertEqual(cmp(p0, p0), 0)
1868 self.assertEqual(cmp(p0, p_1), 1)
1869 self.assertEqual(str(p0), "DProxy:0")
1870 self.assertEqual(repr(p0), "DProxy(0)")
1871 p10 = DProxy(range(10))
1872 self.assertFalse(-1 in p10)
1873 for i in range(10):
1874 self.assert_(i in p10)
1875 self.assertFalse(10 in p10)
1876
1877 # Safety test for __cmp__
1878 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001879 if not hasattr(a, '__cmp__'):
1880 return # some types don't have a __cmp__ any more (so the
1881 # test doesn't make sense any more), or maybe they
1882 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001883 try:
1884 a.__class__.__cmp__(a, b)
1885 except TypeError:
1886 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001887 else:
Georg Brandl48545522008-02-02 10:12:36 +00001888 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1889 a.__class__, a, b))
1890
1891 unsafecmp(u"123", "123")
1892 unsafecmp("123", u"123")
1893 unsafecmp(1, 1.0)
1894 unsafecmp(1.0, 1)
1895 unsafecmp(1, 1L)
1896 unsafecmp(1L, 1)
1897
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001898 @test_support.impl_detail("custom logic for printing to real file objects")
1899 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001900 # Testing recursion checks ...
1901 class Letter(str):
1902 def __new__(cls, letter):
1903 if letter == 'EPS':
1904 return str.__new__(cls)
1905 return str.__new__(cls, letter)
1906 def __str__(self):
1907 if not self:
1908 return 'EPS'
1909 return self
1910 # sys.stdout needs to be the original to trigger the recursion bug
1911 import sys
1912 test_stdout = sys.stdout
1913 sys.stdout = test_support.get_original_stdout()
1914 try:
1915 # nothing should actually be printed, this should raise an exception
1916 print Letter('w')
1917 except RuntimeError:
1918 pass
1919 else:
1920 self.fail("expected a RuntimeError for print recursion")
1921 finally:
1922 sys.stdout = test_stdout
1923
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001924 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001925 # Bug #1202533.
1926 class A(object):
1927 pass
1928 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1929 try:
1930 A()*2
1931 except RuntimeError:
1932 pass
1933 else:
1934 self.fail("expected a RuntimeError")
1935
1936 def test_weakrefs(self):
1937 # Testing weak references...
1938 import weakref
1939 class C(object):
1940 pass
1941 c = C()
1942 r = weakref.ref(c)
1943 self.assertEqual(r(), c)
1944 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001945 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001946 self.assertEqual(r(), None)
1947 del r
1948 class NoWeak(object):
1949 __slots__ = ['foo']
1950 no = NoWeak()
1951 try:
1952 weakref.ref(no)
1953 except TypeError, msg:
1954 self.assert_(str(msg).find("weak reference") >= 0)
1955 else:
1956 self.fail("weakref.ref(no) should be illegal")
1957 class Weak(object):
1958 __slots__ = ['foo', '__weakref__']
1959 yes = Weak()
1960 r = weakref.ref(yes)
1961 self.assertEqual(r(), yes)
1962 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001963 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001964 self.assertEqual(r(), None)
1965 del r
1966
1967 def test_properties(self):
1968 # Testing property...
1969 class C(object):
1970 def getx(self):
1971 return self.__x
1972 def setx(self, value):
1973 self.__x = value
1974 def delx(self):
1975 del self.__x
1976 x = property(getx, setx, delx, doc="I'm the x property.")
1977 a = C()
1978 self.assertFalse(hasattr(a, "x"))
1979 a.x = 42
1980 self.assertEqual(a._C__x, 42)
1981 self.assertEqual(a.x, 42)
1982 del a.x
1983 self.assertFalse(hasattr(a, "x"))
1984 self.assertFalse(hasattr(a, "_C__x"))
1985 C.x.__set__(a, 100)
1986 self.assertEqual(C.x.__get__(a), 100)
1987 C.x.__delete__(a)
1988 self.assertFalse(hasattr(a, "x"))
1989
1990 raw = C.__dict__['x']
1991 self.assert_(isinstance(raw, property))
1992
1993 attrs = dir(raw)
1994 self.assert_("__doc__" in attrs)
1995 self.assert_("fget" in attrs)
1996 self.assert_("fset" in attrs)
1997 self.assert_("fdel" in attrs)
1998
1999 self.assertEqual(raw.__doc__, "I'm the x property.")
2000 self.assert_(raw.fget is C.__dict__['getx'])
2001 self.assert_(raw.fset is C.__dict__['setx'])
2002 self.assert_(raw.fdel is C.__dict__['delx'])
2003
2004 for attr in "__doc__", "fget", "fset", "fdel":
2005 try:
2006 setattr(raw, attr, 42)
2007 except TypeError, msg:
2008 if str(msg).find('readonly') < 0:
2009 self.fail("when setting readonly attr %r on a property, "
2010 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002011 else:
Georg Brandl48545522008-02-02 10:12:36 +00002012 self.fail("expected TypeError from trying to set readonly %r "
2013 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002014
Georg Brandl48545522008-02-02 10:12:36 +00002015 class D(object):
2016 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002017
Georg Brandl48545522008-02-02 10:12:36 +00002018 d = D()
2019 try:
2020 for i in d:
2021 str(i)
2022 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002023 pass
Georg Brandl48545522008-02-02 10:12:36 +00002024 else:
2025 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002026
Georg Brandl48545522008-02-02 10:12:36 +00002027 class E(object):
2028 def getter(self):
2029 "getter method"
2030 return 0
2031 def setter(self_, value):
2032 "setter method"
2033 pass
2034 prop = property(getter)
2035 self.assertEqual(prop.__doc__, "getter method")
2036 prop2 = property(fset=setter)
2037 self.assertEqual(prop2.__doc__, None)
2038
2039 # this segfaulted in 2.5b2
2040 try:
2041 import _testcapi
2042 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002043 pass
Georg Brandl48545522008-02-02 10:12:36 +00002044 else:
2045 class X(object):
2046 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002047
Georg Brandl48545522008-02-02 10:12:36 +00002048 def test_properties_plus(self):
2049 class C(object):
2050 foo = property(doc="hello")
2051 @foo.getter
2052 def foo(self):
2053 return self._foo
2054 @foo.setter
2055 def foo(self, value):
2056 self._foo = abs(value)
2057 @foo.deleter
2058 def foo(self):
2059 del self._foo
2060 c = C()
2061 self.assertEqual(C.foo.__doc__, "hello")
2062 self.assertFalse(hasattr(c, "foo"))
2063 c.foo = -42
2064 self.assert_(hasattr(c, '_foo'))
2065 self.assertEqual(c._foo, 42)
2066 self.assertEqual(c.foo, 42)
2067 del c.foo
2068 self.assertFalse(hasattr(c, '_foo'))
2069 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002070
Georg Brandl48545522008-02-02 10:12:36 +00002071 class D(C):
2072 @C.foo.deleter
2073 def foo(self):
2074 try:
2075 del self._foo
2076 except AttributeError:
2077 pass
2078 d = D()
2079 d.foo = 24
2080 self.assertEqual(d.foo, 24)
2081 del d.foo
2082 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002083
Georg Brandl48545522008-02-02 10:12:36 +00002084 class E(object):
2085 @property
2086 def foo(self):
2087 return self._foo
2088 @foo.setter
2089 def foo(self, value):
2090 raise RuntimeError
2091 @foo.setter
2092 def foo(self, value):
2093 self._foo = abs(value)
2094 @foo.deleter
2095 def foo(self, value=None):
2096 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002097
Georg Brandl48545522008-02-02 10:12:36 +00002098 e = E()
2099 e.foo = -42
2100 self.assertEqual(e.foo, 42)
2101 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002102
Georg Brandl48545522008-02-02 10:12:36 +00002103 class F(E):
2104 @E.foo.deleter
2105 def foo(self):
2106 del self._foo
2107 @foo.setter
2108 def foo(self, value):
2109 self._foo = max(0, value)
2110 f = F()
2111 f.foo = -10
2112 self.assertEqual(f.foo, 0)
2113 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002114
Georg Brandl48545522008-02-02 10:12:36 +00002115 def test_dict_constructors(self):
2116 # Testing dict constructor ...
2117 d = dict()
2118 self.assertEqual(d, {})
2119 d = dict({})
2120 self.assertEqual(d, {})
2121 d = dict({1: 2, 'a': 'b'})
2122 self.assertEqual(d, {1: 2, 'a': 'b'})
2123 self.assertEqual(d, dict(d.items()))
2124 self.assertEqual(d, dict(d.iteritems()))
2125 d = dict({'one':1, 'two':2})
2126 self.assertEqual(d, dict(one=1, two=2))
2127 self.assertEqual(d, dict(**d))
2128 self.assertEqual(d, dict({"one": 1}, two=2))
2129 self.assertEqual(d, dict([("two", 2)], one=1))
2130 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2131 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002132
Georg Brandl48545522008-02-02 10:12:36 +00002133 for badarg in 0, 0L, 0j, "0", [0], (0,):
2134 try:
2135 dict(badarg)
2136 except TypeError:
2137 pass
2138 except ValueError:
2139 if badarg == "0":
2140 # It's a sequence, and its elements are also sequences (gotta
2141 # love strings <wink>), but they aren't of length 2, so this
2142 # one seemed better as a ValueError than a TypeError.
2143 pass
2144 else:
2145 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002146 else:
Georg Brandl48545522008-02-02 10:12:36 +00002147 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002148
Georg Brandl48545522008-02-02 10:12:36 +00002149 try:
2150 dict({}, {})
2151 except TypeError:
2152 pass
2153 else:
2154 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002155
Georg Brandl48545522008-02-02 10:12:36 +00002156 class Mapping:
2157 # Lacks a .keys() method; will be added later.
2158 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002159
Georg Brandl48545522008-02-02 10:12:36 +00002160 try:
2161 dict(Mapping())
2162 except TypeError:
2163 pass
2164 else:
2165 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002166
Georg Brandl48545522008-02-02 10:12:36 +00002167 Mapping.keys = lambda self: self.dict.keys()
2168 Mapping.__getitem__ = lambda self, i: self.dict[i]
2169 d = dict(Mapping())
2170 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002171
Georg Brandl48545522008-02-02 10:12:36 +00002172 # Init from sequence of iterable objects, each producing a 2-sequence.
2173 class AddressBookEntry:
2174 def __init__(self, first, last):
2175 self.first = first
2176 self.last = last
2177 def __iter__(self):
2178 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002179
Georg Brandl48545522008-02-02 10:12:36 +00002180 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2181 AddressBookEntry('Barry', 'Peters'),
2182 AddressBookEntry('Tim', 'Peters'),
2183 AddressBookEntry('Barry', 'Warsaw')])
2184 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002185
Georg Brandl48545522008-02-02 10:12:36 +00002186 d = dict(zip(range(4), range(1, 5)))
2187 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002188
Georg Brandl48545522008-02-02 10:12:36 +00002189 # Bad sequence lengths.
2190 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2191 try:
2192 dict(bad)
2193 except ValueError:
2194 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002195 else:
Georg Brandl48545522008-02-02 10:12:36 +00002196 self.fail("no ValueError from dict(%r)" % bad)
2197
2198 def test_dir(self):
2199 # Testing dir() ...
2200 junk = 12
2201 self.assertEqual(dir(), ['junk', 'self'])
2202 del junk
2203
2204 # Just make sure these don't blow up!
2205 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2206 dir(arg)
2207
2208 # Try classic classes.
2209 class C:
2210 Cdata = 1
2211 def Cmethod(self): pass
2212
2213 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2214 self.assertEqual(dir(C), cstuff)
2215 self.assert_('im_self' in dir(C.Cmethod))
2216
2217 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2218 self.assertEqual(dir(c), cstuff)
2219
2220 c.cdata = 2
2221 c.cmethod = lambda self: 0
2222 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
2223 self.assert_('im_self' in dir(c.Cmethod))
2224
2225 class A(C):
2226 Adata = 1
2227 def Amethod(self): pass
2228
2229 astuff = ['Adata', 'Amethod'] + cstuff
2230 self.assertEqual(dir(A), astuff)
2231 self.assert_('im_self' in dir(A.Amethod))
2232 a = A()
2233 self.assertEqual(dir(a), astuff)
2234 self.assert_('im_self' in dir(a.Amethod))
2235 a.adata = 42
2236 a.amethod = lambda self: 3
2237 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2238
2239 # The same, but with new-style classes. Since these have object as a
2240 # base class, a lot more gets sucked in.
2241 def interesting(strings):
2242 return [s for s in strings if not s.startswith('_')]
2243
2244 class C(object):
2245 Cdata = 1
2246 def Cmethod(self): pass
2247
2248 cstuff = ['Cdata', 'Cmethod']
2249 self.assertEqual(interesting(dir(C)), cstuff)
2250
2251 c = C()
2252 self.assertEqual(interesting(dir(c)), cstuff)
2253 self.assert_('im_self' in dir(C.Cmethod))
2254
2255 c.cdata = 2
2256 c.cmethod = lambda self: 0
2257 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2258 self.assert_('im_self' in dir(c.Cmethod))
2259
2260 class A(C):
2261 Adata = 1
2262 def Amethod(self): pass
2263
2264 astuff = ['Adata', 'Amethod'] + cstuff
2265 self.assertEqual(interesting(dir(A)), astuff)
2266 self.assert_('im_self' in dir(A.Amethod))
2267 a = A()
2268 self.assertEqual(interesting(dir(a)), astuff)
2269 a.adata = 42
2270 a.amethod = lambda self: 3
2271 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2272 self.assert_('im_self' in dir(a.Amethod))
2273
2274 # Try a module subclass.
2275 import sys
2276 class M(type(sys)):
2277 pass
2278 minstance = M("m")
2279 minstance.b = 2
2280 minstance.a = 1
2281 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2282 self.assertEqual(names, ['a', 'b'])
2283
2284 class M2(M):
2285 def getdict(self):
2286 return "Not a dict!"
2287 __dict__ = property(getdict)
2288
2289 m2instance = M2("m2")
2290 m2instance.b = 2
2291 m2instance.a = 1
2292 self.assertEqual(m2instance.__dict__, "Not a dict!")
2293 try:
2294 dir(m2instance)
2295 except TypeError:
2296 pass
2297
2298 # Two essentially featureless objects, just inheriting stuff from
2299 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002300 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2301 if test_support.check_impl_detail():
2302 # None differs in PyPy: it has a __nonzero__
2303 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002304
2305 # Nasty test case for proxied objects
2306 class Wrapper(object):
2307 def __init__(self, obj):
2308 self.__obj = obj
2309 def __repr__(self):
2310 return "Wrapper(%s)" % repr(self.__obj)
2311 def __getitem__(self, key):
2312 return Wrapper(self.__obj[key])
2313 def __len__(self):
2314 return len(self.__obj)
2315 def __getattr__(self, name):
2316 return Wrapper(getattr(self.__obj, name))
2317
2318 class C(object):
2319 def __getclass(self):
2320 return Wrapper(type(self))
2321 __class__ = property(__getclass)
2322
2323 dir(C()) # This used to segfault
2324
2325 def test_supers(self):
2326 # Testing super...
2327
2328 class A(object):
2329 def meth(self, a):
2330 return "A(%r)" % a
2331
2332 self.assertEqual(A().meth(1), "A(1)")
2333
2334 class B(A):
2335 def __init__(self):
2336 self.__super = super(B, self)
2337 def meth(self, a):
2338 return "B(%r)" % a + self.__super.meth(a)
2339
2340 self.assertEqual(B().meth(2), "B(2)A(2)")
2341
2342 class C(A):
2343 def meth(self, a):
2344 return "C(%r)" % a + self.__super.meth(a)
2345 C._C__super = super(C)
2346
2347 self.assertEqual(C().meth(3), "C(3)A(3)")
2348
2349 class D(C, B):
2350 def meth(self, a):
2351 return "D(%r)" % a + super(D, self).meth(a)
2352
2353 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2354
2355 # Test for subclassing super
2356
2357 class mysuper(super):
2358 def __init__(self, *args):
2359 return super(mysuper, self).__init__(*args)
2360
2361 class E(D):
2362 def meth(self, a):
2363 return "E(%r)" % a + mysuper(E, self).meth(a)
2364
2365 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2366
2367 class F(E):
2368 def meth(self, a):
2369 s = self.__super # == mysuper(F, self)
2370 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2371 F._F__super = mysuper(F)
2372
2373 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2374
2375 # Make sure certain errors are raised
2376
2377 try:
2378 super(D, 42)
2379 except TypeError:
2380 pass
2381 else:
2382 self.fail("shouldn't allow super(D, 42)")
2383
2384 try:
2385 super(D, C())
2386 except TypeError:
2387 pass
2388 else:
2389 self.fail("shouldn't allow super(D, C())")
2390
2391 try:
2392 super(D).__get__(12)
2393 except TypeError:
2394 pass
2395 else:
2396 self.fail("shouldn't allow super(D).__get__(12)")
2397
2398 try:
2399 super(D).__get__(C())
2400 except TypeError:
2401 pass
2402 else:
2403 self.fail("shouldn't allow super(D).__get__(C())")
2404
2405 # Make sure data descriptors can be overridden and accessed via super
2406 # (new feature in Python 2.3)
2407
2408 class DDbase(object):
2409 def getx(self): return 42
2410 x = property(getx)
2411
2412 class DDsub(DDbase):
2413 def getx(self): return "hello"
2414 x = property(getx)
2415
2416 dd = DDsub()
2417 self.assertEqual(dd.x, "hello")
2418 self.assertEqual(super(DDsub, dd).x, 42)
2419
2420 # Ensure that super() lookup of descriptor from classmethod
2421 # works (SF ID# 743627)
2422
2423 class Base(object):
2424 aProp = property(lambda self: "foo")
2425
2426 class Sub(Base):
2427 @classmethod
2428 def test(klass):
2429 return super(Sub,klass).aProp
2430
2431 self.assertEqual(Sub.test(), Base.aProp)
2432
2433 # Verify that super() doesn't allow keyword args
2434 try:
2435 super(Base, kw=1)
2436 except TypeError:
2437 pass
2438 else:
2439 self.assertEqual("super shouldn't accept keyword args")
2440
2441 def test_basic_inheritance(self):
2442 # Testing inheritance from basic types...
2443
2444 class hexint(int):
2445 def __repr__(self):
2446 return hex(self)
2447 def __add__(self, other):
2448 return hexint(int.__add__(self, other))
2449 # (Note that overriding __radd__ doesn't work,
2450 # because the int type gets first dibs.)
2451 self.assertEqual(repr(hexint(7) + 9), "0x10")
2452 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2453 a = hexint(12345)
2454 self.assertEqual(a, 12345)
2455 self.assertEqual(int(a), 12345)
2456 self.assert_(int(a).__class__ is int)
2457 self.assertEqual(hash(a), hash(12345))
2458 self.assert_((+a).__class__ is int)
2459 self.assert_((a >> 0).__class__ is int)
2460 self.assert_((a << 0).__class__ is int)
2461 self.assert_((hexint(0) << 12).__class__ is int)
2462 self.assert_((hexint(0) >> 12).__class__ is int)
2463
2464 class octlong(long):
2465 __slots__ = []
2466 def __str__(self):
2467 s = oct(self)
2468 if s[-1] == 'L':
2469 s = s[:-1]
2470 return s
2471 def __add__(self, other):
2472 return self.__class__(super(octlong, self).__add__(other))
2473 __radd__ = __add__
2474 self.assertEqual(str(octlong(3) + 5), "010")
2475 # (Note that overriding __radd__ here only seems to work
2476 # because the example uses a short int left argument.)
2477 self.assertEqual(str(5 + octlong(3000)), "05675")
2478 a = octlong(12345)
2479 self.assertEqual(a, 12345L)
2480 self.assertEqual(long(a), 12345L)
2481 self.assertEqual(hash(a), hash(12345L))
2482 self.assert_(long(a).__class__ is long)
2483 self.assert_((+a).__class__ is long)
2484 self.assert_((-a).__class__ is long)
2485 self.assert_((-octlong(0)).__class__ is long)
2486 self.assert_((a >> 0).__class__ is long)
2487 self.assert_((a << 0).__class__ is long)
2488 self.assert_((a - 0).__class__ is long)
2489 self.assert_((a * 1).__class__ is long)
2490 self.assert_((a ** 1).__class__ is long)
2491 self.assert_((a // 1).__class__ is long)
2492 self.assert_((1 * a).__class__ is long)
2493 self.assert_((a | 0).__class__ is long)
2494 self.assert_((a ^ 0).__class__ is long)
2495 self.assert_((a & -1L).__class__ is long)
2496 self.assert_((octlong(0) << 12).__class__ is long)
2497 self.assert_((octlong(0) >> 12).__class__ is long)
2498 self.assert_(abs(octlong(0)).__class__ is long)
2499
2500 # Because octlong overrides __add__, we can't check the absence of +0
2501 # optimizations using octlong.
2502 class longclone(long):
2503 pass
2504 a = longclone(1)
2505 self.assert_((a + 0).__class__ is long)
2506 self.assert_((0 + a).__class__ is long)
2507
2508 # Check that negative clones don't segfault
2509 a = longclone(-1)
2510 self.assertEqual(a.__dict__, {})
2511 self.assertEqual(long(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2512
2513 class precfloat(float):
2514 __slots__ = ['prec']
2515 def __init__(self, value=0.0, prec=12):
2516 self.prec = int(prec)
2517 def __repr__(self):
2518 return "%.*g" % (self.prec, self)
2519 self.assertEqual(repr(precfloat(1.1)), "1.1")
2520 a = precfloat(12345)
2521 self.assertEqual(a, 12345.0)
2522 self.assertEqual(float(a), 12345.0)
2523 self.assert_(float(a).__class__ is float)
2524 self.assertEqual(hash(a), hash(12345.0))
2525 self.assert_((+a).__class__ is float)
2526
2527 class madcomplex(complex):
2528 def __repr__(self):
2529 return "%.17gj%+.17g" % (self.imag, self.real)
2530 a = madcomplex(-3, 4)
2531 self.assertEqual(repr(a), "4j-3")
2532 base = complex(-3, 4)
2533 self.assertEqual(base.__class__, complex)
2534 self.assertEqual(a, base)
2535 self.assertEqual(complex(a), base)
2536 self.assertEqual(complex(a).__class__, complex)
2537 a = madcomplex(a) # just trying another form of the constructor
2538 self.assertEqual(repr(a), "4j-3")
2539 self.assertEqual(a, base)
2540 self.assertEqual(complex(a), base)
2541 self.assertEqual(complex(a).__class__, complex)
2542 self.assertEqual(hash(a), hash(base))
2543 self.assertEqual((+a).__class__, complex)
2544 self.assertEqual((a + 0).__class__, complex)
2545 self.assertEqual(a + 0, base)
2546 self.assertEqual((a - 0).__class__, complex)
2547 self.assertEqual(a - 0, base)
2548 self.assertEqual((a * 1).__class__, complex)
2549 self.assertEqual(a * 1, base)
2550 self.assertEqual((a / 1).__class__, complex)
2551 self.assertEqual(a / 1, base)
2552
2553 class madtuple(tuple):
2554 _rev = None
2555 def rev(self):
2556 if self._rev is not None:
2557 return self._rev
2558 L = list(self)
2559 L.reverse()
2560 self._rev = self.__class__(L)
2561 return self._rev
2562 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2563 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2564 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2565 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2566 for i in range(512):
2567 t = madtuple(range(i))
2568 u = t.rev()
2569 v = u.rev()
2570 self.assertEqual(v, t)
2571 a = madtuple((1,2,3,4,5))
2572 self.assertEqual(tuple(a), (1,2,3,4,5))
2573 self.assert_(tuple(a).__class__ is tuple)
2574 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2575 self.assert_(a[:].__class__ is tuple)
2576 self.assert_((a * 1).__class__ is tuple)
2577 self.assert_((a * 0).__class__ is tuple)
2578 self.assert_((a + ()).__class__ is tuple)
2579 a = madtuple(())
2580 self.assertEqual(tuple(a), ())
2581 self.assert_(tuple(a).__class__ is tuple)
2582 self.assert_((a + a).__class__ is tuple)
2583 self.assert_((a * 0).__class__ is tuple)
2584 self.assert_((a * 1).__class__ is tuple)
2585 self.assert_((a * 2).__class__ is tuple)
2586 self.assert_(a[:].__class__ is tuple)
2587
2588 class madstring(str):
2589 _rev = None
2590 def rev(self):
2591 if self._rev is not None:
2592 return self._rev
2593 L = list(self)
2594 L.reverse()
2595 self._rev = self.__class__("".join(L))
2596 return self._rev
2597 s = madstring("abcdefghijklmnopqrstuvwxyz")
2598 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2599 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2600 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2601 for i in range(256):
2602 s = madstring("".join(map(chr, range(i))))
2603 t = s.rev()
2604 u = t.rev()
2605 self.assertEqual(u, s)
2606 s = madstring("12345")
2607 self.assertEqual(str(s), "12345")
2608 self.assert_(str(s).__class__ is str)
2609
2610 base = "\x00" * 5
2611 s = madstring(base)
2612 self.assertEqual(s, base)
2613 self.assertEqual(str(s), base)
2614 self.assert_(str(s).__class__ is str)
2615 self.assertEqual(hash(s), hash(base))
2616 self.assertEqual({s: 1}[base], 1)
2617 self.assertEqual({base: 1}[s], 1)
2618 self.assert_((s + "").__class__ is str)
2619 self.assertEqual(s + "", base)
2620 self.assert_(("" + s).__class__ is str)
2621 self.assertEqual("" + s, base)
2622 self.assert_((s * 0).__class__ is str)
2623 self.assertEqual(s * 0, "")
2624 self.assert_((s * 1).__class__ is str)
2625 self.assertEqual(s * 1, base)
2626 self.assert_((s * 2).__class__ is str)
2627 self.assertEqual(s * 2, base + base)
2628 self.assert_(s[:].__class__ is str)
2629 self.assertEqual(s[:], base)
2630 self.assert_(s[0:0].__class__ is str)
2631 self.assertEqual(s[0:0], "")
2632 self.assert_(s.strip().__class__ is str)
2633 self.assertEqual(s.strip(), base)
2634 self.assert_(s.lstrip().__class__ is str)
2635 self.assertEqual(s.lstrip(), base)
2636 self.assert_(s.rstrip().__class__ is str)
2637 self.assertEqual(s.rstrip(), base)
2638 identitytab = ''.join([chr(i) for i in range(256)])
2639 self.assert_(s.translate(identitytab).__class__ is str)
2640 self.assertEqual(s.translate(identitytab), base)
2641 self.assert_(s.translate(identitytab, "x").__class__ is str)
2642 self.assertEqual(s.translate(identitytab, "x"), base)
2643 self.assertEqual(s.translate(identitytab, "\x00"), "")
2644 self.assert_(s.replace("x", "x").__class__ is str)
2645 self.assertEqual(s.replace("x", "x"), base)
2646 self.assert_(s.ljust(len(s)).__class__ is str)
2647 self.assertEqual(s.ljust(len(s)), base)
2648 self.assert_(s.rjust(len(s)).__class__ is str)
2649 self.assertEqual(s.rjust(len(s)), base)
2650 self.assert_(s.center(len(s)).__class__ is str)
2651 self.assertEqual(s.center(len(s)), base)
2652 self.assert_(s.lower().__class__ is str)
2653 self.assertEqual(s.lower(), base)
2654
2655 class madunicode(unicode):
2656 _rev = None
2657 def rev(self):
2658 if self._rev is not None:
2659 return self._rev
2660 L = list(self)
2661 L.reverse()
2662 self._rev = self.__class__(u"".join(L))
2663 return self._rev
2664 u = madunicode("ABCDEF")
2665 self.assertEqual(u, u"ABCDEF")
2666 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2667 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2668 base = u"12345"
2669 u = madunicode(base)
2670 self.assertEqual(unicode(u), base)
2671 self.assert_(unicode(u).__class__ is unicode)
2672 self.assertEqual(hash(u), hash(base))
2673 self.assertEqual({u: 1}[base], 1)
2674 self.assertEqual({base: 1}[u], 1)
2675 self.assert_(u.strip().__class__ is unicode)
2676 self.assertEqual(u.strip(), base)
2677 self.assert_(u.lstrip().__class__ is unicode)
2678 self.assertEqual(u.lstrip(), base)
2679 self.assert_(u.rstrip().__class__ is unicode)
2680 self.assertEqual(u.rstrip(), base)
2681 self.assert_(u.replace(u"x", u"x").__class__ is unicode)
2682 self.assertEqual(u.replace(u"x", u"x"), base)
2683 self.assert_(u.replace(u"xy", u"xy").__class__ is unicode)
2684 self.assertEqual(u.replace(u"xy", u"xy"), base)
2685 self.assert_(u.center(len(u)).__class__ is unicode)
2686 self.assertEqual(u.center(len(u)), base)
2687 self.assert_(u.ljust(len(u)).__class__ is unicode)
2688 self.assertEqual(u.ljust(len(u)), base)
2689 self.assert_(u.rjust(len(u)).__class__ is unicode)
2690 self.assertEqual(u.rjust(len(u)), base)
2691 self.assert_(u.lower().__class__ is unicode)
2692 self.assertEqual(u.lower(), base)
2693 self.assert_(u.upper().__class__ is unicode)
2694 self.assertEqual(u.upper(), base)
2695 self.assert_(u.capitalize().__class__ is unicode)
2696 self.assertEqual(u.capitalize(), base)
2697 self.assert_(u.title().__class__ is unicode)
2698 self.assertEqual(u.title(), base)
2699 self.assert_((u + u"").__class__ is unicode)
2700 self.assertEqual(u + u"", base)
2701 self.assert_((u"" + u).__class__ is unicode)
2702 self.assertEqual(u"" + u, base)
2703 self.assert_((u * 0).__class__ is unicode)
2704 self.assertEqual(u * 0, u"")
2705 self.assert_((u * 1).__class__ is unicode)
2706 self.assertEqual(u * 1, base)
2707 self.assert_((u * 2).__class__ is unicode)
2708 self.assertEqual(u * 2, base + base)
2709 self.assert_(u[:].__class__ is unicode)
2710 self.assertEqual(u[:], base)
2711 self.assert_(u[0:0].__class__ is unicode)
2712 self.assertEqual(u[0:0], u"")
2713
2714 class sublist(list):
2715 pass
2716 a = sublist(range(5))
2717 self.assertEqual(a, range(5))
2718 a.append("hello")
2719 self.assertEqual(a, range(5) + ["hello"])
2720 a[5] = 5
2721 self.assertEqual(a, range(6))
2722 a.extend(range(6, 20))
2723 self.assertEqual(a, range(20))
2724 a[-5:] = []
2725 self.assertEqual(a, range(15))
2726 del a[10:15]
2727 self.assertEqual(len(a), 10)
2728 self.assertEqual(a, range(10))
2729 self.assertEqual(list(a), range(10))
2730 self.assertEqual(a[0], 0)
2731 self.assertEqual(a[9], 9)
2732 self.assertEqual(a[-10], 0)
2733 self.assertEqual(a[-1], 9)
2734 self.assertEqual(a[:5], range(5))
2735
2736 class CountedInput(file):
2737 """Counts lines read by self.readline().
2738
2739 self.lineno is the 0-based ordinal of the last line read, up to
2740 a maximum of one greater than the number of lines in the file.
2741
2742 self.ateof is true if and only if the final "" line has been read,
2743 at which point self.lineno stops incrementing, and further calls
2744 to readline() continue to return "".
2745 """
2746
2747 lineno = 0
2748 ateof = 0
2749 def readline(self):
2750 if self.ateof:
2751 return ""
2752 s = file.readline(self)
2753 # Next line works too.
2754 # s = super(CountedInput, self).readline()
2755 self.lineno += 1
2756 if s == "":
2757 self.ateof = 1
2758 return s
2759
2760 f = file(name=test_support.TESTFN, mode='w')
2761 lines = ['a\n', 'b\n', 'c\n']
2762 try:
2763 f.writelines(lines)
2764 f.close()
2765 f = CountedInput(test_support.TESTFN)
2766 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2767 got = f.readline()
2768 self.assertEqual(expected, got)
2769 self.assertEqual(f.lineno, i)
2770 self.assertEqual(f.ateof, (i > len(lines)))
2771 f.close()
2772 finally:
2773 try:
2774 f.close()
2775 except:
2776 pass
2777 test_support.unlink(test_support.TESTFN)
2778
2779 def test_keywords(self):
2780 # Testing keyword args to basic type constructors ...
2781 self.assertEqual(int(x=1), 1)
2782 self.assertEqual(float(x=2), 2.0)
2783 self.assertEqual(long(x=3), 3L)
2784 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2785 self.assertEqual(str(object=500), '500')
2786 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2787 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2788 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2789 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2790
2791 for constructor in (int, float, long, complex, str, unicode,
2792 tuple, list, file):
2793 try:
2794 constructor(bogus_keyword_arg=1)
2795 except TypeError:
2796 pass
2797 else:
2798 self.fail("expected TypeError from bogus keyword argument to %r"
2799 % constructor)
2800
2801 def test_str_subclass_as_dict_key(self):
2802 # Testing a str subclass used as dict key ..
2803
2804 class cistr(str):
2805 """Sublcass of str that computes __eq__ case-insensitively.
2806
2807 Also computes a hash code of the string in canonical form.
2808 """
2809
2810 def __init__(self, value):
2811 self.canonical = value.lower()
2812 self.hashcode = hash(self.canonical)
2813
2814 def __eq__(self, other):
2815 if not isinstance(other, cistr):
2816 other = cistr(other)
2817 return self.canonical == other.canonical
2818
2819 def __hash__(self):
2820 return self.hashcode
2821
2822 self.assertEqual(cistr('ABC'), 'abc')
2823 self.assertEqual('aBc', cistr('ABC'))
2824 self.assertEqual(str(cistr('ABC')), 'ABC')
2825
2826 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2827 self.assertEqual(d[cistr('one')], 1)
2828 self.assertEqual(d[cistr('tWo')], 2)
2829 self.assertEqual(d[cistr('THrEE')], 3)
2830 self.assert_(cistr('ONe') in d)
2831 self.assertEqual(d.get(cistr('thrEE')), 3)
2832
2833 def test_classic_comparisons(self):
2834 # Testing classic comparisons...
2835 class classic:
2836 pass
2837
2838 for base in (classic, int, object):
2839 class C(base):
2840 def __init__(self, value):
2841 self.value = int(value)
2842 def __cmp__(self, other):
2843 if isinstance(other, C):
2844 return cmp(self.value, other.value)
2845 if isinstance(other, int) or isinstance(other, long):
2846 return cmp(self.value, other)
2847 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002848 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002849
2850 c1 = C(1)
2851 c2 = C(2)
2852 c3 = C(3)
2853 self.assertEqual(c1, 1)
2854 c = {1: c1, 2: c2, 3: c3}
2855 for x in 1, 2, 3:
2856 for y in 1, 2, 3:
2857 self.assert_(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2858 for op in "<", "<=", "==", "!=", ">", ">=":
2859 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2860 "x=%d, y=%d" % (x, y))
2861 self.assert_(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2862 self.assert_(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2863
2864 def test_rich_comparisons(self):
2865 # Testing rich comparisons...
2866 class Z(complex):
2867 pass
2868 z = Z(1)
2869 self.assertEqual(z, 1+0j)
2870 self.assertEqual(1+0j, z)
2871 class ZZ(complex):
2872 def __eq__(self, other):
2873 try:
2874 return abs(self - other) <= 1e-6
2875 except:
2876 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002877 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002878 zz = ZZ(1.0000003)
2879 self.assertEqual(zz, 1+0j)
2880 self.assertEqual(1+0j, zz)
2881
2882 class classic:
2883 pass
2884 for base in (classic, int, object, list):
2885 class C(base):
2886 def __init__(self, value):
2887 self.value = int(value)
2888 def __cmp__(self_, other):
2889 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002890 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002891 def __eq__(self, other):
2892 if isinstance(other, C):
2893 return self.value == other.value
2894 if isinstance(other, int) or isinstance(other, long):
2895 return self.value == other
2896 return NotImplemented
2897 def __ne__(self, other):
2898 if isinstance(other, C):
2899 return self.value != other.value
2900 if isinstance(other, int) or isinstance(other, long):
2901 return self.value != other
2902 return NotImplemented
2903 def __lt__(self, other):
2904 if isinstance(other, C):
2905 return self.value < other.value
2906 if isinstance(other, int) or isinstance(other, long):
2907 return self.value < other
2908 return NotImplemented
2909 def __le__(self, other):
2910 if isinstance(other, C):
2911 return self.value <= other.value
2912 if isinstance(other, int) or isinstance(other, long):
2913 return self.value <= other
2914 return NotImplemented
2915 def __gt__(self, other):
2916 if isinstance(other, C):
2917 return self.value > other.value
2918 if isinstance(other, int) or isinstance(other, long):
2919 return self.value > other
2920 return NotImplemented
2921 def __ge__(self, other):
2922 if isinstance(other, C):
2923 return self.value >= other.value
2924 if isinstance(other, int) or isinstance(other, long):
2925 return self.value >= other
2926 return NotImplemented
2927 c1 = C(1)
2928 c2 = C(2)
2929 c3 = C(3)
2930 self.assertEqual(c1, 1)
2931 c = {1: c1, 2: c2, 3: c3}
2932 for x in 1, 2, 3:
2933 for y in 1, 2, 3:
2934 for op in "<", "<=", "==", "!=", ">", ">=":
2935 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2936 "x=%d, y=%d" % (x, y))
2937 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2938 "x=%d, y=%d" % (x, y))
2939 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2940 "x=%d, y=%d" % (x, y))
2941
2942 def test_coercions(self):
2943 # Testing coercions...
2944 class I(int): pass
2945 coerce(I(0), 0)
2946 coerce(0, I(0))
2947 class L(long): pass
2948 coerce(L(0), 0)
2949 coerce(L(0), 0L)
2950 coerce(0, L(0))
2951 coerce(0L, L(0))
2952 class F(float): pass
2953 coerce(F(0), 0)
2954 coerce(F(0), 0L)
2955 coerce(F(0), 0.)
2956 coerce(0, F(0))
2957 coerce(0L, F(0))
2958 coerce(0., F(0))
2959 class C(complex): pass
2960 coerce(C(0), 0)
2961 coerce(C(0), 0L)
2962 coerce(C(0), 0.)
2963 coerce(C(0), 0j)
2964 coerce(0, C(0))
2965 coerce(0L, C(0))
2966 coerce(0., C(0))
2967 coerce(0j, C(0))
2968
2969 def test_descrdoc(self):
2970 # Testing descriptor doc strings...
2971 def check(descr, what):
2972 self.assertEqual(descr.__doc__, what)
2973 check(file.closed, "True if the file is closed") # getset descriptor
2974 check(file.name, "file name") # member descriptor
2975
2976 def test_doc_descriptor(self):
2977 # Testing __doc__ descriptor...
2978 # SF bug 542984
2979 class DocDescr(object):
2980 def __get__(self, object, otype):
2981 if object:
2982 object = object.__class__.__name__ + ' instance'
2983 if otype:
2984 otype = otype.__name__
2985 return 'object=%s; type=%s' % (object, otype)
2986 class OldClass:
2987 __doc__ = DocDescr()
2988 class NewClass(object):
2989 __doc__ = DocDescr()
2990 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2991 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2992 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2993 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2994
2995 def test_set_class(self):
2996 # Testing __class__ assignment...
2997 class C(object): pass
2998 class D(object): pass
2999 class E(object): pass
3000 class F(D, E): pass
3001 for cls in C, D, E, F:
3002 for cls2 in C, D, E, F:
3003 x = cls()
3004 x.__class__ = cls2
3005 self.assert_(x.__class__ is cls2)
3006 x.__class__ = cls
3007 self.assert_(x.__class__ is cls)
3008 def cant(x, C):
3009 try:
3010 x.__class__ = C
3011 except TypeError:
3012 pass
3013 else:
3014 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3015 try:
3016 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003017 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003018 pass
3019 else:
3020 self.fail("shouldn't allow del %r.__class__" % x)
3021 cant(C(), list)
3022 cant(list(), C)
3023 cant(C(), 1)
3024 cant(C(), object)
3025 cant(object(), list)
3026 cant(list(), object)
3027 class Int(int): __slots__ = []
3028 cant(2, Int)
3029 cant(Int(), int)
3030 cant(True, int)
3031 cant(2, bool)
3032 o = object()
3033 cant(o, type(1))
3034 cant(o, type(None))
3035 del o
3036 class G(object):
3037 __slots__ = ["a", "b"]
3038 class H(object):
3039 __slots__ = ["b", "a"]
3040 try:
3041 unicode
3042 except NameError:
3043 class I(object):
3044 __slots__ = ["a", "b"]
3045 else:
3046 class I(object):
3047 __slots__ = [unicode("a"), unicode("b")]
3048 class J(object):
3049 __slots__ = ["c", "b"]
3050 class K(object):
3051 __slots__ = ["a", "b", "d"]
3052 class L(H):
3053 __slots__ = ["e"]
3054 class M(I):
3055 __slots__ = ["e"]
3056 class N(J):
3057 __slots__ = ["__weakref__"]
3058 class P(J):
3059 __slots__ = ["__dict__"]
3060 class Q(J):
3061 pass
3062 class R(J):
3063 __slots__ = ["__dict__", "__weakref__"]
3064
3065 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3066 x = cls()
3067 x.a = 1
3068 x.__class__ = cls2
3069 self.assert_(x.__class__ is cls2,
3070 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3071 self.assertEqual(x.a, 1)
3072 x.__class__ = cls
3073 self.assert_(x.__class__ is cls,
3074 "assigning %r as __class__ for %r silently failed" % (cls, x))
3075 self.assertEqual(x.a, 1)
3076 for cls in G, J, K, L, M, N, P, R, list, Int:
3077 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3078 if cls is cls2:
3079 continue
3080 cant(cls(), cls2)
3081
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003082 # Issue5283: when __class__ changes in __del__, the wrong
3083 # type gets DECREF'd.
3084 class O(object):
3085 pass
3086 class A(object):
3087 def __del__(self):
3088 self.__class__ = O
3089 l = [A() for x in range(100)]
3090 del l
3091
Georg Brandl48545522008-02-02 10:12:36 +00003092 def test_set_dict(self):
3093 # Testing __dict__ assignment...
3094 class C(object): pass
3095 a = C()
3096 a.__dict__ = {'b': 1}
3097 self.assertEqual(a.b, 1)
3098 def cant(x, dict):
3099 try:
3100 x.__dict__ = dict
3101 except (AttributeError, TypeError):
3102 pass
3103 else:
3104 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3105 cant(a, None)
3106 cant(a, [])
3107 cant(a, 1)
3108 del a.__dict__ # Deleting __dict__ is allowed
3109
3110 class Base(object):
3111 pass
3112 def verify_dict_readonly(x):
3113 """
3114 x has to be an instance of a class inheriting from Base.
3115 """
3116 cant(x, {})
3117 try:
3118 del x.__dict__
3119 except (AttributeError, TypeError):
3120 pass
3121 else:
3122 self.fail("shouldn't allow del %r.__dict__" % x)
3123 dict_descr = Base.__dict__["__dict__"]
3124 try:
3125 dict_descr.__set__(x, {})
3126 except (AttributeError, TypeError):
3127 pass
3128 else:
3129 self.fail("dict_descr allowed access to %r's dict" % x)
3130
3131 # Classes don't allow __dict__ assignment and have readonly dicts
3132 class Meta1(type, Base):
3133 pass
3134 class Meta2(Base, type):
3135 pass
3136 class D(object):
3137 __metaclass__ = Meta1
3138 class E(object):
3139 __metaclass__ = Meta2
3140 for cls in C, D, E:
3141 verify_dict_readonly(cls)
3142 class_dict = cls.__dict__
3143 try:
3144 class_dict["spam"] = "eggs"
3145 except TypeError:
3146 pass
3147 else:
3148 self.fail("%r's __dict__ can be modified" % cls)
3149
3150 # Modules also disallow __dict__ assignment
3151 class Module1(types.ModuleType, Base):
3152 pass
3153 class Module2(Base, types.ModuleType):
3154 pass
3155 for ModuleType in Module1, Module2:
3156 mod = ModuleType("spam")
3157 verify_dict_readonly(mod)
3158 mod.__dict__["spam"] = "eggs"
3159
3160 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003161 # (at least not any more than regular exception's __dict__ can
3162 # be deleted; on CPython it is not the case, whereas on PyPy they
3163 # can, just like any other new-style instance's __dict__.)
3164 def can_delete_dict(e):
3165 try:
3166 del e.__dict__
3167 except (TypeError, AttributeError):
3168 return False
3169 else:
3170 return True
Georg Brandl48545522008-02-02 10:12:36 +00003171 class Exception1(Exception, Base):
3172 pass
3173 class Exception2(Base, Exception):
3174 pass
3175 for ExceptionType in Exception, Exception1, Exception2:
3176 e = ExceptionType()
3177 e.__dict__ = {"a": 1}
3178 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003179 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003180
3181 def test_pickles(self):
3182 # Testing pickling and copying new-style classes and objects...
3183 import pickle, cPickle
3184
3185 def sorteditems(d):
3186 L = d.items()
3187 L.sort()
3188 return L
3189
3190 global C
3191 class C(object):
3192 def __init__(self, a, b):
3193 super(C, self).__init__()
3194 self.a = a
3195 self.b = b
3196 def __repr__(self):
3197 return "C(%r, %r)" % (self.a, self.b)
3198
3199 global C1
3200 class C1(list):
3201 def __new__(cls, a, b):
3202 return super(C1, cls).__new__(cls)
3203 def __getnewargs__(self):
3204 return (self.a, self.b)
3205 def __init__(self, a, b):
3206 self.a = a
3207 self.b = b
3208 def __repr__(self):
3209 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3210
3211 global C2
3212 class C2(int):
3213 def __new__(cls, a, b, val=0):
3214 return super(C2, cls).__new__(cls, val)
3215 def __getnewargs__(self):
3216 return (self.a, self.b, int(self))
3217 def __init__(self, a, b, val=0):
3218 self.a = a
3219 self.b = b
3220 def __repr__(self):
3221 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3222
3223 global C3
3224 class C3(object):
3225 def __init__(self, foo):
3226 self.foo = foo
3227 def __getstate__(self):
3228 return self.foo
3229 def __setstate__(self, foo):
3230 self.foo = foo
3231
3232 global C4classic, C4
3233 class C4classic: # classic
3234 pass
3235 class C4(C4classic, object): # mixed inheritance
3236 pass
3237
3238 for p in pickle, cPickle:
3239 for bin in 0, 1:
3240 for cls in C, C1, C2:
3241 s = p.dumps(cls, bin)
3242 cls2 = p.loads(s)
3243 self.assert_(cls2 is cls)
3244
3245 a = C1(1, 2); a.append(42); a.append(24)
3246 b = C2("hello", "world", 42)
3247 s = p.dumps((a, b), bin)
3248 x, y = p.loads(s)
3249 self.assertEqual(x.__class__, a.__class__)
3250 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3251 self.assertEqual(y.__class__, b.__class__)
3252 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3253 self.assertEqual(repr(x), repr(a))
3254 self.assertEqual(repr(y), repr(b))
3255 # Test for __getstate__ and __setstate__ on new style class
3256 u = C3(42)
3257 s = p.dumps(u, bin)
3258 v = p.loads(s)
3259 self.assertEqual(u.__class__, v.__class__)
3260 self.assertEqual(u.foo, v.foo)
3261 # Test for picklability of hybrid class
3262 u = C4()
3263 u.foo = 42
3264 s = p.dumps(u, bin)
3265 v = p.loads(s)
3266 self.assertEqual(u.__class__, v.__class__)
3267 self.assertEqual(u.foo, v.foo)
3268
3269 # Testing copy.deepcopy()
3270 import copy
3271 for cls in C, C1, C2:
3272 cls2 = copy.deepcopy(cls)
3273 self.assert_(cls2 is cls)
3274
3275 a = C1(1, 2); a.append(42); a.append(24)
3276 b = C2("hello", "world", 42)
3277 x, y = copy.deepcopy((a, b))
3278 self.assertEqual(x.__class__, a.__class__)
3279 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3280 self.assertEqual(y.__class__, b.__class__)
3281 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3282 self.assertEqual(repr(x), repr(a))
3283 self.assertEqual(repr(y), repr(b))
3284
3285 def test_pickle_slots(self):
3286 # Testing pickling of classes with __slots__ ...
3287 import pickle, cPickle
3288 # Pickling of classes with __slots__ but without __getstate__ should fail
3289 global B, C, D, E
3290 class B(object):
3291 pass
3292 for base in [object, B]:
3293 class C(base):
3294 __slots__ = ['a']
3295 class D(C):
3296 pass
3297 try:
3298 pickle.dumps(C())
3299 except TypeError:
3300 pass
3301 else:
3302 self.fail("should fail: pickle C instance - %s" % base)
3303 try:
3304 cPickle.dumps(C())
3305 except TypeError:
3306 pass
3307 else:
3308 self.fail("should fail: cPickle C instance - %s" % base)
3309 try:
3310 pickle.dumps(C())
3311 except TypeError:
3312 pass
3313 else:
3314 self.fail("should fail: pickle D instance - %s" % base)
3315 try:
3316 cPickle.dumps(D())
3317 except TypeError:
3318 pass
3319 else:
3320 self.fail("should fail: cPickle D instance - %s" % base)
3321 # Give C a nice generic __getstate__ and __setstate__
3322 class C(base):
3323 __slots__ = ['a']
3324 def __getstate__(self):
3325 try:
3326 d = self.__dict__.copy()
3327 except AttributeError:
3328 d = {}
3329 for cls in self.__class__.__mro__:
3330 for sn in cls.__dict__.get('__slots__', ()):
3331 try:
3332 d[sn] = getattr(self, sn)
3333 except AttributeError:
3334 pass
3335 return d
3336 def __setstate__(self, d):
3337 for k, v in d.items():
3338 setattr(self, k, v)
3339 class D(C):
3340 pass
3341 # Now it should work
3342 x = C()
3343 y = pickle.loads(pickle.dumps(x))
3344 self.assertEqual(hasattr(y, 'a'), 0)
3345 y = cPickle.loads(cPickle.dumps(x))
3346 self.assertEqual(hasattr(y, 'a'), 0)
3347 x.a = 42
3348 y = pickle.loads(pickle.dumps(x))
3349 self.assertEqual(y.a, 42)
3350 y = cPickle.loads(cPickle.dumps(x))
3351 self.assertEqual(y.a, 42)
3352 x = D()
3353 x.a = 42
3354 x.b = 100
3355 y = pickle.loads(pickle.dumps(x))
3356 self.assertEqual(y.a + y.b, 142)
3357 y = cPickle.loads(cPickle.dumps(x))
3358 self.assertEqual(y.a + y.b, 142)
3359 # A subclass that adds a slot should also work
3360 class E(C):
3361 __slots__ = ['b']
3362 x = E()
3363 x.a = 42
3364 x.b = "foo"
3365 y = pickle.loads(pickle.dumps(x))
3366 self.assertEqual(y.a, x.a)
3367 self.assertEqual(y.b, x.b)
3368 y = cPickle.loads(cPickle.dumps(x))
3369 self.assertEqual(y.a, x.a)
3370 self.assertEqual(y.b, x.b)
3371
3372 def test_binary_operator_override(self):
3373 # Testing overrides of binary operations...
3374 class I(int):
3375 def __repr__(self):
3376 return "I(%r)" % int(self)
3377 def __add__(self, other):
3378 return I(int(self) + int(other))
3379 __radd__ = __add__
3380 def __pow__(self, other, mod=None):
3381 if mod is None:
3382 return I(pow(int(self), int(other)))
3383 else:
3384 return I(pow(int(self), int(other), int(mod)))
3385 def __rpow__(self, other, mod=None):
3386 if mod is None:
3387 return I(pow(int(other), int(self), mod))
3388 else:
3389 return I(pow(int(other), int(self), int(mod)))
3390
3391 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3392 self.assertEqual(repr(I(1) + 2), "I(3)")
3393 self.assertEqual(repr(1 + I(2)), "I(3)")
3394 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3395 self.assertEqual(repr(2 ** I(3)), "I(8)")
3396 self.assertEqual(repr(I(2) ** 3), "I(8)")
3397 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3398 class S(str):
3399 def __eq__(self, other):
3400 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003401 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003402
3403 def test_subclass_propagation(self):
3404 # Testing propagation of slot functions to subclasses...
3405 class A(object):
3406 pass
3407 class B(A):
3408 pass
3409 class C(A):
3410 pass
3411 class D(B, C):
3412 pass
3413 d = D()
3414 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3415 A.__hash__ = lambda self: 42
3416 self.assertEqual(hash(d), 42)
3417 C.__hash__ = lambda self: 314
3418 self.assertEqual(hash(d), 314)
3419 B.__hash__ = lambda self: 144
3420 self.assertEqual(hash(d), 144)
3421 D.__hash__ = lambda self: 100
3422 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003423 D.__hash__ = None
3424 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003425 del D.__hash__
3426 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003427 B.__hash__ = None
3428 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003429 del B.__hash__
3430 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003431 C.__hash__ = None
3432 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003433 del C.__hash__
3434 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003435 A.__hash__ = None
3436 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003437 del A.__hash__
3438 self.assertEqual(hash(d), orig_hash)
3439 d.foo = 42
3440 d.bar = 42
3441 self.assertEqual(d.foo, 42)
3442 self.assertEqual(d.bar, 42)
3443 def __getattribute__(self, name):
3444 if name == "foo":
3445 return 24
3446 return object.__getattribute__(self, name)
3447 A.__getattribute__ = __getattribute__
3448 self.assertEqual(d.foo, 24)
3449 self.assertEqual(d.bar, 42)
3450 def __getattr__(self, name):
3451 if name in ("spam", "foo", "bar"):
3452 return "hello"
3453 raise AttributeError, name
3454 B.__getattr__ = __getattr__
3455 self.assertEqual(d.spam, "hello")
3456 self.assertEqual(d.foo, 24)
3457 self.assertEqual(d.bar, 42)
3458 del A.__getattribute__
3459 self.assertEqual(d.foo, 42)
3460 del d.foo
3461 self.assertEqual(d.foo, "hello")
3462 self.assertEqual(d.bar, 42)
3463 del B.__getattr__
3464 try:
3465 d.foo
3466 except AttributeError:
3467 pass
3468 else:
3469 self.fail("d.foo should be undefined now")
3470
3471 # Test a nasty bug in recurse_down_subclasses()
3472 import gc
3473 class A(object):
3474 pass
3475 class B(A):
3476 pass
3477 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003478 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003479 A.__setitem__ = lambda *a: None # crash
3480
3481 def test_buffer_inheritance(self):
3482 # Testing that buffer interface is inherited ...
3483
3484 import binascii
3485 # SF bug [#470040] ParseTuple t# vs subclasses.
3486
3487 class MyStr(str):
3488 pass
3489 base = 'abc'
3490 m = MyStr(base)
3491 # b2a_hex uses the buffer interface to get its argument's value, via
3492 # PyArg_ParseTuple 't#' code.
3493 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3494
3495 # It's not clear that unicode will continue to support the character
3496 # buffer interface, and this test will fail if that's taken away.
3497 class MyUni(unicode):
3498 pass
3499 base = u'abc'
3500 m = MyUni(base)
3501 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3502
3503 class MyInt(int):
3504 pass
3505 m = MyInt(42)
3506 try:
3507 binascii.b2a_hex(m)
3508 self.fail('subclass of int should not have a buffer interface')
3509 except TypeError:
3510 pass
3511
3512 def test_str_of_str_subclass(self):
3513 # Testing __str__ defined in subclass of str ...
3514 import binascii
3515 import cStringIO
3516
3517 class octetstring(str):
3518 def __str__(self):
3519 return binascii.b2a_hex(self)
3520 def __repr__(self):
3521 return self + " repr"
3522
3523 o = octetstring('A')
3524 self.assertEqual(type(o), octetstring)
3525 self.assertEqual(type(str(o)), str)
3526 self.assertEqual(type(repr(o)), str)
3527 self.assertEqual(ord(o), 0x41)
3528 self.assertEqual(str(o), '41')
3529 self.assertEqual(repr(o), 'A repr')
3530 self.assertEqual(o.__str__(), '41')
3531 self.assertEqual(o.__repr__(), 'A repr')
3532
3533 capture = cStringIO.StringIO()
3534 # Calling str() or not exercises different internal paths.
3535 print >> capture, o
3536 print >> capture, str(o)
3537 self.assertEqual(capture.getvalue(), '41\n41\n')
3538 capture.close()
3539
3540 def test_keyword_arguments(self):
3541 # Testing keyword arguments to __init__, __call__...
3542 def f(a): return a
3543 self.assertEqual(f.__call__(a=42), 42)
3544 a = []
3545 list.__init__(a, sequence=[0, 1, 2])
3546 self.assertEqual(a, [0, 1, 2])
3547
3548 def test_recursive_call(self):
3549 # Testing recursive __call__() by setting to instance of class...
3550 class A(object):
3551 pass
3552
3553 A.__call__ = A()
3554 try:
3555 A()()
3556 except RuntimeError:
3557 pass
3558 else:
3559 self.fail("Recursion limit should have been reached for __call__()")
3560
3561 def test_delete_hook(self):
3562 # Testing __del__ hook...
3563 log = []
3564 class C(object):
3565 def __del__(self):
3566 log.append(1)
3567 c = C()
3568 self.assertEqual(log, [])
3569 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003570 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003571 self.assertEqual(log, [1])
3572
3573 class D(object): pass
3574 d = D()
3575 try: del d[0]
3576 except TypeError: pass
3577 else: self.fail("invalid del() didn't raise TypeError")
3578
3579 def test_hash_inheritance(self):
3580 # Testing hash of mutable subclasses...
3581
3582 class mydict(dict):
3583 pass
3584 d = mydict()
3585 try:
3586 hash(d)
3587 except TypeError:
3588 pass
3589 else:
3590 self.fail("hash() of dict subclass should fail")
3591
3592 class mylist(list):
3593 pass
3594 d = mylist()
3595 try:
3596 hash(d)
3597 except TypeError:
3598 pass
3599 else:
3600 self.fail("hash() of list subclass should fail")
3601
3602 def test_str_operations(self):
3603 try: 'a' + 5
3604 except TypeError: pass
3605 else: self.fail("'' + 5 doesn't raise TypeError")
3606
3607 try: ''.split('')
3608 except ValueError: pass
3609 else: self.fail("''.split('') doesn't raise ValueError")
3610
3611 try: ''.join([0])
3612 except TypeError: pass
3613 else: self.fail("''.join([0]) doesn't raise TypeError")
3614
3615 try: ''.rindex('5')
3616 except ValueError: pass
3617 else: self.fail("''.rindex('5') doesn't raise ValueError")
3618
3619 try: '%(n)s' % None
3620 except TypeError: pass
3621 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3622
3623 try: '%(n' % {}
3624 except ValueError: pass
3625 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3626
3627 try: '%*s' % ('abc')
3628 except TypeError: pass
3629 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3630
3631 try: '%*.*s' % ('abc', 5)
3632 except TypeError: pass
3633 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3634
3635 try: '%s' % (1, 2)
3636 except TypeError: pass
3637 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3638
3639 try: '%' % None
3640 except ValueError: pass
3641 else: self.fail("'%' % None doesn't raise ValueError")
3642
3643 self.assertEqual('534253'.isdigit(), 1)
3644 self.assertEqual('534253x'.isdigit(), 0)
3645 self.assertEqual('%c' % 5, '\x05')
3646 self.assertEqual('%c' % '5', '5')
3647
3648 def test_deepcopy_recursive(self):
3649 # Testing deepcopy of recursive objects...
3650 class Node:
3651 pass
3652 a = Node()
3653 b = Node()
3654 a.b = b
3655 b.a = a
3656 z = deepcopy(a) # This blew up before
3657
3658 def test_unintialized_modules(self):
3659 # Testing uninitialized module objects...
3660 from types import ModuleType as M
3661 m = M.__new__(M)
3662 str(m)
3663 self.assertEqual(hasattr(m, "__name__"), 0)
3664 self.assertEqual(hasattr(m, "__file__"), 0)
3665 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003666 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003667 m.foo = 1
3668 self.assertEqual(m.__dict__, {"foo": 1})
3669
3670 def test_funny_new(self):
3671 # Testing __new__ returning something unexpected...
3672 class C(object):
3673 def __new__(cls, arg):
3674 if isinstance(arg, str): return [1, 2, 3]
3675 elif isinstance(arg, int): return object.__new__(D)
3676 else: return object.__new__(cls)
3677 class D(C):
3678 def __init__(self, arg):
3679 self.foo = arg
3680 self.assertEqual(C("1"), [1, 2, 3])
3681 self.assertEqual(D("1"), [1, 2, 3])
3682 d = D(None)
3683 self.assertEqual(d.foo, None)
3684 d = C(1)
3685 self.assertEqual(isinstance(d, D), True)
3686 self.assertEqual(d.foo, 1)
3687 d = D(1)
3688 self.assertEqual(isinstance(d, D), True)
3689 self.assertEqual(d.foo, 1)
3690
3691 def test_imul_bug(self):
3692 # Testing for __imul__ problems...
3693 # SF bug 544647
3694 class C(object):
3695 def __imul__(self, other):
3696 return (self, other)
3697 x = C()
3698 y = x
3699 y *= 1.0
3700 self.assertEqual(y, (x, 1.0))
3701 y = x
3702 y *= 2
3703 self.assertEqual(y, (x, 2))
3704 y = x
3705 y *= 3L
3706 self.assertEqual(y, (x, 3L))
3707 y = x
3708 y *= 1L<<100
3709 self.assertEqual(y, (x, 1L<<100))
3710 y = x
3711 y *= None
3712 self.assertEqual(y, (x, None))
3713 y = x
3714 y *= "foo"
3715 self.assertEqual(y, (x, "foo"))
3716
3717 def test_copy_setstate(self):
3718 # Testing that copy.*copy() correctly uses __setstate__...
3719 import copy
3720 class C(object):
3721 def __init__(self, foo=None):
3722 self.foo = foo
3723 self.__foo = foo
3724 def setfoo(self, foo=None):
3725 self.foo = foo
3726 def getfoo(self):
3727 return self.__foo
3728 def __getstate__(self):
3729 return [self.foo]
3730 def __setstate__(self_, lst):
3731 self.assertEqual(len(lst), 1)
3732 self_.__foo = self_.foo = lst[0]
3733 a = C(42)
3734 a.setfoo(24)
3735 self.assertEqual(a.foo, 24)
3736 self.assertEqual(a.getfoo(), 42)
3737 b = copy.copy(a)
3738 self.assertEqual(b.foo, 24)
3739 self.assertEqual(b.getfoo(), 24)
3740 b = copy.deepcopy(a)
3741 self.assertEqual(b.foo, 24)
3742 self.assertEqual(b.getfoo(), 24)
3743
3744 def test_slices(self):
3745 # Testing cases with slices and overridden __getitem__ ...
3746
3747 # Strings
3748 self.assertEqual("hello"[:4], "hell")
3749 self.assertEqual("hello"[slice(4)], "hell")
3750 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3751 class S(str):
3752 def __getitem__(self, x):
3753 return str.__getitem__(self, x)
3754 self.assertEqual(S("hello")[:4], "hell")
3755 self.assertEqual(S("hello")[slice(4)], "hell")
3756 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3757 # Tuples
3758 self.assertEqual((1,2,3)[:2], (1,2))
3759 self.assertEqual((1,2,3)[slice(2)], (1,2))
3760 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3761 class T(tuple):
3762 def __getitem__(self, x):
3763 return tuple.__getitem__(self, x)
3764 self.assertEqual(T((1,2,3))[:2], (1,2))
3765 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3766 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3767 # Lists
3768 self.assertEqual([1,2,3][:2], [1,2])
3769 self.assertEqual([1,2,3][slice(2)], [1,2])
3770 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3771 class L(list):
3772 def __getitem__(self, x):
3773 return list.__getitem__(self, x)
3774 self.assertEqual(L([1,2,3])[:2], [1,2])
3775 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3776 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3777 # Now do lists and __setitem__
3778 a = L([1,2,3])
3779 a[slice(1, 3)] = [3,2]
3780 self.assertEqual(a, [1,3,2])
3781 a[slice(0, 2, 1)] = [3,1]
3782 self.assertEqual(a, [3,1,2])
3783 a.__setitem__(slice(1, 3), [2,1])
3784 self.assertEqual(a, [3,2,1])
3785 a.__setitem__(slice(0, 2, 1), [2,3])
3786 self.assertEqual(a, [2,3,1])
3787
3788 def test_subtype_resurrection(self):
3789 # Testing resurrection of new-style instance...
3790
3791 class C(object):
3792 container = []
3793
3794 def __del__(self):
3795 # resurrect the instance
3796 C.container.append(self)
3797
3798 c = C()
3799 c.attr = 42
3800
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003801 # The most interesting thing here is whether this blows up, due to
3802 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3803 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003804 del c
3805
3806 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003807 # the last container slot works: that will attempt to delete c again,
3808 # which will cause c to get appended back to the container again
3809 # "during" the del. (On non-CPython implementations, however, __del__
3810 # is typically not called again.)
3811 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003812 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003813 del C.container[-1]
3814 if test_support.check_impl_detail():
3815 test_support.gc_collect()
3816 self.assertEqual(len(C.container), 1)
3817 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003818
3819 # Make c mortal again, so that the test framework with -l doesn't report
3820 # it as a leak.
3821 del C.__del__
3822
3823 def test_slots_trash(self):
3824 # Testing slot trash...
3825 # Deallocating deeply nested slotted trash caused stack overflows
3826 class trash(object):
3827 __slots__ = ['x']
3828 def __init__(self, x):
3829 self.x = x
3830 o = None
3831 for i in xrange(50000):
3832 o = trash(o)
3833 del o
3834
3835 def test_slots_multiple_inheritance(self):
3836 # SF bug 575229, multiple inheritance w/ slots dumps core
3837 class A(object):
3838 __slots__=()
3839 class B(object):
3840 pass
3841 class C(A,B) :
3842 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003843 if test_support.check_impl_detail():
3844 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl48545522008-02-02 10:12:36 +00003845 self.assert_(hasattr(C, '__dict__'))
3846 self.assert_(hasattr(C, '__weakref__'))
3847 C().x = 2
3848
3849 def test_rmul(self):
3850 # Testing correct invocation of __rmul__...
3851 # SF patch 592646
3852 class C(object):
3853 def __mul__(self, other):
3854 return "mul"
3855 def __rmul__(self, other):
3856 return "rmul"
3857 a = C()
3858 self.assertEqual(a*2, "mul")
3859 self.assertEqual(a*2.2, "mul")
3860 self.assertEqual(2*a, "rmul")
3861 self.assertEqual(2.2*a, "rmul")
3862
3863 def test_ipow(self):
3864 # Testing correct invocation of __ipow__...
3865 # [SF bug 620179]
3866 class C(object):
3867 def __ipow__(self, other):
3868 pass
3869 a = C()
3870 a **= 2
3871
3872 def test_mutable_bases(self):
3873 # Testing mutable bases...
3874
3875 # stuff that should work:
3876 class C(object):
3877 pass
3878 class C2(object):
3879 def __getattribute__(self, attr):
3880 if attr == 'a':
3881 return 2
3882 else:
3883 return super(C2, self).__getattribute__(attr)
3884 def meth(self):
3885 return 1
3886 class D(C):
3887 pass
3888 class E(D):
3889 pass
3890 d = D()
3891 e = E()
3892 D.__bases__ = (C,)
3893 D.__bases__ = (C2,)
3894 self.assertEqual(d.meth(), 1)
3895 self.assertEqual(e.meth(), 1)
3896 self.assertEqual(d.a, 2)
3897 self.assertEqual(e.a, 2)
3898 self.assertEqual(C2.__subclasses__(), [D])
3899
Georg Brandl48545522008-02-02 10:12:36 +00003900 try:
3901 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003902 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003903 pass
3904 else:
3905 self.fail("shouldn't be able to delete .__bases__")
3906
3907 try:
3908 D.__bases__ = ()
3909 except TypeError, msg:
3910 if str(msg) == "a new-style class can't have only classic bases":
3911 self.fail("wrong error message for .__bases__ = ()")
3912 else:
3913 self.fail("shouldn't be able to set .__bases__ to ()")
3914
3915 try:
3916 D.__bases__ = (D,)
3917 except TypeError:
3918 pass
3919 else:
3920 # actually, we'll have crashed by here...
3921 self.fail("shouldn't be able to create inheritance cycles")
3922
3923 try:
3924 D.__bases__ = (C, C)
3925 except TypeError:
3926 pass
3927 else:
3928 self.fail("didn't detect repeated base classes")
3929
3930 try:
3931 D.__bases__ = (E,)
3932 except TypeError:
3933 pass
3934 else:
3935 self.fail("shouldn't be able to create inheritance cycles")
3936
3937 # let's throw a classic class into the mix:
3938 class Classic:
3939 def meth2(self):
3940 return 3
3941
3942 D.__bases__ = (C, Classic)
3943
3944 self.assertEqual(d.meth2(), 3)
3945 self.assertEqual(e.meth2(), 3)
3946 try:
3947 d.a
3948 except AttributeError:
3949 pass
3950 else:
3951 self.fail("attribute should have vanished")
3952
3953 try:
3954 D.__bases__ = (Classic,)
3955 except TypeError:
3956 pass
3957 else:
3958 self.fail("new-style class must have a new-style base")
3959
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003960 def test_builtin_bases(self):
3961 # Make sure all the builtin types can have their base queried without
3962 # segfaulting. See issue #5787.
3963 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3964 if isinstance(tp, type)]
3965 for tp in builtin_types:
3966 object.__getattribute__(tp, "__bases__")
3967 if tp is not object:
3968 self.assertEqual(len(tp.__bases__), 1, tp)
3969
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003970 class L(list):
3971 pass
3972
3973 class C(object):
3974 pass
3975
3976 class D(C):
3977 pass
3978
3979 try:
3980 L.__bases__ = (dict,)
3981 except TypeError:
3982 pass
3983 else:
3984 self.fail("shouldn't turn list subclass into dict subclass")
3985
3986 try:
3987 list.__bases__ = (dict,)
3988 except TypeError:
3989 pass
3990 else:
3991 self.fail("shouldn't be able to assign to list.__bases__")
3992
3993 try:
3994 D.__bases__ = (C, list)
3995 except TypeError:
3996 pass
3997 else:
3998 assert 0, "best_base calculation found wanting"
3999
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004000
Georg Brandl48545522008-02-02 10:12:36 +00004001 def test_mutable_bases_with_failing_mro(self):
4002 # Testing mutable bases with failing mro...
4003 class WorkOnce(type):
4004 def __new__(self, name, bases, ns):
4005 self.flag = 0
4006 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4007 def mro(self):
4008 if self.flag > 0:
4009 raise RuntimeError, "bozo"
4010 else:
4011 self.flag += 1
4012 return type.mro(self)
4013
4014 class WorkAlways(type):
4015 def mro(self):
4016 # this is here to make sure that .mro()s aren't called
4017 # with an exception set (which was possible at one point).
4018 # An error message will be printed in a debug build.
4019 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004020 return type.mro(self)
4021
Georg Brandl48545522008-02-02 10:12:36 +00004022 class C(object):
4023 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004024
Georg Brandl48545522008-02-02 10:12:36 +00004025 class C2(object):
4026 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004027
Georg Brandl48545522008-02-02 10:12:36 +00004028 class D(C):
4029 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004030
Georg Brandl48545522008-02-02 10:12:36 +00004031 class E(D):
4032 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004033
Georg Brandl48545522008-02-02 10:12:36 +00004034 class F(D):
4035 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004036
Georg Brandl48545522008-02-02 10:12:36 +00004037 class G(D):
4038 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004039
Georg Brandl48545522008-02-02 10:12:36 +00004040 # Immediate subclasses have their mro's adjusted in alphabetical
4041 # order, so E's will get adjusted before adjusting F's fails. We
4042 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004043
Georg Brandl48545522008-02-02 10:12:36 +00004044 E_mro_before = E.__mro__
4045 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004046
Armin Rigofd163f92005-12-29 15:59:19 +00004047 try:
Georg Brandl48545522008-02-02 10:12:36 +00004048 D.__bases__ = (C2,)
4049 except RuntimeError:
4050 self.assertEqual(E.__mro__, E_mro_before)
4051 self.assertEqual(D.__mro__, D_mro_before)
4052 else:
4053 self.fail("exception not propagated")
4054
4055 def test_mutable_bases_catch_mro_conflict(self):
4056 # Testing mutable bases catch mro conflict...
4057 class A(object):
4058 pass
4059
4060 class B(object):
4061 pass
4062
4063 class C(A, B):
4064 pass
4065
4066 class D(A, B):
4067 pass
4068
4069 class E(C, D):
4070 pass
4071
4072 try:
4073 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004074 except TypeError:
4075 pass
4076 else:
Georg Brandl48545522008-02-02 10:12:36 +00004077 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004078
Georg Brandl48545522008-02-02 10:12:36 +00004079 def test_mutable_names(self):
4080 # Testing mutable names...
4081 class C(object):
4082 pass
4083
4084 # C.__module__ could be 'test_descr' or '__main__'
4085 mod = C.__module__
4086
4087 C.__name__ = 'D'
4088 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4089
4090 C.__name__ = 'D.E'
4091 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4092
4093 def test_subclass_right_op(self):
4094 # Testing correct dispatch of subclass overloading __r<op>__...
4095
4096 # This code tests various cases where right-dispatch of a subclass
4097 # should be preferred over left-dispatch of a base class.
4098
4099 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4100
4101 class B(int):
4102 def __floordiv__(self, other):
4103 return "B.__floordiv__"
4104 def __rfloordiv__(self, other):
4105 return "B.__rfloordiv__"
4106
4107 self.assertEqual(B(1) // 1, "B.__floordiv__")
4108 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4109
4110 # Case 2: subclass of object; this is just the baseline for case 3
4111
4112 class C(object):
4113 def __floordiv__(self, other):
4114 return "C.__floordiv__"
4115 def __rfloordiv__(self, other):
4116 return "C.__rfloordiv__"
4117
4118 self.assertEqual(C() // 1, "C.__floordiv__")
4119 self.assertEqual(1 // C(), "C.__rfloordiv__")
4120
4121 # Case 3: subclass of new-style class; here it gets interesting
4122
4123 class D(C):
4124 def __floordiv__(self, other):
4125 return "D.__floordiv__"
4126 def __rfloordiv__(self, other):
4127 return "D.__rfloordiv__"
4128
4129 self.assertEqual(D() // C(), "D.__floordiv__")
4130 self.assertEqual(C() // D(), "D.__rfloordiv__")
4131
4132 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4133
4134 class E(C):
4135 pass
4136
4137 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4138
4139 self.assertEqual(E() // 1, "C.__floordiv__")
4140 self.assertEqual(1 // E(), "C.__rfloordiv__")
4141 self.assertEqual(E() // C(), "C.__floordiv__")
4142 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4143
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004144 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004145 def test_meth_class_get(self):
4146 # Testing __get__ method of METH_CLASS C methods...
4147 # Full coverage of descrobject.c::classmethod_get()
4148
4149 # Baseline
4150 arg = [1, 2, 3]
4151 res = {1: None, 2: None, 3: None}
4152 self.assertEqual(dict.fromkeys(arg), res)
4153 self.assertEqual({}.fromkeys(arg), res)
4154
4155 # Now get the descriptor
4156 descr = dict.__dict__["fromkeys"]
4157
4158 # More baseline using the descriptor directly
4159 self.assertEqual(descr.__get__(None, dict)(arg), res)
4160 self.assertEqual(descr.__get__({})(arg), res)
4161
4162 # Now check various error cases
4163 try:
4164 descr.__get__(None, None)
4165 except TypeError:
4166 pass
4167 else:
4168 self.fail("shouldn't have allowed descr.__get__(None, None)")
4169 try:
4170 descr.__get__(42)
4171 except TypeError:
4172 pass
4173 else:
4174 self.fail("shouldn't have allowed descr.__get__(42)")
4175 try:
4176 descr.__get__(None, 42)
4177 except TypeError:
4178 pass
4179 else:
4180 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4181 try:
4182 descr.__get__(None, int)
4183 except TypeError:
4184 pass
4185 else:
4186 self.fail("shouldn't have allowed descr.__get__(None, int)")
4187
4188 def test_isinst_isclass(self):
4189 # Testing proxy isinstance() and isclass()...
4190 class Proxy(object):
4191 def __init__(self, obj):
4192 self.__obj = obj
4193 def __getattribute__(self, name):
4194 if name.startswith("_Proxy__"):
4195 return object.__getattribute__(self, name)
4196 else:
4197 return getattr(self.__obj, name)
4198 # Test with a classic class
4199 class C:
4200 pass
4201 a = C()
4202 pa = Proxy(a)
4203 self.assert_(isinstance(a, C)) # Baseline
4204 self.assert_(isinstance(pa, C)) # Test
4205 # Test with a classic subclass
4206 class D(C):
4207 pass
4208 a = D()
4209 pa = Proxy(a)
4210 self.assert_(isinstance(a, C)) # Baseline
4211 self.assert_(isinstance(pa, C)) # Test
4212 # Test with a new-style class
4213 class C(object):
4214 pass
4215 a = C()
4216 pa = Proxy(a)
4217 self.assert_(isinstance(a, C)) # Baseline
4218 self.assert_(isinstance(pa, C)) # Test
4219 # Test with a new-style subclass
4220 class D(C):
4221 pass
4222 a = D()
4223 pa = Proxy(a)
4224 self.assert_(isinstance(a, C)) # Baseline
4225 self.assert_(isinstance(pa, C)) # Test
4226
4227 def test_proxy_super(self):
4228 # Testing super() for a proxy object...
4229 class Proxy(object):
4230 def __init__(self, obj):
4231 self.__obj = obj
4232 def __getattribute__(self, name):
4233 if name.startswith("_Proxy__"):
4234 return object.__getattribute__(self, name)
4235 else:
4236 return getattr(self.__obj, name)
4237
4238 class B(object):
4239 def f(self):
4240 return "B.f"
4241
4242 class C(B):
4243 def f(self):
4244 return super(C, self).f() + "->C.f"
4245
4246 obj = C()
4247 p = Proxy(obj)
4248 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4249
4250 def test_carloverre(self):
4251 # Testing prohibition of Carlo Verre's hack...
4252 try:
4253 object.__setattr__(str, "foo", 42)
4254 except TypeError:
4255 pass
4256 else:
4257 self.fail("Carlo Verre __setattr__ suceeded!")
4258 try:
4259 object.__delattr__(str, "lower")
4260 except TypeError:
4261 pass
4262 else:
4263 self.fail("Carlo Verre __delattr__ succeeded!")
4264
4265 def test_weakref_segfault(self):
4266 # Testing weakref segfault...
4267 # SF 742911
4268 import weakref
4269
4270 class Provoker:
4271 def __init__(self, referrent):
4272 self.ref = weakref.ref(referrent)
4273
4274 def __del__(self):
4275 x = self.ref()
4276
4277 class Oops(object):
4278 pass
4279
4280 o = Oops()
4281 o.whatever = Provoker(o)
4282 del o
4283
4284 def test_wrapper_segfault(self):
4285 # SF 927248: deeply nested wrappers could cause stack overflow
4286 f = lambda:None
4287 for i in xrange(1000000):
4288 f = f.__call__
4289 f = None
4290
4291 def test_file_fault(self):
4292 # Testing sys.stdout is changed in getattr...
4293 import sys
4294 class StdoutGuard:
4295 def __getattr__(self, attr):
4296 sys.stdout = sys.__stdout__
4297 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4298 sys.stdout = StdoutGuard()
4299 try:
4300 print "Oops!"
4301 except RuntimeError:
4302 pass
4303
4304 def test_vicious_descriptor_nonsense(self):
4305 # Testing vicious_descriptor_nonsense...
4306
4307 # A potential segfault spotted by Thomas Wouters in mail to
4308 # python-dev 2003-04-17, turned into an example & fixed by Michael
4309 # Hudson just less than four months later...
4310
4311 class Evil(object):
4312 def __hash__(self):
4313 return hash('attr')
4314 def __eq__(self, other):
4315 del C.attr
4316 return 0
4317
4318 class Descr(object):
4319 def __get__(self, ob, type=None):
4320 return 1
4321
4322 class C(object):
4323 attr = Descr()
4324
4325 c = C()
4326 c.__dict__[Evil()] = 0
4327
4328 self.assertEqual(c.attr, 1)
4329 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004330 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004331 self.assertEqual(hasattr(c, 'attr'), False)
4332
4333 def test_init(self):
4334 # SF 1155938
4335 class Foo(object):
4336 def __init__(self):
4337 return 10
4338 try:
4339 Foo()
4340 except TypeError:
4341 pass
4342 else:
4343 self.fail("did not test __init__() for None return")
4344
4345 def test_method_wrapper(self):
4346 # Testing method-wrapper objects...
4347 # <type 'method-wrapper'> did not support any reflection before 2.5
4348
4349 l = []
4350 self.assertEqual(l.__add__, l.__add__)
4351 self.assertEqual(l.__add__, [].__add__)
4352 self.assert_(l.__add__ != [5].__add__)
4353 self.assert_(l.__add__ != l.__mul__)
4354 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004355 if hasattr(l.__add__, '__self__'):
4356 # CPython
4357 self.assert_(l.__add__.__self__ is l)
4358 self.assert_(l.__add__.__objclass__ is list)
4359 else:
4360 # Python implementations where [].__add__ is a normal bound method
4361 self.assert_(l.__add__.im_self is l)
4362 self.assert_(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004363 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4364 try:
4365 hash(l.__add__)
4366 except TypeError:
4367 pass
4368 else:
4369 self.fail("no TypeError from hash([].__add__)")
4370
4371 t = ()
4372 t += (7,)
4373 self.assertEqual(t.__add__, (7,).__add__)
4374 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4375
4376 def test_not_implemented(self):
4377 # Testing NotImplemented...
4378 # all binary methods should be able to return a NotImplemented
4379 import sys
4380 import types
4381 import operator
4382
4383 def specialmethod(self, other):
4384 return NotImplemented
4385
4386 def check(expr, x, y):
4387 try:
4388 exec expr in {'x': x, 'y': y, 'operator': operator}
4389 except TypeError:
4390 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004391 else:
Georg Brandl48545522008-02-02 10:12:36 +00004392 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004393
Georg Brandl48545522008-02-02 10:12:36 +00004394 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4395 # TypeErrors
4396 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4397 # ValueErrors instead of TypeErrors
4398 for metaclass in [type, types.ClassType]:
4399 for name, expr, iexpr in [
4400 ('__add__', 'x + y', 'x += y'),
4401 ('__sub__', 'x - y', 'x -= y'),
4402 ('__mul__', 'x * y', 'x *= y'),
4403 ('__truediv__', 'operator.truediv(x, y)', None),
4404 ('__floordiv__', 'operator.floordiv(x, y)', None),
4405 ('__div__', 'x / y', 'x /= y'),
4406 ('__mod__', 'x % y', 'x %= y'),
4407 ('__divmod__', 'divmod(x, y)', None),
4408 ('__pow__', 'x ** y', 'x **= y'),
4409 ('__lshift__', 'x << y', 'x <<= y'),
4410 ('__rshift__', 'x >> y', 'x >>= y'),
4411 ('__and__', 'x & y', 'x &= y'),
4412 ('__or__', 'x | y', 'x |= y'),
4413 ('__xor__', 'x ^ y', 'x ^= y'),
4414 ('__coerce__', 'coerce(x, y)', None)]:
4415 if name == '__coerce__':
4416 rname = name
4417 else:
4418 rname = '__r' + name[2:]
4419 A = metaclass('A', (), {name: specialmethod})
4420 B = metaclass('B', (), {rname: specialmethod})
4421 a = A()
4422 b = B()
4423 check(expr, a, a)
4424 check(expr, a, b)
4425 check(expr, b, a)
4426 check(expr, b, b)
4427 check(expr, a, N1)
4428 check(expr, a, N2)
4429 check(expr, N1, b)
4430 check(expr, N2, b)
4431 if iexpr:
4432 check(iexpr, a, a)
4433 check(iexpr, a, b)
4434 check(iexpr, b, a)
4435 check(iexpr, b, b)
4436 check(iexpr, a, N1)
4437 check(iexpr, a, N2)
4438 iname = '__i' + name[2:]
4439 C = metaclass('C', (), {iname: specialmethod})
4440 c = C()
4441 check(iexpr, c, a)
4442 check(iexpr, c, b)
4443 check(iexpr, c, N1)
4444 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004445
Georg Brandl48545522008-02-02 10:12:36 +00004446 def test_assign_slice(self):
4447 # ceval.c's assign_slice used to check for
4448 # tp->tp_as_sequence->sq_slice instead of
4449 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004450
Georg Brandl48545522008-02-02 10:12:36 +00004451 class C(object):
4452 def __setslice__(self, start, stop, value):
4453 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004454
Georg Brandl48545522008-02-02 10:12:36 +00004455 c = C()
4456 c[1:2] = 3
4457 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004458
Benjamin Peterson273c2332008-11-17 22:39:09 +00004459 def test_getattr_hooks(self):
4460 # issue 4230
4461
4462 class Descriptor(object):
4463 counter = 0
4464 def __get__(self, obj, objtype=None):
4465 def getter(name):
4466 self.counter += 1
4467 raise AttributeError(name)
4468 return getter
4469
4470 descr = Descriptor()
4471 class A(object):
4472 __getattribute__ = descr
4473 class B(object):
4474 __getattr__ = descr
4475 class C(object):
4476 __getattribute__ = descr
4477 __getattr__ = descr
4478
4479 self.assertRaises(AttributeError, getattr, A(), "attr")
4480 self.assertEquals(descr.counter, 1)
4481 self.assertRaises(AttributeError, getattr, B(), "attr")
4482 self.assertEquals(descr.counter, 2)
4483 self.assertRaises(AttributeError, getattr, C(), "attr")
4484 self.assertEquals(descr.counter, 4)
4485
4486 import gc
4487 class EvilGetattribute(object):
4488 # This used to segfault
4489 def __getattr__(self, name):
4490 raise AttributeError(name)
4491 def __getattribute__(self, name):
4492 del EvilGetattribute.__getattr__
4493 for i in range(5):
4494 gc.collect()
4495 raise AttributeError(name)
4496
4497 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4498
Guido van Rossum9acc3872008-01-23 23:23:43 +00004499
Georg Brandl48545522008-02-02 10:12:36 +00004500class DictProxyTests(unittest.TestCase):
4501 def setUp(self):
4502 class C(object):
4503 def meth(self):
4504 pass
4505 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004506
Georg Brandl48545522008-02-02 10:12:36 +00004507 def test_iter_keys(self):
4508 # Testing dict-proxy iterkeys...
4509 keys = [ key for key in self.C.__dict__.iterkeys() ]
4510 keys.sort()
4511 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4512 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004513
Georg Brandl48545522008-02-02 10:12:36 +00004514 def test_iter_values(self):
4515 # Testing dict-proxy itervalues...
4516 values = [ values for values in self.C.__dict__.itervalues() ]
4517 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004518
Georg Brandl48545522008-02-02 10:12:36 +00004519 def test_iter_items(self):
4520 # Testing dict-proxy iteritems...
4521 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4522 keys.sort()
4523 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4524 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004525
Georg Brandl48545522008-02-02 10:12:36 +00004526 def test_dict_type_with_metaclass(self):
4527 # Testing type of __dict__ when __metaclass__ set...
4528 class B(object):
4529 pass
4530 class M(type):
4531 pass
4532 class C:
4533 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4534 __metaclass__ = M
4535 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004536
Guido van Rossum9acc3872008-01-23 23:23:43 +00004537
Georg Brandl48545522008-02-02 10:12:36 +00004538class PTypesLongInitTest(unittest.TestCase):
4539 # This is in its own TestCase so that it can be run before any other tests.
4540 def test_pytype_long_ready(self):
4541 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004542
Georg Brandl48545522008-02-02 10:12:36 +00004543 # This dumps core when SF bug 551412 isn't fixed --
4544 # but only when test_descr.py is run separately.
4545 # (That can't be helped -- as soon as PyType_Ready()
4546 # is called for PyLong_Type, the bug is gone.)
4547 class UserLong(object):
4548 def __pow__(self, *args):
4549 pass
4550 try:
4551 pow(0L, UserLong(), 0L)
4552 except:
4553 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004554
Georg Brandl48545522008-02-02 10:12:36 +00004555 # Another segfault only when run early
4556 # (before PyType_Ready(tuple) is called)
4557 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004558
4559
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004560def test_main():
Georg Brandl48545522008-02-02 10:12:36 +00004561 # Run all local test cases, with PTypesLongInitTest first.
4562 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4563 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004564
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004565if __name__ == "__main__":
4566 test_main()