blob: 2b00ce9ea6e9704093c8c2658d7404ea82b46fdd [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)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001702 return self.impl.__get__(obj, owner)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001703
1704
1705 for name, runner, meth_impl in specials:
1706 class X(Checker):
1707 pass
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001708 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001709 runner(X())
1710
1711 record = []
1712 class X(Checker):
1713 pass
1714 setattr(X, name, SpecialDescr(meth_impl))
1715 runner(X())
1716 self.assertEqual(record, [1], name)
1717
Georg Brandl48545522008-02-02 10:12:36 +00001718 def test_specials(self):
1719 # Testing special operators...
1720 # Test operators like __hash__ for which a built-in default exists
1721
1722 # Test the default behavior for static classes
1723 class C(object):
1724 def __getitem__(self, i):
1725 if 0 <= i < 10: return i
1726 raise IndexError
1727 c1 = C()
1728 c2 = C()
1729 self.assert_(not not c1) # What?
1730 self.assertNotEqual(id(c1), id(c2))
1731 hash(c1)
1732 hash(c2)
1733 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1734 self.assertEqual(c1, c1)
1735 self.assert_(c1 != c2)
1736 self.assert_(not c1 != c1)
1737 self.assert_(not c1 == c2)
1738 # Note that the module name appears in str/repr, and that varies
1739 # depending on whether this test is run standalone or from a framework.
1740 self.assert_(str(c1).find('C object at ') >= 0)
1741 self.assertEqual(str(c1), repr(c1))
1742 self.assert_(-1 not in c1)
1743 for i in range(10):
1744 self.assert_(i in c1)
1745 self.assertFalse(10 in c1)
1746 # Test the default behavior for dynamic classes
1747 class D(object):
1748 def __getitem__(self, i):
1749 if 0 <= i < 10: return i
1750 raise IndexError
1751 d1 = D()
1752 d2 = D()
1753 self.assert_(not not d1)
1754 self.assertNotEqual(id(d1), id(d2))
1755 hash(d1)
1756 hash(d2)
1757 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1758 self.assertEqual(d1, d1)
1759 self.assertNotEqual(d1, d2)
1760 self.assert_(not d1 != d1)
1761 self.assert_(not d1 == d2)
1762 # Note that the module name appears in str/repr, and that varies
1763 # depending on whether this test is run standalone or from a framework.
1764 self.assert_(str(d1).find('D object at ') >= 0)
1765 self.assertEqual(str(d1), repr(d1))
1766 self.assert_(-1 not in d1)
1767 for i in range(10):
1768 self.assert_(i in d1)
1769 self.assertFalse(10 in d1)
1770 # Test overridden behavior for static classes
1771 class Proxy(object):
1772 def __init__(self, x):
1773 self.x = x
1774 def __nonzero__(self):
1775 return not not self.x
1776 def __hash__(self):
1777 return hash(self.x)
1778 def __eq__(self, other):
1779 return self.x == other
1780 def __ne__(self, other):
1781 return self.x != other
1782 def __cmp__(self, other):
1783 return cmp(self.x, other.x)
1784 def __str__(self):
1785 return "Proxy:%s" % self.x
1786 def __repr__(self):
1787 return "Proxy(%r)" % self.x
1788 def __contains__(self, value):
1789 return value in self.x
1790 p0 = Proxy(0)
1791 p1 = Proxy(1)
1792 p_1 = Proxy(-1)
1793 self.assertFalse(p0)
1794 self.assert_(not not p1)
1795 self.assertEqual(hash(p0), hash(0))
1796 self.assertEqual(p0, p0)
1797 self.assertNotEqual(p0, p1)
1798 self.assert_(not p0 != p0)
1799 self.assertEqual(not p0, p1)
1800 self.assertEqual(cmp(p0, p1), -1)
1801 self.assertEqual(cmp(p0, p0), 0)
1802 self.assertEqual(cmp(p0, p_1), 1)
1803 self.assertEqual(str(p0), "Proxy:0")
1804 self.assertEqual(repr(p0), "Proxy(0)")
1805 p10 = Proxy(range(10))
1806 self.assertFalse(-1 in p10)
1807 for i in range(10):
1808 self.assert_(i in p10)
1809 self.assertFalse(10 in p10)
1810 # Test overridden behavior for dynamic classes
1811 class DProxy(object):
1812 def __init__(self, x):
1813 self.x = x
1814 def __nonzero__(self):
1815 return not not self.x
1816 def __hash__(self):
1817 return hash(self.x)
1818 def __eq__(self, other):
1819 return self.x == other
1820 def __ne__(self, other):
1821 return self.x != other
1822 def __cmp__(self, other):
1823 return cmp(self.x, other.x)
1824 def __str__(self):
1825 return "DProxy:%s" % self.x
1826 def __repr__(self):
1827 return "DProxy(%r)" % self.x
1828 def __contains__(self, value):
1829 return value in self.x
1830 p0 = DProxy(0)
1831 p1 = DProxy(1)
1832 p_1 = DProxy(-1)
1833 self.assertFalse(p0)
1834 self.assert_(not not p1)
1835 self.assertEqual(hash(p0), hash(0))
1836 self.assertEqual(p0, p0)
1837 self.assertNotEqual(p0, p1)
1838 self.assertNotEqual(not p0, p0)
1839 self.assertEqual(not p0, p1)
1840 self.assertEqual(cmp(p0, p1), -1)
1841 self.assertEqual(cmp(p0, p0), 0)
1842 self.assertEqual(cmp(p0, p_1), 1)
1843 self.assertEqual(str(p0), "DProxy:0")
1844 self.assertEqual(repr(p0), "DProxy(0)")
1845 p10 = DProxy(range(10))
1846 self.assertFalse(-1 in p10)
1847 for i in range(10):
1848 self.assert_(i in p10)
1849 self.assertFalse(10 in p10)
1850
1851 # Safety test for __cmp__
1852 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001853 if not hasattr(a, '__cmp__'):
1854 return # some types don't have a __cmp__ any more (so the
1855 # test doesn't make sense any more), or maybe they
1856 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001857 try:
1858 a.__class__.__cmp__(a, b)
1859 except TypeError:
1860 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001861 else:
Georg Brandl48545522008-02-02 10:12:36 +00001862 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1863 a.__class__, a, b))
1864
1865 unsafecmp(u"123", "123")
1866 unsafecmp("123", u"123")
1867 unsafecmp(1, 1.0)
1868 unsafecmp(1.0, 1)
1869 unsafecmp(1, 1L)
1870 unsafecmp(1L, 1)
1871
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001872 @test_support.impl_detail("custom logic for printing to real file objects")
1873 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001874 # Testing recursion checks ...
1875 class Letter(str):
1876 def __new__(cls, letter):
1877 if letter == 'EPS':
1878 return str.__new__(cls)
1879 return str.__new__(cls, letter)
1880 def __str__(self):
1881 if not self:
1882 return 'EPS'
1883 return self
1884 # sys.stdout needs to be the original to trigger the recursion bug
1885 import sys
1886 test_stdout = sys.stdout
1887 sys.stdout = test_support.get_original_stdout()
1888 try:
1889 # nothing should actually be printed, this should raise an exception
1890 print Letter('w')
1891 except RuntimeError:
1892 pass
1893 else:
1894 self.fail("expected a RuntimeError for print recursion")
1895 finally:
1896 sys.stdout = test_stdout
1897
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001898 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001899 # Bug #1202533.
1900 class A(object):
1901 pass
1902 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1903 try:
1904 A()*2
1905 except RuntimeError:
1906 pass
1907 else:
1908 self.fail("expected a RuntimeError")
1909
1910 def test_weakrefs(self):
1911 # Testing weak references...
1912 import weakref
1913 class C(object):
1914 pass
1915 c = C()
1916 r = weakref.ref(c)
1917 self.assertEqual(r(), c)
1918 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001919 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001920 self.assertEqual(r(), None)
1921 del r
1922 class NoWeak(object):
1923 __slots__ = ['foo']
1924 no = NoWeak()
1925 try:
1926 weakref.ref(no)
1927 except TypeError, msg:
1928 self.assert_(str(msg).find("weak reference") >= 0)
1929 else:
1930 self.fail("weakref.ref(no) should be illegal")
1931 class Weak(object):
1932 __slots__ = ['foo', '__weakref__']
1933 yes = Weak()
1934 r = weakref.ref(yes)
1935 self.assertEqual(r(), yes)
1936 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001937 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001938 self.assertEqual(r(), None)
1939 del r
1940
1941 def test_properties(self):
1942 # Testing property...
1943 class C(object):
1944 def getx(self):
1945 return self.__x
1946 def setx(self, value):
1947 self.__x = value
1948 def delx(self):
1949 del self.__x
1950 x = property(getx, setx, delx, doc="I'm the x property.")
1951 a = C()
1952 self.assertFalse(hasattr(a, "x"))
1953 a.x = 42
1954 self.assertEqual(a._C__x, 42)
1955 self.assertEqual(a.x, 42)
1956 del a.x
1957 self.assertFalse(hasattr(a, "x"))
1958 self.assertFalse(hasattr(a, "_C__x"))
1959 C.x.__set__(a, 100)
1960 self.assertEqual(C.x.__get__(a), 100)
1961 C.x.__delete__(a)
1962 self.assertFalse(hasattr(a, "x"))
1963
1964 raw = C.__dict__['x']
1965 self.assert_(isinstance(raw, property))
1966
1967 attrs = dir(raw)
1968 self.assert_("__doc__" in attrs)
1969 self.assert_("fget" in attrs)
1970 self.assert_("fset" in attrs)
1971 self.assert_("fdel" in attrs)
1972
1973 self.assertEqual(raw.__doc__, "I'm the x property.")
1974 self.assert_(raw.fget is C.__dict__['getx'])
1975 self.assert_(raw.fset is C.__dict__['setx'])
1976 self.assert_(raw.fdel is C.__dict__['delx'])
1977
1978 for attr in "__doc__", "fget", "fset", "fdel":
1979 try:
1980 setattr(raw, attr, 42)
1981 except TypeError, msg:
1982 if str(msg).find('readonly') < 0:
1983 self.fail("when setting readonly attr %r on a property, "
1984 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001985 else:
Georg Brandl48545522008-02-02 10:12:36 +00001986 self.fail("expected TypeError from trying to set readonly %r "
1987 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00001988
Georg Brandl48545522008-02-02 10:12:36 +00001989 class D(object):
1990 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001991
Georg Brandl48545522008-02-02 10:12:36 +00001992 d = D()
1993 try:
1994 for i in d:
1995 str(i)
1996 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00001997 pass
Georg Brandl48545522008-02-02 10:12:36 +00001998 else:
1999 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002000
Georg Brandl48545522008-02-02 10:12:36 +00002001 class E(object):
2002 def getter(self):
2003 "getter method"
2004 return 0
2005 def setter(self_, value):
2006 "setter method"
2007 pass
2008 prop = property(getter)
2009 self.assertEqual(prop.__doc__, "getter method")
2010 prop2 = property(fset=setter)
2011 self.assertEqual(prop2.__doc__, None)
2012
2013 # this segfaulted in 2.5b2
2014 try:
2015 import _testcapi
2016 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002017 pass
Georg Brandl48545522008-02-02 10:12:36 +00002018 else:
2019 class X(object):
2020 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002021
Georg Brandl48545522008-02-02 10:12:36 +00002022 def test_properties_plus(self):
2023 class C(object):
2024 foo = property(doc="hello")
2025 @foo.getter
2026 def foo(self):
2027 return self._foo
2028 @foo.setter
2029 def foo(self, value):
2030 self._foo = abs(value)
2031 @foo.deleter
2032 def foo(self):
2033 del self._foo
2034 c = C()
2035 self.assertEqual(C.foo.__doc__, "hello")
2036 self.assertFalse(hasattr(c, "foo"))
2037 c.foo = -42
2038 self.assert_(hasattr(c, '_foo'))
2039 self.assertEqual(c._foo, 42)
2040 self.assertEqual(c.foo, 42)
2041 del c.foo
2042 self.assertFalse(hasattr(c, '_foo'))
2043 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002044
Georg Brandl48545522008-02-02 10:12:36 +00002045 class D(C):
2046 @C.foo.deleter
2047 def foo(self):
2048 try:
2049 del self._foo
2050 except AttributeError:
2051 pass
2052 d = D()
2053 d.foo = 24
2054 self.assertEqual(d.foo, 24)
2055 del d.foo
2056 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002057
Georg Brandl48545522008-02-02 10:12:36 +00002058 class E(object):
2059 @property
2060 def foo(self):
2061 return self._foo
2062 @foo.setter
2063 def foo(self, value):
2064 raise RuntimeError
2065 @foo.setter
2066 def foo(self, value):
2067 self._foo = abs(value)
2068 @foo.deleter
2069 def foo(self, value=None):
2070 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002071
Georg Brandl48545522008-02-02 10:12:36 +00002072 e = E()
2073 e.foo = -42
2074 self.assertEqual(e.foo, 42)
2075 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002076
Georg Brandl48545522008-02-02 10:12:36 +00002077 class F(E):
2078 @E.foo.deleter
2079 def foo(self):
2080 del self._foo
2081 @foo.setter
2082 def foo(self, value):
2083 self._foo = max(0, value)
2084 f = F()
2085 f.foo = -10
2086 self.assertEqual(f.foo, 0)
2087 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002088
Georg Brandl48545522008-02-02 10:12:36 +00002089 def test_dict_constructors(self):
2090 # Testing dict constructor ...
2091 d = dict()
2092 self.assertEqual(d, {})
2093 d = dict({})
2094 self.assertEqual(d, {})
2095 d = dict({1: 2, 'a': 'b'})
2096 self.assertEqual(d, {1: 2, 'a': 'b'})
2097 self.assertEqual(d, dict(d.items()))
2098 self.assertEqual(d, dict(d.iteritems()))
2099 d = dict({'one':1, 'two':2})
2100 self.assertEqual(d, dict(one=1, two=2))
2101 self.assertEqual(d, dict(**d))
2102 self.assertEqual(d, dict({"one": 1}, two=2))
2103 self.assertEqual(d, dict([("two", 2)], one=1))
2104 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2105 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002106
Georg Brandl48545522008-02-02 10:12:36 +00002107 for badarg in 0, 0L, 0j, "0", [0], (0,):
2108 try:
2109 dict(badarg)
2110 except TypeError:
2111 pass
2112 except ValueError:
2113 if badarg == "0":
2114 # It's a sequence, and its elements are also sequences (gotta
2115 # love strings <wink>), but they aren't of length 2, so this
2116 # one seemed better as a ValueError than a TypeError.
2117 pass
2118 else:
2119 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002120 else:
Georg Brandl48545522008-02-02 10:12:36 +00002121 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002122
Georg Brandl48545522008-02-02 10:12:36 +00002123 try:
2124 dict({}, {})
2125 except TypeError:
2126 pass
2127 else:
2128 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002129
Georg Brandl48545522008-02-02 10:12:36 +00002130 class Mapping:
2131 # Lacks a .keys() method; will be added later.
2132 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002133
Georg Brandl48545522008-02-02 10:12:36 +00002134 try:
2135 dict(Mapping())
2136 except TypeError:
2137 pass
2138 else:
2139 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002140
Georg Brandl48545522008-02-02 10:12:36 +00002141 Mapping.keys = lambda self: self.dict.keys()
2142 Mapping.__getitem__ = lambda self, i: self.dict[i]
2143 d = dict(Mapping())
2144 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002145
Georg Brandl48545522008-02-02 10:12:36 +00002146 # Init from sequence of iterable objects, each producing a 2-sequence.
2147 class AddressBookEntry:
2148 def __init__(self, first, last):
2149 self.first = first
2150 self.last = last
2151 def __iter__(self):
2152 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002153
Georg Brandl48545522008-02-02 10:12:36 +00002154 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2155 AddressBookEntry('Barry', 'Peters'),
2156 AddressBookEntry('Tim', 'Peters'),
2157 AddressBookEntry('Barry', 'Warsaw')])
2158 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002159
Georg Brandl48545522008-02-02 10:12:36 +00002160 d = dict(zip(range(4), range(1, 5)))
2161 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002162
Georg Brandl48545522008-02-02 10:12:36 +00002163 # Bad sequence lengths.
2164 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2165 try:
2166 dict(bad)
2167 except ValueError:
2168 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002169 else:
Georg Brandl48545522008-02-02 10:12:36 +00002170 self.fail("no ValueError from dict(%r)" % bad)
2171
2172 def test_dir(self):
2173 # Testing dir() ...
2174 junk = 12
2175 self.assertEqual(dir(), ['junk', 'self'])
2176 del junk
2177
2178 # Just make sure these don't blow up!
2179 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2180 dir(arg)
2181
2182 # Try classic classes.
2183 class C:
2184 Cdata = 1
2185 def Cmethod(self): pass
2186
2187 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2188 self.assertEqual(dir(C), cstuff)
2189 self.assert_('im_self' in dir(C.Cmethod))
2190
2191 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2192 self.assertEqual(dir(c), cstuff)
2193
2194 c.cdata = 2
2195 c.cmethod = lambda self: 0
2196 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
2197 self.assert_('im_self' in dir(c.Cmethod))
2198
2199 class A(C):
2200 Adata = 1
2201 def Amethod(self): pass
2202
2203 astuff = ['Adata', 'Amethod'] + cstuff
2204 self.assertEqual(dir(A), astuff)
2205 self.assert_('im_self' in dir(A.Amethod))
2206 a = A()
2207 self.assertEqual(dir(a), astuff)
2208 self.assert_('im_self' in dir(a.Amethod))
2209 a.adata = 42
2210 a.amethod = lambda self: 3
2211 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2212
2213 # The same, but with new-style classes. Since these have object as a
2214 # base class, a lot more gets sucked in.
2215 def interesting(strings):
2216 return [s for s in strings if not s.startswith('_')]
2217
2218 class C(object):
2219 Cdata = 1
2220 def Cmethod(self): pass
2221
2222 cstuff = ['Cdata', 'Cmethod']
2223 self.assertEqual(interesting(dir(C)), cstuff)
2224
2225 c = C()
2226 self.assertEqual(interesting(dir(c)), cstuff)
2227 self.assert_('im_self' in dir(C.Cmethod))
2228
2229 c.cdata = 2
2230 c.cmethod = lambda self: 0
2231 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2232 self.assert_('im_self' in dir(c.Cmethod))
2233
2234 class A(C):
2235 Adata = 1
2236 def Amethod(self): pass
2237
2238 astuff = ['Adata', 'Amethod'] + cstuff
2239 self.assertEqual(interesting(dir(A)), astuff)
2240 self.assert_('im_self' in dir(A.Amethod))
2241 a = A()
2242 self.assertEqual(interesting(dir(a)), astuff)
2243 a.adata = 42
2244 a.amethod = lambda self: 3
2245 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2246 self.assert_('im_self' in dir(a.Amethod))
2247
2248 # Try a module subclass.
2249 import sys
2250 class M(type(sys)):
2251 pass
2252 minstance = M("m")
2253 minstance.b = 2
2254 minstance.a = 1
2255 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2256 self.assertEqual(names, ['a', 'b'])
2257
2258 class M2(M):
2259 def getdict(self):
2260 return "Not a dict!"
2261 __dict__ = property(getdict)
2262
2263 m2instance = M2("m2")
2264 m2instance.b = 2
2265 m2instance.a = 1
2266 self.assertEqual(m2instance.__dict__, "Not a dict!")
2267 try:
2268 dir(m2instance)
2269 except TypeError:
2270 pass
2271
2272 # Two essentially featureless objects, just inheriting stuff from
2273 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002274 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2275 if test_support.check_impl_detail():
2276 # None differs in PyPy: it has a __nonzero__
2277 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002278
2279 # Nasty test case for proxied objects
2280 class Wrapper(object):
2281 def __init__(self, obj):
2282 self.__obj = obj
2283 def __repr__(self):
2284 return "Wrapper(%s)" % repr(self.__obj)
2285 def __getitem__(self, key):
2286 return Wrapper(self.__obj[key])
2287 def __len__(self):
2288 return len(self.__obj)
2289 def __getattr__(self, name):
2290 return Wrapper(getattr(self.__obj, name))
2291
2292 class C(object):
2293 def __getclass(self):
2294 return Wrapper(type(self))
2295 __class__ = property(__getclass)
2296
2297 dir(C()) # This used to segfault
2298
2299 def test_supers(self):
2300 # Testing super...
2301
2302 class A(object):
2303 def meth(self, a):
2304 return "A(%r)" % a
2305
2306 self.assertEqual(A().meth(1), "A(1)")
2307
2308 class B(A):
2309 def __init__(self):
2310 self.__super = super(B, self)
2311 def meth(self, a):
2312 return "B(%r)" % a + self.__super.meth(a)
2313
2314 self.assertEqual(B().meth(2), "B(2)A(2)")
2315
2316 class C(A):
2317 def meth(self, a):
2318 return "C(%r)" % a + self.__super.meth(a)
2319 C._C__super = super(C)
2320
2321 self.assertEqual(C().meth(3), "C(3)A(3)")
2322
2323 class D(C, B):
2324 def meth(self, a):
2325 return "D(%r)" % a + super(D, self).meth(a)
2326
2327 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2328
2329 # Test for subclassing super
2330
2331 class mysuper(super):
2332 def __init__(self, *args):
2333 return super(mysuper, self).__init__(*args)
2334
2335 class E(D):
2336 def meth(self, a):
2337 return "E(%r)" % a + mysuper(E, self).meth(a)
2338
2339 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2340
2341 class F(E):
2342 def meth(self, a):
2343 s = self.__super # == mysuper(F, self)
2344 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2345 F._F__super = mysuper(F)
2346
2347 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2348
2349 # Make sure certain errors are raised
2350
2351 try:
2352 super(D, 42)
2353 except TypeError:
2354 pass
2355 else:
2356 self.fail("shouldn't allow super(D, 42)")
2357
2358 try:
2359 super(D, C())
2360 except TypeError:
2361 pass
2362 else:
2363 self.fail("shouldn't allow super(D, C())")
2364
2365 try:
2366 super(D).__get__(12)
2367 except TypeError:
2368 pass
2369 else:
2370 self.fail("shouldn't allow super(D).__get__(12)")
2371
2372 try:
2373 super(D).__get__(C())
2374 except TypeError:
2375 pass
2376 else:
2377 self.fail("shouldn't allow super(D).__get__(C())")
2378
2379 # Make sure data descriptors can be overridden and accessed via super
2380 # (new feature in Python 2.3)
2381
2382 class DDbase(object):
2383 def getx(self): return 42
2384 x = property(getx)
2385
2386 class DDsub(DDbase):
2387 def getx(self): return "hello"
2388 x = property(getx)
2389
2390 dd = DDsub()
2391 self.assertEqual(dd.x, "hello")
2392 self.assertEqual(super(DDsub, dd).x, 42)
2393
2394 # Ensure that super() lookup of descriptor from classmethod
2395 # works (SF ID# 743627)
2396
2397 class Base(object):
2398 aProp = property(lambda self: "foo")
2399
2400 class Sub(Base):
2401 @classmethod
2402 def test(klass):
2403 return super(Sub,klass).aProp
2404
2405 self.assertEqual(Sub.test(), Base.aProp)
2406
2407 # Verify that super() doesn't allow keyword args
2408 try:
2409 super(Base, kw=1)
2410 except TypeError:
2411 pass
2412 else:
2413 self.assertEqual("super shouldn't accept keyword args")
2414
2415 def test_basic_inheritance(self):
2416 # Testing inheritance from basic types...
2417
2418 class hexint(int):
2419 def __repr__(self):
2420 return hex(self)
2421 def __add__(self, other):
2422 return hexint(int.__add__(self, other))
2423 # (Note that overriding __radd__ doesn't work,
2424 # because the int type gets first dibs.)
2425 self.assertEqual(repr(hexint(7) + 9), "0x10")
2426 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2427 a = hexint(12345)
2428 self.assertEqual(a, 12345)
2429 self.assertEqual(int(a), 12345)
2430 self.assert_(int(a).__class__ is int)
2431 self.assertEqual(hash(a), hash(12345))
2432 self.assert_((+a).__class__ is int)
2433 self.assert_((a >> 0).__class__ is int)
2434 self.assert_((a << 0).__class__ is int)
2435 self.assert_((hexint(0) << 12).__class__ is int)
2436 self.assert_((hexint(0) >> 12).__class__ is int)
2437
2438 class octlong(long):
2439 __slots__ = []
2440 def __str__(self):
2441 s = oct(self)
2442 if s[-1] == 'L':
2443 s = s[:-1]
2444 return s
2445 def __add__(self, other):
2446 return self.__class__(super(octlong, self).__add__(other))
2447 __radd__ = __add__
2448 self.assertEqual(str(octlong(3) + 5), "010")
2449 # (Note that overriding __radd__ here only seems to work
2450 # because the example uses a short int left argument.)
2451 self.assertEqual(str(5 + octlong(3000)), "05675")
2452 a = octlong(12345)
2453 self.assertEqual(a, 12345L)
2454 self.assertEqual(long(a), 12345L)
2455 self.assertEqual(hash(a), hash(12345L))
2456 self.assert_(long(a).__class__ is long)
2457 self.assert_((+a).__class__ is long)
2458 self.assert_((-a).__class__ is long)
2459 self.assert_((-octlong(0)).__class__ is long)
2460 self.assert_((a >> 0).__class__ is long)
2461 self.assert_((a << 0).__class__ is long)
2462 self.assert_((a - 0).__class__ is long)
2463 self.assert_((a * 1).__class__ is long)
2464 self.assert_((a ** 1).__class__ is long)
2465 self.assert_((a // 1).__class__ is long)
2466 self.assert_((1 * a).__class__ is long)
2467 self.assert_((a | 0).__class__ is long)
2468 self.assert_((a ^ 0).__class__ is long)
2469 self.assert_((a & -1L).__class__ is long)
2470 self.assert_((octlong(0) << 12).__class__ is long)
2471 self.assert_((octlong(0) >> 12).__class__ is long)
2472 self.assert_(abs(octlong(0)).__class__ is long)
2473
2474 # Because octlong overrides __add__, we can't check the absence of +0
2475 # optimizations using octlong.
2476 class longclone(long):
2477 pass
2478 a = longclone(1)
2479 self.assert_((a + 0).__class__ is long)
2480 self.assert_((0 + a).__class__ is long)
2481
2482 # Check that negative clones don't segfault
2483 a = longclone(-1)
2484 self.assertEqual(a.__dict__, {})
2485 self.assertEqual(long(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2486
2487 class precfloat(float):
2488 __slots__ = ['prec']
2489 def __init__(self, value=0.0, prec=12):
2490 self.prec = int(prec)
2491 def __repr__(self):
2492 return "%.*g" % (self.prec, self)
2493 self.assertEqual(repr(precfloat(1.1)), "1.1")
2494 a = precfloat(12345)
2495 self.assertEqual(a, 12345.0)
2496 self.assertEqual(float(a), 12345.0)
2497 self.assert_(float(a).__class__ is float)
2498 self.assertEqual(hash(a), hash(12345.0))
2499 self.assert_((+a).__class__ is float)
2500
2501 class madcomplex(complex):
2502 def __repr__(self):
2503 return "%.17gj%+.17g" % (self.imag, self.real)
2504 a = madcomplex(-3, 4)
2505 self.assertEqual(repr(a), "4j-3")
2506 base = complex(-3, 4)
2507 self.assertEqual(base.__class__, complex)
2508 self.assertEqual(a, base)
2509 self.assertEqual(complex(a), base)
2510 self.assertEqual(complex(a).__class__, complex)
2511 a = madcomplex(a) # just trying another form of the constructor
2512 self.assertEqual(repr(a), "4j-3")
2513 self.assertEqual(a, base)
2514 self.assertEqual(complex(a), base)
2515 self.assertEqual(complex(a).__class__, complex)
2516 self.assertEqual(hash(a), hash(base))
2517 self.assertEqual((+a).__class__, complex)
2518 self.assertEqual((a + 0).__class__, complex)
2519 self.assertEqual(a + 0, base)
2520 self.assertEqual((a - 0).__class__, complex)
2521 self.assertEqual(a - 0, base)
2522 self.assertEqual((a * 1).__class__, complex)
2523 self.assertEqual(a * 1, base)
2524 self.assertEqual((a / 1).__class__, complex)
2525 self.assertEqual(a / 1, base)
2526
2527 class madtuple(tuple):
2528 _rev = None
2529 def rev(self):
2530 if self._rev is not None:
2531 return self._rev
2532 L = list(self)
2533 L.reverse()
2534 self._rev = self.__class__(L)
2535 return self._rev
2536 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2537 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2538 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2539 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2540 for i in range(512):
2541 t = madtuple(range(i))
2542 u = t.rev()
2543 v = u.rev()
2544 self.assertEqual(v, t)
2545 a = madtuple((1,2,3,4,5))
2546 self.assertEqual(tuple(a), (1,2,3,4,5))
2547 self.assert_(tuple(a).__class__ is tuple)
2548 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2549 self.assert_(a[:].__class__ is tuple)
2550 self.assert_((a * 1).__class__ is tuple)
2551 self.assert_((a * 0).__class__ is tuple)
2552 self.assert_((a + ()).__class__ is tuple)
2553 a = madtuple(())
2554 self.assertEqual(tuple(a), ())
2555 self.assert_(tuple(a).__class__ is tuple)
2556 self.assert_((a + a).__class__ is tuple)
2557 self.assert_((a * 0).__class__ is tuple)
2558 self.assert_((a * 1).__class__ is tuple)
2559 self.assert_((a * 2).__class__ is tuple)
2560 self.assert_(a[:].__class__ is tuple)
2561
2562 class madstring(str):
2563 _rev = None
2564 def rev(self):
2565 if self._rev is not None:
2566 return self._rev
2567 L = list(self)
2568 L.reverse()
2569 self._rev = self.__class__("".join(L))
2570 return self._rev
2571 s = madstring("abcdefghijklmnopqrstuvwxyz")
2572 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2573 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2574 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2575 for i in range(256):
2576 s = madstring("".join(map(chr, range(i))))
2577 t = s.rev()
2578 u = t.rev()
2579 self.assertEqual(u, s)
2580 s = madstring("12345")
2581 self.assertEqual(str(s), "12345")
2582 self.assert_(str(s).__class__ is str)
2583
2584 base = "\x00" * 5
2585 s = madstring(base)
2586 self.assertEqual(s, base)
2587 self.assertEqual(str(s), base)
2588 self.assert_(str(s).__class__ is str)
2589 self.assertEqual(hash(s), hash(base))
2590 self.assertEqual({s: 1}[base], 1)
2591 self.assertEqual({base: 1}[s], 1)
2592 self.assert_((s + "").__class__ is str)
2593 self.assertEqual(s + "", base)
2594 self.assert_(("" + s).__class__ is str)
2595 self.assertEqual("" + s, base)
2596 self.assert_((s * 0).__class__ is str)
2597 self.assertEqual(s * 0, "")
2598 self.assert_((s * 1).__class__ is str)
2599 self.assertEqual(s * 1, base)
2600 self.assert_((s * 2).__class__ is str)
2601 self.assertEqual(s * 2, base + base)
2602 self.assert_(s[:].__class__ is str)
2603 self.assertEqual(s[:], base)
2604 self.assert_(s[0:0].__class__ is str)
2605 self.assertEqual(s[0:0], "")
2606 self.assert_(s.strip().__class__ is str)
2607 self.assertEqual(s.strip(), base)
2608 self.assert_(s.lstrip().__class__ is str)
2609 self.assertEqual(s.lstrip(), base)
2610 self.assert_(s.rstrip().__class__ is str)
2611 self.assertEqual(s.rstrip(), base)
2612 identitytab = ''.join([chr(i) for i in range(256)])
2613 self.assert_(s.translate(identitytab).__class__ is str)
2614 self.assertEqual(s.translate(identitytab), base)
2615 self.assert_(s.translate(identitytab, "x").__class__ is str)
2616 self.assertEqual(s.translate(identitytab, "x"), base)
2617 self.assertEqual(s.translate(identitytab, "\x00"), "")
2618 self.assert_(s.replace("x", "x").__class__ is str)
2619 self.assertEqual(s.replace("x", "x"), base)
2620 self.assert_(s.ljust(len(s)).__class__ is str)
2621 self.assertEqual(s.ljust(len(s)), base)
2622 self.assert_(s.rjust(len(s)).__class__ is str)
2623 self.assertEqual(s.rjust(len(s)), base)
2624 self.assert_(s.center(len(s)).__class__ is str)
2625 self.assertEqual(s.center(len(s)), base)
2626 self.assert_(s.lower().__class__ is str)
2627 self.assertEqual(s.lower(), base)
2628
2629 class madunicode(unicode):
2630 _rev = None
2631 def rev(self):
2632 if self._rev is not None:
2633 return self._rev
2634 L = list(self)
2635 L.reverse()
2636 self._rev = self.__class__(u"".join(L))
2637 return self._rev
2638 u = madunicode("ABCDEF")
2639 self.assertEqual(u, u"ABCDEF")
2640 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2641 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2642 base = u"12345"
2643 u = madunicode(base)
2644 self.assertEqual(unicode(u), base)
2645 self.assert_(unicode(u).__class__ is unicode)
2646 self.assertEqual(hash(u), hash(base))
2647 self.assertEqual({u: 1}[base], 1)
2648 self.assertEqual({base: 1}[u], 1)
2649 self.assert_(u.strip().__class__ is unicode)
2650 self.assertEqual(u.strip(), base)
2651 self.assert_(u.lstrip().__class__ is unicode)
2652 self.assertEqual(u.lstrip(), base)
2653 self.assert_(u.rstrip().__class__ is unicode)
2654 self.assertEqual(u.rstrip(), base)
2655 self.assert_(u.replace(u"x", u"x").__class__ is unicode)
2656 self.assertEqual(u.replace(u"x", u"x"), base)
2657 self.assert_(u.replace(u"xy", u"xy").__class__ is unicode)
2658 self.assertEqual(u.replace(u"xy", u"xy"), base)
2659 self.assert_(u.center(len(u)).__class__ is unicode)
2660 self.assertEqual(u.center(len(u)), base)
2661 self.assert_(u.ljust(len(u)).__class__ is unicode)
2662 self.assertEqual(u.ljust(len(u)), base)
2663 self.assert_(u.rjust(len(u)).__class__ is unicode)
2664 self.assertEqual(u.rjust(len(u)), base)
2665 self.assert_(u.lower().__class__ is unicode)
2666 self.assertEqual(u.lower(), base)
2667 self.assert_(u.upper().__class__ is unicode)
2668 self.assertEqual(u.upper(), base)
2669 self.assert_(u.capitalize().__class__ is unicode)
2670 self.assertEqual(u.capitalize(), base)
2671 self.assert_(u.title().__class__ is unicode)
2672 self.assertEqual(u.title(), base)
2673 self.assert_((u + u"").__class__ is unicode)
2674 self.assertEqual(u + u"", base)
2675 self.assert_((u"" + u).__class__ is unicode)
2676 self.assertEqual(u"" + u, base)
2677 self.assert_((u * 0).__class__ is unicode)
2678 self.assertEqual(u * 0, u"")
2679 self.assert_((u * 1).__class__ is unicode)
2680 self.assertEqual(u * 1, base)
2681 self.assert_((u * 2).__class__ is unicode)
2682 self.assertEqual(u * 2, base + base)
2683 self.assert_(u[:].__class__ is unicode)
2684 self.assertEqual(u[:], base)
2685 self.assert_(u[0:0].__class__ is unicode)
2686 self.assertEqual(u[0:0], u"")
2687
2688 class sublist(list):
2689 pass
2690 a = sublist(range(5))
2691 self.assertEqual(a, range(5))
2692 a.append("hello")
2693 self.assertEqual(a, range(5) + ["hello"])
2694 a[5] = 5
2695 self.assertEqual(a, range(6))
2696 a.extend(range(6, 20))
2697 self.assertEqual(a, range(20))
2698 a[-5:] = []
2699 self.assertEqual(a, range(15))
2700 del a[10:15]
2701 self.assertEqual(len(a), 10)
2702 self.assertEqual(a, range(10))
2703 self.assertEqual(list(a), range(10))
2704 self.assertEqual(a[0], 0)
2705 self.assertEqual(a[9], 9)
2706 self.assertEqual(a[-10], 0)
2707 self.assertEqual(a[-1], 9)
2708 self.assertEqual(a[:5], range(5))
2709
2710 class CountedInput(file):
2711 """Counts lines read by self.readline().
2712
2713 self.lineno is the 0-based ordinal of the last line read, up to
2714 a maximum of one greater than the number of lines in the file.
2715
2716 self.ateof is true if and only if the final "" line has been read,
2717 at which point self.lineno stops incrementing, and further calls
2718 to readline() continue to return "".
2719 """
2720
2721 lineno = 0
2722 ateof = 0
2723 def readline(self):
2724 if self.ateof:
2725 return ""
2726 s = file.readline(self)
2727 # Next line works too.
2728 # s = super(CountedInput, self).readline()
2729 self.lineno += 1
2730 if s == "":
2731 self.ateof = 1
2732 return s
2733
2734 f = file(name=test_support.TESTFN, mode='w')
2735 lines = ['a\n', 'b\n', 'c\n']
2736 try:
2737 f.writelines(lines)
2738 f.close()
2739 f = CountedInput(test_support.TESTFN)
2740 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2741 got = f.readline()
2742 self.assertEqual(expected, got)
2743 self.assertEqual(f.lineno, i)
2744 self.assertEqual(f.ateof, (i > len(lines)))
2745 f.close()
2746 finally:
2747 try:
2748 f.close()
2749 except:
2750 pass
2751 test_support.unlink(test_support.TESTFN)
2752
2753 def test_keywords(self):
2754 # Testing keyword args to basic type constructors ...
2755 self.assertEqual(int(x=1), 1)
2756 self.assertEqual(float(x=2), 2.0)
2757 self.assertEqual(long(x=3), 3L)
2758 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2759 self.assertEqual(str(object=500), '500')
2760 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2761 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2762 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2763 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2764
2765 for constructor in (int, float, long, complex, str, unicode,
2766 tuple, list, file):
2767 try:
2768 constructor(bogus_keyword_arg=1)
2769 except TypeError:
2770 pass
2771 else:
2772 self.fail("expected TypeError from bogus keyword argument to %r"
2773 % constructor)
2774
2775 def test_str_subclass_as_dict_key(self):
2776 # Testing a str subclass used as dict key ..
2777
2778 class cistr(str):
2779 """Sublcass of str that computes __eq__ case-insensitively.
2780
2781 Also computes a hash code of the string in canonical form.
2782 """
2783
2784 def __init__(self, value):
2785 self.canonical = value.lower()
2786 self.hashcode = hash(self.canonical)
2787
2788 def __eq__(self, other):
2789 if not isinstance(other, cistr):
2790 other = cistr(other)
2791 return self.canonical == other.canonical
2792
2793 def __hash__(self):
2794 return self.hashcode
2795
2796 self.assertEqual(cistr('ABC'), 'abc')
2797 self.assertEqual('aBc', cistr('ABC'))
2798 self.assertEqual(str(cistr('ABC')), 'ABC')
2799
2800 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2801 self.assertEqual(d[cistr('one')], 1)
2802 self.assertEqual(d[cistr('tWo')], 2)
2803 self.assertEqual(d[cistr('THrEE')], 3)
2804 self.assert_(cistr('ONe') in d)
2805 self.assertEqual(d.get(cistr('thrEE')), 3)
2806
2807 def test_classic_comparisons(self):
2808 # Testing classic comparisons...
2809 class classic:
2810 pass
2811
2812 for base in (classic, int, object):
2813 class C(base):
2814 def __init__(self, value):
2815 self.value = int(value)
2816 def __cmp__(self, other):
2817 if isinstance(other, C):
2818 return cmp(self.value, other.value)
2819 if isinstance(other, int) or isinstance(other, long):
2820 return cmp(self.value, other)
2821 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002822 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002823
2824 c1 = C(1)
2825 c2 = C(2)
2826 c3 = C(3)
2827 self.assertEqual(c1, 1)
2828 c = {1: c1, 2: c2, 3: c3}
2829 for x in 1, 2, 3:
2830 for y in 1, 2, 3:
2831 self.assert_(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2832 for op in "<", "<=", "==", "!=", ">", ">=":
2833 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2834 "x=%d, y=%d" % (x, y))
2835 self.assert_(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2836 self.assert_(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2837
2838 def test_rich_comparisons(self):
2839 # Testing rich comparisons...
2840 class Z(complex):
2841 pass
2842 z = Z(1)
2843 self.assertEqual(z, 1+0j)
2844 self.assertEqual(1+0j, z)
2845 class ZZ(complex):
2846 def __eq__(self, other):
2847 try:
2848 return abs(self - other) <= 1e-6
2849 except:
2850 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002851 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002852 zz = ZZ(1.0000003)
2853 self.assertEqual(zz, 1+0j)
2854 self.assertEqual(1+0j, zz)
2855
2856 class classic:
2857 pass
2858 for base in (classic, int, object, list):
2859 class C(base):
2860 def __init__(self, value):
2861 self.value = int(value)
2862 def __cmp__(self_, other):
2863 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002864 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002865 def __eq__(self, other):
2866 if isinstance(other, C):
2867 return self.value == other.value
2868 if isinstance(other, int) or isinstance(other, long):
2869 return self.value == other
2870 return NotImplemented
2871 def __ne__(self, other):
2872 if isinstance(other, C):
2873 return self.value != other.value
2874 if isinstance(other, int) or isinstance(other, long):
2875 return self.value != other
2876 return NotImplemented
2877 def __lt__(self, other):
2878 if isinstance(other, C):
2879 return self.value < other.value
2880 if isinstance(other, int) or isinstance(other, long):
2881 return self.value < other
2882 return NotImplemented
2883 def __le__(self, other):
2884 if isinstance(other, C):
2885 return self.value <= other.value
2886 if isinstance(other, int) or isinstance(other, long):
2887 return self.value <= other
2888 return NotImplemented
2889 def __gt__(self, other):
2890 if isinstance(other, C):
2891 return self.value > other.value
2892 if isinstance(other, int) or isinstance(other, long):
2893 return self.value > other
2894 return NotImplemented
2895 def __ge__(self, other):
2896 if isinstance(other, C):
2897 return self.value >= other.value
2898 if isinstance(other, int) or isinstance(other, long):
2899 return self.value >= other
2900 return NotImplemented
2901 c1 = C(1)
2902 c2 = C(2)
2903 c3 = C(3)
2904 self.assertEqual(c1, 1)
2905 c = {1: c1, 2: c2, 3: c3}
2906 for x in 1, 2, 3:
2907 for y in 1, 2, 3:
2908 for op in "<", "<=", "==", "!=", ">", ">=":
2909 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2910 "x=%d, y=%d" % (x, y))
2911 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2912 "x=%d, y=%d" % (x, y))
2913 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2914 "x=%d, y=%d" % (x, y))
2915
2916 def test_coercions(self):
2917 # Testing coercions...
2918 class I(int): pass
2919 coerce(I(0), 0)
2920 coerce(0, I(0))
2921 class L(long): pass
2922 coerce(L(0), 0)
2923 coerce(L(0), 0L)
2924 coerce(0, L(0))
2925 coerce(0L, L(0))
2926 class F(float): pass
2927 coerce(F(0), 0)
2928 coerce(F(0), 0L)
2929 coerce(F(0), 0.)
2930 coerce(0, F(0))
2931 coerce(0L, F(0))
2932 coerce(0., F(0))
2933 class C(complex): pass
2934 coerce(C(0), 0)
2935 coerce(C(0), 0L)
2936 coerce(C(0), 0.)
2937 coerce(C(0), 0j)
2938 coerce(0, C(0))
2939 coerce(0L, C(0))
2940 coerce(0., C(0))
2941 coerce(0j, C(0))
2942
2943 def test_descrdoc(self):
2944 # Testing descriptor doc strings...
2945 def check(descr, what):
2946 self.assertEqual(descr.__doc__, what)
2947 check(file.closed, "True if the file is closed") # getset descriptor
2948 check(file.name, "file name") # member descriptor
2949
2950 def test_doc_descriptor(self):
2951 # Testing __doc__ descriptor...
2952 # SF bug 542984
2953 class DocDescr(object):
2954 def __get__(self, object, otype):
2955 if object:
2956 object = object.__class__.__name__ + ' instance'
2957 if otype:
2958 otype = otype.__name__
2959 return 'object=%s; type=%s' % (object, otype)
2960 class OldClass:
2961 __doc__ = DocDescr()
2962 class NewClass(object):
2963 __doc__ = DocDescr()
2964 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2965 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2966 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2967 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2968
2969 def test_set_class(self):
2970 # Testing __class__ assignment...
2971 class C(object): pass
2972 class D(object): pass
2973 class E(object): pass
2974 class F(D, E): pass
2975 for cls in C, D, E, F:
2976 for cls2 in C, D, E, F:
2977 x = cls()
2978 x.__class__ = cls2
2979 self.assert_(x.__class__ is cls2)
2980 x.__class__ = cls
2981 self.assert_(x.__class__ is cls)
2982 def cant(x, C):
2983 try:
2984 x.__class__ = C
2985 except TypeError:
2986 pass
2987 else:
2988 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2989 try:
2990 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002991 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00002992 pass
2993 else:
2994 self.fail("shouldn't allow del %r.__class__" % x)
2995 cant(C(), list)
2996 cant(list(), C)
2997 cant(C(), 1)
2998 cant(C(), object)
2999 cant(object(), list)
3000 cant(list(), object)
3001 class Int(int): __slots__ = []
3002 cant(2, Int)
3003 cant(Int(), int)
3004 cant(True, int)
3005 cant(2, bool)
3006 o = object()
3007 cant(o, type(1))
3008 cant(o, type(None))
3009 del o
3010 class G(object):
3011 __slots__ = ["a", "b"]
3012 class H(object):
3013 __slots__ = ["b", "a"]
3014 try:
3015 unicode
3016 except NameError:
3017 class I(object):
3018 __slots__ = ["a", "b"]
3019 else:
3020 class I(object):
3021 __slots__ = [unicode("a"), unicode("b")]
3022 class J(object):
3023 __slots__ = ["c", "b"]
3024 class K(object):
3025 __slots__ = ["a", "b", "d"]
3026 class L(H):
3027 __slots__ = ["e"]
3028 class M(I):
3029 __slots__ = ["e"]
3030 class N(J):
3031 __slots__ = ["__weakref__"]
3032 class P(J):
3033 __slots__ = ["__dict__"]
3034 class Q(J):
3035 pass
3036 class R(J):
3037 __slots__ = ["__dict__", "__weakref__"]
3038
3039 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3040 x = cls()
3041 x.a = 1
3042 x.__class__ = cls2
3043 self.assert_(x.__class__ is cls2,
3044 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3045 self.assertEqual(x.a, 1)
3046 x.__class__ = cls
3047 self.assert_(x.__class__ is cls,
3048 "assigning %r as __class__ for %r silently failed" % (cls, x))
3049 self.assertEqual(x.a, 1)
3050 for cls in G, J, K, L, M, N, P, R, list, Int:
3051 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3052 if cls is cls2:
3053 continue
3054 cant(cls(), cls2)
3055
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003056 # Issue5283: when __class__ changes in __del__, the wrong
3057 # type gets DECREF'd.
3058 class O(object):
3059 pass
3060 class A(object):
3061 def __del__(self):
3062 self.__class__ = O
3063 l = [A() for x in range(100)]
3064 del l
3065
Georg Brandl48545522008-02-02 10:12:36 +00003066 def test_set_dict(self):
3067 # Testing __dict__ assignment...
3068 class C(object): pass
3069 a = C()
3070 a.__dict__ = {'b': 1}
3071 self.assertEqual(a.b, 1)
3072 def cant(x, dict):
3073 try:
3074 x.__dict__ = dict
3075 except (AttributeError, TypeError):
3076 pass
3077 else:
3078 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3079 cant(a, None)
3080 cant(a, [])
3081 cant(a, 1)
3082 del a.__dict__ # Deleting __dict__ is allowed
3083
3084 class Base(object):
3085 pass
3086 def verify_dict_readonly(x):
3087 """
3088 x has to be an instance of a class inheriting from Base.
3089 """
3090 cant(x, {})
3091 try:
3092 del x.__dict__
3093 except (AttributeError, TypeError):
3094 pass
3095 else:
3096 self.fail("shouldn't allow del %r.__dict__" % x)
3097 dict_descr = Base.__dict__["__dict__"]
3098 try:
3099 dict_descr.__set__(x, {})
3100 except (AttributeError, TypeError):
3101 pass
3102 else:
3103 self.fail("dict_descr allowed access to %r's dict" % x)
3104
3105 # Classes don't allow __dict__ assignment and have readonly dicts
3106 class Meta1(type, Base):
3107 pass
3108 class Meta2(Base, type):
3109 pass
3110 class D(object):
3111 __metaclass__ = Meta1
3112 class E(object):
3113 __metaclass__ = Meta2
3114 for cls in C, D, E:
3115 verify_dict_readonly(cls)
3116 class_dict = cls.__dict__
3117 try:
3118 class_dict["spam"] = "eggs"
3119 except TypeError:
3120 pass
3121 else:
3122 self.fail("%r's __dict__ can be modified" % cls)
3123
3124 # Modules also disallow __dict__ assignment
3125 class Module1(types.ModuleType, Base):
3126 pass
3127 class Module2(Base, types.ModuleType):
3128 pass
3129 for ModuleType in Module1, Module2:
3130 mod = ModuleType("spam")
3131 verify_dict_readonly(mod)
3132 mod.__dict__["spam"] = "eggs"
3133
3134 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003135 # (at least not any more than regular exception's __dict__ can
3136 # be deleted; on CPython it is not the case, whereas on PyPy they
3137 # can, just like any other new-style instance's __dict__.)
3138 def can_delete_dict(e):
3139 try:
3140 del e.__dict__
3141 except (TypeError, AttributeError):
3142 return False
3143 else:
3144 return True
Georg Brandl48545522008-02-02 10:12:36 +00003145 class Exception1(Exception, Base):
3146 pass
3147 class Exception2(Base, Exception):
3148 pass
3149 for ExceptionType in Exception, Exception1, Exception2:
3150 e = ExceptionType()
3151 e.__dict__ = {"a": 1}
3152 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003153 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003154
3155 def test_pickles(self):
3156 # Testing pickling and copying new-style classes and objects...
3157 import pickle, cPickle
3158
3159 def sorteditems(d):
3160 L = d.items()
3161 L.sort()
3162 return L
3163
3164 global C
3165 class C(object):
3166 def __init__(self, a, b):
3167 super(C, self).__init__()
3168 self.a = a
3169 self.b = b
3170 def __repr__(self):
3171 return "C(%r, %r)" % (self.a, self.b)
3172
3173 global C1
3174 class C1(list):
3175 def __new__(cls, a, b):
3176 return super(C1, cls).__new__(cls)
3177 def __getnewargs__(self):
3178 return (self.a, self.b)
3179 def __init__(self, a, b):
3180 self.a = a
3181 self.b = b
3182 def __repr__(self):
3183 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3184
3185 global C2
3186 class C2(int):
3187 def __new__(cls, a, b, val=0):
3188 return super(C2, cls).__new__(cls, val)
3189 def __getnewargs__(self):
3190 return (self.a, self.b, int(self))
3191 def __init__(self, a, b, val=0):
3192 self.a = a
3193 self.b = b
3194 def __repr__(self):
3195 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3196
3197 global C3
3198 class C3(object):
3199 def __init__(self, foo):
3200 self.foo = foo
3201 def __getstate__(self):
3202 return self.foo
3203 def __setstate__(self, foo):
3204 self.foo = foo
3205
3206 global C4classic, C4
3207 class C4classic: # classic
3208 pass
3209 class C4(C4classic, object): # mixed inheritance
3210 pass
3211
3212 for p in pickle, cPickle:
3213 for bin in 0, 1:
3214 for cls in C, C1, C2:
3215 s = p.dumps(cls, bin)
3216 cls2 = p.loads(s)
3217 self.assert_(cls2 is cls)
3218
3219 a = C1(1, 2); a.append(42); a.append(24)
3220 b = C2("hello", "world", 42)
3221 s = p.dumps((a, b), bin)
3222 x, y = p.loads(s)
3223 self.assertEqual(x.__class__, a.__class__)
3224 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3225 self.assertEqual(y.__class__, b.__class__)
3226 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3227 self.assertEqual(repr(x), repr(a))
3228 self.assertEqual(repr(y), repr(b))
3229 # Test for __getstate__ and __setstate__ on new style class
3230 u = C3(42)
3231 s = p.dumps(u, bin)
3232 v = p.loads(s)
3233 self.assertEqual(u.__class__, v.__class__)
3234 self.assertEqual(u.foo, v.foo)
3235 # Test for picklability of hybrid class
3236 u = C4()
3237 u.foo = 42
3238 s = p.dumps(u, bin)
3239 v = p.loads(s)
3240 self.assertEqual(u.__class__, v.__class__)
3241 self.assertEqual(u.foo, v.foo)
3242
3243 # Testing copy.deepcopy()
3244 import copy
3245 for cls in C, C1, C2:
3246 cls2 = copy.deepcopy(cls)
3247 self.assert_(cls2 is cls)
3248
3249 a = C1(1, 2); a.append(42); a.append(24)
3250 b = C2("hello", "world", 42)
3251 x, y = copy.deepcopy((a, b))
3252 self.assertEqual(x.__class__, a.__class__)
3253 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3254 self.assertEqual(y.__class__, b.__class__)
3255 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3256 self.assertEqual(repr(x), repr(a))
3257 self.assertEqual(repr(y), repr(b))
3258
3259 def test_pickle_slots(self):
3260 # Testing pickling of classes with __slots__ ...
3261 import pickle, cPickle
3262 # Pickling of classes with __slots__ but without __getstate__ should fail
3263 global B, C, D, E
3264 class B(object):
3265 pass
3266 for base in [object, B]:
3267 class C(base):
3268 __slots__ = ['a']
3269 class D(C):
3270 pass
3271 try:
3272 pickle.dumps(C())
3273 except TypeError:
3274 pass
3275 else:
3276 self.fail("should fail: pickle C instance - %s" % base)
3277 try:
3278 cPickle.dumps(C())
3279 except TypeError:
3280 pass
3281 else:
3282 self.fail("should fail: cPickle C instance - %s" % base)
3283 try:
3284 pickle.dumps(C())
3285 except TypeError:
3286 pass
3287 else:
3288 self.fail("should fail: pickle D instance - %s" % base)
3289 try:
3290 cPickle.dumps(D())
3291 except TypeError:
3292 pass
3293 else:
3294 self.fail("should fail: cPickle D instance - %s" % base)
3295 # Give C a nice generic __getstate__ and __setstate__
3296 class C(base):
3297 __slots__ = ['a']
3298 def __getstate__(self):
3299 try:
3300 d = self.__dict__.copy()
3301 except AttributeError:
3302 d = {}
3303 for cls in self.__class__.__mro__:
3304 for sn in cls.__dict__.get('__slots__', ()):
3305 try:
3306 d[sn] = getattr(self, sn)
3307 except AttributeError:
3308 pass
3309 return d
3310 def __setstate__(self, d):
3311 for k, v in d.items():
3312 setattr(self, k, v)
3313 class D(C):
3314 pass
3315 # Now it should work
3316 x = C()
3317 y = pickle.loads(pickle.dumps(x))
3318 self.assertEqual(hasattr(y, 'a'), 0)
3319 y = cPickle.loads(cPickle.dumps(x))
3320 self.assertEqual(hasattr(y, 'a'), 0)
3321 x.a = 42
3322 y = pickle.loads(pickle.dumps(x))
3323 self.assertEqual(y.a, 42)
3324 y = cPickle.loads(cPickle.dumps(x))
3325 self.assertEqual(y.a, 42)
3326 x = D()
3327 x.a = 42
3328 x.b = 100
3329 y = pickle.loads(pickle.dumps(x))
3330 self.assertEqual(y.a + y.b, 142)
3331 y = cPickle.loads(cPickle.dumps(x))
3332 self.assertEqual(y.a + y.b, 142)
3333 # A subclass that adds a slot should also work
3334 class E(C):
3335 __slots__ = ['b']
3336 x = E()
3337 x.a = 42
3338 x.b = "foo"
3339 y = pickle.loads(pickle.dumps(x))
3340 self.assertEqual(y.a, x.a)
3341 self.assertEqual(y.b, x.b)
3342 y = cPickle.loads(cPickle.dumps(x))
3343 self.assertEqual(y.a, x.a)
3344 self.assertEqual(y.b, x.b)
3345
3346 def test_binary_operator_override(self):
3347 # Testing overrides of binary operations...
3348 class I(int):
3349 def __repr__(self):
3350 return "I(%r)" % int(self)
3351 def __add__(self, other):
3352 return I(int(self) + int(other))
3353 __radd__ = __add__
3354 def __pow__(self, other, mod=None):
3355 if mod is None:
3356 return I(pow(int(self), int(other)))
3357 else:
3358 return I(pow(int(self), int(other), int(mod)))
3359 def __rpow__(self, other, mod=None):
3360 if mod is None:
3361 return I(pow(int(other), int(self), mod))
3362 else:
3363 return I(pow(int(other), int(self), int(mod)))
3364
3365 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3366 self.assertEqual(repr(I(1) + 2), "I(3)")
3367 self.assertEqual(repr(1 + I(2)), "I(3)")
3368 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3369 self.assertEqual(repr(2 ** I(3)), "I(8)")
3370 self.assertEqual(repr(I(2) ** 3), "I(8)")
3371 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3372 class S(str):
3373 def __eq__(self, other):
3374 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003375 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003376
3377 def test_subclass_propagation(self):
3378 # Testing propagation of slot functions to subclasses...
3379 class A(object):
3380 pass
3381 class B(A):
3382 pass
3383 class C(A):
3384 pass
3385 class D(B, C):
3386 pass
3387 d = D()
3388 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3389 A.__hash__ = lambda self: 42
3390 self.assertEqual(hash(d), 42)
3391 C.__hash__ = lambda self: 314
3392 self.assertEqual(hash(d), 314)
3393 B.__hash__ = lambda self: 144
3394 self.assertEqual(hash(d), 144)
3395 D.__hash__ = lambda self: 100
3396 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003397 D.__hash__ = None
3398 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003399 del D.__hash__
3400 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003401 B.__hash__ = None
3402 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003403 del B.__hash__
3404 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003405 C.__hash__ = None
3406 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003407 del C.__hash__
3408 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003409 A.__hash__ = None
3410 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003411 del A.__hash__
3412 self.assertEqual(hash(d), orig_hash)
3413 d.foo = 42
3414 d.bar = 42
3415 self.assertEqual(d.foo, 42)
3416 self.assertEqual(d.bar, 42)
3417 def __getattribute__(self, name):
3418 if name == "foo":
3419 return 24
3420 return object.__getattribute__(self, name)
3421 A.__getattribute__ = __getattribute__
3422 self.assertEqual(d.foo, 24)
3423 self.assertEqual(d.bar, 42)
3424 def __getattr__(self, name):
3425 if name in ("spam", "foo", "bar"):
3426 return "hello"
3427 raise AttributeError, name
3428 B.__getattr__ = __getattr__
3429 self.assertEqual(d.spam, "hello")
3430 self.assertEqual(d.foo, 24)
3431 self.assertEqual(d.bar, 42)
3432 del A.__getattribute__
3433 self.assertEqual(d.foo, 42)
3434 del d.foo
3435 self.assertEqual(d.foo, "hello")
3436 self.assertEqual(d.bar, 42)
3437 del B.__getattr__
3438 try:
3439 d.foo
3440 except AttributeError:
3441 pass
3442 else:
3443 self.fail("d.foo should be undefined now")
3444
3445 # Test a nasty bug in recurse_down_subclasses()
3446 import gc
3447 class A(object):
3448 pass
3449 class B(A):
3450 pass
3451 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003452 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003453 A.__setitem__ = lambda *a: None # crash
3454
3455 def test_buffer_inheritance(self):
3456 # Testing that buffer interface is inherited ...
3457
3458 import binascii
3459 # SF bug [#470040] ParseTuple t# vs subclasses.
3460
3461 class MyStr(str):
3462 pass
3463 base = 'abc'
3464 m = MyStr(base)
3465 # b2a_hex uses the buffer interface to get its argument's value, via
3466 # PyArg_ParseTuple 't#' code.
3467 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3468
3469 # It's not clear that unicode will continue to support the character
3470 # buffer interface, and this test will fail if that's taken away.
3471 class MyUni(unicode):
3472 pass
3473 base = u'abc'
3474 m = MyUni(base)
3475 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3476
3477 class MyInt(int):
3478 pass
3479 m = MyInt(42)
3480 try:
3481 binascii.b2a_hex(m)
3482 self.fail('subclass of int should not have a buffer interface')
3483 except TypeError:
3484 pass
3485
3486 def test_str_of_str_subclass(self):
3487 # Testing __str__ defined in subclass of str ...
3488 import binascii
3489 import cStringIO
3490
3491 class octetstring(str):
3492 def __str__(self):
3493 return binascii.b2a_hex(self)
3494 def __repr__(self):
3495 return self + " repr"
3496
3497 o = octetstring('A')
3498 self.assertEqual(type(o), octetstring)
3499 self.assertEqual(type(str(o)), str)
3500 self.assertEqual(type(repr(o)), str)
3501 self.assertEqual(ord(o), 0x41)
3502 self.assertEqual(str(o), '41')
3503 self.assertEqual(repr(o), 'A repr')
3504 self.assertEqual(o.__str__(), '41')
3505 self.assertEqual(o.__repr__(), 'A repr')
3506
3507 capture = cStringIO.StringIO()
3508 # Calling str() or not exercises different internal paths.
3509 print >> capture, o
3510 print >> capture, str(o)
3511 self.assertEqual(capture.getvalue(), '41\n41\n')
3512 capture.close()
3513
3514 def test_keyword_arguments(self):
3515 # Testing keyword arguments to __init__, __call__...
3516 def f(a): return a
3517 self.assertEqual(f.__call__(a=42), 42)
3518 a = []
3519 list.__init__(a, sequence=[0, 1, 2])
3520 self.assertEqual(a, [0, 1, 2])
3521
3522 def test_recursive_call(self):
3523 # Testing recursive __call__() by setting to instance of class...
3524 class A(object):
3525 pass
3526
3527 A.__call__ = A()
3528 try:
3529 A()()
3530 except RuntimeError:
3531 pass
3532 else:
3533 self.fail("Recursion limit should have been reached for __call__()")
3534
3535 def test_delete_hook(self):
3536 # Testing __del__ hook...
3537 log = []
3538 class C(object):
3539 def __del__(self):
3540 log.append(1)
3541 c = C()
3542 self.assertEqual(log, [])
3543 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003544 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003545 self.assertEqual(log, [1])
3546
3547 class D(object): pass
3548 d = D()
3549 try: del d[0]
3550 except TypeError: pass
3551 else: self.fail("invalid del() didn't raise TypeError")
3552
3553 def test_hash_inheritance(self):
3554 # Testing hash of mutable subclasses...
3555
3556 class mydict(dict):
3557 pass
3558 d = mydict()
3559 try:
3560 hash(d)
3561 except TypeError:
3562 pass
3563 else:
3564 self.fail("hash() of dict subclass should fail")
3565
3566 class mylist(list):
3567 pass
3568 d = mylist()
3569 try:
3570 hash(d)
3571 except TypeError:
3572 pass
3573 else:
3574 self.fail("hash() of list subclass should fail")
3575
3576 def test_str_operations(self):
3577 try: 'a' + 5
3578 except TypeError: pass
3579 else: self.fail("'' + 5 doesn't raise TypeError")
3580
3581 try: ''.split('')
3582 except ValueError: pass
3583 else: self.fail("''.split('') doesn't raise ValueError")
3584
3585 try: ''.join([0])
3586 except TypeError: pass
3587 else: self.fail("''.join([0]) doesn't raise TypeError")
3588
3589 try: ''.rindex('5')
3590 except ValueError: pass
3591 else: self.fail("''.rindex('5') doesn't raise ValueError")
3592
3593 try: '%(n)s' % None
3594 except TypeError: pass
3595 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3596
3597 try: '%(n' % {}
3598 except ValueError: pass
3599 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3600
3601 try: '%*s' % ('abc')
3602 except TypeError: pass
3603 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3604
3605 try: '%*.*s' % ('abc', 5)
3606 except TypeError: pass
3607 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3608
3609 try: '%s' % (1, 2)
3610 except TypeError: pass
3611 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3612
3613 try: '%' % None
3614 except ValueError: pass
3615 else: self.fail("'%' % None doesn't raise ValueError")
3616
3617 self.assertEqual('534253'.isdigit(), 1)
3618 self.assertEqual('534253x'.isdigit(), 0)
3619 self.assertEqual('%c' % 5, '\x05')
3620 self.assertEqual('%c' % '5', '5')
3621
3622 def test_deepcopy_recursive(self):
3623 # Testing deepcopy of recursive objects...
3624 class Node:
3625 pass
3626 a = Node()
3627 b = Node()
3628 a.b = b
3629 b.a = a
3630 z = deepcopy(a) # This blew up before
3631
3632 def test_unintialized_modules(self):
3633 # Testing uninitialized module objects...
3634 from types import ModuleType as M
3635 m = M.__new__(M)
3636 str(m)
3637 self.assertEqual(hasattr(m, "__name__"), 0)
3638 self.assertEqual(hasattr(m, "__file__"), 0)
3639 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003640 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003641 m.foo = 1
3642 self.assertEqual(m.__dict__, {"foo": 1})
3643
3644 def test_funny_new(self):
3645 # Testing __new__ returning something unexpected...
3646 class C(object):
3647 def __new__(cls, arg):
3648 if isinstance(arg, str): return [1, 2, 3]
3649 elif isinstance(arg, int): return object.__new__(D)
3650 else: return object.__new__(cls)
3651 class D(C):
3652 def __init__(self, arg):
3653 self.foo = arg
3654 self.assertEqual(C("1"), [1, 2, 3])
3655 self.assertEqual(D("1"), [1, 2, 3])
3656 d = D(None)
3657 self.assertEqual(d.foo, None)
3658 d = C(1)
3659 self.assertEqual(isinstance(d, D), True)
3660 self.assertEqual(d.foo, 1)
3661 d = D(1)
3662 self.assertEqual(isinstance(d, D), True)
3663 self.assertEqual(d.foo, 1)
3664
3665 def test_imul_bug(self):
3666 # Testing for __imul__ problems...
3667 # SF bug 544647
3668 class C(object):
3669 def __imul__(self, other):
3670 return (self, other)
3671 x = C()
3672 y = x
3673 y *= 1.0
3674 self.assertEqual(y, (x, 1.0))
3675 y = x
3676 y *= 2
3677 self.assertEqual(y, (x, 2))
3678 y = x
3679 y *= 3L
3680 self.assertEqual(y, (x, 3L))
3681 y = x
3682 y *= 1L<<100
3683 self.assertEqual(y, (x, 1L<<100))
3684 y = x
3685 y *= None
3686 self.assertEqual(y, (x, None))
3687 y = x
3688 y *= "foo"
3689 self.assertEqual(y, (x, "foo"))
3690
3691 def test_copy_setstate(self):
3692 # Testing that copy.*copy() correctly uses __setstate__...
3693 import copy
3694 class C(object):
3695 def __init__(self, foo=None):
3696 self.foo = foo
3697 self.__foo = foo
3698 def setfoo(self, foo=None):
3699 self.foo = foo
3700 def getfoo(self):
3701 return self.__foo
3702 def __getstate__(self):
3703 return [self.foo]
3704 def __setstate__(self_, lst):
3705 self.assertEqual(len(lst), 1)
3706 self_.__foo = self_.foo = lst[0]
3707 a = C(42)
3708 a.setfoo(24)
3709 self.assertEqual(a.foo, 24)
3710 self.assertEqual(a.getfoo(), 42)
3711 b = copy.copy(a)
3712 self.assertEqual(b.foo, 24)
3713 self.assertEqual(b.getfoo(), 24)
3714 b = copy.deepcopy(a)
3715 self.assertEqual(b.foo, 24)
3716 self.assertEqual(b.getfoo(), 24)
3717
3718 def test_slices(self):
3719 # Testing cases with slices and overridden __getitem__ ...
3720
3721 # Strings
3722 self.assertEqual("hello"[:4], "hell")
3723 self.assertEqual("hello"[slice(4)], "hell")
3724 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3725 class S(str):
3726 def __getitem__(self, x):
3727 return str.__getitem__(self, x)
3728 self.assertEqual(S("hello")[:4], "hell")
3729 self.assertEqual(S("hello")[slice(4)], "hell")
3730 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3731 # Tuples
3732 self.assertEqual((1,2,3)[:2], (1,2))
3733 self.assertEqual((1,2,3)[slice(2)], (1,2))
3734 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3735 class T(tuple):
3736 def __getitem__(self, x):
3737 return tuple.__getitem__(self, x)
3738 self.assertEqual(T((1,2,3))[:2], (1,2))
3739 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3740 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3741 # Lists
3742 self.assertEqual([1,2,3][:2], [1,2])
3743 self.assertEqual([1,2,3][slice(2)], [1,2])
3744 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3745 class L(list):
3746 def __getitem__(self, x):
3747 return list.__getitem__(self, x)
3748 self.assertEqual(L([1,2,3])[:2], [1,2])
3749 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3750 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3751 # Now do lists and __setitem__
3752 a = L([1,2,3])
3753 a[slice(1, 3)] = [3,2]
3754 self.assertEqual(a, [1,3,2])
3755 a[slice(0, 2, 1)] = [3,1]
3756 self.assertEqual(a, [3,1,2])
3757 a.__setitem__(slice(1, 3), [2,1])
3758 self.assertEqual(a, [3,2,1])
3759 a.__setitem__(slice(0, 2, 1), [2,3])
3760 self.assertEqual(a, [2,3,1])
3761
3762 def test_subtype_resurrection(self):
3763 # Testing resurrection of new-style instance...
3764
3765 class C(object):
3766 container = []
3767
3768 def __del__(self):
3769 # resurrect the instance
3770 C.container.append(self)
3771
3772 c = C()
3773 c.attr = 42
3774
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003775 # The most interesting thing here is whether this blows up, due to
3776 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3777 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003778 del c
3779
3780 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003781 # the last container slot works: that will attempt to delete c again,
3782 # which will cause c to get appended back to the container again
3783 # "during" the del. (On non-CPython implementations, however, __del__
3784 # is typically not called again.)
3785 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003786 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003787 del C.container[-1]
3788 if test_support.check_impl_detail():
3789 test_support.gc_collect()
3790 self.assertEqual(len(C.container), 1)
3791 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003792
3793 # Make c mortal again, so that the test framework with -l doesn't report
3794 # it as a leak.
3795 del C.__del__
3796
3797 def test_slots_trash(self):
3798 # Testing slot trash...
3799 # Deallocating deeply nested slotted trash caused stack overflows
3800 class trash(object):
3801 __slots__ = ['x']
3802 def __init__(self, x):
3803 self.x = x
3804 o = None
3805 for i in xrange(50000):
3806 o = trash(o)
3807 del o
3808
3809 def test_slots_multiple_inheritance(self):
3810 # SF bug 575229, multiple inheritance w/ slots dumps core
3811 class A(object):
3812 __slots__=()
3813 class B(object):
3814 pass
3815 class C(A,B) :
3816 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003817 if test_support.check_impl_detail():
3818 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl48545522008-02-02 10:12:36 +00003819 self.assert_(hasattr(C, '__dict__'))
3820 self.assert_(hasattr(C, '__weakref__'))
3821 C().x = 2
3822
3823 def test_rmul(self):
3824 # Testing correct invocation of __rmul__...
3825 # SF patch 592646
3826 class C(object):
3827 def __mul__(self, other):
3828 return "mul"
3829 def __rmul__(self, other):
3830 return "rmul"
3831 a = C()
3832 self.assertEqual(a*2, "mul")
3833 self.assertEqual(a*2.2, "mul")
3834 self.assertEqual(2*a, "rmul")
3835 self.assertEqual(2.2*a, "rmul")
3836
3837 def test_ipow(self):
3838 # Testing correct invocation of __ipow__...
3839 # [SF bug 620179]
3840 class C(object):
3841 def __ipow__(self, other):
3842 pass
3843 a = C()
3844 a **= 2
3845
3846 def test_mutable_bases(self):
3847 # Testing mutable bases...
3848
3849 # stuff that should work:
3850 class C(object):
3851 pass
3852 class C2(object):
3853 def __getattribute__(self, attr):
3854 if attr == 'a':
3855 return 2
3856 else:
3857 return super(C2, self).__getattribute__(attr)
3858 def meth(self):
3859 return 1
3860 class D(C):
3861 pass
3862 class E(D):
3863 pass
3864 d = D()
3865 e = E()
3866 D.__bases__ = (C,)
3867 D.__bases__ = (C2,)
3868 self.assertEqual(d.meth(), 1)
3869 self.assertEqual(e.meth(), 1)
3870 self.assertEqual(d.a, 2)
3871 self.assertEqual(e.a, 2)
3872 self.assertEqual(C2.__subclasses__(), [D])
3873
Georg Brandl48545522008-02-02 10:12:36 +00003874 try:
3875 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003876 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003877 pass
3878 else:
3879 self.fail("shouldn't be able to delete .__bases__")
3880
3881 try:
3882 D.__bases__ = ()
3883 except TypeError, msg:
3884 if str(msg) == "a new-style class can't have only classic bases":
3885 self.fail("wrong error message for .__bases__ = ()")
3886 else:
3887 self.fail("shouldn't be able to set .__bases__ to ()")
3888
3889 try:
3890 D.__bases__ = (D,)
3891 except TypeError:
3892 pass
3893 else:
3894 # actually, we'll have crashed by here...
3895 self.fail("shouldn't be able to create inheritance cycles")
3896
3897 try:
3898 D.__bases__ = (C, C)
3899 except TypeError:
3900 pass
3901 else:
3902 self.fail("didn't detect repeated base classes")
3903
3904 try:
3905 D.__bases__ = (E,)
3906 except TypeError:
3907 pass
3908 else:
3909 self.fail("shouldn't be able to create inheritance cycles")
3910
3911 # let's throw a classic class into the mix:
3912 class Classic:
3913 def meth2(self):
3914 return 3
3915
3916 D.__bases__ = (C, Classic)
3917
3918 self.assertEqual(d.meth2(), 3)
3919 self.assertEqual(e.meth2(), 3)
3920 try:
3921 d.a
3922 except AttributeError:
3923 pass
3924 else:
3925 self.fail("attribute should have vanished")
3926
3927 try:
3928 D.__bases__ = (Classic,)
3929 except TypeError:
3930 pass
3931 else:
3932 self.fail("new-style class must have a new-style base")
3933
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003934 def test_builtin_bases(self):
3935 # Make sure all the builtin types can have their base queried without
3936 # segfaulting. See issue #5787.
3937 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3938 if isinstance(tp, type)]
3939 for tp in builtin_types:
3940 object.__getattribute__(tp, "__bases__")
3941 if tp is not object:
3942 self.assertEqual(len(tp.__bases__), 1, tp)
3943
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003944 class L(list):
3945 pass
3946
3947 class C(object):
3948 pass
3949
3950 class D(C):
3951 pass
3952
3953 try:
3954 L.__bases__ = (dict,)
3955 except TypeError:
3956 pass
3957 else:
3958 self.fail("shouldn't turn list subclass into dict subclass")
3959
3960 try:
3961 list.__bases__ = (dict,)
3962 except TypeError:
3963 pass
3964 else:
3965 self.fail("shouldn't be able to assign to list.__bases__")
3966
3967 try:
3968 D.__bases__ = (C, list)
3969 except TypeError:
3970 pass
3971 else:
3972 assert 0, "best_base calculation found wanting"
3973
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003974
Georg Brandl48545522008-02-02 10:12:36 +00003975 def test_mutable_bases_with_failing_mro(self):
3976 # Testing mutable bases with failing mro...
3977 class WorkOnce(type):
3978 def __new__(self, name, bases, ns):
3979 self.flag = 0
3980 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3981 def mro(self):
3982 if self.flag > 0:
3983 raise RuntimeError, "bozo"
3984 else:
3985 self.flag += 1
3986 return type.mro(self)
3987
3988 class WorkAlways(type):
3989 def mro(self):
3990 # this is here to make sure that .mro()s aren't called
3991 # with an exception set (which was possible at one point).
3992 # An error message will be printed in a debug build.
3993 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003994 return type.mro(self)
3995
Georg Brandl48545522008-02-02 10:12:36 +00003996 class C(object):
3997 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003998
Georg Brandl48545522008-02-02 10:12:36 +00003999 class C2(object):
4000 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004001
Georg Brandl48545522008-02-02 10:12:36 +00004002 class D(C):
4003 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004004
Georg Brandl48545522008-02-02 10:12:36 +00004005 class E(D):
4006 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004007
Georg Brandl48545522008-02-02 10:12:36 +00004008 class F(D):
4009 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004010
Georg Brandl48545522008-02-02 10:12:36 +00004011 class G(D):
4012 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004013
Georg Brandl48545522008-02-02 10:12:36 +00004014 # Immediate subclasses have their mro's adjusted in alphabetical
4015 # order, so E's will get adjusted before adjusting F's fails. We
4016 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004017
Georg Brandl48545522008-02-02 10:12:36 +00004018 E_mro_before = E.__mro__
4019 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004020
Armin Rigofd163f92005-12-29 15:59:19 +00004021 try:
Georg Brandl48545522008-02-02 10:12:36 +00004022 D.__bases__ = (C2,)
4023 except RuntimeError:
4024 self.assertEqual(E.__mro__, E_mro_before)
4025 self.assertEqual(D.__mro__, D_mro_before)
4026 else:
4027 self.fail("exception not propagated")
4028
4029 def test_mutable_bases_catch_mro_conflict(self):
4030 # Testing mutable bases catch mro conflict...
4031 class A(object):
4032 pass
4033
4034 class B(object):
4035 pass
4036
4037 class C(A, B):
4038 pass
4039
4040 class D(A, B):
4041 pass
4042
4043 class E(C, D):
4044 pass
4045
4046 try:
4047 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004048 except TypeError:
4049 pass
4050 else:
Georg Brandl48545522008-02-02 10:12:36 +00004051 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004052
Georg Brandl48545522008-02-02 10:12:36 +00004053 def test_mutable_names(self):
4054 # Testing mutable names...
4055 class C(object):
4056 pass
4057
4058 # C.__module__ could be 'test_descr' or '__main__'
4059 mod = C.__module__
4060
4061 C.__name__ = 'D'
4062 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4063
4064 C.__name__ = 'D.E'
4065 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4066
4067 def test_subclass_right_op(self):
4068 # Testing correct dispatch of subclass overloading __r<op>__...
4069
4070 # This code tests various cases where right-dispatch of a subclass
4071 # should be preferred over left-dispatch of a base class.
4072
4073 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4074
4075 class B(int):
4076 def __floordiv__(self, other):
4077 return "B.__floordiv__"
4078 def __rfloordiv__(self, other):
4079 return "B.__rfloordiv__"
4080
4081 self.assertEqual(B(1) // 1, "B.__floordiv__")
4082 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4083
4084 # Case 2: subclass of object; this is just the baseline for case 3
4085
4086 class C(object):
4087 def __floordiv__(self, other):
4088 return "C.__floordiv__"
4089 def __rfloordiv__(self, other):
4090 return "C.__rfloordiv__"
4091
4092 self.assertEqual(C() // 1, "C.__floordiv__")
4093 self.assertEqual(1 // C(), "C.__rfloordiv__")
4094
4095 # Case 3: subclass of new-style class; here it gets interesting
4096
4097 class D(C):
4098 def __floordiv__(self, other):
4099 return "D.__floordiv__"
4100 def __rfloordiv__(self, other):
4101 return "D.__rfloordiv__"
4102
4103 self.assertEqual(D() // C(), "D.__floordiv__")
4104 self.assertEqual(C() // D(), "D.__rfloordiv__")
4105
4106 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4107
4108 class E(C):
4109 pass
4110
4111 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4112
4113 self.assertEqual(E() // 1, "C.__floordiv__")
4114 self.assertEqual(1 // E(), "C.__rfloordiv__")
4115 self.assertEqual(E() // C(), "C.__floordiv__")
4116 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4117
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004118 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004119 def test_meth_class_get(self):
4120 # Testing __get__ method of METH_CLASS C methods...
4121 # Full coverage of descrobject.c::classmethod_get()
4122
4123 # Baseline
4124 arg = [1, 2, 3]
4125 res = {1: None, 2: None, 3: None}
4126 self.assertEqual(dict.fromkeys(arg), res)
4127 self.assertEqual({}.fromkeys(arg), res)
4128
4129 # Now get the descriptor
4130 descr = dict.__dict__["fromkeys"]
4131
4132 # More baseline using the descriptor directly
4133 self.assertEqual(descr.__get__(None, dict)(arg), res)
4134 self.assertEqual(descr.__get__({})(arg), res)
4135
4136 # Now check various error cases
4137 try:
4138 descr.__get__(None, None)
4139 except TypeError:
4140 pass
4141 else:
4142 self.fail("shouldn't have allowed descr.__get__(None, None)")
4143 try:
4144 descr.__get__(42)
4145 except TypeError:
4146 pass
4147 else:
4148 self.fail("shouldn't have allowed descr.__get__(42)")
4149 try:
4150 descr.__get__(None, 42)
4151 except TypeError:
4152 pass
4153 else:
4154 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4155 try:
4156 descr.__get__(None, int)
4157 except TypeError:
4158 pass
4159 else:
4160 self.fail("shouldn't have allowed descr.__get__(None, int)")
4161
4162 def test_isinst_isclass(self):
4163 # Testing proxy isinstance() and isclass()...
4164 class Proxy(object):
4165 def __init__(self, obj):
4166 self.__obj = obj
4167 def __getattribute__(self, name):
4168 if name.startswith("_Proxy__"):
4169 return object.__getattribute__(self, name)
4170 else:
4171 return getattr(self.__obj, name)
4172 # Test with a classic class
4173 class C:
4174 pass
4175 a = C()
4176 pa = Proxy(a)
4177 self.assert_(isinstance(a, C)) # Baseline
4178 self.assert_(isinstance(pa, C)) # Test
4179 # Test with a classic subclass
4180 class D(C):
4181 pass
4182 a = D()
4183 pa = Proxy(a)
4184 self.assert_(isinstance(a, C)) # Baseline
4185 self.assert_(isinstance(pa, C)) # Test
4186 # Test with a new-style class
4187 class C(object):
4188 pass
4189 a = C()
4190 pa = Proxy(a)
4191 self.assert_(isinstance(a, C)) # Baseline
4192 self.assert_(isinstance(pa, C)) # Test
4193 # Test with a new-style subclass
4194 class D(C):
4195 pass
4196 a = D()
4197 pa = Proxy(a)
4198 self.assert_(isinstance(a, C)) # Baseline
4199 self.assert_(isinstance(pa, C)) # Test
4200
4201 def test_proxy_super(self):
4202 # Testing super() for a proxy object...
4203 class Proxy(object):
4204 def __init__(self, obj):
4205 self.__obj = obj
4206 def __getattribute__(self, name):
4207 if name.startswith("_Proxy__"):
4208 return object.__getattribute__(self, name)
4209 else:
4210 return getattr(self.__obj, name)
4211
4212 class B(object):
4213 def f(self):
4214 return "B.f"
4215
4216 class C(B):
4217 def f(self):
4218 return super(C, self).f() + "->C.f"
4219
4220 obj = C()
4221 p = Proxy(obj)
4222 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4223
4224 def test_carloverre(self):
4225 # Testing prohibition of Carlo Verre's hack...
4226 try:
4227 object.__setattr__(str, "foo", 42)
4228 except TypeError:
4229 pass
4230 else:
4231 self.fail("Carlo Verre __setattr__ suceeded!")
4232 try:
4233 object.__delattr__(str, "lower")
4234 except TypeError:
4235 pass
4236 else:
4237 self.fail("Carlo Verre __delattr__ succeeded!")
4238
4239 def test_weakref_segfault(self):
4240 # Testing weakref segfault...
4241 # SF 742911
4242 import weakref
4243
4244 class Provoker:
4245 def __init__(self, referrent):
4246 self.ref = weakref.ref(referrent)
4247
4248 def __del__(self):
4249 x = self.ref()
4250
4251 class Oops(object):
4252 pass
4253
4254 o = Oops()
4255 o.whatever = Provoker(o)
4256 del o
4257
4258 def test_wrapper_segfault(self):
4259 # SF 927248: deeply nested wrappers could cause stack overflow
4260 f = lambda:None
4261 for i in xrange(1000000):
4262 f = f.__call__
4263 f = None
4264
4265 def test_file_fault(self):
4266 # Testing sys.stdout is changed in getattr...
4267 import sys
4268 class StdoutGuard:
4269 def __getattr__(self, attr):
4270 sys.stdout = sys.__stdout__
4271 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4272 sys.stdout = StdoutGuard()
4273 try:
4274 print "Oops!"
4275 except RuntimeError:
4276 pass
4277
4278 def test_vicious_descriptor_nonsense(self):
4279 # Testing vicious_descriptor_nonsense...
4280
4281 # A potential segfault spotted by Thomas Wouters in mail to
4282 # python-dev 2003-04-17, turned into an example & fixed by Michael
4283 # Hudson just less than four months later...
4284
4285 class Evil(object):
4286 def __hash__(self):
4287 return hash('attr')
4288 def __eq__(self, other):
4289 del C.attr
4290 return 0
4291
4292 class Descr(object):
4293 def __get__(self, ob, type=None):
4294 return 1
4295
4296 class C(object):
4297 attr = Descr()
4298
4299 c = C()
4300 c.__dict__[Evil()] = 0
4301
4302 self.assertEqual(c.attr, 1)
4303 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004304 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004305 self.assertEqual(hasattr(c, 'attr'), False)
4306
4307 def test_init(self):
4308 # SF 1155938
4309 class Foo(object):
4310 def __init__(self):
4311 return 10
4312 try:
4313 Foo()
4314 except TypeError:
4315 pass
4316 else:
4317 self.fail("did not test __init__() for None return")
4318
4319 def test_method_wrapper(self):
4320 # Testing method-wrapper objects...
4321 # <type 'method-wrapper'> did not support any reflection before 2.5
4322
4323 l = []
4324 self.assertEqual(l.__add__, l.__add__)
4325 self.assertEqual(l.__add__, [].__add__)
4326 self.assert_(l.__add__ != [5].__add__)
4327 self.assert_(l.__add__ != l.__mul__)
4328 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004329 if hasattr(l.__add__, '__self__'):
4330 # CPython
4331 self.assert_(l.__add__.__self__ is l)
4332 self.assert_(l.__add__.__objclass__ is list)
4333 else:
4334 # Python implementations where [].__add__ is a normal bound method
4335 self.assert_(l.__add__.im_self is l)
4336 self.assert_(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004337 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4338 try:
4339 hash(l.__add__)
4340 except TypeError:
4341 pass
4342 else:
4343 self.fail("no TypeError from hash([].__add__)")
4344
4345 t = ()
4346 t += (7,)
4347 self.assertEqual(t.__add__, (7,).__add__)
4348 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4349
4350 def test_not_implemented(self):
4351 # Testing NotImplemented...
4352 # all binary methods should be able to return a NotImplemented
4353 import sys
4354 import types
4355 import operator
4356
4357 def specialmethod(self, other):
4358 return NotImplemented
4359
4360 def check(expr, x, y):
4361 try:
4362 exec expr in {'x': x, 'y': y, 'operator': operator}
4363 except TypeError:
4364 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004365 else:
Georg Brandl48545522008-02-02 10:12:36 +00004366 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004367
Georg Brandl48545522008-02-02 10:12:36 +00004368 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4369 # TypeErrors
4370 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4371 # ValueErrors instead of TypeErrors
4372 for metaclass in [type, types.ClassType]:
4373 for name, expr, iexpr in [
4374 ('__add__', 'x + y', 'x += y'),
4375 ('__sub__', 'x - y', 'x -= y'),
4376 ('__mul__', 'x * y', 'x *= y'),
4377 ('__truediv__', 'operator.truediv(x, y)', None),
4378 ('__floordiv__', 'operator.floordiv(x, y)', None),
4379 ('__div__', 'x / y', 'x /= y'),
4380 ('__mod__', 'x % y', 'x %= y'),
4381 ('__divmod__', 'divmod(x, y)', None),
4382 ('__pow__', 'x ** y', 'x **= y'),
4383 ('__lshift__', 'x << y', 'x <<= y'),
4384 ('__rshift__', 'x >> y', 'x >>= y'),
4385 ('__and__', 'x & y', 'x &= y'),
4386 ('__or__', 'x | y', 'x |= y'),
4387 ('__xor__', 'x ^ y', 'x ^= y'),
4388 ('__coerce__', 'coerce(x, y)', None)]:
4389 if name == '__coerce__':
4390 rname = name
4391 else:
4392 rname = '__r' + name[2:]
4393 A = metaclass('A', (), {name: specialmethod})
4394 B = metaclass('B', (), {rname: specialmethod})
4395 a = A()
4396 b = B()
4397 check(expr, a, a)
4398 check(expr, a, b)
4399 check(expr, b, a)
4400 check(expr, b, b)
4401 check(expr, a, N1)
4402 check(expr, a, N2)
4403 check(expr, N1, b)
4404 check(expr, N2, b)
4405 if iexpr:
4406 check(iexpr, a, a)
4407 check(iexpr, a, b)
4408 check(iexpr, b, a)
4409 check(iexpr, b, b)
4410 check(iexpr, a, N1)
4411 check(iexpr, a, N2)
4412 iname = '__i' + name[2:]
4413 C = metaclass('C', (), {iname: specialmethod})
4414 c = C()
4415 check(iexpr, c, a)
4416 check(iexpr, c, b)
4417 check(iexpr, c, N1)
4418 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004419
Georg Brandl48545522008-02-02 10:12:36 +00004420 def test_assign_slice(self):
4421 # ceval.c's assign_slice used to check for
4422 # tp->tp_as_sequence->sq_slice instead of
4423 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004424
Georg Brandl48545522008-02-02 10:12:36 +00004425 class C(object):
4426 def __setslice__(self, start, stop, value):
4427 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004428
Georg Brandl48545522008-02-02 10:12:36 +00004429 c = C()
4430 c[1:2] = 3
4431 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004432
Benjamin Peterson273c2332008-11-17 22:39:09 +00004433 def test_getattr_hooks(self):
4434 # issue 4230
4435
4436 class Descriptor(object):
4437 counter = 0
4438 def __get__(self, obj, objtype=None):
4439 def getter(name):
4440 self.counter += 1
4441 raise AttributeError(name)
4442 return getter
4443
4444 descr = Descriptor()
4445 class A(object):
4446 __getattribute__ = descr
4447 class B(object):
4448 __getattr__ = descr
4449 class C(object):
4450 __getattribute__ = descr
4451 __getattr__ = descr
4452
4453 self.assertRaises(AttributeError, getattr, A(), "attr")
4454 self.assertEquals(descr.counter, 1)
4455 self.assertRaises(AttributeError, getattr, B(), "attr")
4456 self.assertEquals(descr.counter, 2)
4457 self.assertRaises(AttributeError, getattr, C(), "attr")
4458 self.assertEquals(descr.counter, 4)
4459
4460 import gc
4461 class EvilGetattribute(object):
4462 # This used to segfault
4463 def __getattr__(self, name):
4464 raise AttributeError(name)
4465 def __getattribute__(self, name):
4466 del EvilGetattribute.__getattr__
4467 for i in range(5):
4468 gc.collect()
4469 raise AttributeError(name)
4470
4471 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4472
Guido van Rossum9acc3872008-01-23 23:23:43 +00004473
Georg Brandl48545522008-02-02 10:12:36 +00004474class DictProxyTests(unittest.TestCase):
4475 def setUp(self):
4476 class C(object):
4477 def meth(self):
4478 pass
4479 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004480
Georg Brandl48545522008-02-02 10:12:36 +00004481 def test_iter_keys(self):
4482 # Testing dict-proxy iterkeys...
4483 keys = [ key for key in self.C.__dict__.iterkeys() ]
4484 keys.sort()
4485 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4486 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004487
Georg Brandl48545522008-02-02 10:12:36 +00004488 def test_iter_values(self):
4489 # Testing dict-proxy itervalues...
4490 values = [ values for values in self.C.__dict__.itervalues() ]
4491 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004492
Georg Brandl48545522008-02-02 10:12:36 +00004493 def test_iter_items(self):
4494 # Testing dict-proxy iteritems...
4495 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4496 keys.sort()
4497 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4498 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004499
Georg Brandl48545522008-02-02 10:12:36 +00004500 def test_dict_type_with_metaclass(self):
4501 # Testing type of __dict__ when __metaclass__ set...
4502 class B(object):
4503 pass
4504 class M(type):
4505 pass
4506 class C:
4507 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4508 __metaclass__ = M
4509 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004510
Guido van Rossum9acc3872008-01-23 23:23:43 +00004511
Georg Brandl48545522008-02-02 10:12:36 +00004512class PTypesLongInitTest(unittest.TestCase):
4513 # This is in its own TestCase so that it can be run before any other tests.
4514 def test_pytype_long_ready(self):
4515 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004516
Georg Brandl48545522008-02-02 10:12:36 +00004517 # This dumps core when SF bug 551412 isn't fixed --
4518 # but only when test_descr.py is run separately.
4519 # (That can't be helped -- as soon as PyType_Ready()
4520 # is called for PyLong_Type, the bug is gone.)
4521 class UserLong(object):
4522 def __pow__(self, *args):
4523 pass
4524 try:
4525 pow(0L, UserLong(), 0L)
4526 except:
4527 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004528
Georg Brandl48545522008-02-02 10:12:36 +00004529 # Another segfault only when run early
4530 # (before PyType_Ready(tuple) is called)
4531 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004532
4533
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004534def test_main():
Georg Brandl48545522008-02-02 10:12:36 +00004535 # Run all local test cases, with PTypesLongInitTest first.
4536 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4537 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004538
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004539if __name__ == "__main__":
4540 test_main()