blob: 00f19ce17bb70a6b32a1094df53e350364a626da [file] [log] [blame]
Benjamin Petersond4d400c2009-04-18 20:12:47 +00001import __builtin__
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00002import sys
Armin Rigo9790a272007-05-02 19:23:31 +00003import types
Georg Brandl48545522008-02-02 10:12:36 +00004import unittest
5import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00006
Georg Brandl48545522008-02-02 10:12:36 +00007from copy import deepcopy
8from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +00009
Guido van Rossum875eeaa2001-10-11 18:33:53 +000010
Georg Brandl48545522008-02-02 10:12:36 +000011class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000012
Georg Brandl48545522008-02-02 10:12:36 +000013 def __init__(self, *args, **kwargs):
14 unittest.TestCase.__init__(self, *args, **kwargs)
15 self.binops = {
16 'add': '+',
17 'sub': '-',
18 'mul': '*',
19 'div': '/',
20 'divmod': 'divmod',
21 'pow': '**',
22 'lshift': '<<',
23 'rshift': '>>',
24 'and': '&',
25 'xor': '^',
26 'or': '|',
27 'cmp': 'cmp',
28 'lt': '<',
29 'le': '<=',
30 'eq': '==',
31 'ne': '!=',
32 'gt': '>',
33 'ge': '>=',
34 }
Tim Peters3caca232001-12-06 06:23:26 +000035
Georg Brandl48545522008-02-02 10:12:36 +000036 for name, expr in self.binops.items():
37 if expr.islower():
38 expr = expr + "(a, b)"
39 else:
40 expr = 'a %s b' % expr
41 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000042
Georg Brandl48545522008-02-02 10:12:36 +000043 self.unops = {
44 'pos': '+',
45 'neg': '-',
46 'abs': 'abs',
47 'invert': '~',
48 'int': 'int',
49 'long': 'long',
50 'float': 'float',
51 'oct': 'oct',
52 'hex': 'hex',
53 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000054
Georg Brandl48545522008-02-02 10:12:36 +000055 for name, expr in self.unops.items():
56 if expr.islower():
57 expr = expr + "(a)"
58 else:
59 expr = '%s a' % expr
60 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000061
Georg Brandl48545522008-02-02 10:12:36 +000062 def setUp(self):
63 self.original_filters = warnings.filters[:]
64 warnings.filterwarnings("ignore",
65 r'complex divmod\(\), // and % are deprecated$',
66 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000067
Georg Brandl48545522008-02-02 10:12:36 +000068 def tearDown(self):
69 warnings.filters = self.original_filters
Tim Peters6d6c1a32001-08-02 04:15:00 +000070
Georg Brandl48545522008-02-02 10:12:36 +000071 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
72 d = {'a': a}
73 self.assertEqual(eval(expr, d), res)
74 t = type(a)
75 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076
Georg Brandl48545522008-02-02 10:12:36 +000077 # Find method in parent class
78 while meth not in t.__dict__:
79 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000080 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
81 # method object; the getattr() below obtains its underlying function.
82 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000083 self.assertEqual(m(a), res)
84 bm = getattr(a, meth)
85 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000086
Georg Brandl48545522008-02-02 10:12:36 +000087 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
88 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000089
Georg Brandl48545522008-02-02 10:12:36 +000090 # XXX Hack so this passes before 2.3 when -Qnew is specified.
91 if meth == "__div__" and 1/2 == 0.5:
92 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000093
Georg Brandl48545522008-02-02 10:12:36 +000094 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000095
Georg Brandl48545522008-02-02 10:12:36 +000096 self.assertEqual(eval(expr, d), res)
97 t = type(a)
98 m = getattr(t, meth)
99 while meth not in t.__dict__:
100 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000101 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
102 # method object; the getattr() below obtains its underlying function.
103 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000104 self.assertEqual(m(a, b), res)
105 bm = getattr(a, meth)
106 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000107
Georg Brandl48545522008-02-02 10:12:36 +0000108 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
109 d = {'a': a, 'b': b, 'c': c}
110 self.assertEqual(eval(expr, d), res)
111 t = type(a)
112 m = getattr(t, meth)
113 while meth not in t.__dict__:
114 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000115 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
116 # method object; the getattr() below obtains its underlying function.
117 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000118 self.assertEqual(m(a, b, c), res)
119 bm = getattr(a, meth)
120 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000121
Georg Brandl48545522008-02-02 10:12:36 +0000122 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
123 d = {'a': deepcopy(a), 'b': b}
124 exec stmt in d
125 self.assertEqual(d['a'], res)
126 t = type(a)
127 m = getattr(t, meth)
128 while meth not in t.__dict__:
129 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000130 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
131 # method object; the getattr() below obtains its underlying function.
132 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000133 d['a'] = deepcopy(a)
134 m(d['a'], b)
135 self.assertEqual(d['a'], res)
136 d['a'] = deepcopy(a)
137 bm = getattr(d['a'], meth)
138 bm(b)
139 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000140
Georg Brandl48545522008-02-02 10:12:36 +0000141 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
142 d = {'a': deepcopy(a), 'b': b, 'c': c}
143 exec stmt in d
144 self.assertEqual(d['a'], res)
145 t = type(a)
146 m = getattr(t, meth)
147 while meth not in t.__dict__:
148 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000149 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
150 # method object; the getattr() below obtains its underlying function.
151 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000152 d['a'] = deepcopy(a)
153 m(d['a'], b, c)
154 self.assertEqual(d['a'], res)
155 d['a'] = deepcopy(a)
156 bm = getattr(d['a'], meth)
157 bm(b, c)
158 self.assertEqual(d['a'], res)
159
160 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
161 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
162 exec stmt in dictionary
163 self.assertEqual(dictionary['a'], res)
164 t = type(a)
165 while meth not in t.__dict__:
166 t = t.__bases__[0]
167 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000168 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
169 # method object; the getattr() below obtains its underlying function.
170 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000171 dictionary['a'] = deepcopy(a)
172 m(dictionary['a'], b, c, d)
173 self.assertEqual(dictionary['a'], res)
174 dictionary['a'] = deepcopy(a)
175 bm = getattr(dictionary['a'], meth)
176 bm(b, c, d)
177 self.assertEqual(dictionary['a'], res)
178
179 def test_lists(self):
180 # Testing list operations...
181 # Asserts are within individual test methods
182 self.binop_test([1], [2], [1,2], "a+b", "__add__")
183 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
184 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
185 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
186 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
187 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
188 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
189 self.unop_test([1,2,3], 3, "len(a)", "__len__")
190 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
191 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
192 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
193 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
194 "__setslice__")
195
196 def test_dicts(self):
197 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000198 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
199 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
200 else:
201 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000202 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
203 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
204 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
205
206 d = {1:2, 3:4}
207 l1 = []
208 for i in d.keys():
209 l1.append(i)
210 l = []
211 for i in iter(d):
212 l.append(i)
213 self.assertEqual(l, l1)
214 l = []
215 for i in d.__iter__():
216 l.append(i)
217 self.assertEqual(l, l1)
218 l = []
219 for i in dict.__iter__(d):
220 l.append(i)
221 self.assertEqual(l, l1)
222 d = {1:2, 3:4}
223 self.unop_test(d, 2, "len(a)", "__len__")
224 self.assertEqual(eval(repr(d), {}), d)
225 self.assertEqual(eval(d.__repr__(), {}), d)
226 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
227 "__setitem__")
228
229 # Tests for unary and binary operators
230 def number_operators(self, a, b, skip=[]):
231 dict = {'a': a, 'b': b}
232
233 for name, expr in self.binops.items():
234 if name not in skip:
235 name = "__%s__" % name
236 if hasattr(a, name):
237 res = eval(expr, dict)
238 self.binop_test(a, b, res, expr, name)
239
240 for name, expr in self.unops.items():
241 if name not in skip:
242 name = "__%s__" % name
243 if hasattr(a, name):
244 res = eval(expr, dict)
245 self.unop_test(a, res, expr, name)
246
247 def test_ints(self):
248 # Testing int operations...
249 self.number_operators(100, 3)
250 # The following crashes in Python 2.2
251 self.assertEqual((1).__nonzero__(), 1)
252 self.assertEqual((0).__nonzero__(), 0)
253 # This returns 'NotImplemented' in Python 2.2
254 class C(int):
255 def __add__(self, other):
256 return NotImplemented
257 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000258 try:
Georg Brandl48545522008-02-02 10:12:36 +0000259 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000260 except TypeError:
261 pass
262 else:
Georg Brandl48545522008-02-02 10:12:36 +0000263 self.fail("NotImplemented should have caused TypeError")
264 import sys
Tim Peters1fc240e2001-10-26 05:06:50 +0000265 try:
Georg Brandl48545522008-02-02 10:12:36 +0000266 C(sys.maxint+1)
267 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000268 pass
269 else:
Georg Brandl48545522008-02-02 10:12:36 +0000270 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000271
Georg Brandl48545522008-02-02 10:12:36 +0000272 def test_longs(self):
273 # Testing long operations...
274 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275
Georg Brandl48545522008-02-02 10:12:36 +0000276 def test_floats(self):
277 # Testing float operations...
278 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000279
Georg Brandl48545522008-02-02 10:12:36 +0000280 def test_complexes(self):
281 # Testing complex operations...
282 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
283 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000284
Georg Brandl48545522008-02-02 10:12:36 +0000285 class Number(complex):
286 __slots__ = ['prec']
287 def __new__(cls, *args, **kwds):
288 result = complex.__new__(cls, *args)
289 result.prec = kwds.get('prec', 12)
290 return result
291 def __repr__(self):
292 prec = self.prec
293 if self.imag == 0.0:
294 return "%.*g" % (prec, self.real)
295 if self.real == 0.0:
296 return "%.*gj" % (prec, self.imag)
297 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
298 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000299
Georg Brandl48545522008-02-02 10:12:36 +0000300 a = Number(3.14, prec=6)
301 self.assertEqual(repr(a), "3.14")
302 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000303
Georg Brandl48545522008-02-02 10:12:36 +0000304 a = Number(a, prec=2)
305 self.assertEqual(repr(a), "3.1")
306 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000307
Georg Brandl48545522008-02-02 10:12:36 +0000308 a = Number(234.5)
309 self.assertEqual(repr(a), "234.5")
310 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000311
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000312 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000313 def test_spam_lists(self):
314 # Testing spamlist operations...
315 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000316
Georg Brandl48545522008-02-02 10:12:36 +0000317 def spamlist(l, memo=None):
318 import xxsubtype as spam
319 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000320
Georg Brandl48545522008-02-02 10:12:36 +0000321 # This is an ugly hack:
322 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000323
Georg Brandl48545522008-02-02 10:12:36 +0000324 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
325 "__add__")
326 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
327 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
328 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
329 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
330 "__getslice__")
331 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
332 "__iadd__")
333 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
334 "__imul__")
335 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
336 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
337 "__mul__")
338 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
339 "__rmul__")
340 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
341 "__setitem__")
342 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
343 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
344 # Test subclassing
345 class C(spam.spamlist):
346 def foo(self): return 1
347 a = C()
348 self.assertEqual(a, [])
349 self.assertEqual(a.foo(), 1)
350 a.append(100)
351 self.assertEqual(a, [100])
352 self.assertEqual(a.getstate(), 0)
353 a.setstate(42)
354 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000355
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000356 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000357 def test_spam_dicts(self):
358 # Testing spamdict operations...
359 import copy, xxsubtype as spam
360 def spamdict(d, memo=None):
361 import xxsubtype as spam
362 sd = spam.spamdict()
363 for k, v in d.items():
364 sd[k] = v
365 return sd
366 # This is an ugly hack:
367 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000368
Georg Brandl48545522008-02-02 10:12:36 +0000369 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
370 "__cmp__")
371 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
372 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
373 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
374 d = spamdict({1:2,3:4})
375 l1 = []
376 for i in d.keys():
377 l1.append(i)
378 l = []
379 for i in iter(d):
380 l.append(i)
381 self.assertEqual(l, l1)
382 l = []
383 for i in d.__iter__():
384 l.append(i)
385 self.assertEqual(l, l1)
386 l = []
387 for i in type(spamdict({})).__iter__(d):
388 l.append(i)
389 self.assertEqual(l, l1)
390 straightd = {1:2, 3:4}
391 spamd = spamdict(straightd)
392 self.unop_test(spamd, 2, "len(a)", "__len__")
393 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
394 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
395 "a[b]=c", "__setitem__")
396 # Test subclassing
397 class C(spam.spamdict):
398 def foo(self): return 1
399 a = C()
400 self.assertEqual(a.items(), [])
401 self.assertEqual(a.foo(), 1)
402 a['foo'] = 'bar'
403 self.assertEqual(a.items(), [('foo', 'bar')])
404 self.assertEqual(a.getstate(), 0)
405 a.setstate(100)
406 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000407
Georg Brandl48545522008-02-02 10:12:36 +0000408class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000409
Georg Brandl48545522008-02-02 10:12:36 +0000410 def test_python_dicts(self):
411 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000412 self.assertTrue(issubclass(dict, dict))
413 self.assertTrue(isinstance({}, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000414 d = dict()
415 self.assertEqual(d, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000416 self.assertTrue(d.__class__ is dict)
417 self.assertTrue(isinstance(d, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000418 class C(dict):
419 state = -1
420 def __init__(self_local, *a, **kw):
421 if a:
422 self.assertEqual(len(a), 1)
423 self_local.state = a[0]
424 if kw:
425 for k, v in kw.items():
426 self_local[v] = k
427 def __getitem__(self, key):
428 return self.get(key, 0)
429 def __setitem__(self_local, key, value):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000430 self.assertTrue(isinstance(key, type(0)))
Georg Brandl48545522008-02-02 10:12:36 +0000431 dict.__setitem__(self_local, key, value)
432 def setstate(self, state):
433 self.state = state
434 def getstate(self):
435 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000436 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000437 a1 = C(12)
438 self.assertEqual(a1.state, 12)
439 a2 = C(foo=1, bar=2)
440 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
441 a = C()
442 self.assertEqual(a.state, -1)
443 self.assertEqual(a.getstate(), -1)
444 a.setstate(0)
445 self.assertEqual(a.state, 0)
446 self.assertEqual(a.getstate(), 0)
447 a.setstate(10)
448 self.assertEqual(a.state, 10)
449 self.assertEqual(a.getstate(), 10)
450 self.assertEqual(a[42], 0)
451 a[42] = 24
452 self.assertEqual(a[42], 24)
453 N = 50
454 for i in range(N):
455 a[i] = C()
456 for j in range(N):
457 a[i][j] = i*j
458 for i in range(N):
459 for j in range(N):
460 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000461
Georg Brandl48545522008-02-02 10:12:36 +0000462 def test_python_lists(self):
463 # Testing Python subclass of list...
464 class C(list):
465 def __getitem__(self, i):
466 return list.__getitem__(self, i) + 100
467 def __getslice__(self, i, j):
468 return (i, j)
469 a = C()
470 a.extend([0,1,2])
471 self.assertEqual(a[0], 100)
472 self.assertEqual(a[1], 101)
473 self.assertEqual(a[2], 102)
474 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000475
Georg Brandl48545522008-02-02 10:12:36 +0000476 def test_metaclass(self):
477 # Testing __metaclass__...
478 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000479 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000480 def __init__(self):
481 self.__state = 0
482 def getstate(self):
483 return self.__state
484 def setstate(self, state):
485 self.__state = state
486 a = C()
487 self.assertEqual(a.getstate(), 0)
488 a.setstate(10)
489 self.assertEqual(a.getstate(), 10)
490 class D:
491 class __metaclass__(type):
492 def myself(cls): return cls
493 self.assertEqual(D.myself(), D)
494 d = D()
495 self.assertEqual(d.__class__, D)
496 class M1(type):
497 def __new__(cls, name, bases, dict):
498 dict['__spam__'] = 1
499 return type.__new__(cls, name, bases, dict)
500 class C:
501 __metaclass__ = M1
502 self.assertEqual(C.__spam__, 1)
503 c = C()
504 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000505
Georg Brandl48545522008-02-02 10:12:36 +0000506 class _instance(object):
507 pass
508 class M2(object):
509 @staticmethod
510 def __new__(cls, name, bases, dict):
511 self = object.__new__(cls)
512 self.name = name
513 self.bases = bases
514 self.dict = dict
515 return self
516 def __call__(self):
517 it = _instance()
518 # Early binding of methods
519 for key in self.dict:
520 if key.startswith("__"):
521 continue
522 setattr(it, key, self.dict[key].__get__(it, self))
523 return it
524 class C:
525 __metaclass__ = M2
526 def spam(self):
527 return 42
528 self.assertEqual(C.name, 'C')
529 self.assertEqual(C.bases, ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000530 self.assertTrue('spam' in C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000531 c = C()
532 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000533
Georg Brandl48545522008-02-02 10:12:36 +0000534 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000535
Georg Brandl48545522008-02-02 10:12:36 +0000536 class autosuper(type):
537 # Automatically add __super to the class
538 # This trick only works for dynamic classes
539 def __new__(metaclass, name, bases, dict):
540 cls = super(autosuper, metaclass).__new__(metaclass,
541 name, bases, dict)
542 # Name mangling for __super removes leading underscores
543 while name[:1] == "_":
544 name = name[1:]
545 if name:
546 name = "_%s__super" % name
547 else:
548 name = "__super"
549 setattr(cls, name, super(cls))
550 return cls
551 class A:
552 __metaclass__ = autosuper
553 def meth(self):
554 return "A"
555 class B(A):
556 def meth(self):
557 return "B" + self.__super.meth()
558 class C(A):
559 def meth(self):
560 return "C" + self.__super.meth()
561 class D(C, B):
562 def meth(self):
563 return "D" + self.__super.meth()
564 self.assertEqual(D().meth(), "DCBA")
565 class E(B, C):
566 def meth(self):
567 return "E" + self.__super.meth()
568 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000569
Georg Brandl48545522008-02-02 10:12:36 +0000570 class autoproperty(type):
571 # Automatically create property attributes when methods
572 # named _get_x and/or _set_x are found
573 def __new__(metaclass, name, bases, dict):
574 hits = {}
575 for key, val in dict.iteritems():
576 if key.startswith("_get_"):
577 key = key[5:]
578 get, set = hits.get(key, (None, None))
579 get = val
580 hits[key] = get, set
581 elif key.startswith("_set_"):
582 key = key[5:]
583 get, set = hits.get(key, (None, None))
584 set = val
585 hits[key] = get, set
586 for key, (get, set) in hits.iteritems():
587 dict[key] = property(get, set)
588 return super(autoproperty, metaclass).__new__(metaclass,
589 name, bases, dict)
590 class A:
591 __metaclass__ = autoproperty
592 def _get_x(self):
593 return -self.__x
594 def _set_x(self, x):
595 self.__x = -x
596 a = A()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000597 self.assertTrue(not hasattr(a, "x"))
Georg Brandl48545522008-02-02 10:12:36 +0000598 a.x = 12
599 self.assertEqual(a.x, 12)
600 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000601
Georg Brandl48545522008-02-02 10:12:36 +0000602 class multimetaclass(autoproperty, autosuper):
603 # Merge of multiple cooperating metaclasses
604 pass
605 class A:
606 __metaclass__ = multimetaclass
607 def _get_x(self):
608 return "A"
609 class B(A):
610 def _get_x(self):
611 return "B" + self.__super._get_x()
612 class C(A):
613 def _get_x(self):
614 return "C" + self.__super._get_x()
615 class D(C, B):
616 def _get_x(self):
617 return "D" + self.__super._get_x()
618 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000619
Georg Brandl48545522008-02-02 10:12:36 +0000620 # Make sure type(x) doesn't call x.__class__.__init__
621 class T(type):
622 counter = 0
623 def __init__(self, *args):
624 T.counter += 1
625 class C:
626 __metaclass__ = T
627 self.assertEqual(T.counter, 1)
628 a = C()
629 self.assertEqual(type(a), C)
630 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000631
Georg Brandl48545522008-02-02 10:12:36 +0000632 class C(object): pass
633 c = C()
634 try: c()
635 except TypeError: pass
636 else: self.fail("calling object w/o call method should raise "
637 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000638
Georg Brandl48545522008-02-02 10:12:36 +0000639 # Testing code to find most derived baseclass
640 class A(type):
641 def __new__(*args, **kwargs):
642 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000643
Georg Brandl48545522008-02-02 10:12:36 +0000644 class B(object):
645 pass
646
647 class C(object):
648 __metaclass__ = A
649
650 # The most derived metaclass of D is A rather than type.
651 class D(B, C):
652 pass
653
654 def test_module_subclasses(self):
655 # Testing Python subclass of module...
656 log = []
657 import types, sys
658 MT = type(sys)
659 class MM(MT):
660 def __init__(self, name):
661 MT.__init__(self, name)
662 def __getattribute__(self, name):
663 log.append(("getattr", name))
664 return MT.__getattribute__(self, name)
665 def __setattr__(self, name, value):
666 log.append(("setattr", name, value))
667 MT.__setattr__(self, name, value)
668 def __delattr__(self, name):
669 log.append(("delattr", name))
670 MT.__delattr__(self, name)
671 a = MM("a")
672 a.foo = 12
673 x = a.foo
674 del a.foo
675 self.assertEqual(log, [("setattr", "foo", 12),
676 ("getattr", "foo"),
677 ("delattr", "foo")])
678
679 # http://python.org/sf/1174712
680 try:
681 class Module(types.ModuleType, str):
682 pass
683 except TypeError:
684 pass
685 else:
686 self.fail("inheriting from ModuleType and str at the same time "
687 "should fail")
688
689 def test_multiple_inheritence(self):
690 # Testing multiple inheritance...
691 class C(object):
692 def __init__(self):
693 self.__state = 0
694 def getstate(self):
695 return self.__state
696 def setstate(self, state):
697 self.__state = state
698 a = C()
699 self.assertEqual(a.getstate(), 0)
700 a.setstate(10)
701 self.assertEqual(a.getstate(), 10)
702 class D(dict, C):
703 def __init__(self):
704 type({}).__init__(self)
705 C.__init__(self)
706 d = D()
707 self.assertEqual(d.keys(), [])
708 d["hello"] = "world"
709 self.assertEqual(d.items(), [("hello", "world")])
710 self.assertEqual(d["hello"], "world")
711 self.assertEqual(d.getstate(), 0)
712 d.setstate(10)
713 self.assertEqual(d.getstate(), 10)
714 self.assertEqual(D.__mro__, (D, dict, C, object))
715
716 # SF bug #442833
717 class Node(object):
718 def __int__(self):
719 return int(self.foo())
720 def foo(self):
721 return "23"
722 class Frag(Node, list):
723 def foo(self):
724 return "42"
725 self.assertEqual(Node().__int__(), 23)
726 self.assertEqual(int(Node()), 23)
727 self.assertEqual(Frag().__int__(), 42)
728 self.assertEqual(int(Frag()), 42)
729
730 # MI mixing classic and new-style classes.
731
732 class A:
733 x = 1
734
735 class B(A):
736 pass
737
738 class C(A):
739 x = 2
740
741 class D(B, C):
742 pass
743 self.assertEqual(D.x, 1)
744
745 # Classic MRO is preserved for a classic base class.
746 class E(D, object):
747 pass
748 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
749 self.assertEqual(E.x, 1)
750
751 # But with a mix of classic bases, their MROs are combined using
752 # new-style MRO.
753 class F(B, C, object):
754 pass
755 self.assertEqual(F.__mro__, (F, B, C, A, object))
756 self.assertEqual(F.x, 2)
757
758 # Try something else.
759 class C:
760 def cmethod(self):
761 return "C a"
762 def all_method(self):
763 return "C b"
764
765 class M1(C, object):
766 def m1method(self):
767 return "M1 a"
768 def all_method(self):
769 return "M1 b"
770
771 self.assertEqual(M1.__mro__, (M1, C, object))
772 m = M1()
773 self.assertEqual(m.cmethod(), "C a")
774 self.assertEqual(m.m1method(), "M1 a")
775 self.assertEqual(m.all_method(), "M1 b")
776
777 class D(C):
778 def dmethod(self):
779 return "D a"
780 def all_method(self):
781 return "D b"
782
783 class M2(D, object):
784 def m2method(self):
785 return "M2 a"
786 def all_method(self):
787 return "M2 b"
788
789 self.assertEqual(M2.__mro__, (M2, D, C, object))
790 m = M2()
791 self.assertEqual(m.cmethod(), "C a")
792 self.assertEqual(m.dmethod(), "D a")
793 self.assertEqual(m.m2method(), "M2 a")
794 self.assertEqual(m.all_method(), "M2 b")
795
796 class M3(M1, M2, object):
797 def m3method(self):
798 return "M3 a"
799 def all_method(self):
800 return "M3 b"
801 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
802 m = M3()
803 self.assertEqual(m.cmethod(), "C a")
804 self.assertEqual(m.dmethod(), "D a")
805 self.assertEqual(m.m1method(), "M1 a")
806 self.assertEqual(m.m2method(), "M2 a")
807 self.assertEqual(m.m3method(), "M3 a")
808 self.assertEqual(m.all_method(), "M3 b")
809
810 class Classic:
811 pass
812 try:
813 class New(Classic):
814 __metaclass__ = type
815 except TypeError:
816 pass
817 else:
818 self.fail("new class with only classic bases - shouldn't be")
819
820 def test_diamond_inheritence(self):
821 # Testing multiple inheritance special cases...
822 class A(object):
823 def spam(self): return "A"
824 self.assertEqual(A().spam(), "A")
825 class B(A):
826 def boo(self): return "B"
827 def spam(self): return "B"
828 self.assertEqual(B().spam(), "B")
829 self.assertEqual(B().boo(), "B")
830 class C(A):
831 def boo(self): return "C"
832 self.assertEqual(C().spam(), "A")
833 self.assertEqual(C().boo(), "C")
834 class D(B, C): pass
835 self.assertEqual(D().spam(), "B")
836 self.assertEqual(D().boo(), "B")
837 self.assertEqual(D.__mro__, (D, B, C, A, object))
838 class E(C, B): pass
839 self.assertEqual(E().spam(), "B")
840 self.assertEqual(E().boo(), "C")
841 self.assertEqual(E.__mro__, (E, C, B, A, object))
842 # MRO order disagreement
843 try:
844 class F(D, E): pass
845 except TypeError:
846 pass
847 else:
848 self.fail("expected MRO order disagreement (F)")
849 try:
850 class G(E, D): pass
851 except TypeError:
852 pass
853 else:
854 self.fail("expected MRO order disagreement (G)")
855
856 # see thread python-dev/2002-October/029035.html
857 def test_ex5_from_c3_switch(self):
858 # Testing ex5 from C3 switch discussion...
859 class A(object): pass
860 class B(object): pass
861 class C(object): pass
862 class X(A): pass
863 class Y(A): pass
864 class Z(X,B,Y,C): pass
865 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
866
867 # see "A Monotonic Superclass Linearization for Dylan",
868 # by Kim Barrett et al. (OOPSLA 1996)
869 def test_monotonicity(self):
870 # Testing MRO monotonicity...
871 class Boat(object): pass
872 class DayBoat(Boat): pass
873 class WheelBoat(Boat): pass
874 class EngineLess(DayBoat): pass
875 class SmallMultihull(DayBoat): pass
876 class PedalWheelBoat(EngineLess,WheelBoat): pass
877 class SmallCatamaran(SmallMultihull): pass
878 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
879
880 self.assertEqual(PedalWheelBoat.__mro__,
881 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
882 self.assertEqual(SmallCatamaran.__mro__,
883 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
884 self.assertEqual(Pedalo.__mro__,
885 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
886 SmallMultihull, DayBoat, WheelBoat, Boat, object))
887
888 # see "A Monotonic Superclass Linearization for Dylan",
889 # by Kim Barrett et al. (OOPSLA 1996)
890 def test_consistency_with_epg(self):
891 # Testing consistentcy with EPG...
892 class Pane(object): pass
893 class ScrollingMixin(object): pass
894 class EditingMixin(object): pass
895 class ScrollablePane(Pane,ScrollingMixin): pass
896 class EditablePane(Pane,EditingMixin): pass
897 class EditableScrollablePane(ScrollablePane,EditablePane): pass
898
899 self.assertEqual(EditableScrollablePane.__mro__,
900 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
901 ScrollingMixin, EditingMixin, object))
902
903 def test_mro_disagreement(self):
904 # Testing error messages for MRO disagreement...
905 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000906order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000907
Georg Brandl48545522008-02-02 10:12:36 +0000908 def raises(exc, expected, callable, *args):
909 try:
910 callable(*args)
911 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000912 # the exact msg is generally considered an impl detail
913 if test_support.check_impl_detail():
914 if not str(msg).startswith(expected):
915 self.fail("Message %r, expected %r" %
916 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000917 else:
918 self.fail("Expected %s" % exc)
919
920 class A(object): pass
921 class B(A): pass
922 class C(object): pass
923
924 # Test some very simple errors
925 raises(TypeError, "duplicate base class A",
926 type, "X", (A, A), {})
927 raises(TypeError, mro_err_msg,
928 type, "X", (A, B), {})
929 raises(TypeError, mro_err_msg,
930 type, "X", (A, C, B), {})
931 # Test a slightly more complex error
932 class GridLayout(object): pass
933 class HorizontalGrid(GridLayout): pass
934 class VerticalGrid(GridLayout): pass
935 class HVGrid(HorizontalGrid, VerticalGrid): pass
936 class VHGrid(VerticalGrid, HorizontalGrid): pass
937 raises(TypeError, mro_err_msg,
938 type, "ConfusedGrid", (HVGrid, VHGrid), {})
939
940 def test_object_class(self):
941 # Testing object class...
942 a = object()
943 self.assertEqual(a.__class__, object)
944 self.assertEqual(type(a), object)
945 b = object()
946 self.assertNotEqual(a, b)
947 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000948 try:
Georg Brandl48545522008-02-02 10:12:36 +0000949 a.foo = 12
950 except (AttributeError, TypeError):
951 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000952 else:
Georg Brandl48545522008-02-02 10:12:36 +0000953 self.fail("object() should not allow setting a foo attribute")
954 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000955
Georg Brandl48545522008-02-02 10:12:36 +0000956 class Cdict(object):
957 pass
958 x = Cdict()
959 self.assertEqual(x.__dict__, {})
960 x.foo = 1
961 self.assertEqual(x.foo, 1)
962 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000963
Georg Brandl48545522008-02-02 10:12:36 +0000964 def test_slots(self):
965 # Testing __slots__...
966 class C0(object):
967 __slots__ = []
968 x = C0()
969 self.assertFalse(hasattr(x, "__dict__"))
970 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000971
Georg Brandl48545522008-02-02 10:12:36 +0000972 class C1(object):
973 __slots__ = ['a']
974 x = C1()
975 self.assertFalse(hasattr(x, "__dict__"))
976 self.assertFalse(hasattr(x, "a"))
977 x.a = 1
978 self.assertEqual(x.a, 1)
979 x.a = None
980 self.assertEqual(x.a, None)
981 del x.a
982 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983
Georg Brandl48545522008-02-02 10:12:36 +0000984 class C3(object):
985 __slots__ = ['a', 'b', 'c']
986 x = C3()
987 self.assertFalse(hasattr(x, "__dict__"))
988 self.assertFalse(hasattr(x, 'a'))
989 self.assertFalse(hasattr(x, 'b'))
990 self.assertFalse(hasattr(x, 'c'))
991 x.a = 1
992 x.b = 2
993 x.c = 3
994 self.assertEqual(x.a, 1)
995 self.assertEqual(x.b, 2)
996 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997
Georg Brandl48545522008-02-02 10:12:36 +0000998 class C4(object):
999 """Validate name mangling"""
1000 __slots__ = ['__a']
1001 def __init__(self, value):
1002 self.__a = value
1003 def get(self):
1004 return self.__a
1005 x = C4(5)
1006 self.assertFalse(hasattr(x, '__dict__'))
1007 self.assertFalse(hasattr(x, '__a'))
1008 self.assertEqual(x.get(), 5)
1009 try:
1010 x.__a = 6
1011 except AttributeError:
1012 pass
1013 else:
1014 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015
Georg Brandl48545522008-02-02 10:12:36 +00001016 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001017 try:
1018 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001019 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001020 except TypeError:
1021 pass
1022 else:
Georg Brandl48545522008-02-02 10:12:36 +00001023 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001024 try:
Georg Brandl48545522008-02-02 10:12:36 +00001025 class C(object):
1026 __slots__ = ["foo bar"]
1027 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001028 pass
Georg Brandl48545522008-02-02 10:12:36 +00001029 else:
1030 self.fail("['foo bar'] slots not caught")
1031 try:
1032 class C(object):
1033 __slots__ = ["foo\0bar"]
1034 except TypeError:
1035 pass
1036 else:
1037 self.fail("['foo\\0bar'] slots not caught")
1038 try:
1039 class C(object):
1040 __slots__ = ["1"]
1041 except TypeError:
1042 pass
1043 else:
1044 self.fail("['1'] slots not caught")
1045 try:
1046 class C(object):
1047 __slots__ = [""]
1048 except TypeError:
1049 pass
1050 else:
1051 self.fail("[''] slots not caught")
1052 class C(object):
1053 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1054 # XXX(nnorwitz): was there supposed to be something tested
1055 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001056
Georg Brandl48545522008-02-02 10:12:36 +00001057 # Test a single string is not expanded as a sequence.
1058 class C(object):
1059 __slots__ = "abc"
1060 c = C()
1061 c.abc = 5
1062 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001063
Georg Brandl48545522008-02-02 10:12:36 +00001064 # Test unicode slot names
1065 try:
1066 unicode
1067 except NameError:
1068 pass
1069 else:
1070 # Test a single unicode string is not expanded as a sequence.
1071 class C(object):
1072 __slots__ = unicode("abc")
1073 c = C()
1074 c.abc = 5
1075 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001076
Georg Brandl48545522008-02-02 10:12:36 +00001077 # _unicode_to_string used to modify slots in certain circumstances
1078 slots = (unicode("foo"), unicode("bar"))
1079 class C(object):
1080 __slots__ = slots
1081 x = C()
1082 x.foo = 5
1083 self.assertEqual(x.foo, 5)
1084 self.assertEqual(type(slots[0]), unicode)
1085 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001086 try:
Georg Brandl48545522008-02-02 10:12:36 +00001087 class C(object):
1088 __slots__ = [unichr(128)]
1089 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001090 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001091 else:
Georg Brandl48545522008-02-02 10:12:36 +00001092 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001093
Georg Brandl48545522008-02-02 10:12:36 +00001094 # Test leaks
1095 class Counted(object):
1096 counter = 0 # counts the number of instances alive
1097 def __init__(self):
1098 Counted.counter += 1
1099 def __del__(self):
1100 Counted.counter -= 1
1101 class C(object):
1102 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001103 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001104 x.a = Counted()
1105 x.b = Counted()
1106 x.c = Counted()
1107 self.assertEqual(Counted.counter, 3)
1108 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001109 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001110 self.assertEqual(Counted.counter, 0)
1111 class D(C):
1112 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001113 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001114 x.a = Counted()
1115 x.z = Counted()
1116 self.assertEqual(Counted.counter, 2)
1117 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001118 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001119 self.assertEqual(Counted.counter, 0)
1120 class E(D):
1121 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001122 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001123 x.a = Counted()
1124 x.z = Counted()
1125 x.e = Counted()
1126 self.assertEqual(Counted.counter, 3)
1127 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001128 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001129 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001130
Georg Brandl48545522008-02-02 10:12:36 +00001131 # Test cyclical leaks [SF bug 519621]
1132 class F(object):
1133 __slots__ = ['a', 'b']
1134 log = []
1135 s = F()
1136 s.a = [Counted(), s]
1137 self.assertEqual(Counted.counter, 1)
1138 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001139 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001140 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001141
Georg Brandl48545522008-02-02 10:12:36 +00001142 # Test lookup leaks [SF bug 572567]
1143 import sys,gc
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001144 if hasattr(gc, 'get_objects'):
1145 class G(object):
1146 def __cmp__(self, other):
1147 return 0
1148 __hash__ = None # Silence Py3k warning
1149 g = G()
1150 orig_objects = len(gc.get_objects())
1151 for i in xrange(10):
1152 g==g
1153 new_objects = len(gc.get_objects())
1154 self.assertEqual(orig_objects, new_objects)
1155
Georg Brandl48545522008-02-02 10:12:36 +00001156 class H(object):
1157 __slots__ = ['a', 'b']
1158 def __init__(self):
1159 self.a = 1
1160 self.b = 2
1161 def __del__(self_):
1162 self.assertEqual(self_.a, 1)
1163 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001164 with test_support.captured_output('stderr') as s:
1165 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001166 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001167 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001168
Georg Brandl48545522008-02-02 10:12:36 +00001169 def test_slots_special(self):
1170 # Testing __dict__ and __weakref__ in __slots__...
1171 class D(object):
1172 __slots__ = ["__dict__"]
1173 a = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001174 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl48545522008-02-02 10:12:36 +00001175 self.assertFalse(hasattr(a, "__weakref__"))
1176 a.foo = 42
1177 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001178
Georg Brandl48545522008-02-02 10:12:36 +00001179 class W(object):
1180 __slots__ = ["__weakref__"]
1181 a = W()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001182 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001183 self.assertFalse(hasattr(a, "__dict__"))
1184 try:
1185 a.foo = 42
1186 except AttributeError:
1187 pass
1188 else:
1189 self.fail("shouldn't be allowed to set a.foo")
1190
1191 class C1(W, D):
1192 __slots__ = []
1193 a = C1()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001194 self.assertTrue(hasattr(a, "__dict__"))
1195 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001196 a.foo = 42
1197 self.assertEqual(a.__dict__, {"foo": 42})
1198
1199 class C2(D, W):
1200 __slots__ = []
1201 a = C2()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001202 self.assertTrue(hasattr(a, "__dict__"))
1203 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001204 a.foo = 42
1205 self.assertEqual(a.__dict__, {"foo": 42})
1206
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001207 def test_slots_descriptor(self):
1208 # Issue2115: slot descriptors did not correctly check
1209 # the type of the given object
1210 import abc
1211 class MyABC:
1212 __metaclass__ = abc.ABCMeta
1213 __slots__ = "a"
1214
1215 class Unrelated(object):
1216 pass
1217 MyABC.register(Unrelated)
1218
1219 u = Unrelated()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001220 self.assertTrue(isinstance(u, MyABC))
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001221
1222 # This used to crash
1223 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1224
Georg Brandl48545522008-02-02 10:12:36 +00001225 def test_dynamics(self):
1226 # Testing class attribute propagation...
1227 class D(object):
1228 pass
1229 class E(D):
1230 pass
1231 class F(D):
1232 pass
1233 D.foo = 1
1234 self.assertEqual(D.foo, 1)
1235 # Test that dynamic attributes are inherited
1236 self.assertEqual(E.foo, 1)
1237 self.assertEqual(F.foo, 1)
1238 # Test dynamic instances
1239 class C(object):
1240 pass
1241 a = C()
1242 self.assertFalse(hasattr(a, "foobar"))
1243 C.foobar = 2
1244 self.assertEqual(a.foobar, 2)
1245 C.method = lambda self: 42
1246 self.assertEqual(a.method(), 42)
1247 C.__repr__ = lambda self: "C()"
1248 self.assertEqual(repr(a), "C()")
1249 C.__int__ = lambda self: 100
1250 self.assertEqual(int(a), 100)
1251 self.assertEqual(a.foobar, 2)
1252 self.assertFalse(hasattr(a, "spam"))
1253 def mygetattr(self, name):
1254 if name == "spam":
1255 return "spam"
1256 raise AttributeError
1257 C.__getattr__ = mygetattr
1258 self.assertEqual(a.spam, "spam")
1259 a.new = 12
1260 self.assertEqual(a.new, 12)
1261 def mysetattr(self, name, value):
1262 if name == "spam":
1263 raise AttributeError
1264 return object.__setattr__(self, name, value)
1265 C.__setattr__ = mysetattr
1266 try:
1267 a.spam = "not spam"
1268 except AttributeError:
1269 pass
1270 else:
1271 self.fail("expected AttributeError")
1272 self.assertEqual(a.spam, "spam")
1273 class D(C):
1274 pass
1275 d = D()
1276 d.foo = 1
1277 self.assertEqual(d.foo, 1)
1278
1279 # Test handling of int*seq and seq*int
1280 class I(int):
1281 pass
1282 self.assertEqual("a"*I(2), "aa")
1283 self.assertEqual(I(2)*"a", "aa")
1284 self.assertEqual(2*I(3), 6)
1285 self.assertEqual(I(3)*2, 6)
1286 self.assertEqual(I(3)*I(2), 6)
1287
1288 # Test handling of long*seq and seq*long
1289 class L(long):
1290 pass
1291 self.assertEqual("a"*L(2L), "aa")
1292 self.assertEqual(L(2L)*"a", "aa")
1293 self.assertEqual(2*L(3), 6)
1294 self.assertEqual(L(3)*2, 6)
1295 self.assertEqual(L(3)*L(2), 6)
1296
1297 # Test comparison of classes with dynamic metaclasses
1298 class dynamicmetaclass(type):
1299 pass
1300 class someclass:
1301 __metaclass__ = dynamicmetaclass
1302 self.assertNotEqual(someclass, object)
1303
1304 def test_errors(self):
1305 # Testing errors...
1306 try:
1307 class C(list, dict):
1308 pass
1309 except TypeError:
1310 pass
1311 else:
1312 self.fail("inheritance from both list and dict should be illegal")
1313
1314 try:
1315 class C(object, None):
1316 pass
1317 except TypeError:
1318 pass
1319 else:
1320 self.fail("inheritance from non-type should be illegal")
1321 class Classic:
1322 pass
1323
1324 try:
1325 class C(type(len)):
1326 pass
1327 except TypeError:
1328 pass
1329 else:
1330 self.fail("inheritance from CFunction should be illegal")
1331
1332 try:
1333 class C(object):
1334 __slots__ = 1
1335 except TypeError:
1336 pass
1337 else:
1338 self.fail("__slots__ = 1 should be illegal")
1339
1340 try:
1341 class C(object):
1342 __slots__ = [1]
1343 except TypeError:
1344 pass
1345 else:
1346 self.fail("__slots__ = [1] should be illegal")
1347
1348 class M1(type):
1349 pass
1350 class M2(type):
1351 pass
1352 class A1(object):
1353 __metaclass__ = M1
1354 class A2(object):
1355 __metaclass__ = M2
1356 try:
1357 class B(A1, A2):
1358 pass
1359 except TypeError:
1360 pass
1361 else:
1362 self.fail("finding the most derived metaclass should have failed")
1363
1364 def test_classmethods(self):
1365 # Testing class methods...
1366 class C(object):
1367 def foo(*a): return a
1368 goo = classmethod(foo)
1369 c = C()
1370 self.assertEqual(C.goo(1), (C, 1))
1371 self.assertEqual(c.goo(1), (C, 1))
1372 self.assertEqual(c.foo(1), (c, 1))
1373 class D(C):
1374 pass
1375 d = D()
1376 self.assertEqual(D.goo(1), (D, 1))
1377 self.assertEqual(d.goo(1), (D, 1))
1378 self.assertEqual(d.foo(1), (d, 1))
1379 self.assertEqual(D.foo(d, 1), (d, 1))
1380 # Test for a specific crash (SF bug 528132)
1381 def f(cls, arg): return (cls, arg)
1382 ff = classmethod(f)
1383 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1384 self.assertEqual(ff.__get__(0)(42), (int, 42))
1385
1386 # Test super() with classmethods (SF bug 535444)
1387 self.assertEqual(C.goo.im_self, C)
1388 self.assertEqual(D.goo.im_self, D)
1389 self.assertEqual(super(D,D).goo.im_self, D)
1390 self.assertEqual(super(D,d).goo.im_self, D)
1391 self.assertEqual(super(D,D).goo(), (D,))
1392 self.assertEqual(super(D,d).goo(), (D,))
1393
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001394 # Verify that a non-callable will raise
1395 meth = classmethod(1).__get__(1)
1396 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001397
1398 # Verify that classmethod() doesn't allow keyword args
1399 try:
1400 classmethod(f, kw=1)
1401 except TypeError:
1402 pass
1403 else:
1404 self.fail("classmethod shouldn't accept keyword args")
1405
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001406 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001407 def test_classmethods_in_c(self):
1408 # Testing C-based class methods...
1409 import xxsubtype as spam
1410 a = (1, 2, 3)
1411 d = {'abc': 123}
1412 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1413 self.assertEqual(x, spam.spamlist)
1414 self.assertEqual(a, a1)
1415 self.assertEqual(d, d1)
1416 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1417 self.assertEqual(x, spam.spamlist)
1418 self.assertEqual(a, a1)
1419 self.assertEqual(d, d1)
1420
1421 def test_staticmethods(self):
1422 # Testing static methods...
1423 class C(object):
1424 def foo(*a): return a
1425 goo = staticmethod(foo)
1426 c = C()
1427 self.assertEqual(C.goo(1), (1,))
1428 self.assertEqual(c.goo(1), (1,))
1429 self.assertEqual(c.foo(1), (c, 1,))
1430 class D(C):
1431 pass
1432 d = D()
1433 self.assertEqual(D.goo(1), (1,))
1434 self.assertEqual(d.goo(1), (1,))
1435 self.assertEqual(d.foo(1), (d, 1))
1436 self.assertEqual(D.foo(d, 1), (d, 1))
1437
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001438 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001439 def test_staticmethods_in_c(self):
1440 # Testing C-based static methods...
1441 import xxsubtype as spam
1442 a = (1, 2, 3)
1443 d = {"abc": 123}
1444 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1445 self.assertEqual(x, None)
1446 self.assertEqual(a, a1)
1447 self.assertEqual(d, d1)
1448 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1449 self.assertEqual(x, None)
1450 self.assertEqual(a, a1)
1451 self.assertEqual(d, d1)
1452
1453 def test_classic(self):
1454 # Testing classic classes...
1455 class C:
1456 def foo(*a): return a
1457 goo = classmethod(foo)
1458 c = C()
1459 self.assertEqual(C.goo(1), (C, 1))
1460 self.assertEqual(c.goo(1), (C, 1))
1461 self.assertEqual(c.foo(1), (c, 1))
1462 class D(C):
1463 pass
1464 d = D()
1465 self.assertEqual(D.goo(1), (D, 1))
1466 self.assertEqual(d.goo(1), (D, 1))
1467 self.assertEqual(d.foo(1), (d, 1))
1468 self.assertEqual(D.foo(d, 1), (d, 1))
1469 class E: # *not* subclassing from C
1470 foo = C.foo
1471 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001472 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001473
1474 def test_compattr(self):
1475 # Testing computed attributes...
1476 class C(object):
1477 class computed_attribute(object):
1478 def __init__(self, get, set=None, delete=None):
1479 self.__get = get
1480 self.__set = set
1481 self.__delete = delete
1482 def __get__(self, obj, type=None):
1483 return self.__get(obj)
1484 def __set__(self, obj, value):
1485 return self.__set(obj, value)
1486 def __delete__(self, obj):
1487 return self.__delete(obj)
1488 def __init__(self):
1489 self.__x = 0
1490 def __get_x(self):
1491 x = self.__x
1492 self.__x = x+1
1493 return x
1494 def __set_x(self, x):
1495 self.__x = x
1496 def __delete_x(self):
1497 del self.__x
1498 x = computed_attribute(__get_x, __set_x, __delete_x)
1499 a = C()
1500 self.assertEqual(a.x, 0)
1501 self.assertEqual(a.x, 1)
1502 a.x = 10
1503 self.assertEqual(a.x, 10)
1504 self.assertEqual(a.x, 11)
1505 del a.x
1506 self.assertEqual(hasattr(a, 'x'), 0)
1507
1508 def test_newslots(self):
1509 # Testing __new__ slot override...
1510 class C(list):
1511 def __new__(cls):
1512 self = list.__new__(cls)
1513 self.foo = 1
1514 return self
1515 def __init__(self):
1516 self.foo = self.foo + 2
1517 a = C()
1518 self.assertEqual(a.foo, 3)
1519 self.assertEqual(a.__class__, C)
1520 class D(C):
1521 pass
1522 b = D()
1523 self.assertEqual(b.foo, 3)
1524 self.assertEqual(b.__class__, D)
1525
1526 def test_altmro(self):
1527 # Testing mro() and overriding it...
1528 class A(object):
1529 def f(self): return "A"
1530 class B(A):
1531 pass
1532 class C(A):
1533 def f(self): return "C"
1534 class D(B, C):
1535 pass
1536 self.assertEqual(D.mro(), [D, B, C, A, object])
1537 self.assertEqual(D.__mro__, (D, B, C, A, object))
1538 self.assertEqual(D().f(), "C")
1539
1540 class PerverseMetaType(type):
1541 def mro(cls):
1542 L = type.mro(cls)
1543 L.reverse()
1544 return L
1545 class X(D,B,C,A):
1546 __metaclass__ = PerverseMetaType
1547 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1548 self.assertEqual(X().f(), "A")
1549
1550 try:
1551 class X(object):
1552 class __metaclass__(type):
1553 def mro(self):
1554 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001555 # In CPython, the class creation above already raises
1556 # TypeError, as a protection against the fact that
1557 # instances of X would segfault it. In other Python
1558 # implementations it would be ok to let the class X
1559 # be created, but instead get a clean TypeError on the
1560 # __setitem__ below.
1561 x = object.__new__(X)
1562 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001563 except TypeError:
1564 pass
1565 else:
1566 self.fail("devious mro() return not caught")
1567
1568 try:
1569 class X(object):
1570 class __metaclass__(type):
1571 def mro(self):
1572 return [1]
1573 except TypeError:
1574 pass
1575 else:
1576 self.fail("non-class mro() return not caught")
1577
1578 try:
1579 class X(object):
1580 class __metaclass__(type):
1581 def mro(self):
1582 return 1
1583 except TypeError:
1584 pass
1585 else:
1586 self.fail("non-sequence mro() return not caught")
1587
1588 def test_overloading(self):
1589 # Testing operator overloading...
1590
1591 class B(object):
1592 "Intermediate class because object doesn't have a __setattr__"
1593
1594 class C(B):
1595 def __getattr__(self, name):
1596 if name == "foo":
1597 return ("getattr", name)
1598 else:
1599 raise AttributeError
1600 def __setattr__(self, name, value):
1601 if name == "foo":
1602 self.setattr = (name, value)
1603 else:
1604 return B.__setattr__(self, name, value)
1605 def __delattr__(self, name):
1606 if name == "foo":
1607 self.delattr = name
1608 else:
1609 return B.__delattr__(self, name)
1610
1611 def __getitem__(self, key):
1612 return ("getitem", key)
1613 def __setitem__(self, key, value):
1614 self.setitem = (key, value)
1615 def __delitem__(self, key):
1616 self.delitem = key
1617
1618 def __getslice__(self, i, j):
1619 return ("getslice", i, j)
1620 def __setslice__(self, i, j, value):
1621 self.setslice = (i, j, value)
1622 def __delslice__(self, i, j):
1623 self.delslice = (i, j)
1624
1625 a = C()
1626 self.assertEqual(a.foo, ("getattr", "foo"))
1627 a.foo = 12
1628 self.assertEqual(a.setattr, ("foo", 12))
1629 del a.foo
1630 self.assertEqual(a.delattr, "foo")
1631
1632 self.assertEqual(a[12], ("getitem", 12))
1633 a[12] = 21
1634 self.assertEqual(a.setitem, (12, 21))
1635 del a[12]
1636 self.assertEqual(a.delitem, 12)
1637
1638 self.assertEqual(a[0:10], ("getslice", 0, 10))
1639 a[0:10] = "foo"
1640 self.assertEqual(a.setslice, (0, 10, "foo"))
1641 del a[0:10]
1642 self.assertEqual(a.delslice, (0, 10))
1643
1644 def test_methods(self):
1645 # Testing methods...
1646 class C(object):
1647 def __init__(self, x):
1648 self.x = x
1649 def foo(self):
1650 return self.x
1651 c1 = C(1)
1652 self.assertEqual(c1.foo(), 1)
1653 class D(C):
1654 boo = C.foo
1655 goo = c1.foo
1656 d2 = D(2)
1657 self.assertEqual(d2.foo(), 2)
1658 self.assertEqual(d2.boo(), 2)
1659 self.assertEqual(d2.goo(), 1)
1660 class E(object):
1661 foo = C.foo
1662 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001663 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001664
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001665 def test_special_method_lookup(self):
1666 # The lookup of special methods bypasses __getattr__ and
1667 # __getattribute__, but they still can be descriptors.
1668
1669 def run_context(manager):
1670 with manager:
1671 pass
1672 def iden(self):
1673 return self
1674 def hello(self):
1675 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001676 def empty_seq(self):
1677 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001678 def zero(self):
1679 return 0
1680 def stop(self):
1681 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001682 def return_true(self, thing=None):
1683 return True
1684 def do_isinstance(obj):
1685 return isinstance(int, obj)
1686 def do_issubclass(obj):
1687 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001688 def swallow(*args):
1689 pass
1690 def do_dict_missing(checker):
1691 class DictSub(checker.__class__, dict):
1692 pass
1693 self.assertEqual(DictSub()["hi"], 4)
1694 def some_number(self_, key):
1695 self.assertEqual(key, "hi")
1696 return 4
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001697
1698 # It would be nice to have every special method tested here, but I'm
1699 # only listing the ones I can remember outside of typeobject.c, since it
1700 # does it right.
1701 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001702 ("__unicode__", unicode, hello, set(), {}),
1703 ("__reversed__", reversed, empty_seq, set(), {}),
1704 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001705 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001706 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1707 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001708 ("__missing__", do_dict_missing, some_number,
1709 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001710 ("__subclasscheck__", do_issubclass, return_true,
1711 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001712 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1713 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001714 ]
1715
1716 class Checker(object):
1717 def __getattr__(self, attr, test=self):
1718 test.fail("__getattr__ called with {0}".format(attr))
1719 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001720 if attr not in ok:
1721 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001722 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001723 class SpecialDescr(object):
1724 def __init__(self, impl):
1725 self.impl = impl
1726 def __get__(self, obj, owner):
1727 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001728 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001729 class MyException(Exception):
1730 pass
1731 class ErrDescr(object):
1732 def __get__(self, obj, owner):
1733 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001734
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001735 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001736 class X(Checker):
1737 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001738 for attr, obj in env.iteritems():
1739 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001740 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001741 runner(X())
1742
1743 record = []
1744 class X(Checker):
1745 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001746 for attr, obj in env.iteritems():
1747 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001748 setattr(X, name, SpecialDescr(meth_impl))
1749 runner(X())
1750 self.assertEqual(record, [1], name)
1751
Benjamin Peterson87e50062009-05-25 02:40:21 +00001752 class X(Checker):
1753 pass
1754 for attr, obj in env.iteritems():
1755 setattr(X, attr, obj)
1756 setattr(X, name, ErrDescr())
1757 try:
1758 runner(X())
1759 except MyException:
1760 pass
1761 else:
1762 self.fail("{0!r} didn't raise".format(name))
1763
Georg Brandl48545522008-02-02 10:12:36 +00001764 def test_specials(self):
1765 # Testing special operators...
1766 # Test operators like __hash__ for which a built-in default exists
1767
1768 # Test the default behavior for static classes
1769 class C(object):
1770 def __getitem__(self, i):
1771 if 0 <= i < 10: return i
1772 raise IndexError
1773 c1 = C()
1774 c2 = C()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001775 self.assertTrue(not not c1) # What?
Georg Brandl48545522008-02-02 10:12:36 +00001776 self.assertNotEqual(id(c1), id(c2))
1777 hash(c1)
1778 hash(c2)
1779 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1780 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001781 self.assertTrue(c1 != c2)
1782 self.assertTrue(not c1 != c1)
1783 self.assertTrue(not c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001784 # Note that the module name appears in str/repr, and that varies
1785 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001786 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001787 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001788 self.assertTrue(-1 not in c1)
Georg Brandl48545522008-02-02 10:12:36 +00001789 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001790 self.assertTrue(i in c1)
Georg Brandl48545522008-02-02 10:12:36 +00001791 self.assertFalse(10 in c1)
1792 # Test the default behavior for dynamic classes
1793 class D(object):
1794 def __getitem__(self, i):
1795 if 0 <= i < 10: return i
1796 raise IndexError
1797 d1 = D()
1798 d2 = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001799 self.assertTrue(not not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001800 self.assertNotEqual(id(d1), id(d2))
1801 hash(d1)
1802 hash(d2)
1803 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1804 self.assertEqual(d1, d1)
1805 self.assertNotEqual(d1, d2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001806 self.assertTrue(not d1 != d1)
1807 self.assertTrue(not d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001808 # Note that the module name appears in str/repr, and that varies
1809 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001810 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001811 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001812 self.assertTrue(-1 not in d1)
Georg Brandl48545522008-02-02 10:12:36 +00001813 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001814 self.assertTrue(i in d1)
Georg Brandl48545522008-02-02 10:12:36 +00001815 self.assertFalse(10 in d1)
1816 # Test overridden behavior for static classes
1817 class Proxy(object):
1818 def __init__(self, x):
1819 self.x = x
1820 def __nonzero__(self):
1821 return not not self.x
1822 def __hash__(self):
1823 return hash(self.x)
1824 def __eq__(self, other):
1825 return self.x == other
1826 def __ne__(self, other):
1827 return self.x != other
1828 def __cmp__(self, other):
1829 return cmp(self.x, other.x)
1830 def __str__(self):
1831 return "Proxy:%s" % self.x
1832 def __repr__(self):
1833 return "Proxy(%r)" % self.x
1834 def __contains__(self, value):
1835 return value in self.x
1836 p0 = Proxy(0)
1837 p1 = Proxy(1)
1838 p_1 = Proxy(-1)
1839 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001840 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001841 self.assertEqual(hash(p0), hash(0))
1842 self.assertEqual(p0, p0)
1843 self.assertNotEqual(p0, p1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001844 self.assertTrue(not p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001845 self.assertEqual(not p0, p1)
1846 self.assertEqual(cmp(p0, p1), -1)
1847 self.assertEqual(cmp(p0, p0), 0)
1848 self.assertEqual(cmp(p0, p_1), 1)
1849 self.assertEqual(str(p0), "Proxy:0")
1850 self.assertEqual(repr(p0), "Proxy(0)")
1851 p10 = Proxy(range(10))
1852 self.assertFalse(-1 in p10)
1853 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001854 self.assertTrue(i in p10)
Georg Brandl48545522008-02-02 10:12:36 +00001855 self.assertFalse(10 in p10)
1856 # Test overridden behavior for dynamic classes
1857 class DProxy(object):
1858 def __init__(self, x):
1859 self.x = x
1860 def __nonzero__(self):
1861 return not not self.x
1862 def __hash__(self):
1863 return hash(self.x)
1864 def __eq__(self, other):
1865 return self.x == other
1866 def __ne__(self, other):
1867 return self.x != other
1868 def __cmp__(self, other):
1869 return cmp(self.x, other.x)
1870 def __str__(self):
1871 return "DProxy:%s" % self.x
1872 def __repr__(self):
1873 return "DProxy(%r)" % self.x
1874 def __contains__(self, value):
1875 return value in self.x
1876 p0 = DProxy(0)
1877 p1 = DProxy(1)
1878 p_1 = DProxy(-1)
1879 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001880 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001881 self.assertEqual(hash(p0), hash(0))
1882 self.assertEqual(p0, p0)
1883 self.assertNotEqual(p0, p1)
1884 self.assertNotEqual(not p0, p0)
1885 self.assertEqual(not p0, p1)
1886 self.assertEqual(cmp(p0, p1), -1)
1887 self.assertEqual(cmp(p0, p0), 0)
1888 self.assertEqual(cmp(p0, p_1), 1)
1889 self.assertEqual(str(p0), "DProxy:0")
1890 self.assertEqual(repr(p0), "DProxy(0)")
1891 p10 = DProxy(range(10))
1892 self.assertFalse(-1 in p10)
1893 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001894 self.assertTrue(i in p10)
Georg Brandl48545522008-02-02 10:12:36 +00001895 self.assertFalse(10 in p10)
1896
1897 # Safety test for __cmp__
1898 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001899 if not hasattr(a, '__cmp__'):
1900 return # some types don't have a __cmp__ any more (so the
1901 # test doesn't make sense any more), or maybe they
1902 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001903 try:
1904 a.__class__.__cmp__(a, b)
1905 except TypeError:
1906 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001907 else:
Georg Brandl48545522008-02-02 10:12:36 +00001908 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1909 a.__class__, a, b))
1910
1911 unsafecmp(u"123", "123")
1912 unsafecmp("123", u"123")
1913 unsafecmp(1, 1.0)
1914 unsafecmp(1.0, 1)
1915 unsafecmp(1, 1L)
1916 unsafecmp(1L, 1)
1917
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001918 @test_support.impl_detail("custom logic for printing to real file objects")
1919 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001920 # Testing recursion checks ...
1921 class Letter(str):
1922 def __new__(cls, letter):
1923 if letter == 'EPS':
1924 return str.__new__(cls)
1925 return str.__new__(cls, letter)
1926 def __str__(self):
1927 if not self:
1928 return 'EPS'
1929 return self
1930 # sys.stdout needs to be the original to trigger the recursion bug
1931 import sys
1932 test_stdout = sys.stdout
1933 sys.stdout = test_support.get_original_stdout()
1934 try:
1935 # nothing should actually be printed, this should raise an exception
1936 print Letter('w')
1937 except RuntimeError:
1938 pass
1939 else:
1940 self.fail("expected a RuntimeError for print recursion")
1941 finally:
1942 sys.stdout = test_stdout
1943
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001944 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001945 # Bug #1202533.
1946 class A(object):
1947 pass
1948 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1949 try:
1950 A()*2
1951 except RuntimeError:
1952 pass
1953 else:
1954 self.fail("expected a RuntimeError")
1955
1956 def test_weakrefs(self):
1957 # Testing weak references...
1958 import weakref
1959 class C(object):
1960 pass
1961 c = C()
1962 r = weakref.ref(c)
1963 self.assertEqual(r(), c)
1964 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001965 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001966 self.assertEqual(r(), None)
1967 del r
1968 class NoWeak(object):
1969 __slots__ = ['foo']
1970 no = NoWeak()
1971 try:
1972 weakref.ref(no)
1973 except TypeError, msg:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001974 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001975 else:
1976 self.fail("weakref.ref(no) should be illegal")
1977 class Weak(object):
1978 __slots__ = ['foo', '__weakref__']
1979 yes = Weak()
1980 r = weakref.ref(yes)
1981 self.assertEqual(r(), yes)
1982 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001983 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001984 self.assertEqual(r(), None)
1985 del r
1986
1987 def test_properties(self):
1988 # Testing property...
1989 class C(object):
1990 def getx(self):
1991 return self.__x
1992 def setx(self, value):
1993 self.__x = value
1994 def delx(self):
1995 del self.__x
1996 x = property(getx, setx, delx, doc="I'm the x property.")
1997 a = C()
1998 self.assertFalse(hasattr(a, "x"))
1999 a.x = 42
2000 self.assertEqual(a._C__x, 42)
2001 self.assertEqual(a.x, 42)
2002 del a.x
2003 self.assertFalse(hasattr(a, "x"))
2004 self.assertFalse(hasattr(a, "_C__x"))
2005 C.x.__set__(a, 100)
2006 self.assertEqual(C.x.__get__(a), 100)
2007 C.x.__delete__(a)
2008 self.assertFalse(hasattr(a, "x"))
2009
2010 raw = C.__dict__['x']
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002011 self.assertTrue(isinstance(raw, property))
Georg Brandl48545522008-02-02 10:12:36 +00002012
2013 attrs = dir(raw)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002014 self.assertTrue("__doc__" in attrs)
2015 self.assertTrue("fget" in attrs)
2016 self.assertTrue("fset" in attrs)
2017 self.assertTrue("fdel" in attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002018
2019 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002020 self.assertTrue(raw.fget is C.__dict__['getx'])
2021 self.assertTrue(raw.fset is C.__dict__['setx'])
2022 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002023
2024 for attr in "__doc__", "fget", "fset", "fdel":
2025 try:
2026 setattr(raw, attr, 42)
2027 except TypeError, msg:
2028 if str(msg).find('readonly') < 0:
2029 self.fail("when setting readonly attr %r on a property, "
2030 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002031 else:
Georg Brandl48545522008-02-02 10:12:36 +00002032 self.fail("expected TypeError from trying to set readonly %r "
2033 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002034
Georg Brandl48545522008-02-02 10:12:36 +00002035 class D(object):
2036 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002037
Georg Brandl48545522008-02-02 10:12:36 +00002038 d = D()
2039 try:
2040 for i in d:
2041 str(i)
2042 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002043 pass
Georg Brandl48545522008-02-02 10:12:36 +00002044 else:
2045 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002046
Georg Brandl48545522008-02-02 10:12:36 +00002047 class E(object):
2048 def getter(self):
2049 "getter method"
2050 return 0
2051 def setter(self_, value):
2052 "setter method"
2053 pass
2054 prop = property(getter)
2055 self.assertEqual(prop.__doc__, "getter method")
2056 prop2 = property(fset=setter)
2057 self.assertEqual(prop2.__doc__, None)
2058
2059 # this segfaulted in 2.5b2
2060 try:
2061 import _testcapi
2062 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002063 pass
Georg Brandl48545522008-02-02 10:12:36 +00002064 else:
2065 class X(object):
2066 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002067
Georg Brandl48545522008-02-02 10:12:36 +00002068 def test_properties_plus(self):
2069 class C(object):
2070 foo = property(doc="hello")
2071 @foo.getter
2072 def foo(self):
2073 return self._foo
2074 @foo.setter
2075 def foo(self, value):
2076 self._foo = abs(value)
2077 @foo.deleter
2078 def foo(self):
2079 del self._foo
2080 c = C()
2081 self.assertEqual(C.foo.__doc__, "hello")
2082 self.assertFalse(hasattr(c, "foo"))
2083 c.foo = -42
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002084 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl48545522008-02-02 10:12:36 +00002085 self.assertEqual(c._foo, 42)
2086 self.assertEqual(c.foo, 42)
2087 del c.foo
2088 self.assertFalse(hasattr(c, '_foo'))
2089 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002090
Georg Brandl48545522008-02-02 10:12:36 +00002091 class D(C):
2092 @C.foo.deleter
2093 def foo(self):
2094 try:
2095 del self._foo
2096 except AttributeError:
2097 pass
2098 d = D()
2099 d.foo = 24
2100 self.assertEqual(d.foo, 24)
2101 del d.foo
2102 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002103
Georg Brandl48545522008-02-02 10:12:36 +00002104 class E(object):
2105 @property
2106 def foo(self):
2107 return self._foo
2108 @foo.setter
2109 def foo(self, value):
2110 raise RuntimeError
2111 @foo.setter
2112 def foo(self, value):
2113 self._foo = abs(value)
2114 @foo.deleter
2115 def foo(self, value=None):
2116 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002117
Georg Brandl48545522008-02-02 10:12:36 +00002118 e = E()
2119 e.foo = -42
2120 self.assertEqual(e.foo, 42)
2121 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002122
Georg Brandl48545522008-02-02 10:12:36 +00002123 class F(E):
2124 @E.foo.deleter
2125 def foo(self):
2126 del self._foo
2127 @foo.setter
2128 def foo(self, value):
2129 self._foo = max(0, value)
2130 f = F()
2131 f.foo = -10
2132 self.assertEqual(f.foo, 0)
2133 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002134
Georg Brandl48545522008-02-02 10:12:36 +00002135 def test_dict_constructors(self):
2136 # Testing dict constructor ...
2137 d = dict()
2138 self.assertEqual(d, {})
2139 d = dict({})
2140 self.assertEqual(d, {})
2141 d = dict({1: 2, 'a': 'b'})
2142 self.assertEqual(d, {1: 2, 'a': 'b'})
2143 self.assertEqual(d, dict(d.items()))
2144 self.assertEqual(d, dict(d.iteritems()))
2145 d = dict({'one':1, 'two':2})
2146 self.assertEqual(d, dict(one=1, two=2))
2147 self.assertEqual(d, dict(**d))
2148 self.assertEqual(d, dict({"one": 1}, two=2))
2149 self.assertEqual(d, dict([("two", 2)], one=1))
2150 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2151 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002152
Georg Brandl48545522008-02-02 10:12:36 +00002153 for badarg in 0, 0L, 0j, "0", [0], (0,):
2154 try:
2155 dict(badarg)
2156 except TypeError:
2157 pass
2158 except ValueError:
2159 if badarg == "0":
2160 # It's a sequence, and its elements are also sequences (gotta
2161 # love strings <wink>), but they aren't of length 2, so this
2162 # one seemed better as a ValueError than a TypeError.
2163 pass
2164 else:
2165 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002166 else:
Georg Brandl48545522008-02-02 10:12:36 +00002167 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002168
Georg Brandl48545522008-02-02 10:12:36 +00002169 try:
2170 dict({}, {})
2171 except TypeError:
2172 pass
2173 else:
2174 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002175
Georg Brandl48545522008-02-02 10:12:36 +00002176 class Mapping:
2177 # Lacks a .keys() method; will be added later.
2178 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002179
Georg Brandl48545522008-02-02 10:12:36 +00002180 try:
2181 dict(Mapping())
2182 except TypeError:
2183 pass
2184 else:
2185 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002186
Georg Brandl48545522008-02-02 10:12:36 +00002187 Mapping.keys = lambda self: self.dict.keys()
2188 Mapping.__getitem__ = lambda self, i: self.dict[i]
2189 d = dict(Mapping())
2190 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002191
Georg Brandl48545522008-02-02 10:12:36 +00002192 # Init from sequence of iterable objects, each producing a 2-sequence.
2193 class AddressBookEntry:
2194 def __init__(self, first, last):
2195 self.first = first
2196 self.last = last
2197 def __iter__(self):
2198 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002199
Georg Brandl48545522008-02-02 10:12:36 +00002200 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2201 AddressBookEntry('Barry', 'Peters'),
2202 AddressBookEntry('Tim', 'Peters'),
2203 AddressBookEntry('Barry', 'Warsaw')])
2204 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002205
Georg Brandl48545522008-02-02 10:12:36 +00002206 d = dict(zip(range(4), range(1, 5)))
2207 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002208
Georg Brandl48545522008-02-02 10:12:36 +00002209 # Bad sequence lengths.
2210 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2211 try:
2212 dict(bad)
2213 except ValueError:
2214 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002215 else:
Georg Brandl48545522008-02-02 10:12:36 +00002216 self.fail("no ValueError from dict(%r)" % bad)
2217
2218 def test_dir(self):
2219 # Testing dir() ...
2220 junk = 12
2221 self.assertEqual(dir(), ['junk', 'self'])
2222 del junk
2223
2224 # Just make sure these don't blow up!
2225 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2226 dir(arg)
2227
2228 # Try classic classes.
2229 class C:
2230 Cdata = 1
2231 def Cmethod(self): pass
2232
2233 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2234 self.assertEqual(dir(C), cstuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002235 self.assertTrue('im_self' in dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002236
2237 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2238 self.assertEqual(dir(c), cstuff)
2239
2240 c.cdata = 2
2241 c.cmethod = lambda self: 0
2242 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002243 self.assertTrue('im_self' in dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002244
2245 class A(C):
2246 Adata = 1
2247 def Amethod(self): pass
2248
2249 astuff = ['Adata', 'Amethod'] + cstuff
2250 self.assertEqual(dir(A), astuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002251 self.assertTrue('im_self' in dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002252 a = A()
2253 self.assertEqual(dir(a), astuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002254 self.assertTrue('im_self' in dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002255 a.adata = 42
2256 a.amethod = lambda self: 3
2257 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2258
2259 # The same, but with new-style classes. Since these have object as a
2260 # base class, a lot more gets sucked in.
2261 def interesting(strings):
2262 return [s for s in strings if not s.startswith('_')]
2263
2264 class C(object):
2265 Cdata = 1
2266 def Cmethod(self): pass
2267
2268 cstuff = ['Cdata', 'Cmethod']
2269 self.assertEqual(interesting(dir(C)), cstuff)
2270
2271 c = C()
2272 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002273 self.assertTrue('im_self' in dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002274
2275 c.cdata = 2
2276 c.cmethod = lambda self: 0
2277 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002278 self.assertTrue('im_self' in dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002279
2280 class A(C):
2281 Adata = 1
2282 def Amethod(self): pass
2283
2284 astuff = ['Adata', 'Amethod'] + cstuff
2285 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002286 self.assertTrue('im_self' in dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002287 a = A()
2288 self.assertEqual(interesting(dir(a)), astuff)
2289 a.adata = 42
2290 a.amethod = lambda self: 3
2291 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002292 self.assertTrue('im_self' in dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002293
2294 # Try a module subclass.
2295 import sys
2296 class M(type(sys)):
2297 pass
2298 minstance = M("m")
2299 minstance.b = 2
2300 minstance.a = 1
2301 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2302 self.assertEqual(names, ['a', 'b'])
2303
2304 class M2(M):
2305 def getdict(self):
2306 return "Not a dict!"
2307 __dict__ = property(getdict)
2308
2309 m2instance = M2("m2")
2310 m2instance.b = 2
2311 m2instance.a = 1
2312 self.assertEqual(m2instance.__dict__, "Not a dict!")
2313 try:
2314 dir(m2instance)
2315 except TypeError:
2316 pass
2317
2318 # Two essentially featureless objects, just inheriting stuff from
2319 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002320 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2321 if test_support.check_impl_detail():
2322 # None differs in PyPy: it has a __nonzero__
2323 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002324
2325 # Nasty test case for proxied objects
2326 class Wrapper(object):
2327 def __init__(self, obj):
2328 self.__obj = obj
2329 def __repr__(self):
2330 return "Wrapper(%s)" % repr(self.__obj)
2331 def __getitem__(self, key):
2332 return Wrapper(self.__obj[key])
2333 def __len__(self):
2334 return len(self.__obj)
2335 def __getattr__(self, name):
2336 return Wrapper(getattr(self.__obj, name))
2337
2338 class C(object):
2339 def __getclass(self):
2340 return Wrapper(type(self))
2341 __class__ = property(__getclass)
2342
2343 dir(C()) # This used to segfault
2344
2345 def test_supers(self):
2346 # Testing super...
2347
2348 class A(object):
2349 def meth(self, a):
2350 return "A(%r)" % a
2351
2352 self.assertEqual(A().meth(1), "A(1)")
2353
2354 class B(A):
2355 def __init__(self):
2356 self.__super = super(B, self)
2357 def meth(self, a):
2358 return "B(%r)" % a + self.__super.meth(a)
2359
2360 self.assertEqual(B().meth(2), "B(2)A(2)")
2361
2362 class C(A):
2363 def meth(self, a):
2364 return "C(%r)" % a + self.__super.meth(a)
2365 C._C__super = super(C)
2366
2367 self.assertEqual(C().meth(3), "C(3)A(3)")
2368
2369 class D(C, B):
2370 def meth(self, a):
2371 return "D(%r)" % a + super(D, self).meth(a)
2372
2373 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2374
2375 # Test for subclassing super
2376
2377 class mysuper(super):
2378 def __init__(self, *args):
2379 return super(mysuper, self).__init__(*args)
2380
2381 class E(D):
2382 def meth(self, a):
2383 return "E(%r)" % a + mysuper(E, self).meth(a)
2384
2385 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2386
2387 class F(E):
2388 def meth(self, a):
2389 s = self.__super # == mysuper(F, self)
2390 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2391 F._F__super = mysuper(F)
2392
2393 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2394
2395 # Make sure certain errors are raised
2396
2397 try:
2398 super(D, 42)
2399 except TypeError:
2400 pass
2401 else:
2402 self.fail("shouldn't allow super(D, 42)")
2403
2404 try:
2405 super(D, C())
2406 except TypeError:
2407 pass
2408 else:
2409 self.fail("shouldn't allow super(D, C())")
2410
2411 try:
2412 super(D).__get__(12)
2413 except TypeError:
2414 pass
2415 else:
2416 self.fail("shouldn't allow super(D).__get__(12)")
2417
2418 try:
2419 super(D).__get__(C())
2420 except TypeError:
2421 pass
2422 else:
2423 self.fail("shouldn't allow super(D).__get__(C())")
2424
2425 # Make sure data descriptors can be overridden and accessed via super
2426 # (new feature in Python 2.3)
2427
2428 class DDbase(object):
2429 def getx(self): return 42
2430 x = property(getx)
2431
2432 class DDsub(DDbase):
2433 def getx(self): return "hello"
2434 x = property(getx)
2435
2436 dd = DDsub()
2437 self.assertEqual(dd.x, "hello")
2438 self.assertEqual(super(DDsub, dd).x, 42)
2439
2440 # Ensure that super() lookup of descriptor from classmethod
2441 # works (SF ID# 743627)
2442
2443 class Base(object):
2444 aProp = property(lambda self: "foo")
2445
2446 class Sub(Base):
2447 @classmethod
2448 def test(klass):
2449 return super(Sub,klass).aProp
2450
2451 self.assertEqual(Sub.test(), Base.aProp)
2452
2453 # Verify that super() doesn't allow keyword args
2454 try:
2455 super(Base, kw=1)
2456 except TypeError:
2457 pass
2458 else:
2459 self.assertEqual("super shouldn't accept keyword args")
2460
2461 def test_basic_inheritance(self):
2462 # Testing inheritance from basic types...
2463
2464 class hexint(int):
2465 def __repr__(self):
2466 return hex(self)
2467 def __add__(self, other):
2468 return hexint(int.__add__(self, other))
2469 # (Note that overriding __radd__ doesn't work,
2470 # because the int type gets first dibs.)
2471 self.assertEqual(repr(hexint(7) + 9), "0x10")
2472 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2473 a = hexint(12345)
2474 self.assertEqual(a, 12345)
2475 self.assertEqual(int(a), 12345)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002476 self.assertTrue(int(a).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002477 self.assertEqual(hash(a), hash(12345))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002478 self.assertTrue((+a).__class__ is int)
2479 self.assertTrue((a >> 0).__class__ is int)
2480 self.assertTrue((a << 0).__class__ is int)
2481 self.assertTrue((hexint(0) << 12).__class__ is int)
2482 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002483
2484 class octlong(long):
2485 __slots__ = []
2486 def __str__(self):
2487 s = oct(self)
2488 if s[-1] == 'L':
2489 s = s[:-1]
2490 return s
2491 def __add__(self, other):
2492 return self.__class__(super(octlong, self).__add__(other))
2493 __radd__ = __add__
2494 self.assertEqual(str(octlong(3) + 5), "010")
2495 # (Note that overriding __radd__ here only seems to work
2496 # because the example uses a short int left argument.)
2497 self.assertEqual(str(5 + octlong(3000)), "05675")
2498 a = octlong(12345)
2499 self.assertEqual(a, 12345L)
2500 self.assertEqual(long(a), 12345L)
2501 self.assertEqual(hash(a), hash(12345L))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002502 self.assertTrue(long(a).__class__ is long)
2503 self.assertTrue((+a).__class__ is long)
2504 self.assertTrue((-a).__class__ is long)
2505 self.assertTrue((-octlong(0)).__class__ is long)
2506 self.assertTrue((a >> 0).__class__ is long)
2507 self.assertTrue((a << 0).__class__ is long)
2508 self.assertTrue((a - 0).__class__ is long)
2509 self.assertTrue((a * 1).__class__ is long)
2510 self.assertTrue((a ** 1).__class__ is long)
2511 self.assertTrue((a // 1).__class__ is long)
2512 self.assertTrue((1 * a).__class__ is long)
2513 self.assertTrue((a | 0).__class__ is long)
2514 self.assertTrue((a ^ 0).__class__ is long)
2515 self.assertTrue((a & -1L).__class__ is long)
2516 self.assertTrue((octlong(0) << 12).__class__ is long)
2517 self.assertTrue((octlong(0) >> 12).__class__ is long)
2518 self.assertTrue(abs(octlong(0)).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002519
2520 # Because octlong overrides __add__, we can't check the absence of +0
2521 # optimizations using octlong.
2522 class longclone(long):
2523 pass
2524 a = longclone(1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002525 self.assertTrue((a + 0).__class__ is long)
2526 self.assertTrue((0 + a).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002527
2528 # Check that negative clones don't segfault
2529 a = longclone(-1)
2530 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002531 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002532
2533 class precfloat(float):
2534 __slots__ = ['prec']
2535 def __init__(self, value=0.0, prec=12):
2536 self.prec = int(prec)
2537 def __repr__(self):
2538 return "%.*g" % (self.prec, self)
2539 self.assertEqual(repr(precfloat(1.1)), "1.1")
2540 a = precfloat(12345)
2541 self.assertEqual(a, 12345.0)
2542 self.assertEqual(float(a), 12345.0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002543 self.assertTrue(float(a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002544 self.assertEqual(hash(a), hash(12345.0))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002545 self.assertTrue((+a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002546
2547 class madcomplex(complex):
2548 def __repr__(self):
2549 return "%.17gj%+.17g" % (self.imag, self.real)
2550 a = madcomplex(-3, 4)
2551 self.assertEqual(repr(a), "4j-3")
2552 base = complex(-3, 4)
2553 self.assertEqual(base.__class__, complex)
2554 self.assertEqual(a, base)
2555 self.assertEqual(complex(a), base)
2556 self.assertEqual(complex(a).__class__, complex)
2557 a = madcomplex(a) # just trying another form of the constructor
2558 self.assertEqual(repr(a), "4j-3")
2559 self.assertEqual(a, base)
2560 self.assertEqual(complex(a), base)
2561 self.assertEqual(complex(a).__class__, complex)
2562 self.assertEqual(hash(a), hash(base))
2563 self.assertEqual((+a).__class__, complex)
2564 self.assertEqual((a + 0).__class__, complex)
2565 self.assertEqual(a + 0, base)
2566 self.assertEqual((a - 0).__class__, complex)
2567 self.assertEqual(a - 0, base)
2568 self.assertEqual((a * 1).__class__, complex)
2569 self.assertEqual(a * 1, base)
2570 self.assertEqual((a / 1).__class__, complex)
2571 self.assertEqual(a / 1, base)
2572
2573 class madtuple(tuple):
2574 _rev = None
2575 def rev(self):
2576 if self._rev is not None:
2577 return self._rev
2578 L = list(self)
2579 L.reverse()
2580 self._rev = self.__class__(L)
2581 return self._rev
2582 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2583 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2584 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2585 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2586 for i in range(512):
2587 t = madtuple(range(i))
2588 u = t.rev()
2589 v = u.rev()
2590 self.assertEqual(v, t)
2591 a = madtuple((1,2,3,4,5))
2592 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002593 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002594 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002595 self.assertTrue(a[:].__class__ is tuple)
2596 self.assertTrue((a * 1).__class__ is tuple)
2597 self.assertTrue((a * 0).__class__ is tuple)
2598 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002599 a = madtuple(())
2600 self.assertEqual(tuple(a), ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002601 self.assertTrue(tuple(a).__class__ is tuple)
2602 self.assertTrue((a + a).__class__ is tuple)
2603 self.assertTrue((a * 0).__class__ is tuple)
2604 self.assertTrue((a * 1).__class__ is tuple)
2605 self.assertTrue((a * 2).__class__ is tuple)
2606 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002607
2608 class madstring(str):
2609 _rev = None
2610 def rev(self):
2611 if self._rev is not None:
2612 return self._rev
2613 L = list(self)
2614 L.reverse()
2615 self._rev = self.__class__("".join(L))
2616 return self._rev
2617 s = madstring("abcdefghijklmnopqrstuvwxyz")
2618 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2619 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2620 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2621 for i in range(256):
2622 s = madstring("".join(map(chr, range(i))))
2623 t = s.rev()
2624 u = t.rev()
2625 self.assertEqual(u, s)
2626 s = madstring("12345")
2627 self.assertEqual(str(s), "12345")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002628 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002629
2630 base = "\x00" * 5
2631 s = madstring(base)
2632 self.assertEqual(s, base)
2633 self.assertEqual(str(s), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002634 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002635 self.assertEqual(hash(s), hash(base))
2636 self.assertEqual({s: 1}[base], 1)
2637 self.assertEqual({base: 1}[s], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002638 self.assertTrue((s + "").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002639 self.assertEqual(s + "", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002640 self.assertTrue(("" + s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002641 self.assertEqual("" + s, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002642 self.assertTrue((s * 0).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002643 self.assertEqual(s * 0, "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002644 self.assertTrue((s * 1).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002645 self.assertEqual(s * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002646 self.assertTrue((s * 2).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002647 self.assertEqual(s * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002648 self.assertTrue(s[:].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002649 self.assertEqual(s[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002650 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002651 self.assertEqual(s[0:0], "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002652 self.assertTrue(s.strip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002653 self.assertEqual(s.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002654 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002655 self.assertEqual(s.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002656 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002657 self.assertEqual(s.rstrip(), base)
2658 identitytab = ''.join([chr(i) for i in range(256)])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002659 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002660 self.assertEqual(s.translate(identitytab), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002661 self.assertTrue(s.translate(identitytab, "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002662 self.assertEqual(s.translate(identitytab, "x"), base)
2663 self.assertEqual(s.translate(identitytab, "\x00"), "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002664 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002665 self.assertEqual(s.replace("x", "x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002666 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002667 self.assertEqual(s.ljust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002668 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002669 self.assertEqual(s.rjust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002670 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002671 self.assertEqual(s.center(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002672 self.assertTrue(s.lower().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002673 self.assertEqual(s.lower(), base)
2674
2675 class madunicode(unicode):
2676 _rev = None
2677 def rev(self):
2678 if self._rev is not None:
2679 return self._rev
2680 L = list(self)
2681 L.reverse()
2682 self._rev = self.__class__(u"".join(L))
2683 return self._rev
2684 u = madunicode("ABCDEF")
2685 self.assertEqual(u, u"ABCDEF")
2686 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2687 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2688 base = u"12345"
2689 u = madunicode(base)
2690 self.assertEqual(unicode(u), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002691 self.assertTrue(unicode(u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002692 self.assertEqual(hash(u), hash(base))
2693 self.assertEqual({u: 1}[base], 1)
2694 self.assertEqual({base: 1}[u], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002695 self.assertTrue(u.strip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002696 self.assertEqual(u.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002697 self.assertTrue(u.lstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002698 self.assertEqual(u.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002699 self.assertTrue(u.rstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002700 self.assertEqual(u.rstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002701 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002702 self.assertEqual(u.replace(u"x", u"x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002703 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002704 self.assertEqual(u.replace(u"xy", u"xy"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002705 self.assertTrue(u.center(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002706 self.assertEqual(u.center(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002707 self.assertTrue(u.ljust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002708 self.assertEqual(u.ljust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002709 self.assertTrue(u.rjust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002710 self.assertEqual(u.rjust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002711 self.assertTrue(u.lower().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002712 self.assertEqual(u.lower(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002713 self.assertTrue(u.upper().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002714 self.assertEqual(u.upper(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002715 self.assertTrue(u.capitalize().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002716 self.assertEqual(u.capitalize(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002717 self.assertTrue(u.title().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002718 self.assertEqual(u.title(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002719 self.assertTrue((u + u"").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002720 self.assertEqual(u + u"", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002721 self.assertTrue((u"" + u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002722 self.assertEqual(u"" + u, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002723 self.assertTrue((u * 0).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002724 self.assertEqual(u * 0, u"")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002725 self.assertTrue((u * 1).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002726 self.assertEqual(u * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002727 self.assertTrue((u * 2).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002728 self.assertEqual(u * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002729 self.assertTrue(u[:].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002730 self.assertEqual(u[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002731 self.assertTrue(u[0:0].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002732 self.assertEqual(u[0:0], u"")
2733
2734 class sublist(list):
2735 pass
2736 a = sublist(range(5))
2737 self.assertEqual(a, range(5))
2738 a.append("hello")
2739 self.assertEqual(a, range(5) + ["hello"])
2740 a[5] = 5
2741 self.assertEqual(a, range(6))
2742 a.extend(range(6, 20))
2743 self.assertEqual(a, range(20))
2744 a[-5:] = []
2745 self.assertEqual(a, range(15))
2746 del a[10:15]
2747 self.assertEqual(len(a), 10)
2748 self.assertEqual(a, range(10))
2749 self.assertEqual(list(a), range(10))
2750 self.assertEqual(a[0], 0)
2751 self.assertEqual(a[9], 9)
2752 self.assertEqual(a[-10], 0)
2753 self.assertEqual(a[-1], 9)
2754 self.assertEqual(a[:5], range(5))
2755
2756 class CountedInput(file):
2757 """Counts lines read by self.readline().
2758
2759 self.lineno is the 0-based ordinal of the last line read, up to
2760 a maximum of one greater than the number of lines in the file.
2761
2762 self.ateof is true if and only if the final "" line has been read,
2763 at which point self.lineno stops incrementing, and further calls
2764 to readline() continue to return "".
2765 """
2766
2767 lineno = 0
2768 ateof = 0
2769 def readline(self):
2770 if self.ateof:
2771 return ""
2772 s = file.readline(self)
2773 # Next line works too.
2774 # s = super(CountedInput, self).readline()
2775 self.lineno += 1
2776 if s == "":
2777 self.ateof = 1
2778 return s
2779
2780 f = file(name=test_support.TESTFN, mode='w')
2781 lines = ['a\n', 'b\n', 'c\n']
2782 try:
2783 f.writelines(lines)
2784 f.close()
2785 f = CountedInput(test_support.TESTFN)
2786 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2787 got = f.readline()
2788 self.assertEqual(expected, got)
2789 self.assertEqual(f.lineno, i)
2790 self.assertEqual(f.ateof, (i > len(lines)))
2791 f.close()
2792 finally:
2793 try:
2794 f.close()
2795 except:
2796 pass
2797 test_support.unlink(test_support.TESTFN)
2798
2799 def test_keywords(self):
2800 # Testing keyword args to basic type constructors ...
2801 self.assertEqual(int(x=1), 1)
2802 self.assertEqual(float(x=2), 2.0)
2803 self.assertEqual(long(x=3), 3L)
2804 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2805 self.assertEqual(str(object=500), '500')
2806 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2807 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2808 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2809 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2810
2811 for constructor in (int, float, long, complex, str, unicode,
2812 tuple, list, file):
2813 try:
2814 constructor(bogus_keyword_arg=1)
2815 except TypeError:
2816 pass
2817 else:
2818 self.fail("expected TypeError from bogus keyword argument to %r"
2819 % constructor)
2820
2821 def test_str_subclass_as_dict_key(self):
2822 # Testing a str subclass used as dict key ..
2823
2824 class cistr(str):
2825 """Sublcass of str that computes __eq__ case-insensitively.
2826
2827 Also computes a hash code of the string in canonical form.
2828 """
2829
2830 def __init__(self, value):
2831 self.canonical = value.lower()
2832 self.hashcode = hash(self.canonical)
2833
2834 def __eq__(self, other):
2835 if not isinstance(other, cistr):
2836 other = cistr(other)
2837 return self.canonical == other.canonical
2838
2839 def __hash__(self):
2840 return self.hashcode
2841
2842 self.assertEqual(cistr('ABC'), 'abc')
2843 self.assertEqual('aBc', cistr('ABC'))
2844 self.assertEqual(str(cistr('ABC')), 'ABC')
2845
2846 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2847 self.assertEqual(d[cistr('one')], 1)
2848 self.assertEqual(d[cistr('tWo')], 2)
2849 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002850 self.assertTrue(cistr('ONe') in d)
Georg Brandl48545522008-02-02 10:12:36 +00002851 self.assertEqual(d.get(cistr('thrEE')), 3)
2852
2853 def test_classic_comparisons(self):
2854 # Testing classic comparisons...
2855 class classic:
2856 pass
2857
2858 for base in (classic, int, object):
2859 class C(base):
2860 def __init__(self, value):
2861 self.value = int(value)
2862 def __cmp__(self, other):
2863 if isinstance(other, C):
2864 return cmp(self.value, other.value)
2865 if isinstance(other, int) or isinstance(other, long):
2866 return cmp(self.value, other)
2867 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002868 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002869
2870 c1 = C(1)
2871 c2 = C(2)
2872 c3 = C(3)
2873 self.assertEqual(c1, 1)
2874 c = {1: c1, 2: c2, 3: c3}
2875 for x in 1, 2, 3:
2876 for y in 1, 2, 3:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002877 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002878 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002879 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002880 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002881 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2882 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002883
2884 def test_rich_comparisons(self):
2885 # Testing rich comparisons...
2886 class Z(complex):
2887 pass
2888 z = Z(1)
2889 self.assertEqual(z, 1+0j)
2890 self.assertEqual(1+0j, z)
2891 class ZZ(complex):
2892 def __eq__(self, other):
2893 try:
2894 return abs(self - other) <= 1e-6
2895 except:
2896 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002897 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002898 zz = ZZ(1.0000003)
2899 self.assertEqual(zz, 1+0j)
2900 self.assertEqual(1+0j, zz)
2901
2902 class classic:
2903 pass
2904 for base in (classic, int, object, list):
2905 class C(base):
2906 def __init__(self, value):
2907 self.value = int(value)
2908 def __cmp__(self_, other):
2909 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002910 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002911 def __eq__(self, other):
2912 if isinstance(other, C):
2913 return self.value == other.value
2914 if isinstance(other, int) or isinstance(other, long):
2915 return self.value == other
2916 return NotImplemented
2917 def __ne__(self, other):
2918 if isinstance(other, C):
2919 return self.value != other.value
2920 if isinstance(other, int) or isinstance(other, long):
2921 return self.value != other
2922 return NotImplemented
2923 def __lt__(self, other):
2924 if isinstance(other, C):
2925 return self.value < other.value
2926 if isinstance(other, int) or isinstance(other, long):
2927 return self.value < other
2928 return NotImplemented
2929 def __le__(self, other):
2930 if isinstance(other, C):
2931 return self.value <= other.value
2932 if isinstance(other, int) or isinstance(other, long):
2933 return self.value <= other
2934 return NotImplemented
2935 def __gt__(self, other):
2936 if isinstance(other, C):
2937 return self.value > other.value
2938 if isinstance(other, int) or isinstance(other, long):
2939 return self.value > other
2940 return NotImplemented
2941 def __ge__(self, other):
2942 if isinstance(other, C):
2943 return self.value >= other.value
2944 if isinstance(other, int) or isinstance(other, long):
2945 return self.value >= other
2946 return NotImplemented
2947 c1 = C(1)
2948 c2 = C(2)
2949 c3 = C(3)
2950 self.assertEqual(c1, 1)
2951 c = {1: c1, 2: c2, 3: c3}
2952 for x in 1, 2, 3:
2953 for y in 1, 2, 3:
2954 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002955 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002956 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002957 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002958 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002959 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002960 "x=%d, y=%d" % (x, y))
2961
2962 def test_coercions(self):
2963 # Testing coercions...
2964 class I(int): pass
2965 coerce(I(0), 0)
2966 coerce(0, I(0))
2967 class L(long): pass
2968 coerce(L(0), 0)
2969 coerce(L(0), 0L)
2970 coerce(0, L(0))
2971 coerce(0L, L(0))
2972 class F(float): pass
2973 coerce(F(0), 0)
2974 coerce(F(0), 0L)
2975 coerce(F(0), 0.)
2976 coerce(0, F(0))
2977 coerce(0L, F(0))
2978 coerce(0., F(0))
2979 class C(complex): pass
2980 coerce(C(0), 0)
2981 coerce(C(0), 0L)
2982 coerce(C(0), 0.)
2983 coerce(C(0), 0j)
2984 coerce(0, C(0))
2985 coerce(0L, C(0))
2986 coerce(0., C(0))
2987 coerce(0j, C(0))
2988
2989 def test_descrdoc(self):
2990 # Testing descriptor doc strings...
2991 def check(descr, what):
2992 self.assertEqual(descr.__doc__, what)
2993 check(file.closed, "True if the file is closed") # getset descriptor
2994 check(file.name, "file name") # member descriptor
2995
2996 def test_doc_descriptor(self):
2997 # Testing __doc__ descriptor...
2998 # SF bug 542984
2999 class DocDescr(object):
3000 def __get__(self, object, otype):
3001 if object:
3002 object = object.__class__.__name__ + ' instance'
3003 if otype:
3004 otype = otype.__name__
3005 return 'object=%s; type=%s' % (object, otype)
3006 class OldClass:
3007 __doc__ = DocDescr()
3008 class NewClass(object):
3009 __doc__ = DocDescr()
3010 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3011 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3012 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3013 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3014
3015 def test_set_class(self):
3016 # Testing __class__ assignment...
3017 class C(object): pass
3018 class D(object): pass
3019 class E(object): pass
3020 class F(D, E): pass
3021 for cls in C, D, E, F:
3022 for cls2 in C, D, E, F:
3023 x = cls()
3024 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003025 self.assertTrue(x.__class__ is cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003026 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003027 self.assertTrue(x.__class__ is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003028 def cant(x, C):
3029 try:
3030 x.__class__ = C
3031 except TypeError:
3032 pass
3033 else:
3034 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3035 try:
3036 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003037 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003038 pass
3039 else:
3040 self.fail("shouldn't allow del %r.__class__" % x)
3041 cant(C(), list)
3042 cant(list(), C)
3043 cant(C(), 1)
3044 cant(C(), object)
3045 cant(object(), list)
3046 cant(list(), object)
3047 class Int(int): __slots__ = []
3048 cant(2, Int)
3049 cant(Int(), int)
3050 cant(True, int)
3051 cant(2, bool)
3052 o = object()
3053 cant(o, type(1))
3054 cant(o, type(None))
3055 del o
3056 class G(object):
3057 __slots__ = ["a", "b"]
3058 class H(object):
3059 __slots__ = ["b", "a"]
3060 try:
3061 unicode
3062 except NameError:
3063 class I(object):
3064 __slots__ = ["a", "b"]
3065 else:
3066 class I(object):
3067 __slots__ = [unicode("a"), unicode("b")]
3068 class J(object):
3069 __slots__ = ["c", "b"]
3070 class K(object):
3071 __slots__ = ["a", "b", "d"]
3072 class L(H):
3073 __slots__ = ["e"]
3074 class M(I):
3075 __slots__ = ["e"]
3076 class N(J):
3077 __slots__ = ["__weakref__"]
3078 class P(J):
3079 __slots__ = ["__dict__"]
3080 class Q(J):
3081 pass
3082 class R(J):
3083 __slots__ = ["__dict__", "__weakref__"]
3084
3085 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3086 x = cls()
3087 x.a = 1
3088 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003089 self.assertTrue(x.__class__ is cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003090 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3091 self.assertEqual(x.a, 1)
3092 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003093 self.assertTrue(x.__class__ is cls,
Georg Brandl48545522008-02-02 10:12:36 +00003094 "assigning %r as __class__ for %r silently failed" % (cls, x))
3095 self.assertEqual(x.a, 1)
3096 for cls in G, J, K, L, M, N, P, R, list, Int:
3097 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3098 if cls is cls2:
3099 continue
3100 cant(cls(), cls2)
3101
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003102 # Issue5283: when __class__ changes in __del__, the wrong
3103 # type gets DECREF'd.
3104 class O(object):
3105 pass
3106 class A(object):
3107 def __del__(self):
3108 self.__class__ = O
3109 l = [A() for x in range(100)]
3110 del l
3111
Georg Brandl48545522008-02-02 10:12:36 +00003112 def test_set_dict(self):
3113 # Testing __dict__ assignment...
3114 class C(object): pass
3115 a = C()
3116 a.__dict__ = {'b': 1}
3117 self.assertEqual(a.b, 1)
3118 def cant(x, dict):
3119 try:
3120 x.__dict__ = dict
3121 except (AttributeError, TypeError):
3122 pass
3123 else:
3124 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3125 cant(a, None)
3126 cant(a, [])
3127 cant(a, 1)
3128 del a.__dict__ # Deleting __dict__ is allowed
3129
3130 class Base(object):
3131 pass
3132 def verify_dict_readonly(x):
3133 """
3134 x has to be an instance of a class inheriting from Base.
3135 """
3136 cant(x, {})
3137 try:
3138 del x.__dict__
3139 except (AttributeError, TypeError):
3140 pass
3141 else:
3142 self.fail("shouldn't allow del %r.__dict__" % x)
3143 dict_descr = Base.__dict__["__dict__"]
3144 try:
3145 dict_descr.__set__(x, {})
3146 except (AttributeError, TypeError):
3147 pass
3148 else:
3149 self.fail("dict_descr allowed access to %r's dict" % x)
3150
3151 # Classes don't allow __dict__ assignment and have readonly dicts
3152 class Meta1(type, Base):
3153 pass
3154 class Meta2(Base, type):
3155 pass
3156 class D(object):
3157 __metaclass__ = Meta1
3158 class E(object):
3159 __metaclass__ = Meta2
3160 for cls in C, D, E:
3161 verify_dict_readonly(cls)
3162 class_dict = cls.__dict__
3163 try:
3164 class_dict["spam"] = "eggs"
3165 except TypeError:
3166 pass
3167 else:
3168 self.fail("%r's __dict__ can be modified" % cls)
3169
3170 # Modules also disallow __dict__ assignment
3171 class Module1(types.ModuleType, Base):
3172 pass
3173 class Module2(Base, types.ModuleType):
3174 pass
3175 for ModuleType in Module1, Module2:
3176 mod = ModuleType("spam")
3177 verify_dict_readonly(mod)
3178 mod.__dict__["spam"] = "eggs"
3179
3180 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003181 # (at least not any more than regular exception's __dict__ can
3182 # be deleted; on CPython it is not the case, whereas on PyPy they
3183 # can, just like any other new-style instance's __dict__.)
3184 def can_delete_dict(e):
3185 try:
3186 del e.__dict__
3187 except (TypeError, AttributeError):
3188 return False
3189 else:
3190 return True
Georg Brandl48545522008-02-02 10:12:36 +00003191 class Exception1(Exception, Base):
3192 pass
3193 class Exception2(Base, Exception):
3194 pass
3195 for ExceptionType in Exception, Exception1, Exception2:
3196 e = ExceptionType()
3197 e.__dict__ = {"a": 1}
3198 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003199 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003200
3201 def test_pickles(self):
3202 # Testing pickling and copying new-style classes and objects...
3203 import pickle, cPickle
3204
3205 def sorteditems(d):
3206 L = d.items()
3207 L.sort()
3208 return L
3209
3210 global C
3211 class C(object):
3212 def __init__(self, a, b):
3213 super(C, self).__init__()
3214 self.a = a
3215 self.b = b
3216 def __repr__(self):
3217 return "C(%r, %r)" % (self.a, self.b)
3218
3219 global C1
3220 class C1(list):
3221 def __new__(cls, a, b):
3222 return super(C1, cls).__new__(cls)
3223 def __getnewargs__(self):
3224 return (self.a, self.b)
3225 def __init__(self, a, b):
3226 self.a = a
3227 self.b = b
3228 def __repr__(self):
3229 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3230
3231 global C2
3232 class C2(int):
3233 def __new__(cls, a, b, val=0):
3234 return super(C2, cls).__new__(cls, val)
3235 def __getnewargs__(self):
3236 return (self.a, self.b, int(self))
3237 def __init__(self, a, b, val=0):
3238 self.a = a
3239 self.b = b
3240 def __repr__(self):
3241 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3242
3243 global C3
3244 class C3(object):
3245 def __init__(self, foo):
3246 self.foo = foo
3247 def __getstate__(self):
3248 return self.foo
3249 def __setstate__(self, foo):
3250 self.foo = foo
3251
3252 global C4classic, C4
3253 class C4classic: # classic
3254 pass
3255 class C4(C4classic, object): # mixed inheritance
3256 pass
3257
3258 for p in pickle, cPickle:
3259 for bin in 0, 1:
3260 for cls in C, C1, C2:
3261 s = p.dumps(cls, bin)
3262 cls2 = p.loads(s)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003263 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003264
3265 a = C1(1, 2); a.append(42); a.append(24)
3266 b = C2("hello", "world", 42)
3267 s = p.dumps((a, b), bin)
3268 x, y = p.loads(s)
3269 self.assertEqual(x.__class__, a.__class__)
3270 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3271 self.assertEqual(y.__class__, b.__class__)
3272 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3273 self.assertEqual(repr(x), repr(a))
3274 self.assertEqual(repr(y), repr(b))
3275 # Test for __getstate__ and __setstate__ on new style class
3276 u = C3(42)
3277 s = p.dumps(u, bin)
3278 v = p.loads(s)
3279 self.assertEqual(u.__class__, v.__class__)
3280 self.assertEqual(u.foo, v.foo)
3281 # Test for picklability of hybrid class
3282 u = C4()
3283 u.foo = 42
3284 s = p.dumps(u, bin)
3285 v = p.loads(s)
3286 self.assertEqual(u.__class__, v.__class__)
3287 self.assertEqual(u.foo, v.foo)
3288
3289 # Testing copy.deepcopy()
3290 import copy
3291 for cls in C, C1, C2:
3292 cls2 = copy.deepcopy(cls)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003293 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003294
3295 a = C1(1, 2); a.append(42); a.append(24)
3296 b = C2("hello", "world", 42)
3297 x, y = copy.deepcopy((a, b))
3298 self.assertEqual(x.__class__, a.__class__)
3299 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3300 self.assertEqual(y.__class__, b.__class__)
3301 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3302 self.assertEqual(repr(x), repr(a))
3303 self.assertEqual(repr(y), repr(b))
3304
3305 def test_pickle_slots(self):
3306 # Testing pickling of classes with __slots__ ...
3307 import pickle, cPickle
3308 # Pickling of classes with __slots__ but without __getstate__ should fail
3309 global B, C, D, E
3310 class B(object):
3311 pass
3312 for base in [object, B]:
3313 class C(base):
3314 __slots__ = ['a']
3315 class D(C):
3316 pass
3317 try:
3318 pickle.dumps(C())
3319 except TypeError:
3320 pass
3321 else:
3322 self.fail("should fail: pickle C instance - %s" % base)
3323 try:
3324 cPickle.dumps(C())
3325 except TypeError:
3326 pass
3327 else:
3328 self.fail("should fail: cPickle C instance - %s" % base)
3329 try:
3330 pickle.dumps(C())
3331 except TypeError:
3332 pass
3333 else:
3334 self.fail("should fail: pickle D instance - %s" % base)
3335 try:
3336 cPickle.dumps(D())
3337 except TypeError:
3338 pass
3339 else:
3340 self.fail("should fail: cPickle D instance - %s" % base)
3341 # Give C a nice generic __getstate__ and __setstate__
3342 class C(base):
3343 __slots__ = ['a']
3344 def __getstate__(self):
3345 try:
3346 d = self.__dict__.copy()
3347 except AttributeError:
3348 d = {}
3349 for cls in self.__class__.__mro__:
3350 for sn in cls.__dict__.get('__slots__', ()):
3351 try:
3352 d[sn] = getattr(self, sn)
3353 except AttributeError:
3354 pass
3355 return d
3356 def __setstate__(self, d):
3357 for k, v in d.items():
3358 setattr(self, k, v)
3359 class D(C):
3360 pass
3361 # Now it should work
3362 x = C()
3363 y = pickle.loads(pickle.dumps(x))
3364 self.assertEqual(hasattr(y, 'a'), 0)
3365 y = cPickle.loads(cPickle.dumps(x))
3366 self.assertEqual(hasattr(y, 'a'), 0)
3367 x.a = 42
3368 y = pickle.loads(pickle.dumps(x))
3369 self.assertEqual(y.a, 42)
3370 y = cPickle.loads(cPickle.dumps(x))
3371 self.assertEqual(y.a, 42)
3372 x = D()
3373 x.a = 42
3374 x.b = 100
3375 y = pickle.loads(pickle.dumps(x))
3376 self.assertEqual(y.a + y.b, 142)
3377 y = cPickle.loads(cPickle.dumps(x))
3378 self.assertEqual(y.a + y.b, 142)
3379 # A subclass that adds a slot should also work
3380 class E(C):
3381 __slots__ = ['b']
3382 x = E()
3383 x.a = 42
3384 x.b = "foo"
3385 y = pickle.loads(pickle.dumps(x))
3386 self.assertEqual(y.a, x.a)
3387 self.assertEqual(y.b, x.b)
3388 y = cPickle.loads(cPickle.dumps(x))
3389 self.assertEqual(y.a, x.a)
3390 self.assertEqual(y.b, x.b)
3391
3392 def test_binary_operator_override(self):
3393 # Testing overrides of binary operations...
3394 class I(int):
3395 def __repr__(self):
3396 return "I(%r)" % int(self)
3397 def __add__(self, other):
3398 return I(int(self) + int(other))
3399 __radd__ = __add__
3400 def __pow__(self, other, mod=None):
3401 if mod is None:
3402 return I(pow(int(self), int(other)))
3403 else:
3404 return I(pow(int(self), int(other), int(mod)))
3405 def __rpow__(self, other, mod=None):
3406 if mod is None:
3407 return I(pow(int(other), int(self), mod))
3408 else:
3409 return I(pow(int(other), int(self), int(mod)))
3410
3411 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3412 self.assertEqual(repr(I(1) + 2), "I(3)")
3413 self.assertEqual(repr(1 + I(2)), "I(3)")
3414 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3415 self.assertEqual(repr(2 ** I(3)), "I(8)")
3416 self.assertEqual(repr(I(2) ** 3), "I(8)")
3417 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3418 class S(str):
3419 def __eq__(self, other):
3420 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003421 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003422
3423 def test_subclass_propagation(self):
3424 # Testing propagation of slot functions to subclasses...
3425 class A(object):
3426 pass
3427 class B(A):
3428 pass
3429 class C(A):
3430 pass
3431 class D(B, C):
3432 pass
3433 d = D()
3434 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3435 A.__hash__ = lambda self: 42
3436 self.assertEqual(hash(d), 42)
3437 C.__hash__ = lambda self: 314
3438 self.assertEqual(hash(d), 314)
3439 B.__hash__ = lambda self: 144
3440 self.assertEqual(hash(d), 144)
3441 D.__hash__ = lambda self: 100
3442 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003443 D.__hash__ = None
3444 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003445 del D.__hash__
3446 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003447 B.__hash__ = None
3448 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003449 del B.__hash__
3450 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003451 C.__hash__ = None
3452 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003453 del C.__hash__
3454 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003455 A.__hash__ = None
3456 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003457 del A.__hash__
3458 self.assertEqual(hash(d), orig_hash)
3459 d.foo = 42
3460 d.bar = 42
3461 self.assertEqual(d.foo, 42)
3462 self.assertEqual(d.bar, 42)
3463 def __getattribute__(self, name):
3464 if name == "foo":
3465 return 24
3466 return object.__getattribute__(self, name)
3467 A.__getattribute__ = __getattribute__
3468 self.assertEqual(d.foo, 24)
3469 self.assertEqual(d.bar, 42)
3470 def __getattr__(self, name):
3471 if name in ("spam", "foo", "bar"):
3472 return "hello"
3473 raise AttributeError, name
3474 B.__getattr__ = __getattr__
3475 self.assertEqual(d.spam, "hello")
3476 self.assertEqual(d.foo, 24)
3477 self.assertEqual(d.bar, 42)
3478 del A.__getattribute__
3479 self.assertEqual(d.foo, 42)
3480 del d.foo
3481 self.assertEqual(d.foo, "hello")
3482 self.assertEqual(d.bar, 42)
3483 del B.__getattr__
3484 try:
3485 d.foo
3486 except AttributeError:
3487 pass
3488 else:
3489 self.fail("d.foo should be undefined now")
3490
3491 # Test a nasty bug in recurse_down_subclasses()
3492 import gc
3493 class A(object):
3494 pass
3495 class B(A):
3496 pass
3497 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003498 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003499 A.__setitem__ = lambda *a: None # crash
3500
3501 def test_buffer_inheritance(self):
3502 # Testing that buffer interface is inherited ...
3503
3504 import binascii
3505 # SF bug [#470040] ParseTuple t# vs subclasses.
3506
3507 class MyStr(str):
3508 pass
3509 base = 'abc'
3510 m = MyStr(base)
3511 # b2a_hex uses the buffer interface to get its argument's value, via
3512 # PyArg_ParseTuple 't#' code.
3513 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3514
3515 # It's not clear that unicode will continue to support the character
3516 # buffer interface, and this test will fail if that's taken away.
3517 class MyUni(unicode):
3518 pass
3519 base = u'abc'
3520 m = MyUni(base)
3521 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3522
3523 class MyInt(int):
3524 pass
3525 m = MyInt(42)
3526 try:
3527 binascii.b2a_hex(m)
3528 self.fail('subclass of int should not have a buffer interface')
3529 except TypeError:
3530 pass
3531
3532 def test_str_of_str_subclass(self):
3533 # Testing __str__ defined in subclass of str ...
3534 import binascii
3535 import cStringIO
3536
3537 class octetstring(str):
3538 def __str__(self):
3539 return binascii.b2a_hex(self)
3540 def __repr__(self):
3541 return self + " repr"
3542
3543 o = octetstring('A')
3544 self.assertEqual(type(o), octetstring)
3545 self.assertEqual(type(str(o)), str)
3546 self.assertEqual(type(repr(o)), str)
3547 self.assertEqual(ord(o), 0x41)
3548 self.assertEqual(str(o), '41')
3549 self.assertEqual(repr(o), 'A repr')
3550 self.assertEqual(o.__str__(), '41')
3551 self.assertEqual(o.__repr__(), 'A repr')
3552
3553 capture = cStringIO.StringIO()
3554 # Calling str() or not exercises different internal paths.
3555 print >> capture, o
3556 print >> capture, str(o)
3557 self.assertEqual(capture.getvalue(), '41\n41\n')
3558 capture.close()
3559
3560 def test_keyword_arguments(self):
3561 # Testing keyword arguments to __init__, __call__...
3562 def f(a): return a
3563 self.assertEqual(f.__call__(a=42), 42)
3564 a = []
3565 list.__init__(a, sequence=[0, 1, 2])
3566 self.assertEqual(a, [0, 1, 2])
3567
3568 def test_recursive_call(self):
3569 # Testing recursive __call__() by setting to instance of class...
3570 class A(object):
3571 pass
3572
3573 A.__call__ = A()
3574 try:
3575 A()()
3576 except RuntimeError:
3577 pass
3578 else:
3579 self.fail("Recursion limit should have been reached for __call__()")
3580
3581 def test_delete_hook(self):
3582 # Testing __del__ hook...
3583 log = []
3584 class C(object):
3585 def __del__(self):
3586 log.append(1)
3587 c = C()
3588 self.assertEqual(log, [])
3589 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003590 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003591 self.assertEqual(log, [1])
3592
3593 class D(object): pass
3594 d = D()
3595 try: del d[0]
3596 except TypeError: pass
3597 else: self.fail("invalid del() didn't raise TypeError")
3598
3599 def test_hash_inheritance(self):
3600 # Testing hash of mutable subclasses...
3601
3602 class mydict(dict):
3603 pass
3604 d = mydict()
3605 try:
3606 hash(d)
3607 except TypeError:
3608 pass
3609 else:
3610 self.fail("hash() of dict subclass should fail")
3611
3612 class mylist(list):
3613 pass
3614 d = mylist()
3615 try:
3616 hash(d)
3617 except TypeError:
3618 pass
3619 else:
3620 self.fail("hash() of list subclass should fail")
3621
3622 def test_str_operations(self):
3623 try: 'a' + 5
3624 except TypeError: pass
3625 else: self.fail("'' + 5 doesn't raise TypeError")
3626
3627 try: ''.split('')
3628 except ValueError: pass
3629 else: self.fail("''.split('') doesn't raise ValueError")
3630
3631 try: ''.join([0])
3632 except TypeError: pass
3633 else: self.fail("''.join([0]) doesn't raise TypeError")
3634
3635 try: ''.rindex('5')
3636 except ValueError: pass
3637 else: self.fail("''.rindex('5') doesn't raise ValueError")
3638
3639 try: '%(n)s' % None
3640 except TypeError: pass
3641 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3642
3643 try: '%(n' % {}
3644 except ValueError: pass
3645 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3646
3647 try: '%*s' % ('abc')
3648 except TypeError: pass
3649 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3650
3651 try: '%*.*s' % ('abc', 5)
3652 except TypeError: pass
3653 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3654
3655 try: '%s' % (1, 2)
3656 except TypeError: pass
3657 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3658
3659 try: '%' % None
3660 except ValueError: pass
3661 else: self.fail("'%' % None doesn't raise ValueError")
3662
3663 self.assertEqual('534253'.isdigit(), 1)
3664 self.assertEqual('534253x'.isdigit(), 0)
3665 self.assertEqual('%c' % 5, '\x05')
3666 self.assertEqual('%c' % '5', '5')
3667
3668 def test_deepcopy_recursive(self):
3669 # Testing deepcopy of recursive objects...
3670 class Node:
3671 pass
3672 a = Node()
3673 b = Node()
3674 a.b = b
3675 b.a = a
3676 z = deepcopy(a) # This blew up before
3677
3678 def test_unintialized_modules(self):
3679 # Testing uninitialized module objects...
3680 from types import ModuleType as M
3681 m = M.__new__(M)
3682 str(m)
3683 self.assertEqual(hasattr(m, "__name__"), 0)
3684 self.assertEqual(hasattr(m, "__file__"), 0)
3685 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003686 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003687 m.foo = 1
3688 self.assertEqual(m.__dict__, {"foo": 1})
3689
3690 def test_funny_new(self):
3691 # Testing __new__ returning something unexpected...
3692 class C(object):
3693 def __new__(cls, arg):
3694 if isinstance(arg, str): return [1, 2, 3]
3695 elif isinstance(arg, int): return object.__new__(D)
3696 else: return object.__new__(cls)
3697 class D(C):
3698 def __init__(self, arg):
3699 self.foo = arg
3700 self.assertEqual(C("1"), [1, 2, 3])
3701 self.assertEqual(D("1"), [1, 2, 3])
3702 d = D(None)
3703 self.assertEqual(d.foo, None)
3704 d = C(1)
3705 self.assertEqual(isinstance(d, D), True)
3706 self.assertEqual(d.foo, 1)
3707 d = D(1)
3708 self.assertEqual(isinstance(d, D), True)
3709 self.assertEqual(d.foo, 1)
3710
3711 def test_imul_bug(self):
3712 # Testing for __imul__ problems...
3713 # SF bug 544647
3714 class C(object):
3715 def __imul__(self, other):
3716 return (self, other)
3717 x = C()
3718 y = x
3719 y *= 1.0
3720 self.assertEqual(y, (x, 1.0))
3721 y = x
3722 y *= 2
3723 self.assertEqual(y, (x, 2))
3724 y = x
3725 y *= 3L
3726 self.assertEqual(y, (x, 3L))
3727 y = x
3728 y *= 1L<<100
3729 self.assertEqual(y, (x, 1L<<100))
3730 y = x
3731 y *= None
3732 self.assertEqual(y, (x, None))
3733 y = x
3734 y *= "foo"
3735 self.assertEqual(y, (x, "foo"))
3736
3737 def test_copy_setstate(self):
3738 # Testing that copy.*copy() correctly uses __setstate__...
3739 import copy
3740 class C(object):
3741 def __init__(self, foo=None):
3742 self.foo = foo
3743 self.__foo = foo
3744 def setfoo(self, foo=None):
3745 self.foo = foo
3746 def getfoo(self):
3747 return self.__foo
3748 def __getstate__(self):
3749 return [self.foo]
3750 def __setstate__(self_, lst):
3751 self.assertEqual(len(lst), 1)
3752 self_.__foo = self_.foo = lst[0]
3753 a = C(42)
3754 a.setfoo(24)
3755 self.assertEqual(a.foo, 24)
3756 self.assertEqual(a.getfoo(), 42)
3757 b = copy.copy(a)
3758 self.assertEqual(b.foo, 24)
3759 self.assertEqual(b.getfoo(), 24)
3760 b = copy.deepcopy(a)
3761 self.assertEqual(b.foo, 24)
3762 self.assertEqual(b.getfoo(), 24)
3763
3764 def test_slices(self):
3765 # Testing cases with slices and overridden __getitem__ ...
3766
3767 # Strings
3768 self.assertEqual("hello"[:4], "hell")
3769 self.assertEqual("hello"[slice(4)], "hell")
3770 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3771 class S(str):
3772 def __getitem__(self, x):
3773 return str.__getitem__(self, x)
3774 self.assertEqual(S("hello")[:4], "hell")
3775 self.assertEqual(S("hello")[slice(4)], "hell")
3776 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3777 # Tuples
3778 self.assertEqual((1,2,3)[:2], (1,2))
3779 self.assertEqual((1,2,3)[slice(2)], (1,2))
3780 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3781 class T(tuple):
3782 def __getitem__(self, x):
3783 return tuple.__getitem__(self, x)
3784 self.assertEqual(T((1,2,3))[:2], (1,2))
3785 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3786 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3787 # Lists
3788 self.assertEqual([1,2,3][:2], [1,2])
3789 self.assertEqual([1,2,3][slice(2)], [1,2])
3790 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3791 class L(list):
3792 def __getitem__(self, x):
3793 return list.__getitem__(self, x)
3794 self.assertEqual(L([1,2,3])[:2], [1,2])
3795 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3796 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3797 # Now do lists and __setitem__
3798 a = L([1,2,3])
3799 a[slice(1, 3)] = [3,2]
3800 self.assertEqual(a, [1,3,2])
3801 a[slice(0, 2, 1)] = [3,1]
3802 self.assertEqual(a, [3,1,2])
3803 a.__setitem__(slice(1, 3), [2,1])
3804 self.assertEqual(a, [3,2,1])
3805 a.__setitem__(slice(0, 2, 1), [2,3])
3806 self.assertEqual(a, [2,3,1])
3807
3808 def test_subtype_resurrection(self):
3809 # Testing resurrection of new-style instance...
3810
3811 class C(object):
3812 container = []
3813
3814 def __del__(self):
3815 # resurrect the instance
3816 C.container.append(self)
3817
3818 c = C()
3819 c.attr = 42
3820
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003821 # The most interesting thing here is whether this blows up, due to
3822 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3823 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003824 del c
3825
3826 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003827 # the last container slot works: that will attempt to delete c again,
3828 # which will cause c to get appended back to the container again
3829 # "during" the del. (On non-CPython implementations, however, __del__
3830 # is typically not called again.)
3831 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003832 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003833 del C.container[-1]
3834 if test_support.check_impl_detail():
3835 test_support.gc_collect()
3836 self.assertEqual(len(C.container), 1)
3837 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003838
3839 # Make c mortal again, so that the test framework with -l doesn't report
3840 # it as a leak.
3841 del C.__del__
3842
3843 def test_slots_trash(self):
3844 # Testing slot trash...
3845 # Deallocating deeply nested slotted trash caused stack overflows
3846 class trash(object):
3847 __slots__ = ['x']
3848 def __init__(self, x):
3849 self.x = x
3850 o = None
3851 for i in xrange(50000):
3852 o = trash(o)
3853 del o
3854
3855 def test_slots_multiple_inheritance(self):
3856 # SF bug 575229, multiple inheritance w/ slots dumps core
3857 class A(object):
3858 __slots__=()
3859 class B(object):
3860 pass
3861 class C(A,B) :
3862 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003863 if test_support.check_impl_detail():
3864 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003865 self.assertTrue(hasattr(C, '__dict__'))
3866 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl48545522008-02-02 10:12:36 +00003867 C().x = 2
3868
3869 def test_rmul(self):
3870 # Testing correct invocation of __rmul__...
3871 # SF patch 592646
3872 class C(object):
3873 def __mul__(self, other):
3874 return "mul"
3875 def __rmul__(self, other):
3876 return "rmul"
3877 a = C()
3878 self.assertEqual(a*2, "mul")
3879 self.assertEqual(a*2.2, "mul")
3880 self.assertEqual(2*a, "rmul")
3881 self.assertEqual(2.2*a, "rmul")
3882
3883 def test_ipow(self):
3884 # Testing correct invocation of __ipow__...
3885 # [SF bug 620179]
3886 class C(object):
3887 def __ipow__(self, other):
3888 pass
3889 a = C()
3890 a **= 2
3891
3892 def test_mutable_bases(self):
3893 # Testing mutable bases...
3894
3895 # stuff that should work:
3896 class C(object):
3897 pass
3898 class C2(object):
3899 def __getattribute__(self, attr):
3900 if attr == 'a':
3901 return 2
3902 else:
3903 return super(C2, self).__getattribute__(attr)
3904 def meth(self):
3905 return 1
3906 class D(C):
3907 pass
3908 class E(D):
3909 pass
3910 d = D()
3911 e = E()
3912 D.__bases__ = (C,)
3913 D.__bases__ = (C2,)
3914 self.assertEqual(d.meth(), 1)
3915 self.assertEqual(e.meth(), 1)
3916 self.assertEqual(d.a, 2)
3917 self.assertEqual(e.a, 2)
3918 self.assertEqual(C2.__subclasses__(), [D])
3919
Georg Brandl48545522008-02-02 10:12:36 +00003920 try:
3921 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003922 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003923 pass
3924 else:
3925 self.fail("shouldn't be able to delete .__bases__")
3926
3927 try:
3928 D.__bases__ = ()
3929 except TypeError, msg:
3930 if str(msg) == "a new-style class can't have only classic bases":
3931 self.fail("wrong error message for .__bases__ = ()")
3932 else:
3933 self.fail("shouldn't be able to set .__bases__ to ()")
3934
3935 try:
3936 D.__bases__ = (D,)
3937 except TypeError:
3938 pass
3939 else:
3940 # actually, we'll have crashed by here...
3941 self.fail("shouldn't be able to create inheritance cycles")
3942
3943 try:
3944 D.__bases__ = (C, C)
3945 except TypeError:
3946 pass
3947 else:
3948 self.fail("didn't detect repeated base classes")
3949
3950 try:
3951 D.__bases__ = (E,)
3952 except TypeError:
3953 pass
3954 else:
3955 self.fail("shouldn't be able to create inheritance cycles")
3956
3957 # let's throw a classic class into the mix:
3958 class Classic:
3959 def meth2(self):
3960 return 3
3961
3962 D.__bases__ = (C, Classic)
3963
3964 self.assertEqual(d.meth2(), 3)
3965 self.assertEqual(e.meth2(), 3)
3966 try:
3967 d.a
3968 except AttributeError:
3969 pass
3970 else:
3971 self.fail("attribute should have vanished")
3972
3973 try:
3974 D.__bases__ = (Classic,)
3975 except TypeError:
3976 pass
3977 else:
3978 self.fail("new-style class must have a new-style base")
3979
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003980 def test_builtin_bases(self):
3981 # Make sure all the builtin types can have their base queried without
3982 # segfaulting. See issue #5787.
3983 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3984 if isinstance(tp, type)]
3985 for tp in builtin_types:
3986 object.__getattribute__(tp, "__bases__")
3987 if tp is not object:
3988 self.assertEqual(len(tp.__bases__), 1, tp)
3989
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003990 class L(list):
3991 pass
3992
3993 class C(object):
3994 pass
3995
3996 class D(C):
3997 pass
3998
3999 try:
4000 L.__bases__ = (dict,)
4001 except TypeError:
4002 pass
4003 else:
4004 self.fail("shouldn't turn list subclass into dict subclass")
4005
4006 try:
4007 list.__bases__ = (dict,)
4008 except TypeError:
4009 pass
4010 else:
4011 self.fail("shouldn't be able to assign to list.__bases__")
4012
4013 try:
4014 D.__bases__ = (C, list)
4015 except TypeError:
4016 pass
4017 else:
4018 assert 0, "best_base calculation found wanting"
4019
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004020
Georg Brandl48545522008-02-02 10:12:36 +00004021 def test_mutable_bases_with_failing_mro(self):
4022 # Testing mutable bases with failing mro...
4023 class WorkOnce(type):
4024 def __new__(self, name, bases, ns):
4025 self.flag = 0
4026 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4027 def mro(self):
4028 if self.flag > 0:
4029 raise RuntimeError, "bozo"
4030 else:
4031 self.flag += 1
4032 return type.mro(self)
4033
4034 class WorkAlways(type):
4035 def mro(self):
4036 # this is here to make sure that .mro()s aren't called
4037 # with an exception set (which was possible at one point).
4038 # An error message will be printed in a debug build.
4039 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004040 return type.mro(self)
4041
Georg Brandl48545522008-02-02 10:12:36 +00004042 class C(object):
4043 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004044
Georg Brandl48545522008-02-02 10:12:36 +00004045 class C2(object):
4046 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004047
Georg Brandl48545522008-02-02 10:12:36 +00004048 class D(C):
4049 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004050
Georg Brandl48545522008-02-02 10:12:36 +00004051 class E(D):
4052 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004053
Georg Brandl48545522008-02-02 10:12:36 +00004054 class F(D):
4055 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004056
Georg Brandl48545522008-02-02 10:12:36 +00004057 class G(D):
4058 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004059
Georg Brandl48545522008-02-02 10:12:36 +00004060 # Immediate subclasses have their mro's adjusted in alphabetical
4061 # order, so E's will get adjusted before adjusting F's fails. We
4062 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004063
Georg Brandl48545522008-02-02 10:12:36 +00004064 E_mro_before = E.__mro__
4065 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004066
Armin Rigofd163f92005-12-29 15:59:19 +00004067 try:
Georg Brandl48545522008-02-02 10:12:36 +00004068 D.__bases__ = (C2,)
4069 except RuntimeError:
4070 self.assertEqual(E.__mro__, E_mro_before)
4071 self.assertEqual(D.__mro__, D_mro_before)
4072 else:
4073 self.fail("exception not propagated")
4074
4075 def test_mutable_bases_catch_mro_conflict(self):
4076 # Testing mutable bases catch mro conflict...
4077 class A(object):
4078 pass
4079
4080 class B(object):
4081 pass
4082
4083 class C(A, B):
4084 pass
4085
4086 class D(A, B):
4087 pass
4088
4089 class E(C, D):
4090 pass
4091
4092 try:
4093 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004094 except TypeError:
4095 pass
4096 else:
Georg Brandl48545522008-02-02 10:12:36 +00004097 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004098
Georg Brandl48545522008-02-02 10:12:36 +00004099 def test_mutable_names(self):
4100 # Testing mutable names...
4101 class C(object):
4102 pass
4103
4104 # C.__module__ could be 'test_descr' or '__main__'
4105 mod = C.__module__
4106
4107 C.__name__ = 'D'
4108 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4109
4110 C.__name__ = 'D.E'
4111 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4112
4113 def test_subclass_right_op(self):
4114 # Testing correct dispatch of subclass overloading __r<op>__...
4115
4116 # This code tests various cases where right-dispatch of a subclass
4117 # should be preferred over left-dispatch of a base class.
4118
4119 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4120
4121 class B(int):
4122 def __floordiv__(self, other):
4123 return "B.__floordiv__"
4124 def __rfloordiv__(self, other):
4125 return "B.__rfloordiv__"
4126
4127 self.assertEqual(B(1) // 1, "B.__floordiv__")
4128 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4129
4130 # Case 2: subclass of object; this is just the baseline for case 3
4131
4132 class C(object):
4133 def __floordiv__(self, other):
4134 return "C.__floordiv__"
4135 def __rfloordiv__(self, other):
4136 return "C.__rfloordiv__"
4137
4138 self.assertEqual(C() // 1, "C.__floordiv__")
4139 self.assertEqual(1 // C(), "C.__rfloordiv__")
4140
4141 # Case 3: subclass of new-style class; here it gets interesting
4142
4143 class D(C):
4144 def __floordiv__(self, other):
4145 return "D.__floordiv__"
4146 def __rfloordiv__(self, other):
4147 return "D.__rfloordiv__"
4148
4149 self.assertEqual(D() // C(), "D.__floordiv__")
4150 self.assertEqual(C() // D(), "D.__rfloordiv__")
4151
4152 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4153
4154 class E(C):
4155 pass
4156
4157 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4158
4159 self.assertEqual(E() // 1, "C.__floordiv__")
4160 self.assertEqual(1 // E(), "C.__rfloordiv__")
4161 self.assertEqual(E() // C(), "C.__floordiv__")
4162 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4163
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004164 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004165 def test_meth_class_get(self):
4166 # Testing __get__ method of METH_CLASS C methods...
4167 # Full coverage of descrobject.c::classmethod_get()
4168
4169 # Baseline
4170 arg = [1, 2, 3]
4171 res = {1: None, 2: None, 3: None}
4172 self.assertEqual(dict.fromkeys(arg), res)
4173 self.assertEqual({}.fromkeys(arg), res)
4174
4175 # Now get the descriptor
4176 descr = dict.__dict__["fromkeys"]
4177
4178 # More baseline using the descriptor directly
4179 self.assertEqual(descr.__get__(None, dict)(arg), res)
4180 self.assertEqual(descr.__get__({})(arg), res)
4181
4182 # Now check various error cases
4183 try:
4184 descr.__get__(None, None)
4185 except TypeError:
4186 pass
4187 else:
4188 self.fail("shouldn't have allowed descr.__get__(None, None)")
4189 try:
4190 descr.__get__(42)
4191 except TypeError:
4192 pass
4193 else:
4194 self.fail("shouldn't have allowed descr.__get__(42)")
4195 try:
4196 descr.__get__(None, 42)
4197 except TypeError:
4198 pass
4199 else:
4200 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4201 try:
4202 descr.__get__(None, int)
4203 except TypeError:
4204 pass
4205 else:
4206 self.fail("shouldn't have allowed descr.__get__(None, int)")
4207
4208 def test_isinst_isclass(self):
4209 # Testing proxy isinstance() and isclass()...
4210 class Proxy(object):
4211 def __init__(self, obj):
4212 self.__obj = obj
4213 def __getattribute__(self, name):
4214 if name.startswith("_Proxy__"):
4215 return object.__getattribute__(self, name)
4216 else:
4217 return getattr(self.__obj, name)
4218 # Test with a classic class
4219 class C:
4220 pass
4221 a = C()
4222 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004223 self.assertTrue(isinstance(a, C)) # Baseline
4224 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004225 # Test with a classic subclass
4226 class D(C):
4227 pass
4228 a = D()
4229 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004230 self.assertTrue(isinstance(a, C)) # Baseline
4231 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004232 # Test with a new-style class
4233 class C(object):
4234 pass
4235 a = C()
4236 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004237 self.assertTrue(isinstance(a, C)) # Baseline
4238 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004239 # Test with a new-style subclass
4240 class D(C):
4241 pass
4242 a = D()
4243 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004244 self.assertTrue(isinstance(a, C)) # Baseline
4245 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004246
4247 def test_proxy_super(self):
4248 # Testing super() for a proxy object...
4249 class Proxy(object):
4250 def __init__(self, obj):
4251 self.__obj = obj
4252 def __getattribute__(self, name):
4253 if name.startswith("_Proxy__"):
4254 return object.__getattribute__(self, name)
4255 else:
4256 return getattr(self.__obj, name)
4257
4258 class B(object):
4259 def f(self):
4260 return "B.f"
4261
4262 class C(B):
4263 def f(self):
4264 return super(C, self).f() + "->C.f"
4265
4266 obj = C()
4267 p = Proxy(obj)
4268 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4269
4270 def test_carloverre(self):
4271 # Testing prohibition of Carlo Verre's hack...
4272 try:
4273 object.__setattr__(str, "foo", 42)
4274 except TypeError:
4275 pass
4276 else:
4277 self.fail("Carlo Verre __setattr__ suceeded!")
4278 try:
4279 object.__delattr__(str, "lower")
4280 except TypeError:
4281 pass
4282 else:
4283 self.fail("Carlo Verre __delattr__ succeeded!")
4284
4285 def test_weakref_segfault(self):
4286 # Testing weakref segfault...
4287 # SF 742911
4288 import weakref
4289
4290 class Provoker:
4291 def __init__(self, referrent):
4292 self.ref = weakref.ref(referrent)
4293
4294 def __del__(self):
4295 x = self.ref()
4296
4297 class Oops(object):
4298 pass
4299
4300 o = Oops()
4301 o.whatever = Provoker(o)
4302 del o
4303
4304 def test_wrapper_segfault(self):
4305 # SF 927248: deeply nested wrappers could cause stack overflow
4306 f = lambda:None
4307 for i in xrange(1000000):
4308 f = f.__call__
4309 f = None
4310
4311 def test_file_fault(self):
4312 # Testing sys.stdout is changed in getattr...
4313 import sys
4314 class StdoutGuard:
4315 def __getattr__(self, attr):
4316 sys.stdout = sys.__stdout__
4317 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4318 sys.stdout = StdoutGuard()
4319 try:
4320 print "Oops!"
4321 except RuntimeError:
4322 pass
4323
4324 def test_vicious_descriptor_nonsense(self):
4325 # Testing vicious_descriptor_nonsense...
4326
4327 # A potential segfault spotted by Thomas Wouters in mail to
4328 # python-dev 2003-04-17, turned into an example & fixed by Michael
4329 # Hudson just less than four months later...
4330
4331 class Evil(object):
4332 def __hash__(self):
4333 return hash('attr')
4334 def __eq__(self, other):
4335 del C.attr
4336 return 0
4337
4338 class Descr(object):
4339 def __get__(self, ob, type=None):
4340 return 1
4341
4342 class C(object):
4343 attr = Descr()
4344
4345 c = C()
4346 c.__dict__[Evil()] = 0
4347
4348 self.assertEqual(c.attr, 1)
4349 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004350 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004351 self.assertEqual(hasattr(c, 'attr'), False)
4352
4353 def test_init(self):
4354 # SF 1155938
4355 class Foo(object):
4356 def __init__(self):
4357 return 10
4358 try:
4359 Foo()
4360 except TypeError:
4361 pass
4362 else:
4363 self.fail("did not test __init__() for None return")
4364
4365 def test_method_wrapper(self):
4366 # Testing method-wrapper objects...
4367 # <type 'method-wrapper'> did not support any reflection before 2.5
4368
4369 l = []
4370 self.assertEqual(l.__add__, l.__add__)
4371 self.assertEqual(l.__add__, [].__add__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004372 self.assertTrue(l.__add__ != [5].__add__)
4373 self.assertTrue(l.__add__ != l.__mul__)
4374 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004375 if hasattr(l.__add__, '__self__'):
4376 # CPython
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004377 self.assertTrue(l.__add__.__self__ is l)
4378 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004379 else:
4380 # Python implementations where [].__add__ is a normal bound method
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004381 self.assertTrue(l.__add__.im_self is l)
4382 self.assertTrue(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004383 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4384 try:
4385 hash(l.__add__)
4386 except TypeError:
4387 pass
4388 else:
4389 self.fail("no TypeError from hash([].__add__)")
4390
4391 t = ()
4392 t += (7,)
4393 self.assertEqual(t.__add__, (7,).__add__)
4394 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4395
4396 def test_not_implemented(self):
4397 # Testing NotImplemented...
4398 # all binary methods should be able to return a NotImplemented
4399 import sys
4400 import types
4401 import operator
4402
4403 def specialmethod(self, other):
4404 return NotImplemented
4405
4406 def check(expr, x, y):
4407 try:
4408 exec expr in {'x': x, 'y': y, 'operator': operator}
4409 except TypeError:
4410 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004411 else:
Georg Brandl48545522008-02-02 10:12:36 +00004412 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004413
Georg Brandl48545522008-02-02 10:12:36 +00004414 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4415 # TypeErrors
4416 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4417 # ValueErrors instead of TypeErrors
4418 for metaclass in [type, types.ClassType]:
4419 for name, expr, iexpr in [
4420 ('__add__', 'x + y', 'x += y'),
4421 ('__sub__', 'x - y', 'x -= y'),
4422 ('__mul__', 'x * y', 'x *= y'),
4423 ('__truediv__', 'operator.truediv(x, y)', None),
4424 ('__floordiv__', 'operator.floordiv(x, y)', None),
4425 ('__div__', 'x / y', 'x /= y'),
4426 ('__mod__', 'x % y', 'x %= y'),
4427 ('__divmod__', 'divmod(x, y)', None),
4428 ('__pow__', 'x ** y', 'x **= y'),
4429 ('__lshift__', 'x << y', 'x <<= y'),
4430 ('__rshift__', 'x >> y', 'x >>= y'),
4431 ('__and__', 'x & y', 'x &= y'),
4432 ('__or__', 'x | y', 'x |= y'),
4433 ('__xor__', 'x ^ y', 'x ^= y'),
4434 ('__coerce__', 'coerce(x, y)', None)]:
4435 if name == '__coerce__':
4436 rname = name
4437 else:
4438 rname = '__r' + name[2:]
4439 A = metaclass('A', (), {name: specialmethod})
4440 B = metaclass('B', (), {rname: specialmethod})
4441 a = A()
4442 b = B()
4443 check(expr, a, a)
4444 check(expr, a, b)
4445 check(expr, b, a)
4446 check(expr, b, b)
4447 check(expr, a, N1)
4448 check(expr, a, N2)
4449 check(expr, N1, b)
4450 check(expr, N2, b)
4451 if iexpr:
4452 check(iexpr, a, a)
4453 check(iexpr, a, b)
4454 check(iexpr, b, a)
4455 check(iexpr, b, b)
4456 check(iexpr, a, N1)
4457 check(iexpr, a, N2)
4458 iname = '__i' + name[2:]
4459 C = metaclass('C', (), {iname: specialmethod})
4460 c = C()
4461 check(iexpr, c, a)
4462 check(iexpr, c, b)
4463 check(iexpr, c, N1)
4464 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004465
Georg Brandl48545522008-02-02 10:12:36 +00004466 def test_assign_slice(self):
4467 # ceval.c's assign_slice used to check for
4468 # tp->tp_as_sequence->sq_slice instead of
4469 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004470
Georg Brandl48545522008-02-02 10:12:36 +00004471 class C(object):
4472 def __setslice__(self, start, stop, value):
4473 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004474
Georg Brandl48545522008-02-02 10:12:36 +00004475 c = C()
4476 c[1:2] = 3
4477 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004478
Benjamin Peterson273c2332008-11-17 22:39:09 +00004479 def test_getattr_hooks(self):
4480 # issue 4230
4481
4482 class Descriptor(object):
4483 counter = 0
4484 def __get__(self, obj, objtype=None):
4485 def getter(name):
4486 self.counter += 1
4487 raise AttributeError(name)
4488 return getter
4489
4490 descr = Descriptor()
4491 class A(object):
4492 __getattribute__ = descr
4493 class B(object):
4494 __getattr__ = descr
4495 class C(object):
4496 __getattribute__ = descr
4497 __getattr__ = descr
4498
4499 self.assertRaises(AttributeError, getattr, A(), "attr")
4500 self.assertEquals(descr.counter, 1)
4501 self.assertRaises(AttributeError, getattr, B(), "attr")
4502 self.assertEquals(descr.counter, 2)
4503 self.assertRaises(AttributeError, getattr, C(), "attr")
4504 self.assertEquals(descr.counter, 4)
4505
4506 import gc
4507 class EvilGetattribute(object):
4508 # This used to segfault
4509 def __getattr__(self, name):
4510 raise AttributeError(name)
4511 def __getattribute__(self, name):
4512 del EvilGetattribute.__getattr__
4513 for i in range(5):
4514 gc.collect()
4515 raise AttributeError(name)
4516
4517 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4518
Guido van Rossum9acc3872008-01-23 23:23:43 +00004519
Georg Brandl48545522008-02-02 10:12:36 +00004520class DictProxyTests(unittest.TestCase):
4521 def setUp(self):
4522 class C(object):
4523 def meth(self):
4524 pass
4525 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004526
Georg Brandl48545522008-02-02 10:12:36 +00004527 def test_iter_keys(self):
4528 # Testing dict-proxy iterkeys...
4529 keys = [ key for key in self.C.__dict__.iterkeys() ]
4530 keys.sort()
4531 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4532 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004533
Georg Brandl48545522008-02-02 10:12:36 +00004534 def test_iter_values(self):
4535 # Testing dict-proxy itervalues...
4536 values = [ values for values in self.C.__dict__.itervalues() ]
4537 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004538
Georg Brandl48545522008-02-02 10:12:36 +00004539 def test_iter_items(self):
4540 # Testing dict-proxy iteritems...
4541 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4542 keys.sort()
4543 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4544 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004545
Georg Brandl48545522008-02-02 10:12:36 +00004546 def test_dict_type_with_metaclass(self):
4547 # Testing type of __dict__ when __metaclass__ set...
4548 class B(object):
4549 pass
4550 class M(type):
4551 pass
4552 class C:
4553 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4554 __metaclass__ = M
4555 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004556
Guido van Rossum9acc3872008-01-23 23:23:43 +00004557
Georg Brandl48545522008-02-02 10:12:36 +00004558class PTypesLongInitTest(unittest.TestCase):
4559 # This is in its own TestCase so that it can be run before any other tests.
4560 def test_pytype_long_ready(self):
4561 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004562
Georg Brandl48545522008-02-02 10:12:36 +00004563 # This dumps core when SF bug 551412 isn't fixed --
4564 # but only when test_descr.py is run separately.
4565 # (That can't be helped -- as soon as PyType_Ready()
4566 # is called for PyLong_Type, the bug is gone.)
4567 class UserLong(object):
4568 def __pow__(self, *args):
4569 pass
4570 try:
4571 pow(0L, UserLong(), 0L)
4572 except:
4573 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004574
Georg Brandl48545522008-02-02 10:12:36 +00004575 # Another segfault only when run early
4576 # (before PyType_Ready(tuple) is called)
4577 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004578
4579
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004580def test_main():
Georg Brandl48545522008-02-02 10:12:36 +00004581 # Run all local test cases, with PTypesLongInitTest first.
4582 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4583 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004584
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004585if __name__ == "__main__":
4586 test_main()