blob: 87d30eb9fafe105542b863d90428ebfb5eafcd4e [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
Benjamin Peterson4895af42009-12-13 16:36:53 +00001225 def test_metaclass_cmp(self):
1226 # See bug 7491.
1227 class M(type):
1228 def __cmp__(self, other):
1229 return -1
1230 class X(object):
1231 __metaclass__ = M
1232 self.assertTrue(X < M)
1233
Georg Brandl48545522008-02-02 10:12:36 +00001234 def test_dynamics(self):
1235 # Testing class attribute propagation...
1236 class D(object):
1237 pass
1238 class E(D):
1239 pass
1240 class F(D):
1241 pass
1242 D.foo = 1
1243 self.assertEqual(D.foo, 1)
1244 # Test that dynamic attributes are inherited
1245 self.assertEqual(E.foo, 1)
1246 self.assertEqual(F.foo, 1)
1247 # Test dynamic instances
1248 class C(object):
1249 pass
1250 a = C()
1251 self.assertFalse(hasattr(a, "foobar"))
1252 C.foobar = 2
1253 self.assertEqual(a.foobar, 2)
1254 C.method = lambda self: 42
1255 self.assertEqual(a.method(), 42)
1256 C.__repr__ = lambda self: "C()"
1257 self.assertEqual(repr(a), "C()")
1258 C.__int__ = lambda self: 100
1259 self.assertEqual(int(a), 100)
1260 self.assertEqual(a.foobar, 2)
1261 self.assertFalse(hasattr(a, "spam"))
1262 def mygetattr(self, name):
1263 if name == "spam":
1264 return "spam"
1265 raise AttributeError
1266 C.__getattr__ = mygetattr
1267 self.assertEqual(a.spam, "spam")
1268 a.new = 12
1269 self.assertEqual(a.new, 12)
1270 def mysetattr(self, name, value):
1271 if name == "spam":
1272 raise AttributeError
1273 return object.__setattr__(self, name, value)
1274 C.__setattr__ = mysetattr
1275 try:
1276 a.spam = "not spam"
1277 except AttributeError:
1278 pass
1279 else:
1280 self.fail("expected AttributeError")
1281 self.assertEqual(a.spam, "spam")
1282 class D(C):
1283 pass
1284 d = D()
1285 d.foo = 1
1286 self.assertEqual(d.foo, 1)
1287
1288 # Test handling of int*seq and seq*int
1289 class I(int):
1290 pass
1291 self.assertEqual("a"*I(2), "aa")
1292 self.assertEqual(I(2)*"a", "aa")
1293 self.assertEqual(2*I(3), 6)
1294 self.assertEqual(I(3)*2, 6)
1295 self.assertEqual(I(3)*I(2), 6)
1296
1297 # Test handling of long*seq and seq*long
1298 class L(long):
1299 pass
1300 self.assertEqual("a"*L(2L), "aa")
1301 self.assertEqual(L(2L)*"a", "aa")
1302 self.assertEqual(2*L(3), 6)
1303 self.assertEqual(L(3)*2, 6)
1304 self.assertEqual(L(3)*L(2), 6)
1305
1306 # Test comparison of classes with dynamic metaclasses
1307 class dynamicmetaclass(type):
1308 pass
1309 class someclass:
1310 __metaclass__ = dynamicmetaclass
1311 self.assertNotEqual(someclass, object)
1312
1313 def test_errors(self):
1314 # Testing errors...
1315 try:
1316 class C(list, dict):
1317 pass
1318 except TypeError:
1319 pass
1320 else:
1321 self.fail("inheritance from both list and dict should be illegal")
1322
1323 try:
1324 class C(object, None):
1325 pass
1326 except TypeError:
1327 pass
1328 else:
1329 self.fail("inheritance from non-type should be illegal")
1330 class Classic:
1331 pass
1332
1333 try:
1334 class C(type(len)):
1335 pass
1336 except TypeError:
1337 pass
1338 else:
1339 self.fail("inheritance from CFunction should be illegal")
1340
1341 try:
1342 class C(object):
1343 __slots__ = 1
1344 except TypeError:
1345 pass
1346 else:
1347 self.fail("__slots__ = 1 should be illegal")
1348
1349 try:
1350 class C(object):
1351 __slots__ = [1]
1352 except TypeError:
1353 pass
1354 else:
1355 self.fail("__slots__ = [1] should be illegal")
1356
1357 class M1(type):
1358 pass
1359 class M2(type):
1360 pass
1361 class A1(object):
1362 __metaclass__ = M1
1363 class A2(object):
1364 __metaclass__ = M2
1365 try:
1366 class B(A1, A2):
1367 pass
1368 except TypeError:
1369 pass
1370 else:
1371 self.fail("finding the most derived metaclass should have failed")
1372
1373 def test_classmethods(self):
1374 # Testing class methods...
1375 class C(object):
1376 def foo(*a): return a
1377 goo = classmethod(foo)
1378 c = C()
1379 self.assertEqual(C.goo(1), (C, 1))
1380 self.assertEqual(c.goo(1), (C, 1))
1381 self.assertEqual(c.foo(1), (c, 1))
1382 class D(C):
1383 pass
1384 d = D()
1385 self.assertEqual(D.goo(1), (D, 1))
1386 self.assertEqual(d.goo(1), (D, 1))
1387 self.assertEqual(d.foo(1), (d, 1))
1388 self.assertEqual(D.foo(d, 1), (d, 1))
1389 # Test for a specific crash (SF bug 528132)
1390 def f(cls, arg): return (cls, arg)
1391 ff = classmethod(f)
1392 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1393 self.assertEqual(ff.__get__(0)(42), (int, 42))
1394
1395 # Test super() with classmethods (SF bug 535444)
1396 self.assertEqual(C.goo.im_self, C)
1397 self.assertEqual(D.goo.im_self, D)
1398 self.assertEqual(super(D,D).goo.im_self, D)
1399 self.assertEqual(super(D,d).goo.im_self, D)
1400 self.assertEqual(super(D,D).goo(), (D,))
1401 self.assertEqual(super(D,d).goo(), (D,))
1402
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001403 # Verify that a non-callable will raise
1404 meth = classmethod(1).__get__(1)
1405 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001406
1407 # Verify that classmethod() doesn't allow keyword args
1408 try:
1409 classmethod(f, kw=1)
1410 except TypeError:
1411 pass
1412 else:
1413 self.fail("classmethod shouldn't accept keyword args")
1414
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001415 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001416 def test_classmethods_in_c(self):
1417 # Testing C-based class methods...
1418 import xxsubtype as spam
1419 a = (1, 2, 3)
1420 d = {'abc': 123}
1421 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1422 self.assertEqual(x, spam.spamlist)
1423 self.assertEqual(a, a1)
1424 self.assertEqual(d, d1)
1425 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1426 self.assertEqual(x, spam.spamlist)
1427 self.assertEqual(a, a1)
1428 self.assertEqual(d, d1)
1429
1430 def test_staticmethods(self):
1431 # Testing static methods...
1432 class C(object):
1433 def foo(*a): return a
1434 goo = staticmethod(foo)
1435 c = C()
1436 self.assertEqual(C.goo(1), (1,))
1437 self.assertEqual(c.goo(1), (1,))
1438 self.assertEqual(c.foo(1), (c, 1,))
1439 class D(C):
1440 pass
1441 d = D()
1442 self.assertEqual(D.goo(1), (1,))
1443 self.assertEqual(d.goo(1), (1,))
1444 self.assertEqual(d.foo(1), (d, 1))
1445 self.assertEqual(D.foo(d, 1), (d, 1))
1446
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001447 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001448 def test_staticmethods_in_c(self):
1449 # Testing C-based static methods...
1450 import xxsubtype as spam
1451 a = (1, 2, 3)
1452 d = {"abc": 123}
1453 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1454 self.assertEqual(x, None)
1455 self.assertEqual(a, a1)
1456 self.assertEqual(d, d1)
1457 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1458 self.assertEqual(x, None)
1459 self.assertEqual(a, a1)
1460 self.assertEqual(d, d1)
1461
1462 def test_classic(self):
1463 # Testing classic classes...
1464 class C:
1465 def foo(*a): return a
1466 goo = classmethod(foo)
1467 c = C()
1468 self.assertEqual(C.goo(1), (C, 1))
1469 self.assertEqual(c.goo(1), (C, 1))
1470 self.assertEqual(c.foo(1), (c, 1))
1471 class D(C):
1472 pass
1473 d = D()
1474 self.assertEqual(D.goo(1), (D, 1))
1475 self.assertEqual(d.goo(1), (D, 1))
1476 self.assertEqual(d.foo(1), (d, 1))
1477 self.assertEqual(D.foo(d, 1), (d, 1))
1478 class E: # *not* subclassing from C
1479 foo = C.foo
1480 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001481 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001482
1483 def test_compattr(self):
1484 # Testing computed attributes...
1485 class C(object):
1486 class computed_attribute(object):
1487 def __init__(self, get, set=None, delete=None):
1488 self.__get = get
1489 self.__set = set
1490 self.__delete = delete
1491 def __get__(self, obj, type=None):
1492 return self.__get(obj)
1493 def __set__(self, obj, value):
1494 return self.__set(obj, value)
1495 def __delete__(self, obj):
1496 return self.__delete(obj)
1497 def __init__(self):
1498 self.__x = 0
1499 def __get_x(self):
1500 x = self.__x
1501 self.__x = x+1
1502 return x
1503 def __set_x(self, x):
1504 self.__x = x
1505 def __delete_x(self):
1506 del self.__x
1507 x = computed_attribute(__get_x, __set_x, __delete_x)
1508 a = C()
1509 self.assertEqual(a.x, 0)
1510 self.assertEqual(a.x, 1)
1511 a.x = 10
1512 self.assertEqual(a.x, 10)
1513 self.assertEqual(a.x, 11)
1514 del a.x
1515 self.assertEqual(hasattr(a, 'x'), 0)
1516
1517 def test_newslots(self):
1518 # Testing __new__ slot override...
1519 class C(list):
1520 def __new__(cls):
1521 self = list.__new__(cls)
1522 self.foo = 1
1523 return self
1524 def __init__(self):
1525 self.foo = self.foo + 2
1526 a = C()
1527 self.assertEqual(a.foo, 3)
1528 self.assertEqual(a.__class__, C)
1529 class D(C):
1530 pass
1531 b = D()
1532 self.assertEqual(b.foo, 3)
1533 self.assertEqual(b.__class__, D)
1534
1535 def test_altmro(self):
1536 # Testing mro() and overriding it...
1537 class A(object):
1538 def f(self): return "A"
1539 class B(A):
1540 pass
1541 class C(A):
1542 def f(self): return "C"
1543 class D(B, C):
1544 pass
1545 self.assertEqual(D.mro(), [D, B, C, A, object])
1546 self.assertEqual(D.__mro__, (D, B, C, A, object))
1547 self.assertEqual(D().f(), "C")
1548
1549 class PerverseMetaType(type):
1550 def mro(cls):
1551 L = type.mro(cls)
1552 L.reverse()
1553 return L
1554 class X(D,B,C,A):
1555 __metaclass__ = PerverseMetaType
1556 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1557 self.assertEqual(X().f(), "A")
1558
1559 try:
1560 class X(object):
1561 class __metaclass__(type):
1562 def mro(self):
1563 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001564 # In CPython, the class creation above already raises
1565 # TypeError, as a protection against the fact that
1566 # instances of X would segfault it. In other Python
1567 # implementations it would be ok to let the class X
1568 # be created, but instead get a clean TypeError on the
1569 # __setitem__ below.
1570 x = object.__new__(X)
1571 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001572 except TypeError:
1573 pass
1574 else:
1575 self.fail("devious mro() return not caught")
1576
1577 try:
1578 class X(object):
1579 class __metaclass__(type):
1580 def mro(self):
1581 return [1]
1582 except TypeError:
1583 pass
1584 else:
1585 self.fail("non-class mro() return not caught")
1586
1587 try:
1588 class X(object):
1589 class __metaclass__(type):
1590 def mro(self):
1591 return 1
1592 except TypeError:
1593 pass
1594 else:
1595 self.fail("non-sequence mro() return not caught")
1596
1597 def test_overloading(self):
1598 # Testing operator overloading...
1599
1600 class B(object):
1601 "Intermediate class because object doesn't have a __setattr__"
1602
1603 class C(B):
1604 def __getattr__(self, name):
1605 if name == "foo":
1606 return ("getattr", name)
1607 else:
1608 raise AttributeError
1609 def __setattr__(self, name, value):
1610 if name == "foo":
1611 self.setattr = (name, value)
1612 else:
1613 return B.__setattr__(self, name, value)
1614 def __delattr__(self, name):
1615 if name == "foo":
1616 self.delattr = name
1617 else:
1618 return B.__delattr__(self, name)
1619
1620 def __getitem__(self, key):
1621 return ("getitem", key)
1622 def __setitem__(self, key, value):
1623 self.setitem = (key, value)
1624 def __delitem__(self, key):
1625 self.delitem = key
1626
1627 def __getslice__(self, i, j):
1628 return ("getslice", i, j)
1629 def __setslice__(self, i, j, value):
1630 self.setslice = (i, j, value)
1631 def __delslice__(self, i, j):
1632 self.delslice = (i, j)
1633
1634 a = C()
1635 self.assertEqual(a.foo, ("getattr", "foo"))
1636 a.foo = 12
1637 self.assertEqual(a.setattr, ("foo", 12))
1638 del a.foo
1639 self.assertEqual(a.delattr, "foo")
1640
1641 self.assertEqual(a[12], ("getitem", 12))
1642 a[12] = 21
1643 self.assertEqual(a.setitem, (12, 21))
1644 del a[12]
1645 self.assertEqual(a.delitem, 12)
1646
1647 self.assertEqual(a[0:10], ("getslice", 0, 10))
1648 a[0:10] = "foo"
1649 self.assertEqual(a.setslice, (0, 10, "foo"))
1650 del a[0:10]
1651 self.assertEqual(a.delslice, (0, 10))
1652
1653 def test_methods(self):
1654 # Testing methods...
1655 class C(object):
1656 def __init__(self, x):
1657 self.x = x
1658 def foo(self):
1659 return self.x
1660 c1 = C(1)
1661 self.assertEqual(c1.foo(), 1)
1662 class D(C):
1663 boo = C.foo
1664 goo = c1.foo
1665 d2 = D(2)
1666 self.assertEqual(d2.foo(), 2)
1667 self.assertEqual(d2.boo(), 2)
1668 self.assertEqual(d2.goo(), 1)
1669 class E(object):
1670 foo = C.foo
1671 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001672 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001673
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001674 def test_special_method_lookup(self):
1675 # The lookup of special methods bypasses __getattr__ and
1676 # __getattribute__, but they still can be descriptors.
1677
1678 def run_context(manager):
1679 with manager:
1680 pass
1681 def iden(self):
1682 return self
1683 def hello(self):
1684 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001685 def empty_seq(self):
1686 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001687 def zero(self):
1688 return 0
1689 def stop(self):
1690 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001691 def return_true(self, thing=None):
1692 return True
1693 def do_isinstance(obj):
1694 return isinstance(int, obj)
1695 def do_issubclass(obj):
1696 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001697 def swallow(*args):
1698 pass
1699 def do_dict_missing(checker):
1700 class DictSub(checker.__class__, dict):
1701 pass
1702 self.assertEqual(DictSub()["hi"], 4)
1703 def some_number(self_, key):
1704 self.assertEqual(key, "hi")
1705 return 4
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001706
1707 # It would be nice to have every special method tested here, but I'm
1708 # only listing the ones I can remember outside of typeobject.c, since it
1709 # does it right.
1710 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001711 ("__unicode__", unicode, hello, set(), {}),
1712 ("__reversed__", reversed, empty_seq, set(), {}),
1713 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001714 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001715 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1716 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001717 ("__missing__", do_dict_missing, some_number,
1718 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001719 ("__subclasscheck__", do_issubclass, return_true,
1720 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001721 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1722 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001723 ]
1724
1725 class Checker(object):
1726 def __getattr__(self, attr, test=self):
1727 test.fail("__getattr__ called with {0}".format(attr))
1728 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001729 if attr not in ok:
1730 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001731 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001732 class SpecialDescr(object):
1733 def __init__(self, impl):
1734 self.impl = impl
1735 def __get__(self, obj, owner):
1736 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001737 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001738 class MyException(Exception):
1739 pass
1740 class ErrDescr(object):
1741 def __get__(self, obj, owner):
1742 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001743
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001744 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001745 class X(Checker):
1746 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001747 for attr, obj in env.iteritems():
1748 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001749 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001750 runner(X())
1751
1752 record = []
1753 class X(Checker):
1754 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001755 for attr, obj in env.iteritems():
1756 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001757 setattr(X, name, SpecialDescr(meth_impl))
1758 runner(X())
1759 self.assertEqual(record, [1], name)
1760
Benjamin Peterson87e50062009-05-25 02:40:21 +00001761 class X(Checker):
1762 pass
1763 for attr, obj in env.iteritems():
1764 setattr(X, attr, obj)
1765 setattr(X, name, ErrDescr())
1766 try:
1767 runner(X())
1768 except MyException:
1769 pass
1770 else:
1771 self.fail("{0!r} didn't raise".format(name))
1772
Georg Brandl48545522008-02-02 10:12:36 +00001773 def test_specials(self):
1774 # Testing special operators...
1775 # Test operators like __hash__ for which a built-in default exists
1776
1777 # Test the default behavior for static classes
1778 class C(object):
1779 def __getitem__(self, i):
1780 if 0 <= i < 10: return i
1781 raise IndexError
1782 c1 = C()
1783 c2 = C()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001784 self.assertTrue(not not c1) # What?
Georg Brandl48545522008-02-02 10:12:36 +00001785 self.assertNotEqual(id(c1), id(c2))
1786 hash(c1)
1787 hash(c2)
1788 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1789 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001790 self.assertTrue(c1 != c2)
1791 self.assertTrue(not c1 != c1)
1792 self.assertTrue(not c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001793 # Note that the module name appears in str/repr, and that varies
1794 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001795 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001796 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001797 self.assertTrue(-1 not in c1)
Georg Brandl48545522008-02-02 10:12:36 +00001798 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001799 self.assertTrue(i in c1)
Georg Brandl48545522008-02-02 10:12:36 +00001800 self.assertFalse(10 in c1)
1801 # Test the default behavior for dynamic classes
1802 class D(object):
1803 def __getitem__(self, i):
1804 if 0 <= i < 10: return i
1805 raise IndexError
1806 d1 = D()
1807 d2 = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001808 self.assertTrue(not not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001809 self.assertNotEqual(id(d1), id(d2))
1810 hash(d1)
1811 hash(d2)
1812 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1813 self.assertEqual(d1, d1)
1814 self.assertNotEqual(d1, d2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001815 self.assertTrue(not d1 != d1)
1816 self.assertTrue(not d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001817 # Note that the module name appears in str/repr, and that varies
1818 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001819 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001820 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001821 self.assertTrue(-1 not in d1)
Georg Brandl48545522008-02-02 10:12:36 +00001822 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001823 self.assertTrue(i in d1)
Georg Brandl48545522008-02-02 10:12:36 +00001824 self.assertFalse(10 in d1)
1825 # Test overridden behavior for static classes
1826 class Proxy(object):
1827 def __init__(self, x):
1828 self.x = x
1829 def __nonzero__(self):
1830 return not not self.x
1831 def __hash__(self):
1832 return hash(self.x)
1833 def __eq__(self, other):
1834 return self.x == other
1835 def __ne__(self, other):
1836 return self.x != other
1837 def __cmp__(self, other):
1838 return cmp(self.x, other.x)
1839 def __str__(self):
1840 return "Proxy:%s" % self.x
1841 def __repr__(self):
1842 return "Proxy(%r)" % self.x
1843 def __contains__(self, value):
1844 return value in self.x
1845 p0 = Proxy(0)
1846 p1 = Proxy(1)
1847 p_1 = Proxy(-1)
1848 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001849 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001850 self.assertEqual(hash(p0), hash(0))
1851 self.assertEqual(p0, p0)
1852 self.assertNotEqual(p0, p1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001853 self.assertTrue(not p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001854 self.assertEqual(not p0, p1)
1855 self.assertEqual(cmp(p0, p1), -1)
1856 self.assertEqual(cmp(p0, p0), 0)
1857 self.assertEqual(cmp(p0, p_1), 1)
1858 self.assertEqual(str(p0), "Proxy:0")
1859 self.assertEqual(repr(p0), "Proxy(0)")
1860 p10 = Proxy(range(10))
1861 self.assertFalse(-1 in p10)
1862 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001863 self.assertTrue(i in p10)
Georg Brandl48545522008-02-02 10:12:36 +00001864 self.assertFalse(10 in p10)
1865 # Test overridden behavior for dynamic classes
1866 class DProxy(object):
1867 def __init__(self, x):
1868 self.x = x
1869 def __nonzero__(self):
1870 return not not self.x
1871 def __hash__(self):
1872 return hash(self.x)
1873 def __eq__(self, other):
1874 return self.x == other
1875 def __ne__(self, other):
1876 return self.x != other
1877 def __cmp__(self, other):
1878 return cmp(self.x, other.x)
1879 def __str__(self):
1880 return "DProxy:%s" % self.x
1881 def __repr__(self):
1882 return "DProxy(%r)" % self.x
1883 def __contains__(self, value):
1884 return value in self.x
1885 p0 = DProxy(0)
1886 p1 = DProxy(1)
1887 p_1 = DProxy(-1)
1888 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001889 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001890 self.assertEqual(hash(p0), hash(0))
1891 self.assertEqual(p0, p0)
1892 self.assertNotEqual(p0, p1)
1893 self.assertNotEqual(not p0, p0)
1894 self.assertEqual(not p0, p1)
1895 self.assertEqual(cmp(p0, p1), -1)
1896 self.assertEqual(cmp(p0, p0), 0)
1897 self.assertEqual(cmp(p0, p_1), 1)
1898 self.assertEqual(str(p0), "DProxy:0")
1899 self.assertEqual(repr(p0), "DProxy(0)")
1900 p10 = DProxy(range(10))
1901 self.assertFalse(-1 in p10)
1902 for i in range(10):
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001903 self.assertTrue(i in p10)
Georg Brandl48545522008-02-02 10:12:36 +00001904 self.assertFalse(10 in p10)
1905
1906 # Safety test for __cmp__
1907 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001908 if not hasattr(a, '__cmp__'):
1909 return # some types don't have a __cmp__ any more (so the
1910 # test doesn't make sense any more), or maybe they
1911 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001912 try:
1913 a.__class__.__cmp__(a, b)
1914 except TypeError:
1915 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001916 else:
Georg Brandl48545522008-02-02 10:12:36 +00001917 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1918 a.__class__, a, b))
1919
1920 unsafecmp(u"123", "123")
1921 unsafecmp("123", u"123")
1922 unsafecmp(1, 1.0)
1923 unsafecmp(1.0, 1)
1924 unsafecmp(1, 1L)
1925 unsafecmp(1L, 1)
1926
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001927 @test_support.impl_detail("custom logic for printing to real file objects")
1928 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001929 # Testing recursion checks ...
1930 class Letter(str):
1931 def __new__(cls, letter):
1932 if letter == 'EPS':
1933 return str.__new__(cls)
1934 return str.__new__(cls, letter)
1935 def __str__(self):
1936 if not self:
1937 return 'EPS'
1938 return self
1939 # sys.stdout needs to be the original to trigger the recursion bug
1940 import sys
1941 test_stdout = sys.stdout
1942 sys.stdout = test_support.get_original_stdout()
1943 try:
1944 # nothing should actually be printed, this should raise an exception
1945 print Letter('w')
1946 except RuntimeError:
1947 pass
1948 else:
1949 self.fail("expected a RuntimeError for print recursion")
1950 finally:
1951 sys.stdout = test_stdout
1952
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001953 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001954 # Bug #1202533.
1955 class A(object):
1956 pass
1957 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1958 try:
1959 A()*2
1960 except RuntimeError:
1961 pass
1962 else:
1963 self.fail("expected a RuntimeError")
1964
1965 def test_weakrefs(self):
1966 # Testing weak references...
1967 import weakref
1968 class C(object):
1969 pass
1970 c = C()
1971 r = weakref.ref(c)
1972 self.assertEqual(r(), c)
1973 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001974 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001975 self.assertEqual(r(), None)
1976 del r
1977 class NoWeak(object):
1978 __slots__ = ['foo']
1979 no = NoWeak()
1980 try:
1981 weakref.ref(no)
1982 except TypeError, msg:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001983 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001984 else:
1985 self.fail("weakref.ref(no) should be illegal")
1986 class Weak(object):
1987 __slots__ = ['foo', '__weakref__']
1988 yes = Weak()
1989 r = weakref.ref(yes)
1990 self.assertEqual(r(), yes)
1991 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001992 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001993 self.assertEqual(r(), None)
1994 del r
1995
1996 def test_properties(self):
1997 # Testing property...
1998 class C(object):
1999 def getx(self):
2000 return self.__x
2001 def setx(self, value):
2002 self.__x = value
2003 def delx(self):
2004 del self.__x
2005 x = property(getx, setx, delx, doc="I'm the x property.")
2006 a = C()
2007 self.assertFalse(hasattr(a, "x"))
2008 a.x = 42
2009 self.assertEqual(a._C__x, 42)
2010 self.assertEqual(a.x, 42)
2011 del a.x
2012 self.assertFalse(hasattr(a, "x"))
2013 self.assertFalse(hasattr(a, "_C__x"))
2014 C.x.__set__(a, 100)
2015 self.assertEqual(C.x.__get__(a), 100)
2016 C.x.__delete__(a)
2017 self.assertFalse(hasattr(a, "x"))
2018
2019 raw = C.__dict__['x']
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002020 self.assertTrue(isinstance(raw, property))
Georg Brandl48545522008-02-02 10:12:36 +00002021
2022 attrs = dir(raw)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002023 self.assertTrue("__doc__" in attrs)
2024 self.assertTrue("fget" in attrs)
2025 self.assertTrue("fset" in attrs)
2026 self.assertTrue("fdel" in attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002027
2028 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002029 self.assertTrue(raw.fget is C.__dict__['getx'])
2030 self.assertTrue(raw.fset is C.__dict__['setx'])
2031 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002032
2033 for attr in "__doc__", "fget", "fset", "fdel":
2034 try:
2035 setattr(raw, attr, 42)
2036 except TypeError, msg:
2037 if str(msg).find('readonly') < 0:
2038 self.fail("when setting readonly attr %r on a property, "
2039 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002040 else:
Georg Brandl48545522008-02-02 10:12:36 +00002041 self.fail("expected TypeError from trying to set readonly %r "
2042 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002043
Georg Brandl48545522008-02-02 10:12:36 +00002044 class D(object):
2045 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002046
Georg Brandl48545522008-02-02 10:12:36 +00002047 d = D()
2048 try:
2049 for i in d:
2050 str(i)
2051 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002052 pass
Georg Brandl48545522008-02-02 10:12:36 +00002053 else:
2054 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002055
Georg Brandl48545522008-02-02 10:12:36 +00002056 class E(object):
2057 def getter(self):
2058 "getter method"
2059 return 0
2060 def setter(self_, value):
2061 "setter method"
2062 pass
2063 prop = property(getter)
2064 self.assertEqual(prop.__doc__, "getter method")
2065 prop2 = property(fset=setter)
2066 self.assertEqual(prop2.__doc__, None)
2067
2068 # this segfaulted in 2.5b2
2069 try:
2070 import _testcapi
2071 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002072 pass
Georg Brandl48545522008-02-02 10:12:36 +00002073 else:
2074 class X(object):
2075 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002076
Georg Brandl48545522008-02-02 10:12:36 +00002077 def test_properties_plus(self):
2078 class C(object):
2079 foo = property(doc="hello")
2080 @foo.getter
2081 def foo(self):
2082 return self._foo
2083 @foo.setter
2084 def foo(self, value):
2085 self._foo = abs(value)
2086 @foo.deleter
2087 def foo(self):
2088 del self._foo
2089 c = C()
2090 self.assertEqual(C.foo.__doc__, "hello")
2091 self.assertFalse(hasattr(c, "foo"))
2092 c.foo = -42
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002093 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl48545522008-02-02 10:12:36 +00002094 self.assertEqual(c._foo, 42)
2095 self.assertEqual(c.foo, 42)
2096 del c.foo
2097 self.assertFalse(hasattr(c, '_foo'))
2098 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002099
Georg Brandl48545522008-02-02 10:12:36 +00002100 class D(C):
2101 @C.foo.deleter
2102 def foo(self):
2103 try:
2104 del self._foo
2105 except AttributeError:
2106 pass
2107 d = D()
2108 d.foo = 24
2109 self.assertEqual(d.foo, 24)
2110 del d.foo
2111 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002112
Georg Brandl48545522008-02-02 10:12:36 +00002113 class E(object):
2114 @property
2115 def foo(self):
2116 return self._foo
2117 @foo.setter
2118 def foo(self, value):
2119 raise RuntimeError
2120 @foo.setter
2121 def foo(self, value):
2122 self._foo = abs(value)
2123 @foo.deleter
2124 def foo(self, value=None):
2125 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002126
Georg Brandl48545522008-02-02 10:12:36 +00002127 e = E()
2128 e.foo = -42
2129 self.assertEqual(e.foo, 42)
2130 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002131
Georg Brandl48545522008-02-02 10:12:36 +00002132 class F(E):
2133 @E.foo.deleter
2134 def foo(self):
2135 del self._foo
2136 @foo.setter
2137 def foo(self, value):
2138 self._foo = max(0, value)
2139 f = F()
2140 f.foo = -10
2141 self.assertEqual(f.foo, 0)
2142 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002143
Georg Brandl48545522008-02-02 10:12:36 +00002144 def test_dict_constructors(self):
2145 # Testing dict constructor ...
2146 d = dict()
2147 self.assertEqual(d, {})
2148 d = dict({})
2149 self.assertEqual(d, {})
2150 d = dict({1: 2, 'a': 'b'})
2151 self.assertEqual(d, {1: 2, 'a': 'b'})
2152 self.assertEqual(d, dict(d.items()))
2153 self.assertEqual(d, dict(d.iteritems()))
2154 d = dict({'one':1, 'two':2})
2155 self.assertEqual(d, dict(one=1, two=2))
2156 self.assertEqual(d, dict(**d))
2157 self.assertEqual(d, dict({"one": 1}, two=2))
2158 self.assertEqual(d, dict([("two", 2)], one=1))
2159 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2160 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002161
Georg Brandl48545522008-02-02 10:12:36 +00002162 for badarg in 0, 0L, 0j, "0", [0], (0,):
2163 try:
2164 dict(badarg)
2165 except TypeError:
2166 pass
2167 except ValueError:
2168 if badarg == "0":
2169 # It's a sequence, and its elements are also sequences (gotta
2170 # love strings <wink>), but they aren't of length 2, so this
2171 # one seemed better as a ValueError than a TypeError.
2172 pass
2173 else:
2174 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002175 else:
Georg Brandl48545522008-02-02 10:12:36 +00002176 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002177
Georg Brandl48545522008-02-02 10:12:36 +00002178 try:
2179 dict({}, {})
2180 except TypeError:
2181 pass
2182 else:
2183 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002184
Georg Brandl48545522008-02-02 10:12:36 +00002185 class Mapping:
2186 # Lacks a .keys() method; will be added later.
2187 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002188
Georg Brandl48545522008-02-02 10:12:36 +00002189 try:
2190 dict(Mapping())
2191 except TypeError:
2192 pass
2193 else:
2194 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002195
Georg Brandl48545522008-02-02 10:12:36 +00002196 Mapping.keys = lambda self: self.dict.keys()
2197 Mapping.__getitem__ = lambda self, i: self.dict[i]
2198 d = dict(Mapping())
2199 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002200
Georg Brandl48545522008-02-02 10:12:36 +00002201 # Init from sequence of iterable objects, each producing a 2-sequence.
2202 class AddressBookEntry:
2203 def __init__(self, first, last):
2204 self.first = first
2205 self.last = last
2206 def __iter__(self):
2207 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002208
Georg Brandl48545522008-02-02 10:12:36 +00002209 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2210 AddressBookEntry('Barry', 'Peters'),
2211 AddressBookEntry('Tim', 'Peters'),
2212 AddressBookEntry('Barry', 'Warsaw')])
2213 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002214
Georg Brandl48545522008-02-02 10:12:36 +00002215 d = dict(zip(range(4), range(1, 5)))
2216 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002217
Georg Brandl48545522008-02-02 10:12:36 +00002218 # Bad sequence lengths.
2219 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2220 try:
2221 dict(bad)
2222 except ValueError:
2223 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002224 else:
Georg Brandl48545522008-02-02 10:12:36 +00002225 self.fail("no ValueError from dict(%r)" % bad)
2226
2227 def test_dir(self):
2228 # Testing dir() ...
2229 junk = 12
2230 self.assertEqual(dir(), ['junk', 'self'])
2231 del junk
2232
2233 # Just make sure these don't blow up!
2234 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2235 dir(arg)
2236
2237 # Try classic classes.
2238 class C:
2239 Cdata = 1
2240 def Cmethod(self): pass
2241
2242 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2243 self.assertEqual(dir(C), cstuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002244 self.assertTrue('im_self' in dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002245
2246 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2247 self.assertEqual(dir(c), cstuff)
2248
2249 c.cdata = 2
2250 c.cmethod = lambda self: 0
2251 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002252 self.assertTrue('im_self' in dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002253
2254 class A(C):
2255 Adata = 1
2256 def Amethod(self): pass
2257
2258 astuff = ['Adata', 'Amethod'] + cstuff
2259 self.assertEqual(dir(A), astuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002260 self.assertTrue('im_self' in dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002261 a = A()
2262 self.assertEqual(dir(a), astuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002263 self.assertTrue('im_self' in dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002264 a.adata = 42
2265 a.amethod = lambda self: 3
2266 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2267
2268 # The same, but with new-style classes. Since these have object as a
2269 # base class, a lot more gets sucked in.
2270 def interesting(strings):
2271 return [s for s in strings if not s.startswith('_')]
2272
2273 class C(object):
2274 Cdata = 1
2275 def Cmethod(self): pass
2276
2277 cstuff = ['Cdata', 'Cmethod']
2278 self.assertEqual(interesting(dir(C)), cstuff)
2279
2280 c = C()
2281 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002282 self.assertTrue('im_self' in dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002283
2284 c.cdata = 2
2285 c.cmethod = lambda self: 0
2286 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002287 self.assertTrue('im_self' in dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002288
2289 class A(C):
2290 Adata = 1
2291 def Amethod(self): pass
2292
2293 astuff = ['Adata', 'Amethod'] + cstuff
2294 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002295 self.assertTrue('im_self' in dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002296 a = A()
2297 self.assertEqual(interesting(dir(a)), astuff)
2298 a.adata = 42
2299 a.amethod = lambda self: 3
2300 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002301 self.assertTrue('im_self' in dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002302
2303 # Try a module subclass.
2304 import sys
2305 class M(type(sys)):
2306 pass
2307 minstance = M("m")
2308 minstance.b = 2
2309 minstance.a = 1
2310 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2311 self.assertEqual(names, ['a', 'b'])
2312
2313 class M2(M):
2314 def getdict(self):
2315 return "Not a dict!"
2316 __dict__ = property(getdict)
2317
2318 m2instance = M2("m2")
2319 m2instance.b = 2
2320 m2instance.a = 1
2321 self.assertEqual(m2instance.__dict__, "Not a dict!")
2322 try:
2323 dir(m2instance)
2324 except TypeError:
2325 pass
2326
2327 # Two essentially featureless objects, just inheriting stuff from
2328 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002329 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2330 if test_support.check_impl_detail():
2331 # None differs in PyPy: it has a __nonzero__
2332 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002333
2334 # Nasty test case for proxied objects
2335 class Wrapper(object):
2336 def __init__(self, obj):
2337 self.__obj = obj
2338 def __repr__(self):
2339 return "Wrapper(%s)" % repr(self.__obj)
2340 def __getitem__(self, key):
2341 return Wrapper(self.__obj[key])
2342 def __len__(self):
2343 return len(self.__obj)
2344 def __getattr__(self, name):
2345 return Wrapper(getattr(self.__obj, name))
2346
2347 class C(object):
2348 def __getclass(self):
2349 return Wrapper(type(self))
2350 __class__ = property(__getclass)
2351
2352 dir(C()) # This used to segfault
2353
2354 def test_supers(self):
2355 # Testing super...
2356
2357 class A(object):
2358 def meth(self, a):
2359 return "A(%r)" % a
2360
2361 self.assertEqual(A().meth(1), "A(1)")
2362
2363 class B(A):
2364 def __init__(self):
2365 self.__super = super(B, self)
2366 def meth(self, a):
2367 return "B(%r)" % a + self.__super.meth(a)
2368
2369 self.assertEqual(B().meth(2), "B(2)A(2)")
2370
2371 class C(A):
2372 def meth(self, a):
2373 return "C(%r)" % a + self.__super.meth(a)
2374 C._C__super = super(C)
2375
2376 self.assertEqual(C().meth(3), "C(3)A(3)")
2377
2378 class D(C, B):
2379 def meth(self, a):
2380 return "D(%r)" % a + super(D, self).meth(a)
2381
2382 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2383
2384 # Test for subclassing super
2385
2386 class mysuper(super):
2387 def __init__(self, *args):
2388 return super(mysuper, self).__init__(*args)
2389
2390 class E(D):
2391 def meth(self, a):
2392 return "E(%r)" % a + mysuper(E, self).meth(a)
2393
2394 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2395
2396 class F(E):
2397 def meth(self, a):
2398 s = self.__super # == mysuper(F, self)
2399 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2400 F._F__super = mysuper(F)
2401
2402 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2403
2404 # Make sure certain errors are raised
2405
2406 try:
2407 super(D, 42)
2408 except TypeError:
2409 pass
2410 else:
2411 self.fail("shouldn't allow super(D, 42)")
2412
2413 try:
2414 super(D, C())
2415 except TypeError:
2416 pass
2417 else:
2418 self.fail("shouldn't allow super(D, C())")
2419
2420 try:
2421 super(D).__get__(12)
2422 except TypeError:
2423 pass
2424 else:
2425 self.fail("shouldn't allow super(D).__get__(12)")
2426
2427 try:
2428 super(D).__get__(C())
2429 except TypeError:
2430 pass
2431 else:
2432 self.fail("shouldn't allow super(D).__get__(C())")
2433
2434 # Make sure data descriptors can be overridden and accessed via super
2435 # (new feature in Python 2.3)
2436
2437 class DDbase(object):
2438 def getx(self): return 42
2439 x = property(getx)
2440
2441 class DDsub(DDbase):
2442 def getx(self): return "hello"
2443 x = property(getx)
2444
2445 dd = DDsub()
2446 self.assertEqual(dd.x, "hello")
2447 self.assertEqual(super(DDsub, dd).x, 42)
2448
2449 # Ensure that super() lookup of descriptor from classmethod
2450 # works (SF ID# 743627)
2451
2452 class Base(object):
2453 aProp = property(lambda self: "foo")
2454
2455 class Sub(Base):
2456 @classmethod
2457 def test(klass):
2458 return super(Sub,klass).aProp
2459
2460 self.assertEqual(Sub.test(), Base.aProp)
2461
2462 # Verify that super() doesn't allow keyword args
2463 try:
2464 super(Base, kw=1)
2465 except TypeError:
2466 pass
2467 else:
2468 self.assertEqual("super shouldn't accept keyword args")
2469
2470 def test_basic_inheritance(self):
2471 # Testing inheritance from basic types...
2472
2473 class hexint(int):
2474 def __repr__(self):
2475 return hex(self)
2476 def __add__(self, other):
2477 return hexint(int.__add__(self, other))
2478 # (Note that overriding __radd__ doesn't work,
2479 # because the int type gets first dibs.)
2480 self.assertEqual(repr(hexint(7) + 9), "0x10")
2481 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2482 a = hexint(12345)
2483 self.assertEqual(a, 12345)
2484 self.assertEqual(int(a), 12345)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002485 self.assertTrue(int(a).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002486 self.assertEqual(hash(a), hash(12345))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002487 self.assertTrue((+a).__class__ is int)
2488 self.assertTrue((a >> 0).__class__ is int)
2489 self.assertTrue((a << 0).__class__ is int)
2490 self.assertTrue((hexint(0) << 12).__class__ is int)
2491 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002492
2493 class octlong(long):
2494 __slots__ = []
2495 def __str__(self):
2496 s = oct(self)
2497 if s[-1] == 'L':
2498 s = s[:-1]
2499 return s
2500 def __add__(self, other):
2501 return self.__class__(super(octlong, self).__add__(other))
2502 __radd__ = __add__
2503 self.assertEqual(str(octlong(3) + 5), "010")
2504 # (Note that overriding __radd__ here only seems to work
2505 # because the example uses a short int left argument.)
2506 self.assertEqual(str(5 + octlong(3000)), "05675")
2507 a = octlong(12345)
2508 self.assertEqual(a, 12345L)
2509 self.assertEqual(long(a), 12345L)
2510 self.assertEqual(hash(a), hash(12345L))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002511 self.assertTrue(long(a).__class__ is long)
2512 self.assertTrue((+a).__class__ is long)
2513 self.assertTrue((-a).__class__ is long)
2514 self.assertTrue((-octlong(0)).__class__ is long)
2515 self.assertTrue((a >> 0).__class__ is long)
2516 self.assertTrue((a << 0).__class__ is long)
2517 self.assertTrue((a - 0).__class__ is long)
2518 self.assertTrue((a * 1).__class__ is long)
2519 self.assertTrue((a ** 1).__class__ is long)
2520 self.assertTrue((a // 1).__class__ is long)
2521 self.assertTrue((1 * a).__class__ is long)
2522 self.assertTrue((a | 0).__class__ is long)
2523 self.assertTrue((a ^ 0).__class__ is long)
2524 self.assertTrue((a & -1L).__class__ is long)
2525 self.assertTrue((octlong(0) << 12).__class__ is long)
2526 self.assertTrue((octlong(0) >> 12).__class__ is long)
2527 self.assertTrue(abs(octlong(0)).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002528
2529 # Because octlong overrides __add__, we can't check the absence of +0
2530 # optimizations using octlong.
2531 class longclone(long):
2532 pass
2533 a = longclone(1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002534 self.assertTrue((a + 0).__class__ is long)
2535 self.assertTrue((0 + a).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002536
2537 # Check that negative clones don't segfault
2538 a = longclone(-1)
2539 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002540 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002541
2542 class precfloat(float):
2543 __slots__ = ['prec']
2544 def __init__(self, value=0.0, prec=12):
2545 self.prec = int(prec)
2546 def __repr__(self):
2547 return "%.*g" % (self.prec, self)
2548 self.assertEqual(repr(precfloat(1.1)), "1.1")
2549 a = precfloat(12345)
2550 self.assertEqual(a, 12345.0)
2551 self.assertEqual(float(a), 12345.0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002552 self.assertTrue(float(a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002553 self.assertEqual(hash(a), hash(12345.0))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002554 self.assertTrue((+a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002555
2556 class madcomplex(complex):
2557 def __repr__(self):
2558 return "%.17gj%+.17g" % (self.imag, self.real)
2559 a = madcomplex(-3, 4)
2560 self.assertEqual(repr(a), "4j-3")
2561 base = complex(-3, 4)
2562 self.assertEqual(base.__class__, complex)
2563 self.assertEqual(a, base)
2564 self.assertEqual(complex(a), base)
2565 self.assertEqual(complex(a).__class__, complex)
2566 a = madcomplex(a) # just trying another form of the constructor
2567 self.assertEqual(repr(a), "4j-3")
2568 self.assertEqual(a, base)
2569 self.assertEqual(complex(a), base)
2570 self.assertEqual(complex(a).__class__, complex)
2571 self.assertEqual(hash(a), hash(base))
2572 self.assertEqual((+a).__class__, complex)
2573 self.assertEqual((a + 0).__class__, complex)
2574 self.assertEqual(a + 0, base)
2575 self.assertEqual((a - 0).__class__, complex)
2576 self.assertEqual(a - 0, base)
2577 self.assertEqual((a * 1).__class__, complex)
2578 self.assertEqual(a * 1, base)
2579 self.assertEqual((a / 1).__class__, complex)
2580 self.assertEqual(a / 1, base)
2581
2582 class madtuple(tuple):
2583 _rev = None
2584 def rev(self):
2585 if self._rev is not None:
2586 return self._rev
2587 L = list(self)
2588 L.reverse()
2589 self._rev = self.__class__(L)
2590 return self._rev
2591 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2592 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2593 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2594 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2595 for i in range(512):
2596 t = madtuple(range(i))
2597 u = t.rev()
2598 v = u.rev()
2599 self.assertEqual(v, t)
2600 a = madtuple((1,2,3,4,5))
2601 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002602 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002603 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002604 self.assertTrue(a[:].__class__ is tuple)
2605 self.assertTrue((a * 1).__class__ is tuple)
2606 self.assertTrue((a * 0).__class__ is tuple)
2607 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002608 a = madtuple(())
2609 self.assertEqual(tuple(a), ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002610 self.assertTrue(tuple(a).__class__ is tuple)
2611 self.assertTrue((a + a).__class__ is tuple)
2612 self.assertTrue((a * 0).__class__ is tuple)
2613 self.assertTrue((a * 1).__class__ is tuple)
2614 self.assertTrue((a * 2).__class__ is tuple)
2615 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002616
2617 class madstring(str):
2618 _rev = None
2619 def rev(self):
2620 if self._rev is not None:
2621 return self._rev
2622 L = list(self)
2623 L.reverse()
2624 self._rev = self.__class__("".join(L))
2625 return self._rev
2626 s = madstring("abcdefghijklmnopqrstuvwxyz")
2627 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2628 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2629 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2630 for i in range(256):
2631 s = madstring("".join(map(chr, range(i))))
2632 t = s.rev()
2633 u = t.rev()
2634 self.assertEqual(u, s)
2635 s = madstring("12345")
2636 self.assertEqual(str(s), "12345")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002637 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002638
2639 base = "\x00" * 5
2640 s = madstring(base)
2641 self.assertEqual(s, base)
2642 self.assertEqual(str(s), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002643 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002644 self.assertEqual(hash(s), hash(base))
2645 self.assertEqual({s: 1}[base], 1)
2646 self.assertEqual({base: 1}[s], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002647 self.assertTrue((s + "").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002648 self.assertEqual(s + "", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002649 self.assertTrue(("" + s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002650 self.assertEqual("" + s, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002651 self.assertTrue((s * 0).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002652 self.assertEqual(s * 0, "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002653 self.assertTrue((s * 1).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002654 self.assertEqual(s * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002655 self.assertTrue((s * 2).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002656 self.assertEqual(s * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002657 self.assertTrue(s[:].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002658 self.assertEqual(s[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002659 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002660 self.assertEqual(s[0:0], "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002661 self.assertTrue(s.strip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002662 self.assertEqual(s.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002663 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002664 self.assertEqual(s.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002665 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002666 self.assertEqual(s.rstrip(), base)
2667 identitytab = ''.join([chr(i) for i in range(256)])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002668 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002669 self.assertEqual(s.translate(identitytab), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002670 self.assertTrue(s.translate(identitytab, "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002671 self.assertEqual(s.translate(identitytab, "x"), base)
2672 self.assertEqual(s.translate(identitytab, "\x00"), "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002673 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002674 self.assertEqual(s.replace("x", "x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002675 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002676 self.assertEqual(s.ljust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002677 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002678 self.assertEqual(s.rjust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002679 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002680 self.assertEqual(s.center(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002681 self.assertTrue(s.lower().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002682 self.assertEqual(s.lower(), base)
2683
2684 class madunicode(unicode):
2685 _rev = None
2686 def rev(self):
2687 if self._rev is not None:
2688 return self._rev
2689 L = list(self)
2690 L.reverse()
2691 self._rev = self.__class__(u"".join(L))
2692 return self._rev
2693 u = madunicode("ABCDEF")
2694 self.assertEqual(u, u"ABCDEF")
2695 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2696 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2697 base = u"12345"
2698 u = madunicode(base)
2699 self.assertEqual(unicode(u), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002700 self.assertTrue(unicode(u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002701 self.assertEqual(hash(u), hash(base))
2702 self.assertEqual({u: 1}[base], 1)
2703 self.assertEqual({base: 1}[u], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002704 self.assertTrue(u.strip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002705 self.assertEqual(u.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002706 self.assertTrue(u.lstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002707 self.assertEqual(u.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002708 self.assertTrue(u.rstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002709 self.assertEqual(u.rstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002710 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002711 self.assertEqual(u.replace(u"x", u"x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002712 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002713 self.assertEqual(u.replace(u"xy", u"xy"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002714 self.assertTrue(u.center(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002715 self.assertEqual(u.center(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002716 self.assertTrue(u.ljust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002717 self.assertEqual(u.ljust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002718 self.assertTrue(u.rjust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002719 self.assertEqual(u.rjust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002720 self.assertTrue(u.lower().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002721 self.assertEqual(u.lower(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002722 self.assertTrue(u.upper().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002723 self.assertEqual(u.upper(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002724 self.assertTrue(u.capitalize().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002725 self.assertEqual(u.capitalize(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002726 self.assertTrue(u.title().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002727 self.assertEqual(u.title(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002728 self.assertTrue((u + u"").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002729 self.assertEqual(u + u"", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002730 self.assertTrue((u"" + u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002731 self.assertEqual(u"" + u, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002732 self.assertTrue((u * 0).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002733 self.assertEqual(u * 0, u"")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002734 self.assertTrue((u * 1).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002735 self.assertEqual(u * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002736 self.assertTrue((u * 2).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002737 self.assertEqual(u * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002738 self.assertTrue(u[:].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002739 self.assertEqual(u[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002740 self.assertTrue(u[0:0].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002741 self.assertEqual(u[0:0], u"")
2742
2743 class sublist(list):
2744 pass
2745 a = sublist(range(5))
2746 self.assertEqual(a, range(5))
2747 a.append("hello")
2748 self.assertEqual(a, range(5) + ["hello"])
2749 a[5] = 5
2750 self.assertEqual(a, range(6))
2751 a.extend(range(6, 20))
2752 self.assertEqual(a, range(20))
2753 a[-5:] = []
2754 self.assertEqual(a, range(15))
2755 del a[10:15]
2756 self.assertEqual(len(a), 10)
2757 self.assertEqual(a, range(10))
2758 self.assertEqual(list(a), range(10))
2759 self.assertEqual(a[0], 0)
2760 self.assertEqual(a[9], 9)
2761 self.assertEqual(a[-10], 0)
2762 self.assertEqual(a[-1], 9)
2763 self.assertEqual(a[:5], range(5))
2764
2765 class CountedInput(file):
2766 """Counts lines read by self.readline().
2767
2768 self.lineno is the 0-based ordinal of the last line read, up to
2769 a maximum of one greater than the number of lines in the file.
2770
2771 self.ateof is true if and only if the final "" line has been read,
2772 at which point self.lineno stops incrementing, and further calls
2773 to readline() continue to return "".
2774 """
2775
2776 lineno = 0
2777 ateof = 0
2778 def readline(self):
2779 if self.ateof:
2780 return ""
2781 s = file.readline(self)
2782 # Next line works too.
2783 # s = super(CountedInput, self).readline()
2784 self.lineno += 1
2785 if s == "":
2786 self.ateof = 1
2787 return s
2788
2789 f = file(name=test_support.TESTFN, mode='w')
2790 lines = ['a\n', 'b\n', 'c\n']
2791 try:
2792 f.writelines(lines)
2793 f.close()
2794 f = CountedInput(test_support.TESTFN)
2795 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2796 got = f.readline()
2797 self.assertEqual(expected, got)
2798 self.assertEqual(f.lineno, i)
2799 self.assertEqual(f.ateof, (i > len(lines)))
2800 f.close()
2801 finally:
2802 try:
2803 f.close()
2804 except:
2805 pass
2806 test_support.unlink(test_support.TESTFN)
2807
2808 def test_keywords(self):
2809 # Testing keyword args to basic type constructors ...
2810 self.assertEqual(int(x=1), 1)
2811 self.assertEqual(float(x=2), 2.0)
2812 self.assertEqual(long(x=3), 3L)
2813 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2814 self.assertEqual(str(object=500), '500')
2815 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2816 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2817 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2818 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2819
2820 for constructor in (int, float, long, complex, str, unicode,
2821 tuple, list, file):
2822 try:
2823 constructor(bogus_keyword_arg=1)
2824 except TypeError:
2825 pass
2826 else:
2827 self.fail("expected TypeError from bogus keyword argument to %r"
2828 % constructor)
2829
2830 def test_str_subclass_as_dict_key(self):
2831 # Testing a str subclass used as dict key ..
2832
2833 class cistr(str):
2834 """Sublcass of str that computes __eq__ case-insensitively.
2835
2836 Also computes a hash code of the string in canonical form.
2837 """
2838
2839 def __init__(self, value):
2840 self.canonical = value.lower()
2841 self.hashcode = hash(self.canonical)
2842
2843 def __eq__(self, other):
2844 if not isinstance(other, cistr):
2845 other = cistr(other)
2846 return self.canonical == other.canonical
2847
2848 def __hash__(self):
2849 return self.hashcode
2850
2851 self.assertEqual(cistr('ABC'), 'abc')
2852 self.assertEqual('aBc', cistr('ABC'))
2853 self.assertEqual(str(cistr('ABC')), 'ABC')
2854
2855 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2856 self.assertEqual(d[cistr('one')], 1)
2857 self.assertEqual(d[cistr('tWo')], 2)
2858 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002859 self.assertTrue(cistr('ONe') in d)
Georg Brandl48545522008-02-02 10:12:36 +00002860 self.assertEqual(d.get(cistr('thrEE')), 3)
2861
2862 def test_classic_comparisons(self):
2863 # Testing classic comparisons...
2864 class classic:
2865 pass
2866
2867 for base in (classic, int, object):
2868 class C(base):
2869 def __init__(self, value):
2870 self.value = int(value)
2871 def __cmp__(self, other):
2872 if isinstance(other, C):
2873 return cmp(self.value, other.value)
2874 if isinstance(other, int) or isinstance(other, long):
2875 return cmp(self.value, other)
2876 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002877 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002878
2879 c1 = C(1)
2880 c2 = C(2)
2881 c3 = C(3)
2882 self.assertEqual(c1, 1)
2883 c = {1: c1, 2: c2, 3: c3}
2884 for x in 1, 2, 3:
2885 for y in 1, 2, 3:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002886 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002887 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002888 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002889 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002890 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2891 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002892
2893 def test_rich_comparisons(self):
2894 # Testing rich comparisons...
2895 class Z(complex):
2896 pass
2897 z = Z(1)
2898 self.assertEqual(z, 1+0j)
2899 self.assertEqual(1+0j, z)
2900 class ZZ(complex):
2901 def __eq__(self, other):
2902 try:
2903 return abs(self - other) <= 1e-6
2904 except:
2905 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002906 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002907 zz = ZZ(1.0000003)
2908 self.assertEqual(zz, 1+0j)
2909 self.assertEqual(1+0j, zz)
2910
2911 class classic:
2912 pass
2913 for base in (classic, int, object, list):
2914 class C(base):
2915 def __init__(self, value):
2916 self.value = int(value)
2917 def __cmp__(self_, other):
2918 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002919 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002920 def __eq__(self, other):
2921 if isinstance(other, C):
2922 return self.value == other.value
2923 if isinstance(other, int) or isinstance(other, long):
2924 return self.value == other
2925 return NotImplemented
2926 def __ne__(self, other):
2927 if isinstance(other, C):
2928 return self.value != other.value
2929 if isinstance(other, int) or isinstance(other, long):
2930 return self.value != other
2931 return NotImplemented
2932 def __lt__(self, other):
2933 if isinstance(other, C):
2934 return self.value < other.value
2935 if isinstance(other, int) or isinstance(other, long):
2936 return self.value < other
2937 return NotImplemented
2938 def __le__(self, other):
2939 if isinstance(other, C):
2940 return self.value <= other.value
2941 if isinstance(other, int) or isinstance(other, long):
2942 return self.value <= other
2943 return NotImplemented
2944 def __gt__(self, other):
2945 if isinstance(other, C):
2946 return self.value > other.value
2947 if isinstance(other, int) or isinstance(other, long):
2948 return self.value > other
2949 return NotImplemented
2950 def __ge__(self, other):
2951 if isinstance(other, C):
2952 return self.value >= other.value
2953 if isinstance(other, int) or isinstance(other, long):
2954 return self.value >= other
2955 return NotImplemented
2956 c1 = C(1)
2957 c2 = C(2)
2958 c3 = C(3)
2959 self.assertEqual(c1, 1)
2960 c = {1: c1, 2: c2, 3: c3}
2961 for x in 1, 2, 3:
2962 for y in 1, 2, 3:
2963 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002964 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002965 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002966 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002967 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002968 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002969 "x=%d, y=%d" % (x, y))
2970
2971 def test_coercions(self):
2972 # Testing coercions...
2973 class I(int): pass
2974 coerce(I(0), 0)
2975 coerce(0, I(0))
2976 class L(long): pass
2977 coerce(L(0), 0)
2978 coerce(L(0), 0L)
2979 coerce(0, L(0))
2980 coerce(0L, L(0))
2981 class F(float): pass
2982 coerce(F(0), 0)
2983 coerce(F(0), 0L)
2984 coerce(F(0), 0.)
2985 coerce(0, F(0))
2986 coerce(0L, F(0))
2987 coerce(0., F(0))
2988 class C(complex): pass
2989 coerce(C(0), 0)
2990 coerce(C(0), 0L)
2991 coerce(C(0), 0.)
2992 coerce(C(0), 0j)
2993 coerce(0, C(0))
2994 coerce(0L, C(0))
2995 coerce(0., C(0))
2996 coerce(0j, C(0))
2997
2998 def test_descrdoc(self):
2999 # Testing descriptor doc strings...
3000 def check(descr, what):
3001 self.assertEqual(descr.__doc__, what)
3002 check(file.closed, "True if the file is closed") # getset descriptor
3003 check(file.name, "file name") # member descriptor
3004
3005 def test_doc_descriptor(self):
3006 # Testing __doc__ descriptor...
3007 # SF bug 542984
3008 class DocDescr(object):
3009 def __get__(self, object, otype):
3010 if object:
3011 object = object.__class__.__name__ + ' instance'
3012 if otype:
3013 otype = otype.__name__
3014 return 'object=%s; type=%s' % (object, otype)
3015 class OldClass:
3016 __doc__ = DocDescr()
3017 class NewClass(object):
3018 __doc__ = DocDescr()
3019 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3020 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3021 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3022 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3023
3024 def test_set_class(self):
3025 # Testing __class__ assignment...
3026 class C(object): pass
3027 class D(object): pass
3028 class E(object): pass
3029 class F(D, E): pass
3030 for cls in C, D, E, F:
3031 for cls2 in C, D, E, F:
3032 x = cls()
3033 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003034 self.assertTrue(x.__class__ is cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003035 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003036 self.assertTrue(x.__class__ is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003037 def cant(x, C):
3038 try:
3039 x.__class__ = C
3040 except TypeError:
3041 pass
3042 else:
3043 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3044 try:
3045 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003046 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003047 pass
3048 else:
3049 self.fail("shouldn't allow del %r.__class__" % x)
3050 cant(C(), list)
3051 cant(list(), C)
3052 cant(C(), 1)
3053 cant(C(), object)
3054 cant(object(), list)
3055 cant(list(), object)
3056 class Int(int): __slots__ = []
3057 cant(2, Int)
3058 cant(Int(), int)
3059 cant(True, int)
3060 cant(2, bool)
3061 o = object()
3062 cant(o, type(1))
3063 cant(o, type(None))
3064 del o
3065 class G(object):
3066 __slots__ = ["a", "b"]
3067 class H(object):
3068 __slots__ = ["b", "a"]
3069 try:
3070 unicode
3071 except NameError:
3072 class I(object):
3073 __slots__ = ["a", "b"]
3074 else:
3075 class I(object):
3076 __slots__ = [unicode("a"), unicode("b")]
3077 class J(object):
3078 __slots__ = ["c", "b"]
3079 class K(object):
3080 __slots__ = ["a", "b", "d"]
3081 class L(H):
3082 __slots__ = ["e"]
3083 class M(I):
3084 __slots__ = ["e"]
3085 class N(J):
3086 __slots__ = ["__weakref__"]
3087 class P(J):
3088 __slots__ = ["__dict__"]
3089 class Q(J):
3090 pass
3091 class R(J):
3092 __slots__ = ["__dict__", "__weakref__"]
3093
3094 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3095 x = cls()
3096 x.a = 1
3097 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003098 self.assertTrue(x.__class__ is cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003099 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3100 self.assertEqual(x.a, 1)
3101 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003102 self.assertTrue(x.__class__ is cls,
Georg Brandl48545522008-02-02 10:12:36 +00003103 "assigning %r as __class__ for %r silently failed" % (cls, x))
3104 self.assertEqual(x.a, 1)
3105 for cls in G, J, K, L, M, N, P, R, list, Int:
3106 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3107 if cls is cls2:
3108 continue
3109 cant(cls(), cls2)
3110
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003111 # Issue5283: when __class__ changes in __del__, the wrong
3112 # type gets DECREF'd.
3113 class O(object):
3114 pass
3115 class A(object):
3116 def __del__(self):
3117 self.__class__ = O
3118 l = [A() for x in range(100)]
3119 del l
3120
Georg Brandl48545522008-02-02 10:12:36 +00003121 def test_set_dict(self):
3122 # Testing __dict__ assignment...
3123 class C(object): pass
3124 a = C()
3125 a.__dict__ = {'b': 1}
3126 self.assertEqual(a.b, 1)
3127 def cant(x, dict):
3128 try:
3129 x.__dict__ = dict
3130 except (AttributeError, TypeError):
3131 pass
3132 else:
3133 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3134 cant(a, None)
3135 cant(a, [])
3136 cant(a, 1)
3137 del a.__dict__ # Deleting __dict__ is allowed
3138
3139 class Base(object):
3140 pass
3141 def verify_dict_readonly(x):
3142 """
3143 x has to be an instance of a class inheriting from Base.
3144 """
3145 cant(x, {})
3146 try:
3147 del x.__dict__
3148 except (AttributeError, TypeError):
3149 pass
3150 else:
3151 self.fail("shouldn't allow del %r.__dict__" % x)
3152 dict_descr = Base.__dict__["__dict__"]
3153 try:
3154 dict_descr.__set__(x, {})
3155 except (AttributeError, TypeError):
3156 pass
3157 else:
3158 self.fail("dict_descr allowed access to %r's dict" % x)
3159
3160 # Classes don't allow __dict__ assignment and have readonly dicts
3161 class Meta1(type, Base):
3162 pass
3163 class Meta2(Base, type):
3164 pass
3165 class D(object):
3166 __metaclass__ = Meta1
3167 class E(object):
3168 __metaclass__ = Meta2
3169 for cls in C, D, E:
3170 verify_dict_readonly(cls)
3171 class_dict = cls.__dict__
3172 try:
3173 class_dict["spam"] = "eggs"
3174 except TypeError:
3175 pass
3176 else:
3177 self.fail("%r's __dict__ can be modified" % cls)
3178
3179 # Modules also disallow __dict__ assignment
3180 class Module1(types.ModuleType, Base):
3181 pass
3182 class Module2(Base, types.ModuleType):
3183 pass
3184 for ModuleType in Module1, Module2:
3185 mod = ModuleType("spam")
3186 verify_dict_readonly(mod)
3187 mod.__dict__["spam"] = "eggs"
3188
3189 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003190 # (at least not any more than regular exception's __dict__ can
3191 # be deleted; on CPython it is not the case, whereas on PyPy they
3192 # can, just like any other new-style instance's __dict__.)
3193 def can_delete_dict(e):
3194 try:
3195 del e.__dict__
3196 except (TypeError, AttributeError):
3197 return False
3198 else:
3199 return True
Georg Brandl48545522008-02-02 10:12:36 +00003200 class Exception1(Exception, Base):
3201 pass
3202 class Exception2(Base, Exception):
3203 pass
3204 for ExceptionType in Exception, Exception1, Exception2:
3205 e = ExceptionType()
3206 e.__dict__ = {"a": 1}
3207 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003208 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003209
3210 def test_pickles(self):
3211 # Testing pickling and copying new-style classes and objects...
3212 import pickle, cPickle
3213
3214 def sorteditems(d):
3215 L = d.items()
3216 L.sort()
3217 return L
3218
3219 global C
3220 class C(object):
3221 def __init__(self, a, b):
3222 super(C, self).__init__()
3223 self.a = a
3224 self.b = b
3225 def __repr__(self):
3226 return "C(%r, %r)" % (self.a, self.b)
3227
3228 global C1
3229 class C1(list):
3230 def __new__(cls, a, b):
3231 return super(C1, cls).__new__(cls)
3232 def __getnewargs__(self):
3233 return (self.a, self.b)
3234 def __init__(self, a, b):
3235 self.a = a
3236 self.b = b
3237 def __repr__(self):
3238 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3239
3240 global C2
3241 class C2(int):
3242 def __new__(cls, a, b, val=0):
3243 return super(C2, cls).__new__(cls, val)
3244 def __getnewargs__(self):
3245 return (self.a, self.b, int(self))
3246 def __init__(self, a, b, val=0):
3247 self.a = a
3248 self.b = b
3249 def __repr__(self):
3250 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3251
3252 global C3
3253 class C3(object):
3254 def __init__(self, foo):
3255 self.foo = foo
3256 def __getstate__(self):
3257 return self.foo
3258 def __setstate__(self, foo):
3259 self.foo = foo
3260
3261 global C4classic, C4
3262 class C4classic: # classic
3263 pass
3264 class C4(C4classic, object): # mixed inheritance
3265 pass
3266
3267 for p in pickle, cPickle:
3268 for bin in 0, 1:
3269 for cls in C, C1, C2:
3270 s = p.dumps(cls, bin)
3271 cls2 = p.loads(s)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003272 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003273
3274 a = C1(1, 2); a.append(42); a.append(24)
3275 b = C2("hello", "world", 42)
3276 s = p.dumps((a, b), bin)
3277 x, y = p.loads(s)
3278 self.assertEqual(x.__class__, a.__class__)
3279 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3280 self.assertEqual(y.__class__, b.__class__)
3281 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3282 self.assertEqual(repr(x), repr(a))
3283 self.assertEqual(repr(y), repr(b))
3284 # Test for __getstate__ and __setstate__ on new style class
3285 u = C3(42)
3286 s = p.dumps(u, bin)
3287 v = p.loads(s)
3288 self.assertEqual(u.__class__, v.__class__)
3289 self.assertEqual(u.foo, v.foo)
3290 # Test for picklability of hybrid class
3291 u = C4()
3292 u.foo = 42
3293 s = p.dumps(u, bin)
3294 v = p.loads(s)
3295 self.assertEqual(u.__class__, v.__class__)
3296 self.assertEqual(u.foo, v.foo)
3297
3298 # Testing copy.deepcopy()
3299 import copy
3300 for cls in C, C1, C2:
3301 cls2 = copy.deepcopy(cls)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003302 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003303
3304 a = C1(1, 2); a.append(42); a.append(24)
3305 b = C2("hello", "world", 42)
3306 x, y = copy.deepcopy((a, b))
3307 self.assertEqual(x.__class__, a.__class__)
3308 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3309 self.assertEqual(y.__class__, b.__class__)
3310 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3311 self.assertEqual(repr(x), repr(a))
3312 self.assertEqual(repr(y), repr(b))
3313
3314 def test_pickle_slots(self):
3315 # Testing pickling of classes with __slots__ ...
3316 import pickle, cPickle
3317 # Pickling of classes with __slots__ but without __getstate__ should fail
3318 global B, C, D, E
3319 class B(object):
3320 pass
3321 for base in [object, B]:
3322 class C(base):
3323 __slots__ = ['a']
3324 class D(C):
3325 pass
3326 try:
3327 pickle.dumps(C())
3328 except TypeError:
3329 pass
3330 else:
3331 self.fail("should fail: pickle C instance - %s" % base)
3332 try:
3333 cPickle.dumps(C())
3334 except TypeError:
3335 pass
3336 else:
3337 self.fail("should fail: cPickle C instance - %s" % base)
3338 try:
3339 pickle.dumps(C())
3340 except TypeError:
3341 pass
3342 else:
3343 self.fail("should fail: pickle D instance - %s" % base)
3344 try:
3345 cPickle.dumps(D())
3346 except TypeError:
3347 pass
3348 else:
3349 self.fail("should fail: cPickle D instance - %s" % base)
3350 # Give C a nice generic __getstate__ and __setstate__
3351 class C(base):
3352 __slots__ = ['a']
3353 def __getstate__(self):
3354 try:
3355 d = self.__dict__.copy()
3356 except AttributeError:
3357 d = {}
3358 for cls in self.__class__.__mro__:
3359 for sn in cls.__dict__.get('__slots__', ()):
3360 try:
3361 d[sn] = getattr(self, sn)
3362 except AttributeError:
3363 pass
3364 return d
3365 def __setstate__(self, d):
3366 for k, v in d.items():
3367 setattr(self, k, v)
3368 class D(C):
3369 pass
3370 # Now it should work
3371 x = C()
3372 y = pickle.loads(pickle.dumps(x))
3373 self.assertEqual(hasattr(y, 'a'), 0)
3374 y = cPickle.loads(cPickle.dumps(x))
3375 self.assertEqual(hasattr(y, 'a'), 0)
3376 x.a = 42
3377 y = pickle.loads(pickle.dumps(x))
3378 self.assertEqual(y.a, 42)
3379 y = cPickle.loads(cPickle.dumps(x))
3380 self.assertEqual(y.a, 42)
3381 x = D()
3382 x.a = 42
3383 x.b = 100
3384 y = pickle.loads(pickle.dumps(x))
3385 self.assertEqual(y.a + y.b, 142)
3386 y = cPickle.loads(cPickle.dumps(x))
3387 self.assertEqual(y.a + y.b, 142)
3388 # A subclass that adds a slot should also work
3389 class E(C):
3390 __slots__ = ['b']
3391 x = E()
3392 x.a = 42
3393 x.b = "foo"
3394 y = pickle.loads(pickle.dumps(x))
3395 self.assertEqual(y.a, x.a)
3396 self.assertEqual(y.b, x.b)
3397 y = cPickle.loads(cPickle.dumps(x))
3398 self.assertEqual(y.a, x.a)
3399 self.assertEqual(y.b, x.b)
3400
3401 def test_binary_operator_override(self):
3402 # Testing overrides of binary operations...
3403 class I(int):
3404 def __repr__(self):
3405 return "I(%r)" % int(self)
3406 def __add__(self, other):
3407 return I(int(self) + int(other))
3408 __radd__ = __add__
3409 def __pow__(self, other, mod=None):
3410 if mod is None:
3411 return I(pow(int(self), int(other)))
3412 else:
3413 return I(pow(int(self), int(other), int(mod)))
3414 def __rpow__(self, other, mod=None):
3415 if mod is None:
3416 return I(pow(int(other), int(self), mod))
3417 else:
3418 return I(pow(int(other), int(self), int(mod)))
3419
3420 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3421 self.assertEqual(repr(I(1) + 2), "I(3)")
3422 self.assertEqual(repr(1 + I(2)), "I(3)")
3423 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3424 self.assertEqual(repr(2 ** I(3)), "I(8)")
3425 self.assertEqual(repr(I(2) ** 3), "I(8)")
3426 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3427 class S(str):
3428 def __eq__(self, other):
3429 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003430 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003431
3432 def test_subclass_propagation(self):
3433 # Testing propagation of slot functions to subclasses...
3434 class A(object):
3435 pass
3436 class B(A):
3437 pass
3438 class C(A):
3439 pass
3440 class D(B, C):
3441 pass
3442 d = D()
3443 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3444 A.__hash__ = lambda self: 42
3445 self.assertEqual(hash(d), 42)
3446 C.__hash__ = lambda self: 314
3447 self.assertEqual(hash(d), 314)
3448 B.__hash__ = lambda self: 144
3449 self.assertEqual(hash(d), 144)
3450 D.__hash__ = lambda self: 100
3451 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003452 D.__hash__ = None
3453 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003454 del D.__hash__
3455 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003456 B.__hash__ = None
3457 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003458 del B.__hash__
3459 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003460 C.__hash__ = None
3461 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003462 del C.__hash__
3463 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003464 A.__hash__ = None
3465 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003466 del A.__hash__
3467 self.assertEqual(hash(d), orig_hash)
3468 d.foo = 42
3469 d.bar = 42
3470 self.assertEqual(d.foo, 42)
3471 self.assertEqual(d.bar, 42)
3472 def __getattribute__(self, name):
3473 if name == "foo":
3474 return 24
3475 return object.__getattribute__(self, name)
3476 A.__getattribute__ = __getattribute__
3477 self.assertEqual(d.foo, 24)
3478 self.assertEqual(d.bar, 42)
3479 def __getattr__(self, name):
3480 if name in ("spam", "foo", "bar"):
3481 return "hello"
3482 raise AttributeError, name
3483 B.__getattr__ = __getattr__
3484 self.assertEqual(d.spam, "hello")
3485 self.assertEqual(d.foo, 24)
3486 self.assertEqual(d.bar, 42)
3487 del A.__getattribute__
3488 self.assertEqual(d.foo, 42)
3489 del d.foo
3490 self.assertEqual(d.foo, "hello")
3491 self.assertEqual(d.bar, 42)
3492 del B.__getattr__
3493 try:
3494 d.foo
3495 except AttributeError:
3496 pass
3497 else:
3498 self.fail("d.foo should be undefined now")
3499
3500 # Test a nasty bug in recurse_down_subclasses()
3501 import gc
3502 class A(object):
3503 pass
3504 class B(A):
3505 pass
3506 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003507 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003508 A.__setitem__ = lambda *a: None # crash
3509
3510 def test_buffer_inheritance(self):
3511 # Testing that buffer interface is inherited ...
3512
3513 import binascii
3514 # SF bug [#470040] ParseTuple t# vs subclasses.
3515
3516 class MyStr(str):
3517 pass
3518 base = 'abc'
3519 m = MyStr(base)
3520 # b2a_hex uses the buffer interface to get its argument's value, via
3521 # PyArg_ParseTuple 't#' code.
3522 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3523
3524 # It's not clear that unicode will continue to support the character
3525 # buffer interface, and this test will fail if that's taken away.
3526 class MyUni(unicode):
3527 pass
3528 base = u'abc'
3529 m = MyUni(base)
3530 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3531
3532 class MyInt(int):
3533 pass
3534 m = MyInt(42)
3535 try:
3536 binascii.b2a_hex(m)
3537 self.fail('subclass of int should not have a buffer interface')
3538 except TypeError:
3539 pass
3540
3541 def test_str_of_str_subclass(self):
3542 # Testing __str__ defined in subclass of str ...
3543 import binascii
3544 import cStringIO
3545
3546 class octetstring(str):
3547 def __str__(self):
3548 return binascii.b2a_hex(self)
3549 def __repr__(self):
3550 return self + " repr"
3551
3552 o = octetstring('A')
3553 self.assertEqual(type(o), octetstring)
3554 self.assertEqual(type(str(o)), str)
3555 self.assertEqual(type(repr(o)), str)
3556 self.assertEqual(ord(o), 0x41)
3557 self.assertEqual(str(o), '41')
3558 self.assertEqual(repr(o), 'A repr')
3559 self.assertEqual(o.__str__(), '41')
3560 self.assertEqual(o.__repr__(), 'A repr')
3561
3562 capture = cStringIO.StringIO()
3563 # Calling str() or not exercises different internal paths.
3564 print >> capture, o
3565 print >> capture, str(o)
3566 self.assertEqual(capture.getvalue(), '41\n41\n')
3567 capture.close()
3568
3569 def test_keyword_arguments(self):
3570 # Testing keyword arguments to __init__, __call__...
3571 def f(a): return a
3572 self.assertEqual(f.__call__(a=42), 42)
3573 a = []
3574 list.__init__(a, sequence=[0, 1, 2])
3575 self.assertEqual(a, [0, 1, 2])
3576
3577 def test_recursive_call(self):
3578 # Testing recursive __call__() by setting to instance of class...
3579 class A(object):
3580 pass
3581
3582 A.__call__ = A()
3583 try:
3584 A()()
3585 except RuntimeError:
3586 pass
3587 else:
3588 self.fail("Recursion limit should have been reached for __call__()")
3589
3590 def test_delete_hook(self):
3591 # Testing __del__ hook...
3592 log = []
3593 class C(object):
3594 def __del__(self):
3595 log.append(1)
3596 c = C()
3597 self.assertEqual(log, [])
3598 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003599 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003600 self.assertEqual(log, [1])
3601
3602 class D(object): pass
3603 d = D()
3604 try: del d[0]
3605 except TypeError: pass
3606 else: self.fail("invalid del() didn't raise TypeError")
3607
3608 def test_hash_inheritance(self):
3609 # Testing hash of mutable subclasses...
3610
3611 class mydict(dict):
3612 pass
3613 d = mydict()
3614 try:
3615 hash(d)
3616 except TypeError:
3617 pass
3618 else:
3619 self.fail("hash() of dict subclass should fail")
3620
3621 class mylist(list):
3622 pass
3623 d = mylist()
3624 try:
3625 hash(d)
3626 except TypeError:
3627 pass
3628 else:
3629 self.fail("hash() of list subclass should fail")
3630
3631 def test_str_operations(self):
3632 try: 'a' + 5
3633 except TypeError: pass
3634 else: self.fail("'' + 5 doesn't raise TypeError")
3635
3636 try: ''.split('')
3637 except ValueError: pass
3638 else: self.fail("''.split('') doesn't raise ValueError")
3639
3640 try: ''.join([0])
3641 except TypeError: pass
3642 else: self.fail("''.join([0]) doesn't raise TypeError")
3643
3644 try: ''.rindex('5')
3645 except ValueError: pass
3646 else: self.fail("''.rindex('5') doesn't raise ValueError")
3647
3648 try: '%(n)s' % None
3649 except TypeError: pass
3650 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3651
3652 try: '%(n' % {}
3653 except ValueError: pass
3654 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3655
3656 try: '%*s' % ('abc')
3657 except TypeError: pass
3658 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3659
3660 try: '%*.*s' % ('abc', 5)
3661 except TypeError: pass
3662 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3663
3664 try: '%s' % (1, 2)
3665 except TypeError: pass
3666 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3667
3668 try: '%' % None
3669 except ValueError: pass
3670 else: self.fail("'%' % None doesn't raise ValueError")
3671
3672 self.assertEqual('534253'.isdigit(), 1)
3673 self.assertEqual('534253x'.isdigit(), 0)
3674 self.assertEqual('%c' % 5, '\x05')
3675 self.assertEqual('%c' % '5', '5')
3676
3677 def test_deepcopy_recursive(self):
3678 # Testing deepcopy of recursive objects...
3679 class Node:
3680 pass
3681 a = Node()
3682 b = Node()
3683 a.b = b
3684 b.a = a
3685 z = deepcopy(a) # This blew up before
3686
3687 def test_unintialized_modules(self):
3688 # Testing uninitialized module objects...
3689 from types import ModuleType as M
3690 m = M.__new__(M)
3691 str(m)
3692 self.assertEqual(hasattr(m, "__name__"), 0)
3693 self.assertEqual(hasattr(m, "__file__"), 0)
3694 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003695 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003696 m.foo = 1
3697 self.assertEqual(m.__dict__, {"foo": 1})
3698
3699 def test_funny_new(self):
3700 # Testing __new__ returning something unexpected...
3701 class C(object):
3702 def __new__(cls, arg):
3703 if isinstance(arg, str): return [1, 2, 3]
3704 elif isinstance(arg, int): return object.__new__(D)
3705 else: return object.__new__(cls)
3706 class D(C):
3707 def __init__(self, arg):
3708 self.foo = arg
3709 self.assertEqual(C("1"), [1, 2, 3])
3710 self.assertEqual(D("1"), [1, 2, 3])
3711 d = D(None)
3712 self.assertEqual(d.foo, None)
3713 d = C(1)
3714 self.assertEqual(isinstance(d, D), True)
3715 self.assertEqual(d.foo, 1)
3716 d = D(1)
3717 self.assertEqual(isinstance(d, D), True)
3718 self.assertEqual(d.foo, 1)
3719
3720 def test_imul_bug(self):
3721 # Testing for __imul__ problems...
3722 # SF bug 544647
3723 class C(object):
3724 def __imul__(self, other):
3725 return (self, other)
3726 x = C()
3727 y = x
3728 y *= 1.0
3729 self.assertEqual(y, (x, 1.0))
3730 y = x
3731 y *= 2
3732 self.assertEqual(y, (x, 2))
3733 y = x
3734 y *= 3L
3735 self.assertEqual(y, (x, 3L))
3736 y = x
3737 y *= 1L<<100
3738 self.assertEqual(y, (x, 1L<<100))
3739 y = x
3740 y *= None
3741 self.assertEqual(y, (x, None))
3742 y = x
3743 y *= "foo"
3744 self.assertEqual(y, (x, "foo"))
3745
3746 def test_copy_setstate(self):
3747 # Testing that copy.*copy() correctly uses __setstate__...
3748 import copy
3749 class C(object):
3750 def __init__(self, foo=None):
3751 self.foo = foo
3752 self.__foo = foo
3753 def setfoo(self, foo=None):
3754 self.foo = foo
3755 def getfoo(self):
3756 return self.__foo
3757 def __getstate__(self):
3758 return [self.foo]
3759 def __setstate__(self_, lst):
3760 self.assertEqual(len(lst), 1)
3761 self_.__foo = self_.foo = lst[0]
3762 a = C(42)
3763 a.setfoo(24)
3764 self.assertEqual(a.foo, 24)
3765 self.assertEqual(a.getfoo(), 42)
3766 b = copy.copy(a)
3767 self.assertEqual(b.foo, 24)
3768 self.assertEqual(b.getfoo(), 24)
3769 b = copy.deepcopy(a)
3770 self.assertEqual(b.foo, 24)
3771 self.assertEqual(b.getfoo(), 24)
3772
3773 def test_slices(self):
3774 # Testing cases with slices and overridden __getitem__ ...
3775
3776 # Strings
3777 self.assertEqual("hello"[:4], "hell")
3778 self.assertEqual("hello"[slice(4)], "hell")
3779 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3780 class S(str):
3781 def __getitem__(self, x):
3782 return str.__getitem__(self, x)
3783 self.assertEqual(S("hello")[:4], "hell")
3784 self.assertEqual(S("hello")[slice(4)], "hell")
3785 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3786 # Tuples
3787 self.assertEqual((1,2,3)[:2], (1,2))
3788 self.assertEqual((1,2,3)[slice(2)], (1,2))
3789 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3790 class T(tuple):
3791 def __getitem__(self, x):
3792 return tuple.__getitem__(self, x)
3793 self.assertEqual(T((1,2,3))[:2], (1,2))
3794 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3795 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3796 # Lists
3797 self.assertEqual([1,2,3][:2], [1,2])
3798 self.assertEqual([1,2,3][slice(2)], [1,2])
3799 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3800 class L(list):
3801 def __getitem__(self, x):
3802 return list.__getitem__(self, x)
3803 self.assertEqual(L([1,2,3])[:2], [1,2])
3804 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3805 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3806 # Now do lists and __setitem__
3807 a = L([1,2,3])
3808 a[slice(1, 3)] = [3,2]
3809 self.assertEqual(a, [1,3,2])
3810 a[slice(0, 2, 1)] = [3,1]
3811 self.assertEqual(a, [3,1,2])
3812 a.__setitem__(slice(1, 3), [2,1])
3813 self.assertEqual(a, [3,2,1])
3814 a.__setitem__(slice(0, 2, 1), [2,3])
3815 self.assertEqual(a, [2,3,1])
3816
3817 def test_subtype_resurrection(self):
3818 # Testing resurrection of new-style instance...
3819
3820 class C(object):
3821 container = []
3822
3823 def __del__(self):
3824 # resurrect the instance
3825 C.container.append(self)
3826
3827 c = C()
3828 c.attr = 42
3829
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003830 # The most interesting thing here is whether this blows up, due to
3831 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3832 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003833 del c
3834
3835 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003836 # the last container slot works: that will attempt to delete c again,
3837 # which will cause c to get appended back to the container again
3838 # "during" the del. (On non-CPython implementations, however, __del__
3839 # is typically not called again.)
3840 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003841 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003842 del C.container[-1]
3843 if test_support.check_impl_detail():
3844 test_support.gc_collect()
3845 self.assertEqual(len(C.container), 1)
3846 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003847
3848 # Make c mortal again, so that the test framework with -l doesn't report
3849 # it as a leak.
3850 del C.__del__
3851
3852 def test_slots_trash(self):
3853 # Testing slot trash...
3854 # Deallocating deeply nested slotted trash caused stack overflows
3855 class trash(object):
3856 __slots__ = ['x']
3857 def __init__(self, x):
3858 self.x = x
3859 o = None
3860 for i in xrange(50000):
3861 o = trash(o)
3862 del o
3863
3864 def test_slots_multiple_inheritance(self):
3865 # SF bug 575229, multiple inheritance w/ slots dumps core
3866 class A(object):
3867 __slots__=()
3868 class B(object):
3869 pass
3870 class C(A,B) :
3871 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003872 if test_support.check_impl_detail():
3873 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003874 self.assertTrue(hasattr(C, '__dict__'))
3875 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl48545522008-02-02 10:12:36 +00003876 C().x = 2
3877
3878 def test_rmul(self):
3879 # Testing correct invocation of __rmul__...
3880 # SF patch 592646
3881 class C(object):
3882 def __mul__(self, other):
3883 return "mul"
3884 def __rmul__(self, other):
3885 return "rmul"
3886 a = C()
3887 self.assertEqual(a*2, "mul")
3888 self.assertEqual(a*2.2, "mul")
3889 self.assertEqual(2*a, "rmul")
3890 self.assertEqual(2.2*a, "rmul")
3891
3892 def test_ipow(self):
3893 # Testing correct invocation of __ipow__...
3894 # [SF bug 620179]
3895 class C(object):
3896 def __ipow__(self, other):
3897 pass
3898 a = C()
3899 a **= 2
3900
3901 def test_mutable_bases(self):
3902 # Testing mutable bases...
3903
3904 # stuff that should work:
3905 class C(object):
3906 pass
3907 class C2(object):
3908 def __getattribute__(self, attr):
3909 if attr == 'a':
3910 return 2
3911 else:
3912 return super(C2, self).__getattribute__(attr)
3913 def meth(self):
3914 return 1
3915 class D(C):
3916 pass
3917 class E(D):
3918 pass
3919 d = D()
3920 e = E()
3921 D.__bases__ = (C,)
3922 D.__bases__ = (C2,)
3923 self.assertEqual(d.meth(), 1)
3924 self.assertEqual(e.meth(), 1)
3925 self.assertEqual(d.a, 2)
3926 self.assertEqual(e.a, 2)
3927 self.assertEqual(C2.__subclasses__(), [D])
3928
Georg Brandl48545522008-02-02 10:12:36 +00003929 try:
3930 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003931 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003932 pass
3933 else:
3934 self.fail("shouldn't be able to delete .__bases__")
3935
3936 try:
3937 D.__bases__ = ()
3938 except TypeError, msg:
3939 if str(msg) == "a new-style class can't have only classic bases":
3940 self.fail("wrong error message for .__bases__ = ()")
3941 else:
3942 self.fail("shouldn't be able to set .__bases__ to ()")
3943
3944 try:
3945 D.__bases__ = (D,)
3946 except TypeError:
3947 pass
3948 else:
3949 # actually, we'll have crashed by here...
3950 self.fail("shouldn't be able to create inheritance cycles")
3951
3952 try:
3953 D.__bases__ = (C, C)
3954 except TypeError:
3955 pass
3956 else:
3957 self.fail("didn't detect repeated base classes")
3958
3959 try:
3960 D.__bases__ = (E,)
3961 except TypeError:
3962 pass
3963 else:
3964 self.fail("shouldn't be able to create inheritance cycles")
3965
3966 # let's throw a classic class into the mix:
3967 class Classic:
3968 def meth2(self):
3969 return 3
3970
3971 D.__bases__ = (C, Classic)
3972
3973 self.assertEqual(d.meth2(), 3)
3974 self.assertEqual(e.meth2(), 3)
3975 try:
3976 d.a
3977 except AttributeError:
3978 pass
3979 else:
3980 self.fail("attribute should have vanished")
3981
3982 try:
3983 D.__bases__ = (Classic,)
3984 except TypeError:
3985 pass
3986 else:
3987 self.fail("new-style class must have a new-style base")
3988
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003989 def test_builtin_bases(self):
3990 # Make sure all the builtin types can have their base queried without
3991 # segfaulting. See issue #5787.
3992 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3993 if isinstance(tp, type)]
3994 for tp in builtin_types:
3995 object.__getattribute__(tp, "__bases__")
3996 if tp is not object:
3997 self.assertEqual(len(tp.__bases__), 1, tp)
3998
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003999 class L(list):
4000 pass
4001
4002 class C(object):
4003 pass
4004
4005 class D(C):
4006 pass
4007
4008 try:
4009 L.__bases__ = (dict,)
4010 except TypeError:
4011 pass
4012 else:
4013 self.fail("shouldn't turn list subclass into dict subclass")
4014
4015 try:
4016 list.__bases__ = (dict,)
4017 except TypeError:
4018 pass
4019 else:
4020 self.fail("shouldn't be able to assign to list.__bases__")
4021
4022 try:
4023 D.__bases__ = (C, list)
4024 except TypeError:
4025 pass
4026 else:
4027 assert 0, "best_base calculation found wanting"
4028
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004029
Georg Brandl48545522008-02-02 10:12:36 +00004030 def test_mutable_bases_with_failing_mro(self):
4031 # Testing mutable bases with failing mro...
4032 class WorkOnce(type):
4033 def __new__(self, name, bases, ns):
4034 self.flag = 0
4035 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4036 def mro(self):
4037 if self.flag > 0:
4038 raise RuntimeError, "bozo"
4039 else:
4040 self.flag += 1
4041 return type.mro(self)
4042
4043 class WorkAlways(type):
4044 def mro(self):
4045 # this is here to make sure that .mro()s aren't called
4046 # with an exception set (which was possible at one point).
4047 # An error message will be printed in a debug build.
4048 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004049 return type.mro(self)
4050
Georg Brandl48545522008-02-02 10:12:36 +00004051 class C(object):
4052 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004053
Georg Brandl48545522008-02-02 10:12:36 +00004054 class C2(object):
4055 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004056
Georg Brandl48545522008-02-02 10:12:36 +00004057 class D(C):
4058 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004059
Georg Brandl48545522008-02-02 10:12:36 +00004060 class E(D):
4061 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004062
Georg Brandl48545522008-02-02 10:12:36 +00004063 class F(D):
4064 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004065
Georg Brandl48545522008-02-02 10:12:36 +00004066 class G(D):
4067 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004068
Georg Brandl48545522008-02-02 10:12:36 +00004069 # Immediate subclasses have their mro's adjusted in alphabetical
4070 # order, so E's will get adjusted before adjusting F's fails. We
4071 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004072
Georg Brandl48545522008-02-02 10:12:36 +00004073 E_mro_before = E.__mro__
4074 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004075
Armin Rigofd163f92005-12-29 15:59:19 +00004076 try:
Georg Brandl48545522008-02-02 10:12:36 +00004077 D.__bases__ = (C2,)
4078 except RuntimeError:
4079 self.assertEqual(E.__mro__, E_mro_before)
4080 self.assertEqual(D.__mro__, D_mro_before)
4081 else:
4082 self.fail("exception not propagated")
4083
4084 def test_mutable_bases_catch_mro_conflict(self):
4085 # Testing mutable bases catch mro conflict...
4086 class A(object):
4087 pass
4088
4089 class B(object):
4090 pass
4091
4092 class C(A, B):
4093 pass
4094
4095 class D(A, B):
4096 pass
4097
4098 class E(C, D):
4099 pass
4100
4101 try:
4102 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004103 except TypeError:
4104 pass
4105 else:
Georg Brandl48545522008-02-02 10:12:36 +00004106 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004107
Georg Brandl48545522008-02-02 10:12:36 +00004108 def test_mutable_names(self):
4109 # Testing mutable names...
4110 class C(object):
4111 pass
4112
4113 # C.__module__ could be 'test_descr' or '__main__'
4114 mod = C.__module__
4115
4116 C.__name__ = 'D'
4117 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4118
4119 C.__name__ = 'D.E'
4120 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4121
4122 def test_subclass_right_op(self):
4123 # Testing correct dispatch of subclass overloading __r<op>__...
4124
4125 # This code tests various cases where right-dispatch of a subclass
4126 # should be preferred over left-dispatch of a base class.
4127
4128 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4129
4130 class B(int):
4131 def __floordiv__(self, other):
4132 return "B.__floordiv__"
4133 def __rfloordiv__(self, other):
4134 return "B.__rfloordiv__"
4135
4136 self.assertEqual(B(1) // 1, "B.__floordiv__")
4137 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4138
4139 # Case 2: subclass of object; this is just the baseline for case 3
4140
4141 class C(object):
4142 def __floordiv__(self, other):
4143 return "C.__floordiv__"
4144 def __rfloordiv__(self, other):
4145 return "C.__rfloordiv__"
4146
4147 self.assertEqual(C() // 1, "C.__floordiv__")
4148 self.assertEqual(1 // C(), "C.__rfloordiv__")
4149
4150 # Case 3: subclass of new-style class; here it gets interesting
4151
4152 class D(C):
4153 def __floordiv__(self, other):
4154 return "D.__floordiv__"
4155 def __rfloordiv__(self, other):
4156 return "D.__rfloordiv__"
4157
4158 self.assertEqual(D() // C(), "D.__floordiv__")
4159 self.assertEqual(C() // D(), "D.__rfloordiv__")
4160
4161 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4162
4163 class E(C):
4164 pass
4165
4166 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4167
4168 self.assertEqual(E() // 1, "C.__floordiv__")
4169 self.assertEqual(1 // E(), "C.__rfloordiv__")
4170 self.assertEqual(E() // C(), "C.__floordiv__")
4171 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4172
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004173 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004174 def test_meth_class_get(self):
4175 # Testing __get__ method of METH_CLASS C methods...
4176 # Full coverage of descrobject.c::classmethod_get()
4177
4178 # Baseline
4179 arg = [1, 2, 3]
4180 res = {1: None, 2: None, 3: None}
4181 self.assertEqual(dict.fromkeys(arg), res)
4182 self.assertEqual({}.fromkeys(arg), res)
4183
4184 # Now get the descriptor
4185 descr = dict.__dict__["fromkeys"]
4186
4187 # More baseline using the descriptor directly
4188 self.assertEqual(descr.__get__(None, dict)(arg), res)
4189 self.assertEqual(descr.__get__({})(arg), res)
4190
4191 # Now check various error cases
4192 try:
4193 descr.__get__(None, None)
4194 except TypeError:
4195 pass
4196 else:
4197 self.fail("shouldn't have allowed descr.__get__(None, None)")
4198 try:
4199 descr.__get__(42)
4200 except TypeError:
4201 pass
4202 else:
4203 self.fail("shouldn't have allowed descr.__get__(42)")
4204 try:
4205 descr.__get__(None, 42)
4206 except TypeError:
4207 pass
4208 else:
4209 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4210 try:
4211 descr.__get__(None, int)
4212 except TypeError:
4213 pass
4214 else:
4215 self.fail("shouldn't have allowed descr.__get__(None, int)")
4216
4217 def test_isinst_isclass(self):
4218 # Testing proxy isinstance() and isclass()...
4219 class Proxy(object):
4220 def __init__(self, obj):
4221 self.__obj = obj
4222 def __getattribute__(self, name):
4223 if name.startswith("_Proxy__"):
4224 return object.__getattribute__(self, name)
4225 else:
4226 return getattr(self.__obj, name)
4227 # Test with a classic class
4228 class C:
4229 pass
4230 a = C()
4231 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004232 self.assertTrue(isinstance(a, C)) # Baseline
4233 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004234 # Test with a classic subclass
4235 class D(C):
4236 pass
4237 a = D()
4238 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004239 self.assertTrue(isinstance(a, C)) # Baseline
4240 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004241 # Test with a new-style class
4242 class C(object):
4243 pass
4244 a = C()
4245 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004246 self.assertTrue(isinstance(a, C)) # Baseline
4247 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004248 # Test with a new-style subclass
4249 class D(C):
4250 pass
4251 a = D()
4252 pa = Proxy(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004253 self.assertTrue(isinstance(a, C)) # Baseline
4254 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004255
4256 def test_proxy_super(self):
4257 # Testing super() for a proxy object...
4258 class Proxy(object):
4259 def __init__(self, obj):
4260 self.__obj = obj
4261 def __getattribute__(self, name):
4262 if name.startswith("_Proxy__"):
4263 return object.__getattribute__(self, name)
4264 else:
4265 return getattr(self.__obj, name)
4266
4267 class B(object):
4268 def f(self):
4269 return "B.f"
4270
4271 class C(B):
4272 def f(self):
4273 return super(C, self).f() + "->C.f"
4274
4275 obj = C()
4276 p = Proxy(obj)
4277 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4278
4279 def test_carloverre(self):
4280 # Testing prohibition of Carlo Verre's hack...
4281 try:
4282 object.__setattr__(str, "foo", 42)
4283 except TypeError:
4284 pass
4285 else:
4286 self.fail("Carlo Verre __setattr__ suceeded!")
4287 try:
4288 object.__delattr__(str, "lower")
4289 except TypeError:
4290 pass
4291 else:
4292 self.fail("Carlo Verre __delattr__ succeeded!")
4293
4294 def test_weakref_segfault(self):
4295 # Testing weakref segfault...
4296 # SF 742911
4297 import weakref
4298
4299 class Provoker:
4300 def __init__(self, referrent):
4301 self.ref = weakref.ref(referrent)
4302
4303 def __del__(self):
4304 x = self.ref()
4305
4306 class Oops(object):
4307 pass
4308
4309 o = Oops()
4310 o.whatever = Provoker(o)
4311 del o
4312
4313 def test_wrapper_segfault(self):
4314 # SF 927248: deeply nested wrappers could cause stack overflow
4315 f = lambda:None
4316 for i in xrange(1000000):
4317 f = f.__call__
4318 f = None
4319
4320 def test_file_fault(self):
4321 # Testing sys.stdout is changed in getattr...
4322 import sys
Nick Coghlan0447cd62009-10-17 06:33:05 +00004323 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004324 class StdoutGuard:
4325 def __getattr__(self, attr):
4326 sys.stdout = sys.__stdout__
4327 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4328 sys.stdout = StdoutGuard()
4329 try:
4330 print "Oops!"
4331 except RuntimeError:
4332 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004333 finally:
4334 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004335
4336 def test_vicious_descriptor_nonsense(self):
4337 # Testing vicious_descriptor_nonsense...
4338
4339 # A potential segfault spotted by Thomas Wouters in mail to
4340 # python-dev 2003-04-17, turned into an example & fixed by Michael
4341 # Hudson just less than four months later...
4342
4343 class Evil(object):
4344 def __hash__(self):
4345 return hash('attr')
4346 def __eq__(self, other):
4347 del C.attr
4348 return 0
4349
4350 class Descr(object):
4351 def __get__(self, ob, type=None):
4352 return 1
4353
4354 class C(object):
4355 attr = Descr()
4356
4357 c = C()
4358 c.__dict__[Evil()] = 0
4359
4360 self.assertEqual(c.attr, 1)
4361 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004362 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004363 self.assertEqual(hasattr(c, 'attr'), False)
4364
4365 def test_init(self):
4366 # SF 1155938
4367 class Foo(object):
4368 def __init__(self):
4369 return 10
4370 try:
4371 Foo()
4372 except TypeError:
4373 pass
4374 else:
4375 self.fail("did not test __init__() for None return")
4376
4377 def test_method_wrapper(self):
4378 # Testing method-wrapper objects...
4379 # <type 'method-wrapper'> did not support any reflection before 2.5
4380
4381 l = []
4382 self.assertEqual(l.__add__, l.__add__)
4383 self.assertEqual(l.__add__, [].__add__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004384 self.assertTrue(l.__add__ != [5].__add__)
4385 self.assertTrue(l.__add__ != l.__mul__)
4386 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004387 if hasattr(l.__add__, '__self__'):
4388 # CPython
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004389 self.assertTrue(l.__add__.__self__ is l)
4390 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004391 else:
4392 # Python implementations where [].__add__ is a normal bound method
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004393 self.assertTrue(l.__add__.im_self is l)
4394 self.assertTrue(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004395 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4396 try:
4397 hash(l.__add__)
4398 except TypeError:
4399 pass
4400 else:
4401 self.fail("no TypeError from hash([].__add__)")
4402
4403 t = ()
4404 t += (7,)
4405 self.assertEqual(t.__add__, (7,).__add__)
4406 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4407
4408 def test_not_implemented(self):
4409 # Testing NotImplemented...
4410 # all binary methods should be able to return a NotImplemented
4411 import sys
4412 import types
4413 import operator
4414
4415 def specialmethod(self, other):
4416 return NotImplemented
4417
4418 def check(expr, x, y):
4419 try:
4420 exec expr in {'x': x, 'y': y, 'operator': operator}
4421 except TypeError:
4422 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004423 else:
Georg Brandl48545522008-02-02 10:12:36 +00004424 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004425
Georg Brandl48545522008-02-02 10:12:36 +00004426 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4427 # TypeErrors
4428 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4429 # ValueErrors instead of TypeErrors
4430 for metaclass in [type, types.ClassType]:
4431 for name, expr, iexpr in [
4432 ('__add__', 'x + y', 'x += y'),
4433 ('__sub__', 'x - y', 'x -= y'),
4434 ('__mul__', 'x * y', 'x *= y'),
4435 ('__truediv__', 'operator.truediv(x, y)', None),
4436 ('__floordiv__', 'operator.floordiv(x, y)', None),
4437 ('__div__', 'x / y', 'x /= y'),
4438 ('__mod__', 'x % y', 'x %= y'),
4439 ('__divmod__', 'divmod(x, y)', None),
4440 ('__pow__', 'x ** y', 'x **= y'),
4441 ('__lshift__', 'x << y', 'x <<= y'),
4442 ('__rshift__', 'x >> y', 'x >>= y'),
4443 ('__and__', 'x & y', 'x &= y'),
4444 ('__or__', 'x | y', 'x |= y'),
4445 ('__xor__', 'x ^ y', 'x ^= y'),
4446 ('__coerce__', 'coerce(x, y)', None)]:
4447 if name == '__coerce__':
4448 rname = name
4449 else:
4450 rname = '__r' + name[2:]
4451 A = metaclass('A', (), {name: specialmethod})
4452 B = metaclass('B', (), {rname: specialmethod})
4453 a = A()
4454 b = B()
4455 check(expr, a, a)
4456 check(expr, a, b)
4457 check(expr, b, a)
4458 check(expr, b, b)
4459 check(expr, a, N1)
4460 check(expr, a, N2)
4461 check(expr, N1, b)
4462 check(expr, N2, b)
4463 if iexpr:
4464 check(iexpr, a, a)
4465 check(iexpr, a, b)
4466 check(iexpr, b, a)
4467 check(iexpr, b, b)
4468 check(iexpr, a, N1)
4469 check(iexpr, a, N2)
4470 iname = '__i' + name[2:]
4471 C = metaclass('C', (), {iname: specialmethod})
4472 c = C()
4473 check(iexpr, c, a)
4474 check(iexpr, c, b)
4475 check(iexpr, c, N1)
4476 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004477
Georg Brandl48545522008-02-02 10:12:36 +00004478 def test_assign_slice(self):
4479 # ceval.c's assign_slice used to check for
4480 # tp->tp_as_sequence->sq_slice instead of
4481 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004482
Georg Brandl48545522008-02-02 10:12:36 +00004483 class C(object):
4484 def __setslice__(self, start, stop, value):
4485 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004486
Georg Brandl48545522008-02-02 10:12:36 +00004487 c = C()
4488 c[1:2] = 3
4489 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004490
Benjamin Peterson273c2332008-11-17 22:39:09 +00004491 def test_getattr_hooks(self):
4492 # issue 4230
4493
4494 class Descriptor(object):
4495 counter = 0
4496 def __get__(self, obj, objtype=None):
4497 def getter(name):
4498 self.counter += 1
4499 raise AttributeError(name)
4500 return getter
4501
4502 descr = Descriptor()
4503 class A(object):
4504 __getattribute__ = descr
4505 class B(object):
4506 __getattr__ = descr
4507 class C(object):
4508 __getattribute__ = descr
4509 __getattr__ = descr
4510
4511 self.assertRaises(AttributeError, getattr, A(), "attr")
4512 self.assertEquals(descr.counter, 1)
4513 self.assertRaises(AttributeError, getattr, B(), "attr")
4514 self.assertEquals(descr.counter, 2)
4515 self.assertRaises(AttributeError, getattr, C(), "attr")
4516 self.assertEquals(descr.counter, 4)
4517
4518 import gc
4519 class EvilGetattribute(object):
4520 # This used to segfault
4521 def __getattr__(self, name):
4522 raise AttributeError(name)
4523 def __getattribute__(self, name):
4524 del EvilGetattribute.__getattr__
4525 for i in range(5):
4526 gc.collect()
4527 raise AttributeError(name)
4528
4529 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4530
Guido van Rossum9acc3872008-01-23 23:23:43 +00004531
Georg Brandl48545522008-02-02 10:12:36 +00004532class DictProxyTests(unittest.TestCase):
4533 def setUp(self):
4534 class C(object):
4535 def meth(self):
4536 pass
4537 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004538
Georg Brandl48545522008-02-02 10:12:36 +00004539 def test_iter_keys(self):
4540 # Testing dict-proxy iterkeys...
4541 keys = [ key for key in self.C.__dict__.iterkeys() ]
4542 keys.sort()
4543 self.assertEquals(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_iter_values(self):
4547 # Testing dict-proxy itervalues...
4548 values = [ values for values in self.C.__dict__.itervalues() ]
4549 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004550
Georg Brandl48545522008-02-02 10:12:36 +00004551 def test_iter_items(self):
4552 # Testing dict-proxy iteritems...
4553 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4554 keys.sort()
4555 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4556 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004557
Georg Brandl48545522008-02-02 10:12:36 +00004558 def test_dict_type_with_metaclass(self):
4559 # Testing type of __dict__ when __metaclass__ set...
4560 class B(object):
4561 pass
4562 class M(type):
4563 pass
4564 class C:
4565 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4566 __metaclass__ = M
4567 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004568
Guido van Rossum9acc3872008-01-23 23:23:43 +00004569
Georg Brandl48545522008-02-02 10:12:36 +00004570class PTypesLongInitTest(unittest.TestCase):
4571 # This is in its own TestCase so that it can be run before any other tests.
4572 def test_pytype_long_ready(self):
4573 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004574
Georg Brandl48545522008-02-02 10:12:36 +00004575 # This dumps core when SF bug 551412 isn't fixed --
4576 # but only when test_descr.py is run separately.
4577 # (That can't be helped -- as soon as PyType_Ready()
4578 # is called for PyLong_Type, the bug is gone.)
4579 class UserLong(object):
4580 def __pow__(self, *args):
4581 pass
4582 try:
4583 pow(0L, UserLong(), 0L)
4584 except:
4585 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004586
Georg Brandl48545522008-02-02 10:12:36 +00004587 # Another segfault only when run early
4588 # (before PyType_Ready(tuple) is called)
4589 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004590
4591
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004592def test_main():
Georg Brandl48545522008-02-02 10:12:36 +00004593 # Run all local test cases, with PTypesLongInitTest first.
4594 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4595 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004596
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004597if __name__ == "__main__":
4598 test_main()