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