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