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