blob: 8ec03087b34ee5c5c3eb9f0705ce2b516c631b32 [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")
Tim Peters1fc240e2001-10-26 05:06:50 +0000264 try:
Georg Brandl48545522008-02-02 10:12:36 +0000265 C(sys.maxint+1)
266 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000267 pass
268 else:
Georg Brandl48545522008-02-02 10:12:36 +0000269 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000270
Georg Brandl48545522008-02-02 10:12:36 +0000271 def test_longs(self):
272 # Testing long operations...
273 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000274
Georg Brandl48545522008-02-02 10:12:36 +0000275 def test_floats(self):
276 # Testing float operations...
277 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000278
Georg Brandl48545522008-02-02 10:12:36 +0000279 def test_complexes(self):
280 # Testing complex operations...
281 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
282 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000283
Georg Brandl48545522008-02-02 10:12:36 +0000284 class Number(complex):
285 __slots__ = ['prec']
286 def __new__(cls, *args, **kwds):
287 result = complex.__new__(cls, *args)
288 result.prec = kwds.get('prec', 12)
289 return result
290 def __repr__(self):
291 prec = self.prec
292 if self.imag == 0.0:
293 return "%.*g" % (prec, self.real)
294 if self.real == 0.0:
295 return "%.*gj" % (prec, self.imag)
296 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
297 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000298
Georg Brandl48545522008-02-02 10:12:36 +0000299 a = Number(3.14, prec=6)
300 self.assertEqual(repr(a), "3.14")
301 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000302
Georg Brandl48545522008-02-02 10:12:36 +0000303 a = Number(a, prec=2)
304 self.assertEqual(repr(a), "3.1")
305 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000306
Georg Brandl48545522008-02-02 10:12:36 +0000307 a = Number(234.5)
308 self.assertEqual(repr(a), "234.5")
309 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000310
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000311 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000312 def test_spam_lists(self):
313 # Testing spamlist operations...
314 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000315
Georg Brandl48545522008-02-02 10:12:36 +0000316 def spamlist(l, memo=None):
317 import xxsubtype as spam
318 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000319
Georg Brandl48545522008-02-02 10:12:36 +0000320 # This is an ugly hack:
321 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000322
Georg Brandl48545522008-02-02 10:12:36 +0000323 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
324 "__add__")
325 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
326 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
327 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
328 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
329 "__getslice__")
330 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
331 "__iadd__")
332 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
333 "__imul__")
334 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
335 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
336 "__mul__")
337 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
338 "__rmul__")
339 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
340 "__setitem__")
341 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
342 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
343 # Test subclassing
344 class C(spam.spamlist):
345 def foo(self): return 1
346 a = C()
347 self.assertEqual(a, [])
348 self.assertEqual(a.foo(), 1)
349 a.append(100)
350 self.assertEqual(a, [100])
351 self.assertEqual(a.getstate(), 0)
352 a.setstate(42)
353 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000354
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000355 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000356 def test_spam_dicts(self):
357 # Testing spamdict operations...
358 import copy, xxsubtype as spam
359 def spamdict(d, memo=None):
360 import xxsubtype as spam
361 sd = spam.spamdict()
362 for k, v in d.items():
363 sd[k] = v
364 return sd
365 # This is an ugly hack:
366 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000367
Georg Brandl48545522008-02-02 10:12:36 +0000368 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
369 "__cmp__")
370 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
371 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
372 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
373 d = spamdict({1:2,3:4})
374 l1 = []
375 for i in d.keys():
376 l1.append(i)
377 l = []
378 for i in iter(d):
379 l.append(i)
380 self.assertEqual(l, l1)
381 l = []
382 for i in d.__iter__():
383 l.append(i)
384 self.assertEqual(l, l1)
385 l = []
386 for i in type(spamdict({})).__iter__(d):
387 l.append(i)
388 self.assertEqual(l, l1)
389 straightd = {1:2, 3:4}
390 spamd = spamdict(straightd)
391 self.unop_test(spamd, 2, "len(a)", "__len__")
392 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
393 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
394 "a[b]=c", "__setitem__")
395 # Test subclassing
396 class C(spam.spamdict):
397 def foo(self): return 1
398 a = C()
399 self.assertEqual(a.items(), [])
400 self.assertEqual(a.foo(), 1)
401 a['foo'] = 'bar'
402 self.assertEqual(a.items(), [('foo', 'bar')])
403 self.assertEqual(a.getstate(), 0)
404 a.setstate(100)
405 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000406
Georg Brandl48545522008-02-02 10:12:36 +0000407class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000408
Georg Brandl48545522008-02-02 10:12:36 +0000409 def test_python_dicts(self):
410 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000411 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000412 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000413 d = dict()
414 self.assertEqual(d, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000415 self.assertTrue(d.__class__ is dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000416 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000417 class C(dict):
418 state = -1
419 def __init__(self_local, *a, **kw):
420 if a:
421 self.assertEqual(len(a), 1)
422 self_local.state = a[0]
423 if kw:
424 for k, v in kw.items():
425 self_local[v] = k
426 def __getitem__(self, key):
427 return self.get(key, 0)
428 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000429 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000430 dict.__setitem__(self_local, key, value)
431 def setstate(self, state):
432 self.state = state
433 def getstate(self):
434 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000435 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000436 a1 = C(12)
437 self.assertEqual(a1.state, 12)
438 a2 = C(foo=1, bar=2)
439 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
440 a = C()
441 self.assertEqual(a.state, -1)
442 self.assertEqual(a.getstate(), -1)
443 a.setstate(0)
444 self.assertEqual(a.state, 0)
445 self.assertEqual(a.getstate(), 0)
446 a.setstate(10)
447 self.assertEqual(a.state, 10)
448 self.assertEqual(a.getstate(), 10)
449 self.assertEqual(a[42], 0)
450 a[42] = 24
451 self.assertEqual(a[42], 24)
452 N = 50
453 for i in range(N):
454 a[i] = C()
455 for j in range(N):
456 a[i][j] = i*j
457 for i in range(N):
458 for j in range(N):
459 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000460
Georg Brandl48545522008-02-02 10:12:36 +0000461 def test_python_lists(self):
462 # Testing Python subclass of list...
463 class C(list):
464 def __getitem__(self, i):
465 return list.__getitem__(self, i) + 100
466 def __getslice__(self, i, j):
467 return (i, j)
468 a = C()
469 a.extend([0,1,2])
470 self.assertEqual(a[0], 100)
471 self.assertEqual(a[1], 101)
472 self.assertEqual(a[2], 102)
473 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000474
Georg Brandl48545522008-02-02 10:12:36 +0000475 def test_metaclass(self):
476 # Testing __metaclass__...
477 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000478 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000479 def __init__(self):
480 self.__state = 0
481 def getstate(self):
482 return self.__state
483 def setstate(self, state):
484 self.__state = state
485 a = C()
486 self.assertEqual(a.getstate(), 0)
487 a.setstate(10)
488 self.assertEqual(a.getstate(), 10)
489 class D:
490 class __metaclass__(type):
491 def myself(cls): return cls
492 self.assertEqual(D.myself(), D)
493 d = D()
494 self.assertEqual(d.__class__, D)
495 class M1(type):
496 def __new__(cls, name, bases, dict):
497 dict['__spam__'] = 1
498 return type.__new__(cls, name, bases, dict)
499 class C:
500 __metaclass__ = M1
501 self.assertEqual(C.__spam__, 1)
502 c = C()
503 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000504
Georg Brandl48545522008-02-02 10:12:36 +0000505 class _instance(object):
506 pass
507 class M2(object):
508 @staticmethod
509 def __new__(cls, name, bases, dict):
510 self = object.__new__(cls)
511 self.name = name
512 self.bases = bases
513 self.dict = dict
514 return self
515 def __call__(self):
516 it = _instance()
517 # Early binding of methods
518 for key in self.dict:
519 if key.startswith("__"):
520 continue
521 setattr(it, key, self.dict[key].__get__(it, self))
522 return it
523 class C:
524 __metaclass__ = M2
525 def spam(self):
526 return 42
527 self.assertEqual(C.name, 'C')
528 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000529 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000530 c = C()
531 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000532
Georg Brandl48545522008-02-02 10:12:36 +0000533 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000534
Georg Brandl48545522008-02-02 10:12:36 +0000535 class autosuper(type):
536 # Automatically add __super to the class
537 # This trick only works for dynamic classes
538 def __new__(metaclass, name, bases, dict):
539 cls = super(autosuper, metaclass).__new__(metaclass,
540 name, bases, dict)
541 # Name mangling for __super removes leading underscores
542 while name[:1] == "_":
543 name = name[1:]
544 if name:
545 name = "_%s__super" % name
546 else:
547 name = "__super"
548 setattr(cls, name, super(cls))
549 return cls
550 class A:
551 __metaclass__ = autosuper
552 def meth(self):
553 return "A"
554 class B(A):
555 def meth(self):
556 return "B" + self.__super.meth()
557 class C(A):
558 def meth(self):
559 return "C" + self.__super.meth()
560 class D(C, B):
561 def meth(self):
562 return "D" + self.__super.meth()
563 self.assertEqual(D().meth(), "DCBA")
564 class E(B, C):
565 def meth(self):
566 return "E" + self.__super.meth()
567 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000568
Georg Brandl48545522008-02-02 10:12:36 +0000569 class autoproperty(type):
570 # Automatically create property attributes when methods
571 # named _get_x and/or _set_x are found
572 def __new__(metaclass, name, bases, dict):
573 hits = {}
574 for key, val in dict.iteritems():
575 if key.startswith("_get_"):
576 key = key[5:]
577 get, set = hits.get(key, (None, None))
578 get = val
579 hits[key] = get, set
580 elif key.startswith("_set_"):
581 key = key[5:]
582 get, set = hits.get(key, (None, None))
583 set = val
584 hits[key] = get, set
585 for key, (get, set) in hits.iteritems():
586 dict[key] = property(get, set)
587 return super(autoproperty, metaclass).__new__(metaclass,
588 name, bases, dict)
589 class A:
590 __metaclass__ = autoproperty
591 def _get_x(self):
592 return -self.__x
593 def _set_x(self, x):
594 self.__x = -x
595 a = A()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000596 self.assertTrue(not hasattr(a, "x"))
Georg Brandl48545522008-02-02 10:12:36 +0000597 a.x = 12
598 self.assertEqual(a.x, 12)
599 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000600
Georg Brandl48545522008-02-02 10:12:36 +0000601 class multimetaclass(autoproperty, autosuper):
602 # Merge of multiple cooperating metaclasses
603 pass
604 class A:
605 __metaclass__ = multimetaclass
606 def _get_x(self):
607 return "A"
608 class B(A):
609 def _get_x(self):
610 return "B" + self.__super._get_x()
611 class C(A):
612 def _get_x(self):
613 return "C" + self.__super._get_x()
614 class D(C, B):
615 def _get_x(self):
616 return "D" + self.__super._get_x()
617 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000618
Georg Brandl48545522008-02-02 10:12:36 +0000619 # Make sure type(x) doesn't call x.__class__.__init__
620 class T(type):
621 counter = 0
622 def __init__(self, *args):
623 T.counter += 1
624 class C:
625 __metaclass__ = T
626 self.assertEqual(T.counter, 1)
627 a = C()
628 self.assertEqual(type(a), C)
629 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000630
Georg Brandl48545522008-02-02 10:12:36 +0000631 class C(object): pass
632 c = C()
633 try: c()
634 except TypeError: pass
635 else: self.fail("calling object w/o call method should raise "
636 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000637
Georg Brandl48545522008-02-02 10:12:36 +0000638 # Testing code to find most derived baseclass
639 class A(type):
640 def __new__(*args, **kwargs):
641 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642
Georg Brandl48545522008-02-02 10:12:36 +0000643 class B(object):
644 pass
645
646 class C(object):
647 __metaclass__ = A
648
649 # The most derived metaclass of D is A rather than type.
650 class D(B, C):
651 pass
652
653 def test_module_subclasses(self):
654 # Testing Python subclass of module...
655 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000656 MT = type(sys)
657 class MM(MT):
658 def __init__(self, name):
659 MT.__init__(self, name)
660 def __getattribute__(self, name):
661 log.append(("getattr", name))
662 return MT.__getattribute__(self, name)
663 def __setattr__(self, name, value):
664 log.append(("setattr", name, value))
665 MT.__setattr__(self, name, value)
666 def __delattr__(self, name):
667 log.append(("delattr", name))
668 MT.__delattr__(self, name)
669 a = MM("a")
670 a.foo = 12
671 x = a.foo
672 del a.foo
673 self.assertEqual(log, [("setattr", "foo", 12),
674 ("getattr", "foo"),
675 ("delattr", "foo")])
676
677 # http://python.org/sf/1174712
678 try:
679 class Module(types.ModuleType, str):
680 pass
681 except TypeError:
682 pass
683 else:
684 self.fail("inheriting from ModuleType and str at the same time "
685 "should fail")
686
687 def test_multiple_inheritence(self):
688 # Testing multiple inheritance...
689 class C(object):
690 def __init__(self):
691 self.__state = 0
692 def getstate(self):
693 return self.__state
694 def setstate(self, state):
695 self.__state = state
696 a = C()
697 self.assertEqual(a.getstate(), 0)
698 a.setstate(10)
699 self.assertEqual(a.getstate(), 10)
700 class D(dict, C):
701 def __init__(self):
702 type({}).__init__(self)
703 C.__init__(self)
704 d = D()
705 self.assertEqual(d.keys(), [])
706 d["hello"] = "world"
707 self.assertEqual(d.items(), [("hello", "world")])
708 self.assertEqual(d["hello"], "world")
709 self.assertEqual(d.getstate(), 0)
710 d.setstate(10)
711 self.assertEqual(d.getstate(), 10)
712 self.assertEqual(D.__mro__, (D, dict, C, object))
713
714 # SF bug #442833
715 class Node(object):
716 def __int__(self):
717 return int(self.foo())
718 def foo(self):
719 return "23"
720 class Frag(Node, list):
721 def foo(self):
722 return "42"
723 self.assertEqual(Node().__int__(), 23)
724 self.assertEqual(int(Node()), 23)
725 self.assertEqual(Frag().__int__(), 42)
726 self.assertEqual(int(Frag()), 42)
727
728 # MI mixing classic and new-style classes.
729
730 class A:
731 x = 1
732
733 class B(A):
734 pass
735
736 class C(A):
737 x = 2
738
739 class D(B, C):
740 pass
741 self.assertEqual(D.x, 1)
742
743 # Classic MRO is preserved for a classic base class.
744 class E(D, object):
745 pass
746 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
747 self.assertEqual(E.x, 1)
748
749 # But with a mix of classic bases, their MROs are combined using
750 # new-style MRO.
751 class F(B, C, object):
752 pass
753 self.assertEqual(F.__mro__, (F, B, C, A, object))
754 self.assertEqual(F.x, 2)
755
756 # Try something else.
757 class C:
758 def cmethod(self):
759 return "C a"
760 def all_method(self):
761 return "C b"
762
763 class M1(C, object):
764 def m1method(self):
765 return "M1 a"
766 def all_method(self):
767 return "M1 b"
768
769 self.assertEqual(M1.__mro__, (M1, C, object))
770 m = M1()
771 self.assertEqual(m.cmethod(), "C a")
772 self.assertEqual(m.m1method(), "M1 a")
773 self.assertEqual(m.all_method(), "M1 b")
774
775 class D(C):
776 def dmethod(self):
777 return "D a"
778 def all_method(self):
779 return "D b"
780
781 class M2(D, object):
782 def m2method(self):
783 return "M2 a"
784 def all_method(self):
785 return "M2 b"
786
787 self.assertEqual(M2.__mro__, (M2, D, C, object))
788 m = M2()
789 self.assertEqual(m.cmethod(), "C a")
790 self.assertEqual(m.dmethod(), "D a")
791 self.assertEqual(m.m2method(), "M2 a")
792 self.assertEqual(m.all_method(), "M2 b")
793
794 class M3(M1, M2, object):
795 def m3method(self):
796 return "M3 a"
797 def all_method(self):
798 return "M3 b"
799 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
800 m = M3()
801 self.assertEqual(m.cmethod(), "C a")
802 self.assertEqual(m.dmethod(), "D a")
803 self.assertEqual(m.m1method(), "M1 a")
804 self.assertEqual(m.m2method(), "M2 a")
805 self.assertEqual(m.m3method(), "M3 a")
806 self.assertEqual(m.all_method(), "M3 b")
807
808 class Classic:
809 pass
810 try:
811 class New(Classic):
812 __metaclass__ = type
813 except TypeError:
814 pass
815 else:
816 self.fail("new class with only classic bases - shouldn't be")
817
818 def test_diamond_inheritence(self):
819 # Testing multiple inheritance special cases...
820 class A(object):
821 def spam(self): return "A"
822 self.assertEqual(A().spam(), "A")
823 class B(A):
824 def boo(self): return "B"
825 def spam(self): return "B"
826 self.assertEqual(B().spam(), "B")
827 self.assertEqual(B().boo(), "B")
828 class C(A):
829 def boo(self): return "C"
830 self.assertEqual(C().spam(), "A")
831 self.assertEqual(C().boo(), "C")
832 class D(B, C): pass
833 self.assertEqual(D().spam(), "B")
834 self.assertEqual(D().boo(), "B")
835 self.assertEqual(D.__mro__, (D, B, C, A, object))
836 class E(C, B): pass
837 self.assertEqual(E().spam(), "B")
838 self.assertEqual(E().boo(), "C")
839 self.assertEqual(E.__mro__, (E, C, B, A, object))
840 # MRO order disagreement
841 try:
842 class F(D, E): pass
843 except TypeError:
844 pass
845 else:
846 self.fail("expected MRO order disagreement (F)")
847 try:
848 class G(E, D): pass
849 except TypeError:
850 pass
851 else:
852 self.fail("expected MRO order disagreement (G)")
853
854 # see thread python-dev/2002-October/029035.html
855 def test_ex5_from_c3_switch(self):
856 # Testing ex5 from C3 switch discussion...
857 class A(object): pass
858 class B(object): pass
859 class C(object): pass
860 class X(A): pass
861 class Y(A): pass
862 class Z(X,B,Y,C): pass
863 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
864
865 # see "A Monotonic Superclass Linearization for Dylan",
866 # by Kim Barrett et al. (OOPSLA 1996)
867 def test_monotonicity(self):
868 # Testing MRO monotonicity...
869 class Boat(object): pass
870 class DayBoat(Boat): pass
871 class WheelBoat(Boat): pass
872 class EngineLess(DayBoat): pass
873 class SmallMultihull(DayBoat): pass
874 class PedalWheelBoat(EngineLess,WheelBoat): pass
875 class SmallCatamaran(SmallMultihull): pass
876 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
877
878 self.assertEqual(PedalWheelBoat.__mro__,
879 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
880 self.assertEqual(SmallCatamaran.__mro__,
881 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
882 self.assertEqual(Pedalo.__mro__,
883 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
884 SmallMultihull, DayBoat, WheelBoat, Boat, object))
885
886 # see "A Monotonic Superclass Linearization for Dylan",
887 # by Kim Barrett et al. (OOPSLA 1996)
888 def test_consistency_with_epg(self):
889 # Testing consistentcy with EPG...
890 class Pane(object): pass
891 class ScrollingMixin(object): pass
892 class EditingMixin(object): pass
893 class ScrollablePane(Pane,ScrollingMixin): pass
894 class EditablePane(Pane,EditingMixin): pass
895 class EditableScrollablePane(ScrollablePane,EditablePane): pass
896
897 self.assertEqual(EditableScrollablePane.__mro__,
898 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
899 ScrollingMixin, EditingMixin, object))
900
901 def test_mro_disagreement(self):
902 # Testing error messages for MRO disagreement...
903 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000904order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000905
Georg Brandl48545522008-02-02 10:12:36 +0000906 def raises(exc, expected, callable, *args):
907 try:
908 callable(*args)
909 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000910 # the exact msg is generally considered an impl detail
911 if test_support.check_impl_detail():
912 if not str(msg).startswith(expected):
913 self.fail("Message %r, expected %r" %
914 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000915 else:
916 self.fail("Expected %s" % exc)
917
918 class A(object): pass
919 class B(A): pass
920 class C(object): pass
921
922 # Test some very simple errors
923 raises(TypeError, "duplicate base class A",
924 type, "X", (A, A), {})
925 raises(TypeError, mro_err_msg,
926 type, "X", (A, B), {})
927 raises(TypeError, mro_err_msg,
928 type, "X", (A, C, B), {})
929 # Test a slightly more complex error
930 class GridLayout(object): pass
931 class HorizontalGrid(GridLayout): pass
932 class VerticalGrid(GridLayout): pass
933 class HVGrid(HorizontalGrid, VerticalGrid): pass
934 class VHGrid(VerticalGrid, HorizontalGrid): pass
935 raises(TypeError, mro_err_msg,
936 type, "ConfusedGrid", (HVGrid, VHGrid), {})
937
938 def test_object_class(self):
939 # Testing object class...
940 a = object()
941 self.assertEqual(a.__class__, object)
942 self.assertEqual(type(a), object)
943 b = object()
944 self.assertNotEqual(a, b)
945 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000946 try:
Georg Brandl48545522008-02-02 10:12:36 +0000947 a.foo = 12
948 except (AttributeError, TypeError):
949 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000950 else:
Georg Brandl48545522008-02-02 10:12:36 +0000951 self.fail("object() should not allow setting a foo attribute")
952 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000953
Georg Brandl48545522008-02-02 10:12:36 +0000954 class Cdict(object):
955 pass
956 x = Cdict()
957 self.assertEqual(x.__dict__, {})
958 x.foo = 1
959 self.assertEqual(x.foo, 1)
960 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000961
Georg Brandl48545522008-02-02 10:12:36 +0000962 def test_slots(self):
963 # Testing __slots__...
964 class C0(object):
965 __slots__ = []
966 x = C0()
967 self.assertFalse(hasattr(x, "__dict__"))
968 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000969
Georg Brandl48545522008-02-02 10:12:36 +0000970 class C1(object):
971 __slots__ = ['a']
972 x = C1()
973 self.assertFalse(hasattr(x, "__dict__"))
974 self.assertFalse(hasattr(x, "a"))
975 x.a = 1
976 self.assertEqual(x.a, 1)
977 x.a = None
978 self.assertEqual(x.a, None)
979 del x.a
980 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981
Georg Brandl48545522008-02-02 10:12:36 +0000982 class C3(object):
983 __slots__ = ['a', 'b', 'c']
984 x = C3()
985 self.assertFalse(hasattr(x, "__dict__"))
986 self.assertFalse(hasattr(x, 'a'))
987 self.assertFalse(hasattr(x, 'b'))
988 self.assertFalse(hasattr(x, 'c'))
989 x.a = 1
990 x.b = 2
991 x.c = 3
992 self.assertEqual(x.a, 1)
993 self.assertEqual(x.b, 2)
994 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995
Georg Brandl48545522008-02-02 10:12:36 +0000996 class C4(object):
997 """Validate name mangling"""
998 __slots__ = ['__a']
999 def __init__(self, value):
1000 self.__a = value
1001 def get(self):
1002 return self.__a
1003 x = C4(5)
1004 self.assertFalse(hasattr(x, '__dict__'))
1005 self.assertFalse(hasattr(x, '__a'))
1006 self.assertEqual(x.get(), 5)
1007 try:
1008 x.__a = 6
1009 except AttributeError:
1010 pass
1011 else:
1012 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013
Georg Brandl48545522008-02-02 10:12:36 +00001014 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001015 try:
1016 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001017 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001018 except TypeError:
1019 pass
1020 else:
Georg Brandl48545522008-02-02 10:12:36 +00001021 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001022 try:
Georg Brandl48545522008-02-02 10:12:36 +00001023 class C(object):
1024 __slots__ = ["foo bar"]
1025 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001026 pass
Georg Brandl48545522008-02-02 10:12:36 +00001027 else:
1028 self.fail("['foo bar'] slots not caught")
1029 try:
1030 class C(object):
1031 __slots__ = ["foo\0bar"]
1032 except TypeError:
1033 pass
1034 else:
1035 self.fail("['foo\\0bar'] slots not caught")
1036 try:
1037 class C(object):
1038 __slots__ = ["1"]
1039 except TypeError:
1040 pass
1041 else:
1042 self.fail("['1'] slots not caught")
1043 try:
1044 class C(object):
1045 __slots__ = [""]
1046 except TypeError:
1047 pass
1048 else:
1049 self.fail("[''] slots not caught")
1050 class C(object):
1051 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1052 # XXX(nnorwitz): was there supposed to be something tested
1053 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001054
Georg Brandl48545522008-02-02 10:12:36 +00001055 # Test a single string is not expanded as a sequence.
1056 class C(object):
1057 __slots__ = "abc"
1058 c = C()
1059 c.abc = 5
1060 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001061
Georg Brandl48545522008-02-02 10:12:36 +00001062 # Test unicode slot names
1063 try:
1064 unicode
1065 except NameError:
1066 pass
1067 else:
1068 # Test a single unicode string is not expanded as a sequence.
1069 class C(object):
1070 __slots__ = unicode("abc")
1071 c = C()
1072 c.abc = 5
1073 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001074
Georg Brandl48545522008-02-02 10:12:36 +00001075 # _unicode_to_string used to modify slots in certain circumstances
1076 slots = (unicode("foo"), unicode("bar"))
1077 class C(object):
1078 __slots__ = slots
1079 x = C()
1080 x.foo = 5
1081 self.assertEqual(x.foo, 5)
1082 self.assertEqual(type(slots[0]), unicode)
1083 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001084 try:
Georg Brandl48545522008-02-02 10:12:36 +00001085 class C(object):
1086 __slots__ = [unichr(128)]
1087 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001088 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001089 else:
Georg Brandl48545522008-02-02 10:12:36 +00001090 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001091
Georg Brandl48545522008-02-02 10:12:36 +00001092 # Test leaks
1093 class Counted(object):
1094 counter = 0 # counts the number of instances alive
1095 def __init__(self):
1096 Counted.counter += 1
1097 def __del__(self):
1098 Counted.counter -= 1
1099 class C(object):
1100 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001101 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001102 x.a = Counted()
1103 x.b = Counted()
1104 x.c = Counted()
1105 self.assertEqual(Counted.counter, 3)
1106 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001107 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001108 self.assertEqual(Counted.counter, 0)
1109 class D(C):
1110 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001111 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001112 x.a = Counted()
1113 x.z = Counted()
1114 self.assertEqual(Counted.counter, 2)
1115 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001116 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001117 self.assertEqual(Counted.counter, 0)
1118 class E(D):
1119 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001120 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001121 x.a = Counted()
1122 x.z = Counted()
1123 x.e = Counted()
1124 self.assertEqual(Counted.counter, 3)
1125 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001126 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001127 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001128
Georg Brandl48545522008-02-02 10:12:36 +00001129 # Test cyclical leaks [SF bug 519621]
1130 class F(object):
1131 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001132 s = F()
1133 s.a = [Counted(), s]
1134 self.assertEqual(Counted.counter, 1)
1135 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001136 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001137 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001138
Georg Brandl48545522008-02-02 10:12:36 +00001139 # Test lookup leaks [SF bug 572567]
Georg Brandla4f46e12010-02-07 17:03:15 +00001140 import gc
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001141 if hasattr(gc, 'get_objects'):
1142 class G(object):
1143 def __cmp__(self, other):
1144 return 0
1145 __hash__ = None # Silence Py3k warning
1146 g = G()
1147 orig_objects = len(gc.get_objects())
1148 for i in xrange(10):
1149 g==g
1150 new_objects = len(gc.get_objects())
1151 self.assertEqual(orig_objects, new_objects)
1152
Georg Brandl48545522008-02-02 10:12:36 +00001153 class H(object):
1154 __slots__ = ['a', 'b']
1155 def __init__(self):
1156 self.a = 1
1157 self.b = 2
1158 def __del__(self_):
1159 self.assertEqual(self_.a, 1)
1160 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001161 with test_support.captured_output('stderr') as s:
1162 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001163 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001164 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001165
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001166 class X(object):
1167 __slots__ = "a"
1168 with self.assertRaises(AttributeError):
1169 del X().a
1170
Georg Brandl48545522008-02-02 10:12:36 +00001171 def test_slots_special(self):
1172 # Testing __dict__ and __weakref__ in __slots__...
1173 class D(object):
1174 __slots__ = ["__dict__"]
1175 a = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001176 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl48545522008-02-02 10:12:36 +00001177 self.assertFalse(hasattr(a, "__weakref__"))
1178 a.foo = 42
1179 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001180
Georg Brandl48545522008-02-02 10:12:36 +00001181 class W(object):
1182 __slots__ = ["__weakref__"]
1183 a = W()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001184 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001185 self.assertFalse(hasattr(a, "__dict__"))
1186 try:
1187 a.foo = 42
1188 except AttributeError:
1189 pass
1190 else:
1191 self.fail("shouldn't be allowed to set a.foo")
1192
1193 class C1(W, D):
1194 __slots__ = []
1195 a = C1()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001196 self.assertTrue(hasattr(a, "__dict__"))
1197 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001198 a.foo = 42
1199 self.assertEqual(a.__dict__, {"foo": 42})
1200
1201 class C2(D, W):
1202 __slots__ = []
1203 a = C2()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001204 self.assertTrue(hasattr(a, "__dict__"))
1205 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001206 a.foo = 42
1207 self.assertEqual(a.__dict__, {"foo": 42})
1208
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001209 def test_slots_descriptor(self):
1210 # Issue2115: slot descriptors did not correctly check
1211 # the type of the given object
1212 import abc
1213 class MyABC:
1214 __metaclass__ = abc.ABCMeta
1215 __slots__ = "a"
1216
1217 class Unrelated(object):
1218 pass
1219 MyABC.register(Unrelated)
1220
1221 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001222 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001223
1224 # This used to crash
1225 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1226
Benjamin Peterson4895af42009-12-13 16:36:53 +00001227 def test_metaclass_cmp(self):
1228 # See bug 7491.
1229 class M(type):
1230 def __cmp__(self, other):
1231 return -1
1232 class X(object):
1233 __metaclass__ = M
1234 self.assertTrue(X < M)
1235
Georg Brandl48545522008-02-02 10:12:36 +00001236 def test_dynamics(self):
1237 # Testing class attribute propagation...
1238 class D(object):
1239 pass
1240 class E(D):
1241 pass
1242 class F(D):
1243 pass
1244 D.foo = 1
1245 self.assertEqual(D.foo, 1)
1246 # Test that dynamic attributes are inherited
1247 self.assertEqual(E.foo, 1)
1248 self.assertEqual(F.foo, 1)
1249 # Test dynamic instances
1250 class C(object):
1251 pass
1252 a = C()
1253 self.assertFalse(hasattr(a, "foobar"))
1254 C.foobar = 2
1255 self.assertEqual(a.foobar, 2)
1256 C.method = lambda self: 42
1257 self.assertEqual(a.method(), 42)
1258 C.__repr__ = lambda self: "C()"
1259 self.assertEqual(repr(a), "C()")
1260 C.__int__ = lambda self: 100
1261 self.assertEqual(int(a), 100)
1262 self.assertEqual(a.foobar, 2)
1263 self.assertFalse(hasattr(a, "spam"))
1264 def mygetattr(self, name):
1265 if name == "spam":
1266 return "spam"
1267 raise AttributeError
1268 C.__getattr__ = mygetattr
1269 self.assertEqual(a.spam, "spam")
1270 a.new = 12
1271 self.assertEqual(a.new, 12)
1272 def mysetattr(self, name, value):
1273 if name == "spam":
1274 raise AttributeError
1275 return object.__setattr__(self, name, value)
1276 C.__setattr__ = mysetattr
1277 try:
1278 a.spam = "not spam"
1279 except AttributeError:
1280 pass
1281 else:
1282 self.fail("expected AttributeError")
1283 self.assertEqual(a.spam, "spam")
1284 class D(C):
1285 pass
1286 d = D()
1287 d.foo = 1
1288 self.assertEqual(d.foo, 1)
1289
1290 # Test handling of int*seq and seq*int
1291 class I(int):
1292 pass
1293 self.assertEqual("a"*I(2), "aa")
1294 self.assertEqual(I(2)*"a", "aa")
1295 self.assertEqual(2*I(3), 6)
1296 self.assertEqual(I(3)*2, 6)
1297 self.assertEqual(I(3)*I(2), 6)
1298
1299 # Test handling of long*seq and seq*long
1300 class L(long):
1301 pass
1302 self.assertEqual("a"*L(2L), "aa")
1303 self.assertEqual(L(2L)*"a", "aa")
1304 self.assertEqual(2*L(3), 6)
1305 self.assertEqual(L(3)*2, 6)
1306 self.assertEqual(L(3)*L(2), 6)
1307
1308 # Test comparison of classes with dynamic metaclasses
1309 class dynamicmetaclass(type):
1310 pass
1311 class someclass:
1312 __metaclass__ = dynamicmetaclass
1313 self.assertNotEqual(someclass, object)
1314
1315 def test_errors(self):
1316 # Testing errors...
1317 try:
1318 class C(list, dict):
1319 pass
1320 except TypeError:
1321 pass
1322 else:
1323 self.fail("inheritance from both list and dict should be illegal")
1324
1325 try:
1326 class C(object, None):
1327 pass
1328 except TypeError:
1329 pass
1330 else:
1331 self.fail("inheritance from non-type should be illegal")
1332 class Classic:
1333 pass
1334
1335 try:
1336 class C(type(len)):
1337 pass
1338 except TypeError:
1339 pass
1340 else:
1341 self.fail("inheritance from CFunction should be illegal")
1342
1343 try:
1344 class C(object):
1345 __slots__ = 1
1346 except TypeError:
1347 pass
1348 else:
1349 self.fail("__slots__ = 1 should be illegal")
1350
1351 try:
1352 class C(object):
1353 __slots__ = [1]
1354 except TypeError:
1355 pass
1356 else:
1357 self.fail("__slots__ = [1] should be illegal")
1358
1359 class M1(type):
1360 pass
1361 class M2(type):
1362 pass
1363 class A1(object):
1364 __metaclass__ = M1
1365 class A2(object):
1366 __metaclass__ = M2
1367 try:
1368 class B(A1, A2):
1369 pass
1370 except TypeError:
1371 pass
1372 else:
1373 self.fail("finding the most derived metaclass should have failed")
1374
1375 def test_classmethods(self):
1376 # Testing class methods...
1377 class C(object):
1378 def foo(*a): return a
1379 goo = classmethod(foo)
1380 c = C()
1381 self.assertEqual(C.goo(1), (C, 1))
1382 self.assertEqual(c.goo(1), (C, 1))
1383 self.assertEqual(c.foo(1), (c, 1))
1384 class D(C):
1385 pass
1386 d = D()
1387 self.assertEqual(D.goo(1), (D, 1))
1388 self.assertEqual(d.goo(1), (D, 1))
1389 self.assertEqual(d.foo(1), (d, 1))
1390 self.assertEqual(D.foo(d, 1), (d, 1))
1391 # Test for a specific crash (SF bug 528132)
1392 def f(cls, arg): return (cls, arg)
1393 ff = classmethod(f)
1394 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1395 self.assertEqual(ff.__get__(0)(42), (int, 42))
1396
1397 # Test super() with classmethods (SF bug 535444)
1398 self.assertEqual(C.goo.im_self, C)
1399 self.assertEqual(D.goo.im_self, D)
1400 self.assertEqual(super(D,D).goo.im_self, D)
1401 self.assertEqual(super(D,d).goo.im_self, D)
1402 self.assertEqual(super(D,D).goo(), (D,))
1403 self.assertEqual(super(D,d).goo(), (D,))
1404
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001405 # Verify that a non-callable will raise
1406 meth = classmethod(1).__get__(1)
1407 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001408
1409 # Verify that classmethod() doesn't allow keyword args
1410 try:
1411 classmethod(f, kw=1)
1412 except TypeError:
1413 pass
1414 else:
1415 self.fail("classmethod shouldn't accept keyword args")
1416
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001417 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001418 def test_classmethods_in_c(self):
1419 # Testing C-based class methods...
1420 import xxsubtype as spam
1421 a = (1, 2, 3)
1422 d = {'abc': 123}
1423 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1424 self.assertEqual(x, spam.spamlist)
1425 self.assertEqual(a, a1)
1426 self.assertEqual(d, d1)
1427 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1428 self.assertEqual(x, spam.spamlist)
1429 self.assertEqual(a, a1)
1430 self.assertEqual(d, d1)
1431
1432 def test_staticmethods(self):
1433 # Testing static methods...
1434 class C(object):
1435 def foo(*a): return a
1436 goo = staticmethod(foo)
1437 c = C()
1438 self.assertEqual(C.goo(1), (1,))
1439 self.assertEqual(c.goo(1), (1,))
1440 self.assertEqual(c.foo(1), (c, 1,))
1441 class D(C):
1442 pass
1443 d = D()
1444 self.assertEqual(D.goo(1), (1,))
1445 self.assertEqual(d.goo(1), (1,))
1446 self.assertEqual(d.foo(1), (d, 1))
1447 self.assertEqual(D.foo(d, 1), (d, 1))
1448
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001449 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001450 def test_staticmethods_in_c(self):
1451 # Testing C-based static methods...
1452 import xxsubtype as spam
1453 a = (1, 2, 3)
1454 d = {"abc": 123}
1455 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1456 self.assertEqual(x, None)
1457 self.assertEqual(a, a1)
1458 self.assertEqual(d, d1)
1459 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1460 self.assertEqual(x, None)
1461 self.assertEqual(a, a1)
1462 self.assertEqual(d, d1)
1463
1464 def test_classic(self):
1465 # Testing classic classes...
1466 class C:
1467 def foo(*a): return a
1468 goo = classmethod(foo)
1469 c = C()
1470 self.assertEqual(C.goo(1), (C, 1))
1471 self.assertEqual(c.goo(1), (C, 1))
1472 self.assertEqual(c.foo(1), (c, 1))
1473 class D(C):
1474 pass
1475 d = D()
1476 self.assertEqual(D.goo(1), (D, 1))
1477 self.assertEqual(d.goo(1), (D, 1))
1478 self.assertEqual(d.foo(1), (d, 1))
1479 self.assertEqual(D.foo(d, 1), (d, 1))
1480 class E: # *not* subclassing from C
1481 foo = C.foo
1482 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001483 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001484
1485 def test_compattr(self):
1486 # Testing computed attributes...
1487 class C(object):
1488 class computed_attribute(object):
1489 def __init__(self, get, set=None, delete=None):
1490 self.__get = get
1491 self.__set = set
1492 self.__delete = delete
1493 def __get__(self, obj, type=None):
1494 return self.__get(obj)
1495 def __set__(self, obj, value):
1496 return self.__set(obj, value)
1497 def __delete__(self, obj):
1498 return self.__delete(obj)
1499 def __init__(self):
1500 self.__x = 0
1501 def __get_x(self):
1502 x = self.__x
1503 self.__x = x+1
1504 return x
1505 def __set_x(self, x):
1506 self.__x = x
1507 def __delete_x(self):
1508 del self.__x
1509 x = computed_attribute(__get_x, __set_x, __delete_x)
1510 a = C()
1511 self.assertEqual(a.x, 0)
1512 self.assertEqual(a.x, 1)
1513 a.x = 10
1514 self.assertEqual(a.x, 10)
1515 self.assertEqual(a.x, 11)
1516 del a.x
1517 self.assertEqual(hasattr(a, 'x'), 0)
1518
1519 def test_newslots(self):
1520 # Testing __new__ slot override...
1521 class C(list):
1522 def __new__(cls):
1523 self = list.__new__(cls)
1524 self.foo = 1
1525 return self
1526 def __init__(self):
1527 self.foo = self.foo + 2
1528 a = C()
1529 self.assertEqual(a.foo, 3)
1530 self.assertEqual(a.__class__, C)
1531 class D(C):
1532 pass
1533 b = D()
1534 self.assertEqual(b.foo, 3)
1535 self.assertEqual(b.__class__, D)
1536
1537 def test_altmro(self):
1538 # Testing mro() and overriding it...
1539 class A(object):
1540 def f(self): return "A"
1541 class B(A):
1542 pass
1543 class C(A):
1544 def f(self): return "C"
1545 class D(B, C):
1546 pass
1547 self.assertEqual(D.mro(), [D, B, C, A, object])
1548 self.assertEqual(D.__mro__, (D, B, C, A, object))
1549 self.assertEqual(D().f(), "C")
1550
1551 class PerverseMetaType(type):
1552 def mro(cls):
1553 L = type.mro(cls)
1554 L.reverse()
1555 return L
1556 class X(D,B,C,A):
1557 __metaclass__ = PerverseMetaType
1558 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1559 self.assertEqual(X().f(), "A")
1560
1561 try:
1562 class X(object):
1563 class __metaclass__(type):
1564 def mro(self):
1565 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001566 # In CPython, the class creation above already raises
1567 # TypeError, as a protection against the fact that
1568 # instances of X would segfault it. In other Python
1569 # implementations it would be ok to let the class X
1570 # be created, but instead get a clean TypeError on the
1571 # __setitem__ below.
1572 x = object.__new__(X)
1573 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001574 except TypeError:
1575 pass
1576 else:
1577 self.fail("devious mro() return not caught")
1578
1579 try:
1580 class X(object):
1581 class __metaclass__(type):
1582 def mro(self):
1583 return [1]
1584 except TypeError:
1585 pass
1586 else:
1587 self.fail("non-class mro() return not caught")
1588
1589 try:
1590 class X(object):
1591 class __metaclass__(type):
1592 def mro(self):
1593 return 1
1594 except TypeError:
1595 pass
1596 else:
1597 self.fail("non-sequence mro() return not caught")
1598
1599 def test_overloading(self):
1600 # Testing operator overloading...
1601
1602 class B(object):
1603 "Intermediate class because object doesn't have a __setattr__"
1604
1605 class C(B):
1606 def __getattr__(self, name):
1607 if name == "foo":
1608 return ("getattr", name)
1609 else:
1610 raise AttributeError
1611 def __setattr__(self, name, value):
1612 if name == "foo":
1613 self.setattr = (name, value)
1614 else:
1615 return B.__setattr__(self, name, value)
1616 def __delattr__(self, name):
1617 if name == "foo":
1618 self.delattr = name
1619 else:
1620 return B.__delattr__(self, name)
1621
1622 def __getitem__(self, key):
1623 return ("getitem", key)
1624 def __setitem__(self, key, value):
1625 self.setitem = (key, value)
1626 def __delitem__(self, key):
1627 self.delitem = key
1628
1629 def __getslice__(self, i, j):
1630 return ("getslice", i, j)
1631 def __setslice__(self, i, j, value):
1632 self.setslice = (i, j, value)
1633 def __delslice__(self, i, j):
1634 self.delslice = (i, j)
1635
1636 a = C()
1637 self.assertEqual(a.foo, ("getattr", "foo"))
1638 a.foo = 12
1639 self.assertEqual(a.setattr, ("foo", 12))
1640 del a.foo
1641 self.assertEqual(a.delattr, "foo")
1642
1643 self.assertEqual(a[12], ("getitem", 12))
1644 a[12] = 21
1645 self.assertEqual(a.setitem, (12, 21))
1646 del a[12]
1647 self.assertEqual(a.delitem, 12)
1648
1649 self.assertEqual(a[0:10], ("getslice", 0, 10))
1650 a[0:10] = "foo"
1651 self.assertEqual(a.setslice, (0, 10, "foo"))
1652 del a[0:10]
1653 self.assertEqual(a.delslice, (0, 10))
1654
1655 def test_methods(self):
1656 # Testing methods...
1657 class C(object):
1658 def __init__(self, x):
1659 self.x = x
1660 def foo(self):
1661 return self.x
1662 c1 = C(1)
1663 self.assertEqual(c1.foo(), 1)
1664 class D(C):
1665 boo = C.foo
1666 goo = c1.foo
1667 d2 = D(2)
1668 self.assertEqual(d2.foo(), 2)
1669 self.assertEqual(d2.boo(), 2)
1670 self.assertEqual(d2.goo(), 1)
1671 class E(object):
1672 foo = C.foo
1673 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001674 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001675
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001676 def test_special_method_lookup(self):
1677 # The lookup of special methods bypasses __getattr__ and
1678 # __getattribute__, but they still can be descriptors.
1679
1680 def run_context(manager):
1681 with manager:
1682 pass
1683 def iden(self):
1684 return self
1685 def hello(self):
1686 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001687 def empty_seq(self):
1688 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001689 def zero(self):
1690 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001691 def complex_num(self):
1692 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001693 def stop(self):
1694 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001695 def return_true(self, thing=None):
1696 return True
1697 def do_isinstance(obj):
1698 return isinstance(int, obj)
1699 def do_issubclass(obj):
1700 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001701 def swallow(*args):
1702 pass
1703 def do_dict_missing(checker):
1704 class DictSub(checker.__class__, dict):
1705 pass
1706 self.assertEqual(DictSub()["hi"], 4)
1707 def some_number(self_, key):
1708 self.assertEqual(key, "hi")
1709 return 4
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001710
1711 # It would be nice to have every special method tested here, but I'm
1712 # only listing the ones I can remember outside of typeobject.c, since it
1713 # does it right.
1714 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001715 ("__unicode__", unicode, hello, set(), {}),
1716 ("__reversed__", reversed, empty_seq, set(), {}),
1717 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001718 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001719 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1720 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001721 ("__missing__", do_dict_missing, some_number,
1722 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001723 ("__subclasscheck__", do_issubclass, return_true,
1724 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001725 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1726 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001727 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001728 ]
1729
1730 class Checker(object):
1731 def __getattr__(self, attr, test=self):
1732 test.fail("__getattr__ called with {0}".format(attr))
1733 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001734 if attr not in ok:
1735 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001736 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001737 class SpecialDescr(object):
1738 def __init__(self, impl):
1739 self.impl = impl
1740 def __get__(self, obj, owner):
1741 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001742 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001743 class MyException(Exception):
1744 pass
1745 class ErrDescr(object):
1746 def __get__(self, obj, owner):
1747 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001748
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001749 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001750 class X(Checker):
1751 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001752 for attr, obj in env.iteritems():
1753 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001754 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001755 runner(X())
1756
1757 record = []
1758 class X(Checker):
1759 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001760 for attr, obj in env.iteritems():
1761 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001762 setattr(X, name, SpecialDescr(meth_impl))
1763 runner(X())
1764 self.assertEqual(record, [1], name)
1765
Benjamin Peterson87e50062009-05-25 02:40:21 +00001766 class X(Checker):
1767 pass
1768 for attr, obj in env.iteritems():
1769 setattr(X, attr, obj)
1770 setattr(X, name, ErrDescr())
1771 try:
1772 runner(X())
1773 except MyException:
1774 pass
1775 else:
1776 self.fail("{0!r} didn't raise".format(name))
1777
Georg Brandl48545522008-02-02 10:12:36 +00001778 def test_specials(self):
1779 # Testing special operators...
1780 # Test operators like __hash__ for which a built-in default exists
1781
1782 # Test the default behavior for static classes
1783 class C(object):
1784 def __getitem__(self, i):
1785 if 0 <= i < 10: return i
1786 raise IndexError
1787 c1 = C()
1788 c2 = C()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001789 self.assertTrue(not not c1) # What?
Georg Brandl48545522008-02-02 10:12:36 +00001790 self.assertNotEqual(id(c1), id(c2))
1791 hash(c1)
1792 hash(c2)
1793 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1794 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001795 self.assertTrue(c1 != c2)
1796 self.assertTrue(not c1 != c1)
1797 self.assertTrue(not c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001798 # Note that the module name appears in str/repr, and that varies
1799 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001800 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001801 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001802 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001803 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001804 self.assertIn(i, c1)
1805 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001806 # Test the default behavior for dynamic classes
1807 class D(object):
1808 def __getitem__(self, i):
1809 if 0 <= i < 10: return i
1810 raise IndexError
1811 d1 = D()
1812 d2 = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001813 self.assertTrue(not not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001814 self.assertNotEqual(id(d1), id(d2))
1815 hash(d1)
1816 hash(d2)
1817 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1818 self.assertEqual(d1, d1)
1819 self.assertNotEqual(d1, d2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001820 self.assertTrue(not d1 != d1)
1821 self.assertTrue(not d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001822 # Note that the module name appears in str/repr, and that varies
1823 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001824 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001825 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001826 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001827 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001828 self.assertIn(i, d1)
1829 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001830 # Test overridden behavior for static classes
1831 class Proxy(object):
1832 def __init__(self, x):
1833 self.x = x
1834 def __nonzero__(self):
1835 return not not self.x
1836 def __hash__(self):
1837 return hash(self.x)
1838 def __eq__(self, other):
1839 return self.x == other
1840 def __ne__(self, other):
1841 return self.x != other
1842 def __cmp__(self, other):
1843 return cmp(self.x, other.x)
1844 def __str__(self):
1845 return "Proxy:%s" % self.x
1846 def __repr__(self):
1847 return "Proxy(%r)" % self.x
1848 def __contains__(self, value):
1849 return value in self.x
1850 p0 = Proxy(0)
1851 p1 = Proxy(1)
1852 p_1 = Proxy(-1)
1853 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001854 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001855 self.assertEqual(hash(p0), hash(0))
1856 self.assertEqual(p0, p0)
1857 self.assertNotEqual(p0, p1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001858 self.assertTrue(not p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001859 self.assertEqual(not p0, p1)
1860 self.assertEqual(cmp(p0, p1), -1)
1861 self.assertEqual(cmp(p0, p0), 0)
1862 self.assertEqual(cmp(p0, p_1), 1)
1863 self.assertEqual(str(p0), "Proxy:0")
1864 self.assertEqual(repr(p0), "Proxy(0)")
1865 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001866 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001867 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001868 self.assertIn(i, p10)
1869 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001870 # Test overridden behavior for dynamic classes
1871 class DProxy(object):
1872 def __init__(self, x):
1873 self.x = x
1874 def __nonzero__(self):
1875 return not not self.x
1876 def __hash__(self):
1877 return hash(self.x)
1878 def __eq__(self, other):
1879 return self.x == other
1880 def __ne__(self, other):
1881 return self.x != other
1882 def __cmp__(self, other):
1883 return cmp(self.x, other.x)
1884 def __str__(self):
1885 return "DProxy:%s" % self.x
1886 def __repr__(self):
1887 return "DProxy(%r)" % self.x
1888 def __contains__(self, value):
1889 return value in self.x
1890 p0 = DProxy(0)
1891 p1 = DProxy(1)
1892 p_1 = DProxy(-1)
1893 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001894 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001895 self.assertEqual(hash(p0), hash(0))
1896 self.assertEqual(p0, p0)
1897 self.assertNotEqual(p0, p1)
1898 self.assertNotEqual(not p0, p0)
1899 self.assertEqual(not p0, p1)
1900 self.assertEqual(cmp(p0, p1), -1)
1901 self.assertEqual(cmp(p0, p0), 0)
1902 self.assertEqual(cmp(p0, p_1), 1)
1903 self.assertEqual(str(p0), "DProxy:0")
1904 self.assertEqual(repr(p0), "DProxy(0)")
1905 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001906 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001907 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001908 self.assertIn(i, p10)
1909 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001910
1911 # Safety test for __cmp__
1912 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001913 if not hasattr(a, '__cmp__'):
1914 return # some types don't have a __cmp__ any more (so the
1915 # test doesn't make sense any more), or maybe they
1916 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001917 try:
1918 a.__class__.__cmp__(a, b)
1919 except TypeError:
1920 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001921 else:
Georg Brandl48545522008-02-02 10:12:36 +00001922 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1923 a.__class__, a, b))
1924
1925 unsafecmp(u"123", "123")
1926 unsafecmp("123", u"123")
1927 unsafecmp(1, 1.0)
1928 unsafecmp(1.0, 1)
1929 unsafecmp(1, 1L)
1930 unsafecmp(1L, 1)
1931
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001932 @test_support.impl_detail("custom logic for printing to real file objects")
1933 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001934 # Testing recursion checks ...
1935 class Letter(str):
1936 def __new__(cls, letter):
1937 if letter == 'EPS':
1938 return str.__new__(cls)
1939 return str.__new__(cls, letter)
1940 def __str__(self):
1941 if not self:
1942 return 'EPS'
1943 return self
1944 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00001945 test_stdout = sys.stdout
1946 sys.stdout = test_support.get_original_stdout()
1947 try:
1948 # nothing should actually be printed, this should raise an exception
1949 print Letter('w')
1950 except RuntimeError:
1951 pass
1952 else:
1953 self.fail("expected a RuntimeError for print recursion")
1954 finally:
1955 sys.stdout = test_stdout
1956
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001957 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001958 # Bug #1202533.
1959 class A(object):
1960 pass
1961 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1962 try:
1963 A()*2
1964 except RuntimeError:
1965 pass
1966 else:
1967 self.fail("expected a RuntimeError")
1968
1969 def test_weakrefs(self):
1970 # Testing weak references...
1971 import weakref
1972 class C(object):
1973 pass
1974 c = C()
1975 r = weakref.ref(c)
1976 self.assertEqual(r(), c)
1977 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001978 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001979 self.assertEqual(r(), None)
1980 del r
1981 class NoWeak(object):
1982 __slots__ = ['foo']
1983 no = NoWeak()
1984 try:
1985 weakref.ref(no)
1986 except TypeError, msg:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001987 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001988 else:
1989 self.fail("weakref.ref(no) should be illegal")
1990 class Weak(object):
1991 __slots__ = ['foo', '__weakref__']
1992 yes = Weak()
1993 r = weakref.ref(yes)
1994 self.assertEqual(r(), yes)
1995 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001996 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001997 self.assertEqual(r(), None)
1998 del r
1999
2000 def test_properties(self):
2001 # Testing property...
2002 class C(object):
2003 def getx(self):
2004 return self.__x
2005 def setx(self, value):
2006 self.__x = value
2007 def delx(self):
2008 del self.__x
2009 x = property(getx, setx, delx, doc="I'm the x property.")
2010 a = C()
2011 self.assertFalse(hasattr(a, "x"))
2012 a.x = 42
2013 self.assertEqual(a._C__x, 42)
2014 self.assertEqual(a.x, 42)
2015 del a.x
2016 self.assertFalse(hasattr(a, "x"))
2017 self.assertFalse(hasattr(a, "_C__x"))
2018 C.x.__set__(a, 100)
2019 self.assertEqual(C.x.__get__(a), 100)
2020 C.x.__delete__(a)
2021 self.assertFalse(hasattr(a, "x"))
2022
2023 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002024 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002025
2026 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002027 self.assertIn("__doc__", attrs)
2028 self.assertIn("fget", attrs)
2029 self.assertIn("fset", attrs)
2030 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002031
2032 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002033 self.assertTrue(raw.fget is C.__dict__['getx'])
2034 self.assertTrue(raw.fset is C.__dict__['setx'])
2035 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002036
2037 for attr in "__doc__", "fget", "fset", "fdel":
2038 try:
2039 setattr(raw, attr, 42)
2040 except TypeError, msg:
2041 if str(msg).find('readonly') < 0:
2042 self.fail("when setting readonly attr %r on a property, "
2043 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002044 else:
Georg Brandl48545522008-02-02 10:12:36 +00002045 self.fail("expected TypeError from trying to set readonly %r "
2046 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002047
Georg Brandl48545522008-02-02 10:12:36 +00002048 class D(object):
2049 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002050
Georg Brandl48545522008-02-02 10:12:36 +00002051 d = D()
2052 try:
2053 for i in d:
2054 str(i)
2055 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002056 pass
Georg Brandl48545522008-02-02 10:12:36 +00002057 else:
2058 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002059
Georg Brandl48545522008-02-02 10:12:36 +00002060 class E(object):
2061 def getter(self):
2062 "getter method"
2063 return 0
2064 def setter(self_, value):
2065 "setter method"
2066 pass
2067 prop = property(getter)
2068 self.assertEqual(prop.__doc__, "getter method")
2069 prop2 = property(fset=setter)
2070 self.assertEqual(prop2.__doc__, None)
2071
2072 # this segfaulted in 2.5b2
2073 try:
2074 import _testcapi
2075 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002076 pass
Georg Brandl48545522008-02-02 10:12:36 +00002077 else:
2078 class X(object):
2079 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002080
Georg Brandl48545522008-02-02 10:12:36 +00002081 def test_properties_plus(self):
2082 class C(object):
2083 foo = property(doc="hello")
2084 @foo.getter
2085 def foo(self):
2086 return self._foo
2087 @foo.setter
2088 def foo(self, value):
2089 self._foo = abs(value)
2090 @foo.deleter
2091 def foo(self):
2092 del self._foo
2093 c = C()
2094 self.assertEqual(C.foo.__doc__, "hello")
2095 self.assertFalse(hasattr(c, "foo"))
2096 c.foo = -42
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002097 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl48545522008-02-02 10:12:36 +00002098 self.assertEqual(c._foo, 42)
2099 self.assertEqual(c.foo, 42)
2100 del c.foo
2101 self.assertFalse(hasattr(c, '_foo'))
2102 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002103
Georg Brandl48545522008-02-02 10:12:36 +00002104 class D(C):
2105 @C.foo.deleter
2106 def foo(self):
2107 try:
2108 del self._foo
2109 except AttributeError:
2110 pass
2111 d = D()
2112 d.foo = 24
2113 self.assertEqual(d.foo, 24)
2114 del d.foo
2115 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002116
Georg Brandl48545522008-02-02 10:12:36 +00002117 class E(object):
2118 @property
2119 def foo(self):
2120 return self._foo
2121 @foo.setter
2122 def foo(self, value):
2123 raise RuntimeError
2124 @foo.setter
2125 def foo(self, value):
2126 self._foo = abs(value)
2127 @foo.deleter
2128 def foo(self, value=None):
2129 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002130
Georg Brandl48545522008-02-02 10:12:36 +00002131 e = E()
2132 e.foo = -42
2133 self.assertEqual(e.foo, 42)
2134 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002135
Georg Brandl48545522008-02-02 10:12:36 +00002136 class F(E):
2137 @E.foo.deleter
2138 def foo(self):
2139 del self._foo
2140 @foo.setter
2141 def foo(self, value):
2142 self._foo = max(0, value)
2143 f = F()
2144 f.foo = -10
2145 self.assertEqual(f.foo, 0)
2146 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002147
Georg Brandl48545522008-02-02 10:12:36 +00002148 def test_dict_constructors(self):
2149 # Testing dict constructor ...
2150 d = dict()
2151 self.assertEqual(d, {})
2152 d = dict({})
2153 self.assertEqual(d, {})
2154 d = dict({1: 2, 'a': 'b'})
2155 self.assertEqual(d, {1: 2, 'a': 'b'})
2156 self.assertEqual(d, dict(d.items()))
2157 self.assertEqual(d, dict(d.iteritems()))
2158 d = dict({'one':1, 'two':2})
2159 self.assertEqual(d, dict(one=1, two=2))
2160 self.assertEqual(d, dict(**d))
2161 self.assertEqual(d, dict({"one": 1}, two=2))
2162 self.assertEqual(d, dict([("two", 2)], one=1))
2163 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2164 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002165
Georg Brandl48545522008-02-02 10:12:36 +00002166 for badarg in 0, 0L, 0j, "0", [0], (0,):
2167 try:
2168 dict(badarg)
2169 except TypeError:
2170 pass
2171 except ValueError:
2172 if badarg == "0":
2173 # It's a sequence, and its elements are also sequences (gotta
2174 # love strings <wink>), but they aren't of length 2, so this
2175 # one seemed better as a ValueError than a TypeError.
2176 pass
2177 else:
2178 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002179 else:
Georg Brandl48545522008-02-02 10:12:36 +00002180 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002181
Georg Brandl48545522008-02-02 10:12:36 +00002182 try:
2183 dict({}, {})
2184 except TypeError:
2185 pass
2186 else:
2187 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002188
Georg Brandl48545522008-02-02 10:12:36 +00002189 class Mapping:
2190 # Lacks a .keys() method; will be added later.
2191 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002192
Georg Brandl48545522008-02-02 10:12:36 +00002193 try:
2194 dict(Mapping())
2195 except TypeError:
2196 pass
2197 else:
2198 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002199
Georg Brandl48545522008-02-02 10:12:36 +00002200 Mapping.keys = lambda self: self.dict.keys()
2201 Mapping.__getitem__ = lambda self, i: self.dict[i]
2202 d = dict(Mapping())
2203 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002204
Georg Brandl48545522008-02-02 10:12:36 +00002205 # Init from sequence of iterable objects, each producing a 2-sequence.
2206 class AddressBookEntry:
2207 def __init__(self, first, last):
2208 self.first = first
2209 self.last = last
2210 def __iter__(self):
2211 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002212
Georg Brandl48545522008-02-02 10:12:36 +00002213 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2214 AddressBookEntry('Barry', 'Peters'),
2215 AddressBookEntry('Tim', 'Peters'),
2216 AddressBookEntry('Barry', 'Warsaw')])
2217 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002218
Georg Brandl48545522008-02-02 10:12:36 +00002219 d = dict(zip(range(4), range(1, 5)))
2220 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002221
Georg Brandl48545522008-02-02 10:12:36 +00002222 # Bad sequence lengths.
2223 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2224 try:
2225 dict(bad)
2226 except ValueError:
2227 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002228 else:
Georg Brandl48545522008-02-02 10:12:36 +00002229 self.fail("no ValueError from dict(%r)" % bad)
2230
2231 def test_dir(self):
2232 # Testing dir() ...
2233 junk = 12
2234 self.assertEqual(dir(), ['junk', 'self'])
2235 del junk
2236
2237 # Just make sure these don't blow up!
2238 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2239 dir(arg)
2240
2241 # Try classic classes.
2242 class C:
2243 Cdata = 1
2244 def Cmethod(self): pass
2245
2246 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2247 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002248 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002249
2250 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2251 self.assertEqual(dir(c), cstuff)
2252
2253 c.cdata = 2
2254 c.cmethod = lambda self: 0
2255 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002256 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002257
2258 class A(C):
2259 Adata = 1
2260 def Amethod(self): pass
2261
2262 astuff = ['Adata', 'Amethod'] + cstuff
2263 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002264 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002265 a = A()
2266 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002267 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002268 a.adata = 42
2269 a.amethod = lambda self: 3
2270 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2271
2272 # The same, but with new-style classes. Since these have object as a
2273 # base class, a lot more gets sucked in.
2274 def interesting(strings):
2275 return [s for s in strings if not s.startswith('_')]
2276
2277 class C(object):
2278 Cdata = 1
2279 def Cmethod(self): pass
2280
2281 cstuff = ['Cdata', 'Cmethod']
2282 self.assertEqual(interesting(dir(C)), cstuff)
2283
2284 c = C()
2285 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002286 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002287
2288 c.cdata = 2
2289 c.cmethod = lambda self: 0
2290 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002291 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002292
2293 class A(C):
2294 Adata = 1
2295 def Amethod(self): pass
2296
2297 astuff = ['Adata', 'Amethod'] + cstuff
2298 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002299 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002300 a = A()
2301 self.assertEqual(interesting(dir(a)), astuff)
2302 a.adata = 42
2303 a.amethod = lambda self: 3
2304 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002305 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002306
2307 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002308 class M(type(sys)):
2309 pass
2310 minstance = M("m")
2311 minstance.b = 2
2312 minstance.a = 1
2313 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2314 self.assertEqual(names, ['a', 'b'])
2315
2316 class M2(M):
2317 def getdict(self):
2318 return "Not a dict!"
2319 __dict__ = property(getdict)
2320
2321 m2instance = M2("m2")
2322 m2instance.b = 2
2323 m2instance.a = 1
2324 self.assertEqual(m2instance.__dict__, "Not a dict!")
2325 try:
2326 dir(m2instance)
2327 except TypeError:
2328 pass
2329
2330 # Two essentially featureless objects, just inheriting stuff from
2331 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002332 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2333 if test_support.check_impl_detail():
2334 # None differs in PyPy: it has a __nonzero__
2335 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002336
2337 # Nasty test case for proxied objects
2338 class Wrapper(object):
2339 def __init__(self, obj):
2340 self.__obj = obj
2341 def __repr__(self):
2342 return "Wrapper(%s)" % repr(self.__obj)
2343 def __getitem__(self, key):
2344 return Wrapper(self.__obj[key])
2345 def __len__(self):
2346 return len(self.__obj)
2347 def __getattr__(self, name):
2348 return Wrapper(getattr(self.__obj, name))
2349
2350 class C(object):
2351 def __getclass(self):
2352 return Wrapper(type(self))
2353 __class__ = property(__getclass)
2354
2355 dir(C()) # This used to segfault
2356
2357 def test_supers(self):
2358 # Testing super...
2359
2360 class A(object):
2361 def meth(self, a):
2362 return "A(%r)" % a
2363
2364 self.assertEqual(A().meth(1), "A(1)")
2365
2366 class B(A):
2367 def __init__(self):
2368 self.__super = super(B, self)
2369 def meth(self, a):
2370 return "B(%r)" % a + self.__super.meth(a)
2371
2372 self.assertEqual(B().meth(2), "B(2)A(2)")
2373
2374 class C(A):
2375 def meth(self, a):
2376 return "C(%r)" % a + self.__super.meth(a)
2377 C._C__super = super(C)
2378
2379 self.assertEqual(C().meth(3), "C(3)A(3)")
2380
2381 class D(C, B):
2382 def meth(self, a):
2383 return "D(%r)" % a + super(D, self).meth(a)
2384
2385 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2386
2387 # Test for subclassing super
2388
2389 class mysuper(super):
2390 def __init__(self, *args):
2391 return super(mysuper, self).__init__(*args)
2392
2393 class E(D):
2394 def meth(self, a):
2395 return "E(%r)" % a + mysuper(E, self).meth(a)
2396
2397 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2398
2399 class F(E):
2400 def meth(self, a):
2401 s = self.__super # == mysuper(F, self)
2402 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2403 F._F__super = mysuper(F)
2404
2405 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2406
2407 # Make sure certain errors are raised
2408
2409 try:
2410 super(D, 42)
2411 except TypeError:
2412 pass
2413 else:
2414 self.fail("shouldn't allow super(D, 42)")
2415
2416 try:
2417 super(D, C())
2418 except TypeError:
2419 pass
2420 else:
2421 self.fail("shouldn't allow super(D, C())")
2422
2423 try:
2424 super(D).__get__(12)
2425 except TypeError:
2426 pass
2427 else:
2428 self.fail("shouldn't allow super(D).__get__(12)")
2429
2430 try:
2431 super(D).__get__(C())
2432 except TypeError:
2433 pass
2434 else:
2435 self.fail("shouldn't allow super(D).__get__(C())")
2436
2437 # Make sure data descriptors can be overridden and accessed via super
2438 # (new feature in Python 2.3)
2439
2440 class DDbase(object):
2441 def getx(self): return 42
2442 x = property(getx)
2443
2444 class DDsub(DDbase):
2445 def getx(self): return "hello"
2446 x = property(getx)
2447
2448 dd = DDsub()
2449 self.assertEqual(dd.x, "hello")
2450 self.assertEqual(super(DDsub, dd).x, 42)
2451
2452 # Ensure that super() lookup of descriptor from classmethod
2453 # works (SF ID# 743627)
2454
2455 class Base(object):
2456 aProp = property(lambda self: "foo")
2457
2458 class Sub(Base):
2459 @classmethod
2460 def test(klass):
2461 return super(Sub,klass).aProp
2462
2463 self.assertEqual(Sub.test(), Base.aProp)
2464
2465 # Verify that super() doesn't allow keyword args
2466 try:
2467 super(Base, kw=1)
2468 except TypeError:
2469 pass
2470 else:
2471 self.assertEqual("super shouldn't accept keyword args")
2472
2473 def test_basic_inheritance(self):
2474 # Testing inheritance from basic types...
2475
2476 class hexint(int):
2477 def __repr__(self):
2478 return hex(self)
2479 def __add__(self, other):
2480 return hexint(int.__add__(self, other))
2481 # (Note that overriding __radd__ doesn't work,
2482 # because the int type gets first dibs.)
2483 self.assertEqual(repr(hexint(7) + 9), "0x10")
2484 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2485 a = hexint(12345)
2486 self.assertEqual(a, 12345)
2487 self.assertEqual(int(a), 12345)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002488 self.assertTrue(int(a).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002489 self.assertEqual(hash(a), hash(12345))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002490 self.assertTrue((+a).__class__ is int)
2491 self.assertTrue((a >> 0).__class__ is int)
2492 self.assertTrue((a << 0).__class__ is int)
2493 self.assertTrue((hexint(0) << 12).__class__ is int)
2494 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002495
2496 class octlong(long):
2497 __slots__ = []
2498 def __str__(self):
2499 s = oct(self)
2500 if s[-1] == 'L':
2501 s = s[:-1]
2502 return s
2503 def __add__(self, other):
2504 return self.__class__(super(octlong, self).__add__(other))
2505 __radd__ = __add__
2506 self.assertEqual(str(octlong(3) + 5), "010")
2507 # (Note that overriding __radd__ here only seems to work
2508 # because the example uses a short int left argument.)
2509 self.assertEqual(str(5 + octlong(3000)), "05675")
2510 a = octlong(12345)
2511 self.assertEqual(a, 12345L)
2512 self.assertEqual(long(a), 12345L)
2513 self.assertEqual(hash(a), hash(12345L))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002514 self.assertTrue(long(a).__class__ is long)
2515 self.assertTrue((+a).__class__ is long)
2516 self.assertTrue((-a).__class__ is long)
2517 self.assertTrue((-octlong(0)).__class__ is long)
2518 self.assertTrue((a >> 0).__class__ is long)
2519 self.assertTrue((a << 0).__class__ is long)
2520 self.assertTrue((a - 0).__class__ is long)
2521 self.assertTrue((a * 1).__class__ is long)
2522 self.assertTrue((a ** 1).__class__ is long)
2523 self.assertTrue((a // 1).__class__ is long)
2524 self.assertTrue((1 * a).__class__ is long)
2525 self.assertTrue((a | 0).__class__ is long)
2526 self.assertTrue((a ^ 0).__class__ is long)
2527 self.assertTrue((a & -1L).__class__ is long)
2528 self.assertTrue((octlong(0) << 12).__class__ is long)
2529 self.assertTrue((octlong(0) >> 12).__class__ is long)
2530 self.assertTrue(abs(octlong(0)).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002531
2532 # Because octlong overrides __add__, we can't check the absence of +0
2533 # optimizations using octlong.
2534 class longclone(long):
2535 pass
2536 a = longclone(1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002537 self.assertTrue((a + 0).__class__ is long)
2538 self.assertTrue((0 + a).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002539
2540 # Check that negative clones don't segfault
2541 a = longclone(-1)
2542 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002543 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002544
2545 class precfloat(float):
2546 __slots__ = ['prec']
2547 def __init__(self, value=0.0, prec=12):
2548 self.prec = int(prec)
2549 def __repr__(self):
2550 return "%.*g" % (self.prec, self)
2551 self.assertEqual(repr(precfloat(1.1)), "1.1")
2552 a = precfloat(12345)
2553 self.assertEqual(a, 12345.0)
2554 self.assertEqual(float(a), 12345.0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002555 self.assertTrue(float(a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002556 self.assertEqual(hash(a), hash(12345.0))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002557 self.assertTrue((+a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002558
2559 class madcomplex(complex):
2560 def __repr__(self):
2561 return "%.17gj%+.17g" % (self.imag, self.real)
2562 a = madcomplex(-3, 4)
2563 self.assertEqual(repr(a), "4j-3")
2564 base = complex(-3, 4)
2565 self.assertEqual(base.__class__, complex)
2566 self.assertEqual(a, base)
2567 self.assertEqual(complex(a), base)
2568 self.assertEqual(complex(a).__class__, complex)
2569 a = madcomplex(a) # just trying another form of the constructor
2570 self.assertEqual(repr(a), "4j-3")
2571 self.assertEqual(a, base)
2572 self.assertEqual(complex(a), base)
2573 self.assertEqual(complex(a).__class__, complex)
2574 self.assertEqual(hash(a), hash(base))
2575 self.assertEqual((+a).__class__, complex)
2576 self.assertEqual((a + 0).__class__, complex)
2577 self.assertEqual(a + 0, base)
2578 self.assertEqual((a - 0).__class__, complex)
2579 self.assertEqual(a - 0, base)
2580 self.assertEqual((a * 1).__class__, complex)
2581 self.assertEqual(a * 1, base)
2582 self.assertEqual((a / 1).__class__, complex)
2583 self.assertEqual(a / 1, base)
2584
2585 class madtuple(tuple):
2586 _rev = None
2587 def rev(self):
2588 if self._rev is not None:
2589 return self._rev
2590 L = list(self)
2591 L.reverse()
2592 self._rev = self.__class__(L)
2593 return self._rev
2594 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2595 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2596 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2597 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2598 for i in range(512):
2599 t = madtuple(range(i))
2600 u = t.rev()
2601 v = u.rev()
2602 self.assertEqual(v, t)
2603 a = madtuple((1,2,3,4,5))
2604 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002605 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002606 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002607 self.assertTrue(a[:].__class__ is tuple)
2608 self.assertTrue((a * 1).__class__ is tuple)
2609 self.assertTrue((a * 0).__class__ is tuple)
2610 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002611 a = madtuple(())
2612 self.assertEqual(tuple(a), ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002613 self.assertTrue(tuple(a).__class__ is tuple)
2614 self.assertTrue((a + a).__class__ is tuple)
2615 self.assertTrue((a * 0).__class__ is tuple)
2616 self.assertTrue((a * 1).__class__ is tuple)
2617 self.assertTrue((a * 2).__class__ is tuple)
2618 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002619
2620 class madstring(str):
2621 _rev = None
2622 def rev(self):
2623 if self._rev is not None:
2624 return self._rev
2625 L = list(self)
2626 L.reverse()
2627 self._rev = self.__class__("".join(L))
2628 return self._rev
2629 s = madstring("abcdefghijklmnopqrstuvwxyz")
2630 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2631 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2632 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2633 for i in range(256):
2634 s = madstring("".join(map(chr, range(i))))
2635 t = s.rev()
2636 u = t.rev()
2637 self.assertEqual(u, s)
2638 s = madstring("12345")
2639 self.assertEqual(str(s), "12345")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002640 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002641
2642 base = "\x00" * 5
2643 s = madstring(base)
2644 self.assertEqual(s, base)
2645 self.assertEqual(str(s), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002646 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002647 self.assertEqual(hash(s), hash(base))
2648 self.assertEqual({s: 1}[base], 1)
2649 self.assertEqual({base: 1}[s], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002650 self.assertTrue((s + "").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002651 self.assertEqual(s + "", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002652 self.assertTrue(("" + s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002653 self.assertEqual("" + s, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002654 self.assertTrue((s * 0).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002655 self.assertEqual(s * 0, "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002656 self.assertTrue((s * 1).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002657 self.assertEqual(s * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002658 self.assertTrue((s * 2).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002659 self.assertEqual(s * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002660 self.assertTrue(s[:].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002661 self.assertEqual(s[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002662 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002663 self.assertEqual(s[0:0], "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002664 self.assertTrue(s.strip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002665 self.assertEqual(s.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002666 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002667 self.assertEqual(s.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002668 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002669 self.assertEqual(s.rstrip(), base)
2670 identitytab = ''.join([chr(i) for i in range(256)])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002671 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002672 self.assertEqual(s.translate(identitytab), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002673 self.assertTrue(s.translate(identitytab, "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002674 self.assertEqual(s.translate(identitytab, "x"), base)
2675 self.assertEqual(s.translate(identitytab, "\x00"), "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002676 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002677 self.assertEqual(s.replace("x", "x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002678 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002679 self.assertEqual(s.ljust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002680 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002681 self.assertEqual(s.rjust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002682 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002683 self.assertEqual(s.center(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002684 self.assertTrue(s.lower().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002685 self.assertEqual(s.lower(), base)
2686
2687 class madunicode(unicode):
2688 _rev = None
2689 def rev(self):
2690 if self._rev is not None:
2691 return self._rev
2692 L = list(self)
2693 L.reverse()
2694 self._rev = self.__class__(u"".join(L))
2695 return self._rev
2696 u = madunicode("ABCDEF")
2697 self.assertEqual(u, u"ABCDEF")
2698 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2699 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2700 base = u"12345"
2701 u = madunicode(base)
2702 self.assertEqual(unicode(u), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002703 self.assertTrue(unicode(u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002704 self.assertEqual(hash(u), hash(base))
2705 self.assertEqual({u: 1}[base], 1)
2706 self.assertEqual({base: 1}[u], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002707 self.assertTrue(u.strip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002708 self.assertEqual(u.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002709 self.assertTrue(u.lstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002710 self.assertEqual(u.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002711 self.assertTrue(u.rstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002712 self.assertEqual(u.rstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002713 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002714 self.assertEqual(u.replace(u"x", u"x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002715 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002716 self.assertEqual(u.replace(u"xy", u"xy"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002717 self.assertTrue(u.center(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002718 self.assertEqual(u.center(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002719 self.assertTrue(u.ljust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002720 self.assertEqual(u.ljust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002721 self.assertTrue(u.rjust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002722 self.assertEqual(u.rjust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002723 self.assertTrue(u.lower().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002724 self.assertEqual(u.lower(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002725 self.assertTrue(u.upper().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002726 self.assertEqual(u.upper(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002727 self.assertTrue(u.capitalize().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002728 self.assertEqual(u.capitalize(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002729 self.assertTrue(u.title().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002730 self.assertEqual(u.title(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002731 self.assertTrue((u + u"").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002732 self.assertEqual(u + u"", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002733 self.assertTrue((u"" + u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002734 self.assertEqual(u"" + u, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002735 self.assertTrue((u * 0).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002736 self.assertEqual(u * 0, u"")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002737 self.assertTrue((u * 1).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002738 self.assertEqual(u * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002739 self.assertTrue((u * 2).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002740 self.assertEqual(u * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002741 self.assertTrue(u[:].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002742 self.assertEqual(u[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002743 self.assertTrue(u[0:0].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002744 self.assertEqual(u[0:0], u"")
2745
2746 class sublist(list):
2747 pass
2748 a = sublist(range(5))
2749 self.assertEqual(a, range(5))
2750 a.append("hello")
2751 self.assertEqual(a, range(5) + ["hello"])
2752 a[5] = 5
2753 self.assertEqual(a, range(6))
2754 a.extend(range(6, 20))
2755 self.assertEqual(a, range(20))
2756 a[-5:] = []
2757 self.assertEqual(a, range(15))
2758 del a[10:15]
2759 self.assertEqual(len(a), 10)
2760 self.assertEqual(a, range(10))
2761 self.assertEqual(list(a), range(10))
2762 self.assertEqual(a[0], 0)
2763 self.assertEqual(a[9], 9)
2764 self.assertEqual(a[-10], 0)
2765 self.assertEqual(a[-1], 9)
2766 self.assertEqual(a[:5], range(5))
2767
2768 class CountedInput(file):
2769 """Counts lines read by self.readline().
2770
2771 self.lineno is the 0-based ordinal of the last line read, up to
2772 a maximum of one greater than the number of lines in the file.
2773
2774 self.ateof is true if and only if the final "" line has been read,
2775 at which point self.lineno stops incrementing, and further calls
2776 to readline() continue to return "".
2777 """
2778
2779 lineno = 0
2780 ateof = 0
2781 def readline(self):
2782 if self.ateof:
2783 return ""
2784 s = file.readline(self)
2785 # Next line works too.
2786 # s = super(CountedInput, self).readline()
2787 self.lineno += 1
2788 if s == "":
2789 self.ateof = 1
2790 return s
2791
2792 f = file(name=test_support.TESTFN, mode='w')
2793 lines = ['a\n', 'b\n', 'c\n']
2794 try:
2795 f.writelines(lines)
2796 f.close()
2797 f = CountedInput(test_support.TESTFN)
2798 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2799 got = f.readline()
2800 self.assertEqual(expected, got)
2801 self.assertEqual(f.lineno, i)
2802 self.assertEqual(f.ateof, (i > len(lines)))
2803 f.close()
2804 finally:
2805 try:
2806 f.close()
2807 except:
2808 pass
2809 test_support.unlink(test_support.TESTFN)
2810
2811 def test_keywords(self):
2812 # Testing keyword args to basic type constructors ...
2813 self.assertEqual(int(x=1), 1)
2814 self.assertEqual(float(x=2), 2.0)
2815 self.assertEqual(long(x=3), 3L)
2816 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2817 self.assertEqual(str(object=500), '500')
2818 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2819 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2820 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2821 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2822
2823 for constructor in (int, float, long, complex, str, unicode,
2824 tuple, list, file):
2825 try:
2826 constructor(bogus_keyword_arg=1)
2827 except TypeError:
2828 pass
2829 else:
2830 self.fail("expected TypeError from bogus keyword argument to %r"
2831 % constructor)
2832
2833 def test_str_subclass_as_dict_key(self):
2834 # Testing a str subclass used as dict key ..
2835
2836 class cistr(str):
2837 """Sublcass of str that computes __eq__ case-insensitively.
2838
2839 Also computes a hash code of the string in canonical form.
2840 """
2841
2842 def __init__(self, value):
2843 self.canonical = value.lower()
2844 self.hashcode = hash(self.canonical)
2845
2846 def __eq__(self, other):
2847 if not isinstance(other, cistr):
2848 other = cistr(other)
2849 return self.canonical == other.canonical
2850
2851 def __hash__(self):
2852 return self.hashcode
2853
2854 self.assertEqual(cistr('ABC'), 'abc')
2855 self.assertEqual('aBc', cistr('ABC'))
2856 self.assertEqual(str(cistr('ABC')), 'ABC')
2857
2858 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2859 self.assertEqual(d[cistr('one')], 1)
2860 self.assertEqual(d[cistr('tWo')], 2)
2861 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002862 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002863 self.assertEqual(d.get(cistr('thrEE')), 3)
2864
2865 def test_classic_comparisons(self):
2866 # Testing classic comparisons...
2867 class classic:
2868 pass
2869
2870 for base in (classic, int, object):
2871 class C(base):
2872 def __init__(self, value):
2873 self.value = int(value)
2874 def __cmp__(self, other):
2875 if isinstance(other, C):
2876 return cmp(self.value, other.value)
2877 if isinstance(other, int) or isinstance(other, long):
2878 return cmp(self.value, other)
2879 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002880 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002881
2882 c1 = C(1)
2883 c2 = C(2)
2884 c3 = C(3)
2885 self.assertEqual(c1, 1)
2886 c = {1: c1, 2: c2, 3: c3}
2887 for x in 1, 2, 3:
2888 for y in 1, 2, 3:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002889 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002890 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002891 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002892 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002893 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2894 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002895
2896 def test_rich_comparisons(self):
2897 # Testing rich comparisons...
2898 class Z(complex):
2899 pass
2900 z = Z(1)
2901 self.assertEqual(z, 1+0j)
2902 self.assertEqual(1+0j, z)
2903 class ZZ(complex):
2904 def __eq__(self, other):
2905 try:
2906 return abs(self - other) <= 1e-6
2907 except:
2908 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002909 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002910 zz = ZZ(1.0000003)
2911 self.assertEqual(zz, 1+0j)
2912 self.assertEqual(1+0j, zz)
2913
2914 class classic:
2915 pass
2916 for base in (classic, int, object, list):
2917 class C(base):
2918 def __init__(self, value):
2919 self.value = int(value)
2920 def __cmp__(self_, other):
2921 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002922 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002923 def __eq__(self, other):
2924 if isinstance(other, C):
2925 return self.value == other.value
2926 if isinstance(other, int) or isinstance(other, long):
2927 return self.value == other
2928 return NotImplemented
2929 def __ne__(self, other):
2930 if isinstance(other, C):
2931 return self.value != other.value
2932 if isinstance(other, int) or isinstance(other, long):
2933 return self.value != other
2934 return NotImplemented
2935 def __lt__(self, other):
2936 if isinstance(other, C):
2937 return self.value < other.value
2938 if isinstance(other, int) or isinstance(other, long):
2939 return self.value < other
2940 return NotImplemented
2941 def __le__(self, other):
2942 if isinstance(other, C):
2943 return self.value <= other.value
2944 if isinstance(other, int) or isinstance(other, long):
2945 return self.value <= other
2946 return NotImplemented
2947 def __gt__(self, other):
2948 if isinstance(other, C):
2949 return self.value > other.value
2950 if isinstance(other, int) or isinstance(other, long):
2951 return self.value > other
2952 return NotImplemented
2953 def __ge__(self, other):
2954 if isinstance(other, C):
2955 return self.value >= other.value
2956 if isinstance(other, int) or isinstance(other, long):
2957 return self.value >= other
2958 return NotImplemented
2959 c1 = C(1)
2960 c2 = C(2)
2961 c3 = C(3)
2962 self.assertEqual(c1, 1)
2963 c = {1: c1, 2: c2, 3: c3}
2964 for x in 1, 2, 3:
2965 for y in 1, 2, 3:
2966 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002967 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002968 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002969 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002970 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002971 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002972 "x=%d, y=%d" % (x, y))
2973
2974 def test_coercions(self):
2975 # Testing coercions...
2976 class I(int): pass
2977 coerce(I(0), 0)
2978 coerce(0, I(0))
2979 class L(long): pass
2980 coerce(L(0), 0)
2981 coerce(L(0), 0L)
2982 coerce(0, L(0))
2983 coerce(0L, L(0))
2984 class F(float): pass
2985 coerce(F(0), 0)
2986 coerce(F(0), 0L)
2987 coerce(F(0), 0.)
2988 coerce(0, F(0))
2989 coerce(0L, F(0))
2990 coerce(0., F(0))
2991 class C(complex): pass
2992 coerce(C(0), 0)
2993 coerce(C(0), 0L)
2994 coerce(C(0), 0.)
2995 coerce(C(0), 0j)
2996 coerce(0, C(0))
2997 coerce(0L, C(0))
2998 coerce(0., C(0))
2999 coerce(0j, C(0))
3000
3001 def test_descrdoc(self):
3002 # Testing descriptor doc strings...
3003 def check(descr, what):
3004 self.assertEqual(descr.__doc__, what)
3005 check(file.closed, "True if the file is closed") # getset descriptor
3006 check(file.name, "file name") # member descriptor
3007
3008 def test_doc_descriptor(self):
3009 # Testing __doc__ descriptor...
3010 # SF bug 542984
3011 class DocDescr(object):
3012 def __get__(self, object, otype):
3013 if object:
3014 object = object.__class__.__name__ + ' instance'
3015 if otype:
3016 otype = otype.__name__
3017 return 'object=%s; type=%s' % (object, otype)
3018 class OldClass:
3019 __doc__ = DocDescr()
3020 class NewClass(object):
3021 __doc__ = DocDescr()
3022 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3023 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3024 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3025 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3026
3027 def test_set_class(self):
3028 # Testing __class__ assignment...
3029 class C(object): pass
3030 class D(object): pass
3031 class E(object): pass
3032 class F(D, E): pass
3033 for cls in C, D, E, F:
3034 for cls2 in C, D, E, F:
3035 x = cls()
3036 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003037 self.assertTrue(x.__class__ is cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003038 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003039 self.assertTrue(x.__class__ is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003040 def cant(x, C):
3041 try:
3042 x.__class__ = C
3043 except TypeError:
3044 pass
3045 else:
3046 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3047 try:
3048 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003049 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003050 pass
3051 else:
3052 self.fail("shouldn't allow del %r.__class__" % x)
3053 cant(C(), list)
3054 cant(list(), C)
3055 cant(C(), 1)
3056 cant(C(), object)
3057 cant(object(), list)
3058 cant(list(), object)
3059 class Int(int): __slots__ = []
3060 cant(2, Int)
3061 cant(Int(), int)
3062 cant(True, int)
3063 cant(2, bool)
3064 o = object()
3065 cant(o, type(1))
3066 cant(o, type(None))
3067 del o
3068 class G(object):
3069 __slots__ = ["a", "b"]
3070 class H(object):
3071 __slots__ = ["b", "a"]
3072 try:
3073 unicode
3074 except NameError:
3075 class I(object):
3076 __slots__ = ["a", "b"]
3077 else:
3078 class I(object):
3079 __slots__ = [unicode("a"), unicode("b")]
3080 class J(object):
3081 __slots__ = ["c", "b"]
3082 class K(object):
3083 __slots__ = ["a", "b", "d"]
3084 class L(H):
3085 __slots__ = ["e"]
3086 class M(I):
3087 __slots__ = ["e"]
3088 class N(J):
3089 __slots__ = ["__weakref__"]
3090 class P(J):
3091 __slots__ = ["__dict__"]
3092 class Q(J):
3093 pass
3094 class R(J):
3095 __slots__ = ["__dict__", "__weakref__"]
3096
3097 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3098 x = cls()
3099 x.a = 1
3100 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003101 self.assertTrue(x.__class__ is cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003102 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3103 self.assertEqual(x.a, 1)
3104 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003105 self.assertTrue(x.__class__ is cls,
Georg Brandl48545522008-02-02 10:12:36 +00003106 "assigning %r as __class__ for %r silently failed" % (cls, x))
3107 self.assertEqual(x.a, 1)
3108 for cls in G, J, K, L, M, N, P, R, list, Int:
3109 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3110 if cls is cls2:
3111 continue
3112 cant(cls(), cls2)
3113
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003114 # Issue5283: when __class__ changes in __del__, the wrong
3115 # type gets DECREF'd.
3116 class O(object):
3117 pass
3118 class A(object):
3119 def __del__(self):
3120 self.__class__ = O
3121 l = [A() for x in range(100)]
3122 del l
3123
Georg Brandl48545522008-02-02 10:12:36 +00003124 def test_set_dict(self):
3125 # Testing __dict__ assignment...
3126 class C(object): pass
3127 a = C()
3128 a.__dict__ = {'b': 1}
3129 self.assertEqual(a.b, 1)
3130 def cant(x, dict):
3131 try:
3132 x.__dict__ = dict
3133 except (AttributeError, TypeError):
3134 pass
3135 else:
3136 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3137 cant(a, None)
3138 cant(a, [])
3139 cant(a, 1)
3140 del a.__dict__ # Deleting __dict__ is allowed
3141
3142 class Base(object):
3143 pass
3144 def verify_dict_readonly(x):
3145 """
3146 x has to be an instance of a class inheriting from Base.
3147 """
3148 cant(x, {})
3149 try:
3150 del x.__dict__
3151 except (AttributeError, TypeError):
3152 pass
3153 else:
3154 self.fail("shouldn't allow del %r.__dict__" % x)
3155 dict_descr = Base.__dict__["__dict__"]
3156 try:
3157 dict_descr.__set__(x, {})
3158 except (AttributeError, TypeError):
3159 pass
3160 else:
3161 self.fail("dict_descr allowed access to %r's dict" % x)
3162
3163 # Classes don't allow __dict__ assignment and have readonly dicts
3164 class Meta1(type, Base):
3165 pass
3166 class Meta2(Base, type):
3167 pass
3168 class D(object):
3169 __metaclass__ = Meta1
3170 class E(object):
3171 __metaclass__ = Meta2
3172 for cls in C, D, E:
3173 verify_dict_readonly(cls)
3174 class_dict = cls.__dict__
3175 try:
3176 class_dict["spam"] = "eggs"
3177 except TypeError:
3178 pass
3179 else:
3180 self.fail("%r's __dict__ can be modified" % cls)
3181
3182 # Modules also disallow __dict__ assignment
3183 class Module1(types.ModuleType, Base):
3184 pass
3185 class Module2(Base, types.ModuleType):
3186 pass
3187 for ModuleType in Module1, Module2:
3188 mod = ModuleType("spam")
3189 verify_dict_readonly(mod)
3190 mod.__dict__["spam"] = "eggs"
3191
3192 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003193 # (at least not any more than regular exception's __dict__ can
3194 # be deleted; on CPython it is not the case, whereas on PyPy they
3195 # can, just like any other new-style instance's __dict__.)
3196 def can_delete_dict(e):
3197 try:
3198 del e.__dict__
3199 except (TypeError, AttributeError):
3200 return False
3201 else:
3202 return True
Georg Brandl48545522008-02-02 10:12:36 +00003203 class Exception1(Exception, Base):
3204 pass
3205 class Exception2(Base, Exception):
3206 pass
3207 for ExceptionType in Exception, Exception1, Exception2:
3208 e = ExceptionType()
3209 e.__dict__ = {"a": 1}
3210 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003211 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003212
3213 def test_pickles(self):
3214 # Testing pickling and copying new-style classes and objects...
3215 import pickle, cPickle
3216
3217 def sorteditems(d):
3218 L = d.items()
3219 L.sort()
3220 return L
3221
3222 global C
3223 class C(object):
3224 def __init__(self, a, b):
3225 super(C, self).__init__()
3226 self.a = a
3227 self.b = b
3228 def __repr__(self):
3229 return "C(%r, %r)" % (self.a, self.b)
3230
3231 global C1
3232 class C1(list):
3233 def __new__(cls, a, b):
3234 return super(C1, cls).__new__(cls)
3235 def __getnewargs__(self):
3236 return (self.a, self.b)
3237 def __init__(self, a, b):
3238 self.a = a
3239 self.b = b
3240 def __repr__(self):
3241 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3242
3243 global C2
3244 class C2(int):
3245 def __new__(cls, a, b, val=0):
3246 return super(C2, cls).__new__(cls, val)
3247 def __getnewargs__(self):
3248 return (self.a, self.b, int(self))
3249 def __init__(self, a, b, val=0):
3250 self.a = a
3251 self.b = b
3252 def __repr__(self):
3253 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3254
3255 global C3
3256 class C3(object):
3257 def __init__(self, foo):
3258 self.foo = foo
3259 def __getstate__(self):
3260 return self.foo
3261 def __setstate__(self, foo):
3262 self.foo = foo
3263
3264 global C4classic, C4
3265 class C4classic: # classic
3266 pass
3267 class C4(C4classic, object): # mixed inheritance
3268 pass
3269
3270 for p in pickle, cPickle:
3271 for bin in 0, 1:
3272 for cls in C, C1, C2:
3273 s = p.dumps(cls, bin)
3274 cls2 = p.loads(s)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003275 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003276
3277 a = C1(1, 2); a.append(42); a.append(24)
3278 b = C2("hello", "world", 42)
3279 s = p.dumps((a, b), bin)
3280 x, y = p.loads(s)
3281 self.assertEqual(x.__class__, a.__class__)
3282 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3283 self.assertEqual(y.__class__, b.__class__)
3284 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3285 self.assertEqual(repr(x), repr(a))
3286 self.assertEqual(repr(y), repr(b))
3287 # Test for __getstate__ and __setstate__ on new style class
3288 u = C3(42)
3289 s = p.dumps(u, bin)
3290 v = p.loads(s)
3291 self.assertEqual(u.__class__, v.__class__)
3292 self.assertEqual(u.foo, v.foo)
3293 # Test for picklability of hybrid class
3294 u = C4()
3295 u.foo = 42
3296 s = p.dumps(u, bin)
3297 v = p.loads(s)
3298 self.assertEqual(u.__class__, v.__class__)
3299 self.assertEqual(u.foo, v.foo)
3300
3301 # Testing copy.deepcopy()
3302 import copy
3303 for cls in C, C1, C2:
3304 cls2 = copy.deepcopy(cls)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003305 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003306
3307 a = C1(1, 2); a.append(42); a.append(24)
3308 b = C2("hello", "world", 42)
3309 x, y = copy.deepcopy((a, b))
3310 self.assertEqual(x.__class__, a.__class__)
3311 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3312 self.assertEqual(y.__class__, b.__class__)
3313 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3314 self.assertEqual(repr(x), repr(a))
3315 self.assertEqual(repr(y), repr(b))
3316
3317 def test_pickle_slots(self):
3318 # Testing pickling of classes with __slots__ ...
3319 import pickle, cPickle
3320 # Pickling of classes with __slots__ but without __getstate__ should fail
3321 global B, C, D, E
3322 class B(object):
3323 pass
3324 for base in [object, B]:
3325 class C(base):
3326 __slots__ = ['a']
3327 class D(C):
3328 pass
3329 try:
3330 pickle.dumps(C())
3331 except TypeError:
3332 pass
3333 else:
3334 self.fail("should fail: pickle C instance - %s" % base)
3335 try:
3336 cPickle.dumps(C())
3337 except TypeError:
3338 pass
3339 else:
3340 self.fail("should fail: cPickle C instance - %s" % base)
3341 try:
3342 pickle.dumps(C())
3343 except TypeError:
3344 pass
3345 else:
3346 self.fail("should fail: pickle D instance - %s" % base)
3347 try:
3348 cPickle.dumps(D())
3349 except TypeError:
3350 pass
3351 else:
3352 self.fail("should fail: cPickle D instance - %s" % base)
3353 # Give C a nice generic __getstate__ and __setstate__
3354 class C(base):
3355 __slots__ = ['a']
3356 def __getstate__(self):
3357 try:
3358 d = self.__dict__.copy()
3359 except AttributeError:
3360 d = {}
3361 for cls in self.__class__.__mro__:
3362 for sn in cls.__dict__.get('__slots__', ()):
3363 try:
3364 d[sn] = getattr(self, sn)
3365 except AttributeError:
3366 pass
3367 return d
3368 def __setstate__(self, d):
3369 for k, v in d.items():
3370 setattr(self, k, v)
3371 class D(C):
3372 pass
3373 # Now it should work
3374 x = C()
3375 y = pickle.loads(pickle.dumps(x))
3376 self.assertEqual(hasattr(y, 'a'), 0)
3377 y = cPickle.loads(cPickle.dumps(x))
3378 self.assertEqual(hasattr(y, 'a'), 0)
3379 x.a = 42
3380 y = pickle.loads(pickle.dumps(x))
3381 self.assertEqual(y.a, 42)
3382 y = cPickle.loads(cPickle.dumps(x))
3383 self.assertEqual(y.a, 42)
3384 x = D()
3385 x.a = 42
3386 x.b = 100
3387 y = pickle.loads(pickle.dumps(x))
3388 self.assertEqual(y.a + y.b, 142)
3389 y = cPickle.loads(cPickle.dumps(x))
3390 self.assertEqual(y.a + y.b, 142)
3391 # A subclass that adds a slot should also work
3392 class E(C):
3393 __slots__ = ['b']
3394 x = E()
3395 x.a = 42
3396 x.b = "foo"
3397 y = pickle.loads(pickle.dumps(x))
3398 self.assertEqual(y.a, x.a)
3399 self.assertEqual(y.b, x.b)
3400 y = cPickle.loads(cPickle.dumps(x))
3401 self.assertEqual(y.a, x.a)
3402 self.assertEqual(y.b, x.b)
3403
3404 def test_binary_operator_override(self):
3405 # Testing overrides of binary operations...
3406 class I(int):
3407 def __repr__(self):
3408 return "I(%r)" % int(self)
3409 def __add__(self, other):
3410 return I(int(self) + int(other))
3411 __radd__ = __add__
3412 def __pow__(self, other, mod=None):
3413 if mod is None:
3414 return I(pow(int(self), int(other)))
3415 else:
3416 return I(pow(int(self), int(other), int(mod)))
3417 def __rpow__(self, other, mod=None):
3418 if mod is None:
3419 return I(pow(int(other), int(self), mod))
3420 else:
3421 return I(pow(int(other), int(self), int(mod)))
3422
3423 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3424 self.assertEqual(repr(I(1) + 2), "I(3)")
3425 self.assertEqual(repr(1 + I(2)), "I(3)")
3426 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3427 self.assertEqual(repr(2 ** I(3)), "I(8)")
3428 self.assertEqual(repr(I(2) ** 3), "I(8)")
3429 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3430 class S(str):
3431 def __eq__(self, other):
3432 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003433 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003434
3435 def test_subclass_propagation(self):
3436 # Testing propagation of slot functions to subclasses...
3437 class A(object):
3438 pass
3439 class B(A):
3440 pass
3441 class C(A):
3442 pass
3443 class D(B, C):
3444 pass
3445 d = D()
3446 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3447 A.__hash__ = lambda self: 42
3448 self.assertEqual(hash(d), 42)
3449 C.__hash__ = lambda self: 314
3450 self.assertEqual(hash(d), 314)
3451 B.__hash__ = lambda self: 144
3452 self.assertEqual(hash(d), 144)
3453 D.__hash__ = lambda self: 100
3454 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003455 D.__hash__ = None
3456 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003457 del D.__hash__
3458 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003459 B.__hash__ = None
3460 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003461 del B.__hash__
3462 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003463 C.__hash__ = None
3464 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003465 del C.__hash__
3466 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003467 A.__hash__ = None
3468 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003469 del A.__hash__
3470 self.assertEqual(hash(d), orig_hash)
3471 d.foo = 42
3472 d.bar = 42
3473 self.assertEqual(d.foo, 42)
3474 self.assertEqual(d.bar, 42)
3475 def __getattribute__(self, name):
3476 if name == "foo":
3477 return 24
3478 return object.__getattribute__(self, name)
3479 A.__getattribute__ = __getattribute__
3480 self.assertEqual(d.foo, 24)
3481 self.assertEqual(d.bar, 42)
3482 def __getattr__(self, name):
3483 if name in ("spam", "foo", "bar"):
3484 return "hello"
3485 raise AttributeError, name
3486 B.__getattr__ = __getattr__
3487 self.assertEqual(d.spam, "hello")
3488 self.assertEqual(d.foo, 24)
3489 self.assertEqual(d.bar, 42)
3490 del A.__getattribute__
3491 self.assertEqual(d.foo, 42)
3492 del d.foo
3493 self.assertEqual(d.foo, "hello")
3494 self.assertEqual(d.bar, 42)
3495 del B.__getattr__
3496 try:
3497 d.foo
3498 except AttributeError:
3499 pass
3500 else:
3501 self.fail("d.foo should be undefined now")
3502
3503 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003504 class A(object):
3505 pass
3506 class B(A):
3507 pass
3508 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003509 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003510 A.__setitem__ = lambda *a: None # crash
3511
3512 def test_buffer_inheritance(self):
3513 # Testing that buffer interface is inherited ...
3514
3515 import binascii
3516 # SF bug [#470040] ParseTuple t# vs subclasses.
3517
3518 class MyStr(str):
3519 pass
3520 base = 'abc'
3521 m = MyStr(base)
3522 # b2a_hex uses the buffer interface to get its argument's value, via
3523 # PyArg_ParseTuple 't#' code.
3524 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3525
3526 # It's not clear that unicode will continue to support the character
3527 # buffer interface, and this test will fail if that's taken away.
3528 class MyUni(unicode):
3529 pass
3530 base = u'abc'
3531 m = MyUni(base)
3532 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3533
3534 class MyInt(int):
3535 pass
3536 m = MyInt(42)
3537 try:
3538 binascii.b2a_hex(m)
3539 self.fail('subclass of int should not have a buffer interface')
3540 except TypeError:
3541 pass
3542
3543 def test_str_of_str_subclass(self):
3544 # Testing __str__ defined in subclass of str ...
3545 import binascii
3546 import cStringIO
3547
3548 class octetstring(str):
3549 def __str__(self):
3550 return binascii.b2a_hex(self)
3551 def __repr__(self):
3552 return self + " repr"
3553
3554 o = octetstring('A')
3555 self.assertEqual(type(o), octetstring)
3556 self.assertEqual(type(str(o)), str)
3557 self.assertEqual(type(repr(o)), str)
3558 self.assertEqual(ord(o), 0x41)
3559 self.assertEqual(str(o), '41')
3560 self.assertEqual(repr(o), 'A repr')
3561 self.assertEqual(o.__str__(), '41')
3562 self.assertEqual(o.__repr__(), 'A repr')
3563
3564 capture = cStringIO.StringIO()
3565 # Calling str() or not exercises different internal paths.
3566 print >> capture, o
3567 print >> capture, str(o)
3568 self.assertEqual(capture.getvalue(), '41\n41\n')
3569 capture.close()
3570
3571 def test_keyword_arguments(self):
3572 # Testing keyword arguments to __init__, __call__...
3573 def f(a): return a
3574 self.assertEqual(f.__call__(a=42), 42)
3575 a = []
3576 list.__init__(a, sequence=[0, 1, 2])
3577 self.assertEqual(a, [0, 1, 2])
3578
3579 def test_recursive_call(self):
3580 # Testing recursive __call__() by setting to instance of class...
3581 class A(object):
3582 pass
3583
3584 A.__call__ = A()
3585 try:
3586 A()()
3587 except RuntimeError:
3588 pass
3589 else:
3590 self.fail("Recursion limit should have been reached for __call__()")
3591
3592 def test_delete_hook(self):
3593 # Testing __del__ hook...
3594 log = []
3595 class C(object):
3596 def __del__(self):
3597 log.append(1)
3598 c = C()
3599 self.assertEqual(log, [])
3600 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003601 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003602 self.assertEqual(log, [1])
3603
3604 class D(object): pass
3605 d = D()
3606 try: del d[0]
3607 except TypeError: pass
3608 else: self.fail("invalid del() didn't raise TypeError")
3609
3610 def test_hash_inheritance(self):
3611 # Testing hash of mutable subclasses...
3612
3613 class mydict(dict):
3614 pass
3615 d = mydict()
3616 try:
3617 hash(d)
3618 except TypeError:
3619 pass
3620 else:
3621 self.fail("hash() of dict subclass should fail")
3622
3623 class mylist(list):
3624 pass
3625 d = mylist()
3626 try:
3627 hash(d)
3628 except TypeError:
3629 pass
3630 else:
3631 self.fail("hash() of list subclass should fail")
3632
3633 def test_str_operations(self):
3634 try: 'a' + 5
3635 except TypeError: pass
3636 else: self.fail("'' + 5 doesn't raise TypeError")
3637
3638 try: ''.split('')
3639 except ValueError: pass
3640 else: self.fail("''.split('') doesn't raise ValueError")
3641
3642 try: ''.join([0])
3643 except TypeError: pass
3644 else: self.fail("''.join([0]) doesn't raise TypeError")
3645
3646 try: ''.rindex('5')
3647 except ValueError: pass
3648 else: self.fail("''.rindex('5') doesn't raise ValueError")
3649
3650 try: '%(n)s' % None
3651 except TypeError: pass
3652 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3653
3654 try: '%(n' % {}
3655 except ValueError: pass
3656 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3657
3658 try: '%*s' % ('abc')
3659 except TypeError: pass
3660 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3661
3662 try: '%*.*s' % ('abc', 5)
3663 except TypeError: pass
3664 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3665
3666 try: '%s' % (1, 2)
3667 except TypeError: pass
3668 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3669
3670 try: '%' % None
3671 except ValueError: pass
3672 else: self.fail("'%' % None doesn't raise ValueError")
3673
3674 self.assertEqual('534253'.isdigit(), 1)
3675 self.assertEqual('534253x'.isdigit(), 0)
3676 self.assertEqual('%c' % 5, '\x05')
3677 self.assertEqual('%c' % '5', '5')
3678
3679 def test_deepcopy_recursive(self):
3680 # Testing deepcopy of recursive objects...
3681 class Node:
3682 pass
3683 a = Node()
3684 b = Node()
3685 a.b = b
3686 b.a = a
3687 z = deepcopy(a) # This blew up before
3688
3689 def test_unintialized_modules(self):
3690 # Testing uninitialized module objects...
3691 from types import ModuleType as M
3692 m = M.__new__(M)
3693 str(m)
3694 self.assertEqual(hasattr(m, "__name__"), 0)
3695 self.assertEqual(hasattr(m, "__file__"), 0)
3696 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003697 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003698 m.foo = 1
3699 self.assertEqual(m.__dict__, {"foo": 1})
3700
3701 def test_funny_new(self):
3702 # Testing __new__ returning something unexpected...
3703 class C(object):
3704 def __new__(cls, arg):
3705 if isinstance(arg, str): return [1, 2, 3]
3706 elif isinstance(arg, int): return object.__new__(D)
3707 else: return object.__new__(cls)
3708 class D(C):
3709 def __init__(self, arg):
3710 self.foo = arg
3711 self.assertEqual(C("1"), [1, 2, 3])
3712 self.assertEqual(D("1"), [1, 2, 3])
3713 d = D(None)
3714 self.assertEqual(d.foo, None)
3715 d = C(1)
3716 self.assertEqual(isinstance(d, D), True)
3717 self.assertEqual(d.foo, 1)
3718 d = D(1)
3719 self.assertEqual(isinstance(d, D), True)
3720 self.assertEqual(d.foo, 1)
3721
3722 def test_imul_bug(self):
3723 # Testing for __imul__ problems...
3724 # SF bug 544647
3725 class C(object):
3726 def __imul__(self, other):
3727 return (self, other)
3728 x = C()
3729 y = x
3730 y *= 1.0
3731 self.assertEqual(y, (x, 1.0))
3732 y = x
3733 y *= 2
3734 self.assertEqual(y, (x, 2))
3735 y = x
3736 y *= 3L
3737 self.assertEqual(y, (x, 3L))
3738 y = x
3739 y *= 1L<<100
3740 self.assertEqual(y, (x, 1L<<100))
3741 y = x
3742 y *= None
3743 self.assertEqual(y, (x, None))
3744 y = x
3745 y *= "foo"
3746 self.assertEqual(y, (x, "foo"))
3747
3748 def test_copy_setstate(self):
3749 # Testing that copy.*copy() correctly uses __setstate__...
3750 import copy
3751 class C(object):
3752 def __init__(self, foo=None):
3753 self.foo = foo
3754 self.__foo = foo
3755 def setfoo(self, foo=None):
3756 self.foo = foo
3757 def getfoo(self):
3758 return self.__foo
3759 def __getstate__(self):
3760 return [self.foo]
3761 def __setstate__(self_, lst):
3762 self.assertEqual(len(lst), 1)
3763 self_.__foo = self_.foo = lst[0]
3764 a = C(42)
3765 a.setfoo(24)
3766 self.assertEqual(a.foo, 24)
3767 self.assertEqual(a.getfoo(), 42)
3768 b = copy.copy(a)
3769 self.assertEqual(b.foo, 24)
3770 self.assertEqual(b.getfoo(), 24)
3771 b = copy.deepcopy(a)
3772 self.assertEqual(b.foo, 24)
3773 self.assertEqual(b.getfoo(), 24)
3774
3775 def test_slices(self):
3776 # Testing cases with slices and overridden __getitem__ ...
3777
3778 # Strings
3779 self.assertEqual("hello"[:4], "hell")
3780 self.assertEqual("hello"[slice(4)], "hell")
3781 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3782 class S(str):
3783 def __getitem__(self, x):
3784 return str.__getitem__(self, x)
3785 self.assertEqual(S("hello")[:4], "hell")
3786 self.assertEqual(S("hello")[slice(4)], "hell")
3787 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3788 # Tuples
3789 self.assertEqual((1,2,3)[:2], (1,2))
3790 self.assertEqual((1,2,3)[slice(2)], (1,2))
3791 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3792 class T(tuple):
3793 def __getitem__(self, x):
3794 return tuple.__getitem__(self, x)
3795 self.assertEqual(T((1,2,3))[:2], (1,2))
3796 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3797 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3798 # Lists
3799 self.assertEqual([1,2,3][:2], [1,2])
3800 self.assertEqual([1,2,3][slice(2)], [1,2])
3801 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3802 class L(list):
3803 def __getitem__(self, x):
3804 return list.__getitem__(self, x)
3805 self.assertEqual(L([1,2,3])[:2], [1,2])
3806 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3807 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3808 # Now do lists and __setitem__
3809 a = L([1,2,3])
3810 a[slice(1, 3)] = [3,2]
3811 self.assertEqual(a, [1,3,2])
3812 a[slice(0, 2, 1)] = [3,1]
3813 self.assertEqual(a, [3,1,2])
3814 a.__setitem__(slice(1, 3), [2,1])
3815 self.assertEqual(a, [3,2,1])
3816 a.__setitem__(slice(0, 2, 1), [2,3])
3817 self.assertEqual(a, [2,3,1])
3818
3819 def test_subtype_resurrection(self):
3820 # Testing resurrection of new-style instance...
3821
3822 class C(object):
3823 container = []
3824
3825 def __del__(self):
3826 # resurrect the instance
3827 C.container.append(self)
3828
3829 c = C()
3830 c.attr = 42
3831
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003832 # The most interesting thing here is whether this blows up, due to
3833 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3834 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003835 del c
3836
3837 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003838 # the last container slot works: that will attempt to delete c again,
3839 # which will cause c to get appended back to the container again
3840 # "during" the del. (On non-CPython implementations, however, __del__
3841 # is typically not called again.)
3842 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003843 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003844 del C.container[-1]
3845 if test_support.check_impl_detail():
3846 test_support.gc_collect()
3847 self.assertEqual(len(C.container), 1)
3848 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003849
3850 # Make c mortal again, so that the test framework with -l doesn't report
3851 # it as a leak.
3852 del C.__del__
3853
3854 def test_slots_trash(self):
3855 # Testing slot trash...
3856 # Deallocating deeply nested slotted trash caused stack overflows
3857 class trash(object):
3858 __slots__ = ['x']
3859 def __init__(self, x):
3860 self.x = x
3861 o = None
3862 for i in xrange(50000):
3863 o = trash(o)
3864 del o
3865
3866 def test_slots_multiple_inheritance(self):
3867 # SF bug 575229, multiple inheritance w/ slots dumps core
3868 class A(object):
3869 __slots__=()
3870 class B(object):
3871 pass
3872 class C(A,B) :
3873 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003874 if test_support.check_impl_detail():
3875 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003876 self.assertTrue(hasattr(C, '__dict__'))
3877 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl48545522008-02-02 10:12:36 +00003878 C().x = 2
3879
3880 def test_rmul(self):
3881 # Testing correct invocation of __rmul__...
3882 # SF patch 592646
3883 class C(object):
3884 def __mul__(self, other):
3885 return "mul"
3886 def __rmul__(self, other):
3887 return "rmul"
3888 a = C()
3889 self.assertEqual(a*2, "mul")
3890 self.assertEqual(a*2.2, "mul")
3891 self.assertEqual(2*a, "rmul")
3892 self.assertEqual(2.2*a, "rmul")
3893
3894 def test_ipow(self):
3895 # Testing correct invocation of __ipow__...
3896 # [SF bug 620179]
3897 class C(object):
3898 def __ipow__(self, other):
3899 pass
3900 a = C()
3901 a **= 2
3902
3903 def test_mutable_bases(self):
3904 # Testing mutable bases...
3905
3906 # stuff that should work:
3907 class C(object):
3908 pass
3909 class C2(object):
3910 def __getattribute__(self, attr):
3911 if attr == 'a':
3912 return 2
3913 else:
3914 return super(C2, self).__getattribute__(attr)
3915 def meth(self):
3916 return 1
3917 class D(C):
3918 pass
3919 class E(D):
3920 pass
3921 d = D()
3922 e = E()
3923 D.__bases__ = (C,)
3924 D.__bases__ = (C2,)
3925 self.assertEqual(d.meth(), 1)
3926 self.assertEqual(e.meth(), 1)
3927 self.assertEqual(d.a, 2)
3928 self.assertEqual(e.a, 2)
3929 self.assertEqual(C2.__subclasses__(), [D])
3930
Georg Brandl48545522008-02-02 10:12:36 +00003931 try:
3932 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003933 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003934 pass
3935 else:
3936 self.fail("shouldn't be able to delete .__bases__")
3937
3938 try:
3939 D.__bases__ = ()
3940 except TypeError, msg:
3941 if str(msg) == "a new-style class can't have only classic bases":
3942 self.fail("wrong error message for .__bases__ = ()")
3943 else:
3944 self.fail("shouldn't be able to set .__bases__ to ()")
3945
3946 try:
3947 D.__bases__ = (D,)
3948 except TypeError:
3949 pass
3950 else:
3951 # actually, we'll have crashed by here...
3952 self.fail("shouldn't be able to create inheritance cycles")
3953
3954 try:
3955 D.__bases__ = (C, C)
3956 except TypeError:
3957 pass
3958 else:
3959 self.fail("didn't detect repeated base classes")
3960
3961 try:
3962 D.__bases__ = (E,)
3963 except TypeError:
3964 pass
3965 else:
3966 self.fail("shouldn't be able to create inheritance cycles")
3967
3968 # let's throw a classic class into the mix:
3969 class Classic:
3970 def meth2(self):
3971 return 3
3972
3973 D.__bases__ = (C, Classic)
3974
3975 self.assertEqual(d.meth2(), 3)
3976 self.assertEqual(e.meth2(), 3)
3977 try:
3978 d.a
3979 except AttributeError:
3980 pass
3981 else:
3982 self.fail("attribute should have vanished")
3983
3984 try:
3985 D.__bases__ = (Classic,)
3986 except TypeError:
3987 pass
3988 else:
3989 self.fail("new-style class must have a new-style base")
3990
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003991 def test_builtin_bases(self):
3992 # Make sure all the builtin types can have their base queried without
3993 # segfaulting. See issue #5787.
3994 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3995 if isinstance(tp, type)]
3996 for tp in builtin_types:
3997 object.__getattribute__(tp, "__bases__")
3998 if tp is not object:
3999 self.assertEqual(len(tp.__bases__), 1, tp)
4000
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00004001 class L(list):
4002 pass
4003
4004 class C(object):
4005 pass
4006
4007 class D(C):
4008 pass
4009
4010 try:
4011 L.__bases__ = (dict,)
4012 except TypeError:
4013 pass
4014 else:
4015 self.fail("shouldn't turn list subclass into dict subclass")
4016
4017 try:
4018 list.__bases__ = (dict,)
4019 except TypeError:
4020 pass
4021 else:
4022 self.fail("shouldn't be able to assign to list.__bases__")
4023
4024 try:
4025 D.__bases__ = (C, list)
4026 except TypeError:
4027 pass
4028 else:
4029 assert 0, "best_base calculation found wanting"
4030
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004031
Georg Brandl48545522008-02-02 10:12:36 +00004032 def test_mutable_bases_with_failing_mro(self):
4033 # Testing mutable bases with failing mro...
4034 class WorkOnce(type):
4035 def __new__(self, name, bases, ns):
4036 self.flag = 0
4037 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4038 def mro(self):
4039 if self.flag > 0:
4040 raise RuntimeError, "bozo"
4041 else:
4042 self.flag += 1
4043 return type.mro(self)
4044
4045 class WorkAlways(type):
4046 def mro(self):
4047 # this is here to make sure that .mro()s aren't called
4048 # with an exception set (which was possible at one point).
4049 # An error message will be printed in a debug build.
4050 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004051 return type.mro(self)
4052
Georg Brandl48545522008-02-02 10:12:36 +00004053 class C(object):
4054 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004055
Georg Brandl48545522008-02-02 10:12:36 +00004056 class C2(object):
4057 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004058
Georg Brandl48545522008-02-02 10:12:36 +00004059 class D(C):
4060 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004061
Georg Brandl48545522008-02-02 10:12:36 +00004062 class E(D):
4063 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004064
Georg Brandl48545522008-02-02 10:12:36 +00004065 class F(D):
4066 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004067
Georg Brandl48545522008-02-02 10:12:36 +00004068 class G(D):
4069 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004070
Georg Brandl48545522008-02-02 10:12:36 +00004071 # Immediate subclasses have their mro's adjusted in alphabetical
4072 # order, so E's will get adjusted before adjusting F's fails. We
4073 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004074
Georg Brandl48545522008-02-02 10:12:36 +00004075 E_mro_before = E.__mro__
4076 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004077
Armin Rigofd163f92005-12-29 15:59:19 +00004078 try:
Georg Brandl48545522008-02-02 10:12:36 +00004079 D.__bases__ = (C2,)
4080 except RuntimeError:
4081 self.assertEqual(E.__mro__, E_mro_before)
4082 self.assertEqual(D.__mro__, D_mro_before)
4083 else:
4084 self.fail("exception not propagated")
4085
4086 def test_mutable_bases_catch_mro_conflict(self):
4087 # Testing mutable bases catch mro conflict...
4088 class A(object):
4089 pass
4090
4091 class B(object):
4092 pass
4093
4094 class C(A, B):
4095 pass
4096
4097 class D(A, B):
4098 pass
4099
4100 class E(C, D):
4101 pass
4102
4103 try:
4104 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004105 except TypeError:
4106 pass
4107 else:
Georg Brandl48545522008-02-02 10:12:36 +00004108 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004109
Georg Brandl48545522008-02-02 10:12:36 +00004110 def test_mutable_names(self):
4111 # Testing mutable names...
4112 class C(object):
4113 pass
4114
4115 # C.__module__ could be 'test_descr' or '__main__'
4116 mod = C.__module__
4117
4118 C.__name__ = 'D'
4119 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4120
4121 C.__name__ = 'D.E'
4122 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4123
4124 def test_subclass_right_op(self):
4125 # Testing correct dispatch of subclass overloading __r<op>__...
4126
4127 # This code tests various cases where right-dispatch of a subclass
4128 # should be preferred over left-dispatch of a base class.
4129
4130 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4131
4132 class B(int):
4133 def __floordiv__(self, other):
4134 return "B.__floordiv__"
4135 def __rfloordiv__(self, other):
4136 return "B.__rfloordiv__"
4137
4138 self.assertEqual(B(1) // 1, "B.__floordiv__")
4139 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4140
4141 # Case 2: subclass of object; this is just the baseline for case 3
4142
4143 class C(object):
4144 def __floordiv__(self, other):
4145 return "C.__floordiv__"
4146 def __rfloordiv__(self, other):
4147 return "C.__rfloordiv__"
4148
4149 self.assertEqual(C() // 1, "C.__floordiv__")
4150 self.assertEqual(1 // C(), "C.__rfloordiv__")
4151
4152 # Case 3: subclass of new-style class; here it gets interesting
4153
4154 class D(C):
4155 def __floordiv__(self, other):
4156 return "D.__floordiv__"
4157 def __rfloordiv__(self, other):
4158 return "D.__rfloordiv__"
4159
4160 self.assertEqual(D() // C(), "D.__floordiv__")
4161 self.assertEqual(C() // D(), "D.__rfloordiv__")
4162
4163 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4164
4165 class E(C):
4166 pass
4167
4168 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4169
4170 self.assertEqual(E() // 1, "C.__floordiv__")
4171 self.assertEqual(1 // E(), "C.__rfloordiv__")
4172 self.assertEqual(E() // C(), "C.__floordiv__")
4173 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4174
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004175 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004176 def test_meth_class_get(self):
4177 # Testing __get__ method of METH_CLASS C methods...
4178 # Full coverage of descrobject.c::classmethod_get()
4179
4180 # Baseline
4181 arg = [1, 2, 3]
4182 res = {1: None, 2: None, 3: None}
4183 self.assertEqual(dict.fromkeys(arg), res)
4184 self.assertEqual({}.fromkeys(arg), res)
4185
4186 # Now get the descriptor
4187 descr = dict.__dict__["fromkeys"]
4188
4189 # More baseline using the descriptor directly
4190 self.assertEqual(descr.__get__(None, dict)(arg), res)
4191 self.assertEqual(descr.__get__({})(arg), res)
4192
4193 # Now check various error cases
4194 try:
4195 descr.__get__(None, None)
4196 except TypeError:
4197 pass
4198 else:
4199 self.fail("shouldn't have allowed descr.__get__(None, None)")
4200 try:
4201 descr.__get__(42)
4202 except TypeError:
4203 pass
4204 else:
4205 self.fail("shouldn't have allowed descr.__get__(42)")
4206 try:
4207 descr.__get__(None, 42)
4208 except TypeError:
4209 pass
4210 else:
4211 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4212 try:
4213 descr.__get__(None, int)
4214 except TypeError:
4215 pass
4216 else:
4217 self.fail("shouldn't have allowed descr.__get__(None, int)")
4218
4219 def test_isinst_isclass(self):
4220 # Testing proxy isinstance() and isclass()...
4221 class Proxy(object):
4222 def __init__(self, obj):
4223 self.__obj = obj
4224 def __getattribute__(self, name):
4225 if name.startswith("_Proxy__"):
4226 return object.__getattribute__(self, name)
4227 else:
4228 return getattr(self.__obj, name)
4229 # Test with a classic class
4230 class C:
4231 pass
4232 a = C()
4233 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004234 self.assertIsInstance(a, C) # Baseline
4235 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004236 # Test with a classic subclass
4237 class D(C):
4238 pass
4239 a = D()
4240 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004241 self.assertIsInstance(a, C) # Baseline
4242 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004243 # Test with a new-style class
4244 class C(object):
4245 pass
4246 a = C()
4247 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004248 self.assertIsInstance(a, C) # Baseline
4249 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004250 # Test with a new-style subclass
4251 class D(C):
4252 pass
4253 a = D()
4254 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004255 self.assertIsInstance(a, C) # Baseline
4256 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004257
4258 def test_proxy_super(self):
4259 # Testing super() for a proxy object...
4260 class Proxy(object):
4261 def __init__(self, obj):
4262 self.__obj = obj
4263 def __getattribute__(self, name):
4264 if name.startswith("_Proxy__"):
4265 return object.__getattribute__(self, name)
4266 else:
4267 return getattr(self.__obj, name)
4268
4269 class B(object):
4270 def f(self):
4271 return "B.f"
4272
4273 class C(B):
4274 def f(self):
4275 return super(C, self).f() + "->C.f"
4276
4277 obj = C()
4278 p = Proxy(obj)
4279 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4280
4281 def test_carloverre(self):
4282 # Testing prohibition of Carlo Verre's hack...
4283 try:
4284 object.__setattr__(str, "foo", 42)
4285 except TypeError:
4286 pass
4287 else:
4288 self.fail("Carlo Verre __setattr__ suceeded!")
4289 try:
4290 object.__delattr__(str, "lower")
4291 except TypeError:
4292 pass
4293 else:
4294 self.fail("Carlo Verre __delattr__ succeeded!")
4295
4296 def test_weakref_segfault(self):
4297 # Testing weakref segfault...
4298 # SF 742911
4299 import weakref
4300
4301 class Provoker:
4302 def __init__(self, referrent):
4303 self.ref = weakref.ref(referrent)
4304
4305 def __del__(self):
4306 x = self.ref()
4307
4308 class Oops(object):
4309 pass
4310
4311 o = Oops()
4312 o.whatever = Provoker(o)
4313 del o
4314
4315 def test_wrapper_segfault(self):
4316 # SF 927248: deeply nested wrappers could cause stack overflow
4317 f = lambda:None
4318 for i in xrange(1000000):
4319 f = f.__call__
4320 f = None
4321
4322 def test_file_fault(self):
4323 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004324 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004325 class StdoutGuard:
4326 def __getattr__(self, attr):
4327 sys.stdout = sys.__stdout__
4328 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4329 sys.stdout = StdoutGuard()
4330 try:
4331 print "Oops!"
4332 except RuntimeError:
4333 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004334 finally:
4335 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004336
4337 def test_vicious_descriptor_nonsense(self):
4338 # Testing vicious_descriptor_nonsense...
4339
4340 # A potential segfault spotted by Thomas Wouters in mail to
4341 # python-dev 2003-04-17, turned into an example & fixed by Michael
4342 # Hudson just less than four months later...
4343
4344 class Evil(object):
4345 def __hash__(self):
4346 return hash('attr')
4347 def __eq__(self, other):
4348 del C.attr
4349 return 0
4350
4351 class Descr(object):
4352 def __get__(self, ob, type=None):
4353 return 1
4354
4355 class C(object):
4356 attr = Descr()
4357
4358 c = C()
4359 c.__dict__[Evil()] = 0
4360
4361 self.assertEqual(c.attr, 1)
4362 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004363 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004364 self.assertEqual(hasattr(c, 'attr'), False)
4365
4366 def test_init(self):
4367 # SF 1155938
4368 class Foo(object):
4369 def __init__(self):
4370 return 10
4371 try:
4372 Foo()
4373 except TypeError:
4374 pass
4375 else:
4376 self.fail("did not test __init__() for None return")
4377
4378 def test_method_wrapper(self):
4379 # Testing method-wrapper objects...
4380 # <type 'method-wrapper'> did not support any reflection before 2.5
4381
4382 l = []
4383 self.assertEqual(l.__add__, l.__add__)
4384 self.assertEqual(l.__add__, [].__add__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004385 self.assertTrue(l.__add__ != [5].__add__)
4386 self.assertTrue(l.__add__ != l.__mul__)
4387 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004388 if hasattr(l.__add__, '__self__'):
4389 # CPython
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004390 self.assertTrue(l.__add__.__self__ is l)
4391 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004392 else:
4393 # Python implementations where [].__add__ is a normal bound method
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004394 self.assertTrue(l.__add__.im_self is l)
4395 self.assertTrue(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004396 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4397 try:
4398 hash(l.__add__)
4399 except TypeError:
4400 pass
4401 else:
4402 self.fail("no TypeError from hash([].__add__)")
4403
4404 t = ()
4405 t += (7,)
4406 self.assertEqual(t.__add__, (7,).__add__)
4407 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4408
4409 def test_not_implemented(self):
4410 # Testing NotImplemented...
4411 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004412 import operator
4413
4414 def specialmethod(self, other):
4415 return NotImplemented
4416
4417 def check(expr, x, y):
4418 try:
4419 exec expr in {'x': x, 'y': y, 'operator': operator}
4420 except TypeError:
4421 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004422 else:
Georg Brandl48545522008-02-02 10:12:36 +00004423 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004424
Georg Brandl48545522008-02-02 10:12:36 +00004425 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4426 # TypeErrors
4427 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4428 # ValueErrors instead of TypeErrors
4429 for metaclass in [type, types.ClassType]:
4430 for name, expr, iexpr in [
4431 ('__add__', 'x + y', 'x += y'),
4432 ('__sub__', 'x - y', 'x -= y'),
4433 ('__mul__', 'x * y', 'x *= y'),
4434 ('__truediv__', 'operator.truediv(x, y)', None),
4435 ('__floordiv__', 'operator.floordiv(x, y)', None),
4436 ('__div__', 'x / y', 'x /= y'),
4437 ('__mod__', 'x % y', 'x %= y'),
4438 ('__divmod__', 'divmod(x, y)', None),
4439 ('__pow__', 'x ** y', 'x **= y'),
4440 ('__lshift__', 'x << y', 'x <<= y'),
4441 ('__rshift__', 'x >> y', 'x >>= y'),
4442 ('__and__', 'x & y', 'x &= y'),
4443 ('__or__', 'x | y', 'x |= y'),
4444 ('__xor__', 'x ^ y', 'x ^= y'),
4445 ('__coerce__', 'coerce(x, y)', None)]:
4446 if name == '__coerce__':
4447 rname = name
4448 else:
4449 rname = '__r' + name[2:]
4450 A = metaclass('A', (), {name: specialmethod})
4451 B = metaclass('B', (), {rname: specialmethod})
4452 a = A()
4453 b = B()
4454 check(expr, a, a)
4455 check(expr, a, b)
4456 check(expr, b, a)
4457 check(expr, b, b)
4458 check(expr, a, N1)
4459 check(expr, a, N2)
4460 check(expr, N1, b)
4461 check(expr, N2, b)
4462 if iexpr:
4463 check(iexpr, a, a)
4464 check(iexpr, a, b)
4465 check(iexpr, b, a)
4466 check(iexpr, b, b)
4467 check(iexpr, a, N1)
4468 check(iexpr, a, N2)
4469 iname = '__i' + name[2:]
4470 C = metaclass('C', (), {iname: specialmethod})
4471 c = C()
4472 check(iexpr, c, a)
4473 check(iexpr, c, b)
4474 check(iexpr, c, N1)
4475 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004476
Georg Brandl48545522008-02-02 10:12:36 +00004477 def test_assign_slice(self):
4478 # ceval.c's assign_slice used to check for
4479 # tp->tp_as_sequence->sq_slice instead of
4480 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004481
Georg Brandl48545522008-02-02 10:12:36 +00004482 class C(object):
4483 def __setslice__(self, start, stop, value):
4484 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004485
Georg Brandl48545522008-02-02 10:12:36 +00004486 c = C()
4487 c[1:2] = 3
4488 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004489
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004490 def test_set_and_no_get(self):
4491 # See
4492 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4493 class Descr(object):
4494
4495 def __init__(self, name):
4496 self.name = name
4497
4498 def __set__(self, obj, value):
4499 obj.__dict__[self.name] = value
4500 descr = Descr("a")
4501
4502 class X(object):
4503 a = descr
4504
4505 x = X()
4506 self.assertIs(x.a, descr)
4507 x.a = 42
4508 self.assertEqual(x.a, 42)
4509
Benjamin Peterson42d59472010-02-06 20:14:10 +00004510 # Also check type_getattro for correctness.
4511 class Meta(type):
4512 pass
4513 class X(object):
4514 __metaclass__ = Meta
4515 X.a = 42
4516 Meta.a = Descr("a")
4517 self.assertEqual(X.a, 42)
4518
Benjamin Peterson273c2332008-11-17 22:39:09 +00004519 def test_getattr_hooks(self):
4520 # issue 4230
4521
4522 class Descriptor(object):
4523 counter = 0
4524 def __get__(self, obj, objtype=None):
4525 def getter(name):
4526 self.counter += 1
4527 raise AttributeError(name)
4528 return getter
4529
4530 descr = Descriptor()
4531 class A(object):
4532 __getattribute__ = descr
4533 class B(object):
4534 __getattr__ = descr
4535 class C(object):
4536 __getattribute__ = descr
4537 __getattr__ = descr
4538
4539 self.assertRaises(AttributeError, getattr, A(), "attr")
4540 self.assertEquals(descr.counter, 1)
4541 self.assertRaises(AttributeError, getattr, B(), "attr")
4542 self.assertEquals(descr.counter, 2)
4543 self.assertRaises(AttributeError, getattr, C(), "attr")
4544 self.assertEquals(descr.counter, 4)
4545
4546 import gc
4547 class EvilGetattribute(object):
4548 # This used to segfault
4549 def __getattr__(self, name):
4550 raise AttributeError(name)
4551 def __getattribute__(self, name):
4552 del EvilGetattribute.__getattr__
4553 for i in range(5):
4554 gc.collect()
4555 raise AttributeError(name)
4556
4557 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4558
Guido van Rossum9acc3872008-01-23 23:23:43 +00004559
Georg Brandl48545522008-02-02 10:12:36 +00004560class DictProxyTests(unittest.TestCase):
4561 def setUp(self):
4562 class C(object):
4563 def meth(self):
4564 pass
4565 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004566
Georg Brandl48545522008-02-02 10:12:36 +00004567 def test_iter_keys(self):
4568 # Testing dict-proxy iterkeys...
4569 keys = [ key for key in self.C.__dict__.iterkeys() ]
4570 keys.sort()
4571 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4572 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004573
Georg Brandl48545522008-02-02 10:12:36 +00004574 def test_iter_values(self):
4575 # Testing dict-proxy itervalues...
4576 values = [ values for values in self.C.__dict__.itervalues() ]
4577 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004578
Georg Brandl48545522008-02-02 10:12:36 +00004579 def test_iter_items(self):
4580 # Testing dict-proxy iteritems...
4581 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4582 keys.sort()
4583 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4584 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004585
Georg Brandl48545522008-02-02 10:12:36 +00004586 def test_dict_type_with_metaclass(self):
4587 # Testing type of __dict__ when __metaclass__ set...
4588 class B(object):
4589 pass
4590 class M(type):
4591 pass
4592 class C:
4593 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4594 __metaclass__ = M
4595 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004596
Guido van Rossum9acc3872008-01-23 23:23:43 +00004597
Georg Brandl48545522008-02-02 10:12:36 +00004598class PTypesLongInitTest(unittest.TestCase):
4599 # This is in its own TestCase so that it can be run before any other tests.
4600 def test_pytype_long_ready(self):
4601 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004602
Georg Brandl48545522008-02-02 10:12:36 +00004603 # This dumps core when SF bug 551412 isn't fixed --
4604 # but only when test_descr.py is run separately.
4605 # (That can't be helped -- as soon as PyType_Ready()
4606 # is called for PyLong_Type, the bug is gone.)
4607 class UserLong(object):
4608 def __pow__(self, *args):
4609 pass
4610 try:
4611 pow(0L, UserLong(), 0L)
4612 except:
4613 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004614
Georg Brandl48545522008-02-02 10:12:36 +00004615 # Another segfault only when run early
4616 # (before PyType_Ready(tuple) is called)
4617 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004618
4619
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004620def test_main():
Senthil Kumarance8e33a2010-01-08 19:04:16 +00004621 # Run all local test cases, with PTypesLongInitTest first.
4622 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4623 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004625if __name__ == "__main__":
4626 test_main()