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