blob: d450eed585f9f74489547a25cc76554e81683633 [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
Tim Peters4d9b4662002-04-16 01:59:17 +00005
Georg Brandl48545522008-02-02 10:12:36 +00006from copy import deepcopy
7from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +00008
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Georg Brandl48545522008-02-02 10:12:36 +000010class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Georg Brandl48545522008-02-02 10:12:36 +000012 def __init__(self, *args, **kwargs):
13 unittest.TestCase.__init__(self, *args, **kwargs)
14 self.binops = {
15 'add': '+',
16 'sub': '-',
17 'mul': '*',
18 'div': '/',
19 'divmod': 'divmod',
20 'pow': '**',
21 'lshift': '<<',
22 'rshift': '>>',
23 'and': '&',
24 'xor': '^',
25 'or': '|',
26 'cmp': 'cmp',
27 'lt': '<',
28 'le': '<=',
29 'eq': '==',
30 'ne': '!=',
31 'gt': '>',
32 'ge': '>=',
33 }
Tim Peters3caca232001-12-06 06:23:26 +000034
Georg Brandl48545522008-02-02 10:12:36 +000035 for name, expr in self.binops.items():
36 if expr.islower():
37 expr = expr + "(a, b)"
38 else:
39 expr = 'a %s b' % expr
40 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000041
Georg Brandl48545522008-02-02 10:12:36 +000042 self.unops = {
43 'pos': '+',
44 'neg': '-',
45 'abs': 'abs',
46 'invert': '~',
47 'int': 'int',
48 'long': 'long',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl48545522008-02-02 10:12:36 +000054 for name, expr in self.unops.items():
55 if expr.islower():
56 expr = expr + "(a)"
57 else:
58 expr = '%s a' % expr
59 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000060
Georg Brandl48545522008-02-02 10:12:36 +000061 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
62 d = {'a': a}
63 self.assertEqual(eval(expr, d), res)
64 t = type(a)
65 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl48545522008-02-02 10:12:36 +000067 # Find method in parent class
68 while meth not in t.__dict__:
69 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000070 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
71 # method object; the getattr() below obtains its underlying function.
72 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000073 self.assertEqual(m(a), res)
74 bm = getattr(a, meth)
75 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000076
Georg Brandl48545522008-02-02 10:12:36 +000077 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
78 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000079
Georg Brandl48545522008-02-02 10:12:36 +000080 # XXX Hack so this passes before 2.3 when -Qnew is specified.
81 if meth == "__div__" and 1/2 == 0.5:
82 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000083
Georg Brandl48545522008-02-02 10:12:36 +000084 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl48545522008-02-02 10:12:36 +000086 self.assertEqual(eval(expr, d), res)
87 t = type(a)
88 m = getattr(t, meth)
89 while meth not in t.__dict__:
90 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000091 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000094 self.assertEqual(m(a, b), res)
95 bm = getattr(a, meth)
96 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000097
Georg Brandl48545522008-02-02 10:12:36 +000098 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
99 d = {'a': a, 'b': b, 'c': c}
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000108 self.assertEqual(m(a, b, c), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl48545522008-02-02 10:12:36 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec stmt in d
115 self.assertEqual(d['a'], res)
116 t = type(a)
117 m = getattr(t, meth)
118 while meth not in t.__dict__:
119 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000123 d['a'] = deepcopy(a)
124 m(d['a'], b)
125 self.assertEqual(d['a'], res)
126 d['a'] = deepcopy(a)
127 bm = getattr(d['a'], meth)
128 bm(b)
129 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130
Georg Brandl48545522008-02-02 10:12:36 +0000131 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132 d = {'a': deepcopy(a), 'b': b, 'c': c}
133 exec stmt in d
134 self.assertEqual(d['a'], res)
135 t = type(a)
136 m = getattr(t, meth)
137 while meth not in t.__dict__:
138 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000142 d['a'] = deepcopy(a)
143 m(d['a'], b, c)
144 self.assertEqual(d['a'], res)
145 d['a'] = deepcopy(a)
146 bm = getattr(d['a'], meth)
147 bm(b, c)
148 self.assertEqual(d['a'], res)
149
150 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec stmt in dictionary
153 self.assertEqual(dictionary['a'], res)
154 t = type(a)
155 while meth not in t.__dict__:
156 t = t.__bases__[0]
157 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], b, c, d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(b, c, d)
167 self.assertEqual(dictionary['a'], res)
168
169 def test_lists(self):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
177 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setslice__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000188 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
189 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
190 else:
191 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000192 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
193 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
194 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
195
196 d = {1:2, 3:4}
197 l1 = []
198 for i in d.keys():
199 l1.append(i)
200 l = []
201 for i in iter(d):
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in d.__iter__():
206 l.append(i)
207 self.assertEqual(l, l1)
208 l = []
209 for i in dict.__iter__(d):
210 l.append(i)
211 self.assertEqual(l, l1)
212 d = {1:2, 3:4}
213 self.unop_test(d, 2, "len(a)", "__len__")
214 self.assertEqual(eval(repr(d), {}), d)
215 self.assertEqual(eval(d.__repr__(), {}), d)
216 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
217 "__setitem__")
218
219 # Tests for unary and binary operators
220 def number_operators(self, a, b, skip=[]):
221 dict = {'a': a, 'b': b}
222
223 for name, expr in self.binops.items():
224 if name not in skip:
225 name = "__%s__" % name
226 if hasattr(a, name):
227 res = eval(expr, dict)
228 self.binop_test(a, b, res, expr, name)
229
230 for name, expr in self.unops.items():
231 if name not in skip:
232 name = "__%s__" % name
233 if hasattr(a, name):
234 res = eval(expr, dict)
235 self.unop_test(a, res, expr, name)
236
237 def test_ints(self):
238 # Testing int operations...
239 self.number_operators(100, 3)
240 # The following crashes in Python 2.2
241 self.assertEqual((1).__nonzero__(), 1)
242 self.assertEqual((0).__nonzero__(), 0)
243 # This returns 'NotImplemented' in Python 2.2
244 class C(int):
245 def __add__(self, other):
246 return NotImplemented
247 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000248 try:
Georg Brandl48545522008-02-02 10:12:36 +0000249 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000250 except TypeError:
251 pass
252 else:
Georg Brandl48545522008-02-02 10:12:36 +0000253 self.fail("NotImplemented should have caused TypeError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000254 try:
Georg Brandl48545522008-02-02 10:12:36 +0000255 C(sys.maxint+1)
256 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000257 pass
258 else:
Georg Brandl48545522008-02-02 10:12:36 +0000259 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000260
Georg Brandl48545522008-02-02 10:12:36 +0000261 def test_longs(self):
262 # Testing long operations...
263 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000264
Georg Brandl48545522008-02-02 10:12:36 +0000265 def test_floats(self):
266 # Testing float operations...
267 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000268
Georg Brandl48545522008-02-02 10:12:36 +0000269 def test_complexes(self):
270 # Testing complex operations...
271 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
272 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000273
Georg Brandl48545522008-02-02 10:12:36 +0000274 class Number(complex):
275 __slots__ = ['prec']
276 def __new__(cls, *args, **kwds):
277 result = complex.__new__(cls, *args)
278 result.prec = kwds.get('prec', 12)
279 return result
280 def __repr__(self):
281 prec = self.prec
282 if self.imag == 0.0:
283 return "%.*g" % (prec, self.real)
284 if self.real == 0.0:
285 return "%.*gj" % (prec, self.imag)
286 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
287 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000288
Georg Brandl48545522008-02-02 10:12:36 +0000289 a = Number(3.14, prec=6)
290 self.assertEqual(repr(a), "3.14")
291 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000292
Georg Brandl48545522008-02-02 10:12:36 +0000293 a = Number(a, prec=2)
294 self.assertEqual(repr(a), "3.1")
295 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000296
Georg Brandl48545522008-02-02 10:12:36 +0000297 a = Number(234.5)
298 self.assertEqual(repr(a), "234.5")
299 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000300
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000301 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000302 def test_spam_lists(self):
303 # Testing spamlist operations...
304 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000305
Georg Brandl48545522008-02-02 10:12:36 +0000306 def spamlist(l, memo=None):
307 import xxsubtype as spam
308 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000309
Georg Brandl48545522008-02-02 10:12:36 +0000310 # This is an ugly hack:
311 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000312
Georg Brandl48545522008-02-02 10:12:36 +0000313 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
314 "__add__")
315 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
316 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
317 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
318 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
319 "__getslice__")
320 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
321 "__iadd__")
322 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
323 "__imul__")
324 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
325 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
326 "__mul__")
327 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
328 "__rmul__")
329 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
330 "__setitem__")
331 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
332 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
333 # Test subclassing
334 class C(spam.spamlist):
335 def foo(self): return 1
336 a = C()
337 self.assertEqual(a, [])
338 self.assertEqual(a.foo(), 1)
339 a.append(100)
340 self.assertEqual(a, [100])
341 self.assertEqual(a.getstate(), 0)
342 a.setstate(42)
343 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000344
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000345 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000346 def test_spam_dicts(self):
347 # Testing spamdict operations...
348 import copy, xxsubtype as spam
349 def spamdict(d, memo=None):
350 import xxsubtype as spam
351 sd = spam.spamdict()
352 for k, v in d.items():
353 sd[k] = v
354 return sd
355 # This is an ugly hack:
356 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000357
Georg Brandl48545522008-02-02 10:12:36 +0000358 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
359 "__cmp__")
360 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
361 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
362 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
363 d = spamdict({1:2,3:4})
364 l1 = []
365 for i in d.keys():
366 l1.append(i)
367 l = []
368 for i in iter(d):
369 l.append(i)
370 self.assertEqual(l, l1)
371 l = []
372 for i in d.__iter__():
373 l.append(i)
374 self.assertEqual(l, l1)
375 l = []
376 for i in type(spamdict({})).__iter__(d):
377 l.append(i)
378 self.assertEqual(l, l1)
379 straightd = {1:2, 3:4}
380 spamd = spamdict(straightd)
381 self.unop_test(spamd, 2, "len(a)", "__len__")
382 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
383 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
384 "a[b]=c", "__setitem__")
385 # Test subclassing
386 class C(spam.spamdict):
387 def foo(self): return 1
388 a = C()
389 self.assertEqual(a.items(), [])
390 self.assertEqual(a.foo(), 1)
391 a['foo'] = 'bar'
392 self.assertEqual(a.items(), [('foo', 'bar')])
393 self.assertEqual(a.getstate(), 0)
394 a.setstate(100)
395 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000396
Georg Brandl48545522008-02-02 10:12:36 +0000397class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000398
Georg Brandl48545522008-02-02 10:12:36 +0000399 def test_python_dicts(self):
400 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000401 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000402 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000403 d = dict()
404 self.assertEqual(d, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000405 self.assertTrue(d.__class__ is dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000406 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000407 class C(dict):
408 state = -1
409 def __init__(self_local, *a, **kw):
410 if a:
411 self.assertEqual(len(a), 1)
412 self_local.state = a[0]
413 if kw:
414 for k, v in kw.items():
415 self_local[v] = k
416 def __getitem__(self, key):
417 return self.get(key, 0)
418 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000419 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000420 dict.__setitem__(self_local, key, value)
421 def setstate(self, state):
422 self.state = state
423 def getstate(self):
424 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000425 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000426 a1 = C(12)
427 self.assertEqual(a1.state, 12)
428 a2 = C(foo=1, bar=2)
429 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
430 a = C()
431 self.assertEqual(a.state, -1)
432 self.assertEqual(a.getstate(), -1)
433 a.setstate(0)
434 self.assertEqual(a.state, 0)
435 self.assertEqual(a.getstate(), 0)
436 a.setstate(10)
437 self.assertEqual(a.state, 10)
438 self.assertEqual(a.getstate(), 10)
439 self.assertEqual(a[42], 0)
440 a[42] = 24
441 self.assertEqual(a[42], 24)
442 N = 50
443 for i in range(N):
444 a[i] = C()
445 for j in range(N):
446 a[i][j] = i*j
447 for i in range(N):
448 for j in range(N):
449 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000450
Georg Brandl48545522008-02-02 10:12:36 +0000451 def test_python_lists(self):
452 # Testing Python subclass of list...
453 class C(list):
454 def __getitem__(self, i):
455 return list.__getitem__(self, i) + 100
456 def __getslice__(self, i, j):
457 return (i, j)
458 a = C()
459 a.extend([0,1,2])
460 self.assertEqual(a[0], 100)
461 self.assertEqual(a[1], 101)
462 self.assertEqual(a[2], 102)
463 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000464
Georg Brandl48545522008-02-02 10:12:36 +0000465 def test_metaclass(self):
466 # Testing __metaclass__...
467 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000468 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000469 def __init__(self):
470 self.__state = 0
471 def getstate(self):
472 return self.__state
473 def setstate(self, state):
474 self.__state = state
475 a = C()
476 self.assertEqual(a.getstate(), 0)
477 a.setstate(10)
478 self.assertEqual(a.getstate(), 10)
479 class D:
480 class __metaclass__(type):
481 def myself(cls): return cls
482 self.assertEqual(D.myself(), D)
483 d = D()
484 self.assertEqual(d.__class__, D)
485 class M1(type):
486 def __new__(cls, name, bases, dict):
487 dict['__spam__'] = 1
488 return type.__new__(cls, name, bases, dict)
489 class C:
490 __metaclass__ = M1
491 self.assertEqual(C.__spam__, 1)
492 c = C()
493 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000494
Georg Brandl48545522008-02-02 10:12:36 +0000495 class _instance(object):
496 pass
497 class M2(object):
498 @staticmethod
499 def __new__(cls, name, bases, dict):
500 self = object.__new__(cls)
501 self.name = name
502 self.bases = bases
503 self.dict = dict
504 return self
505 def __call__(self):
506 it = _instance()
507 # Early binding of methods
508 for key in self.dict:
509 if key.startswith("__"):
510 continue
511 setattr(it, key, self.dict[key].__get__(it, self))
512 return it
513 class C:
514 __metaclass__ = M2
515 def spam(self):
516 return 42
517 self.assertEqual(C.name, 'C')
518 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000519 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000520 c = C()
521 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000522
Georg Brandl48545522008-02-02 10:12:36 +0000523 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000524
Georg Brandl48545522008-02-02 10:12:36 +0000525 class autosuper(type):
526 # Automatically add __super to the class
527 # This trick only works for dynamic classes
528 def __new__(metaclass, name, bases, dict):
529 cls = super(autosuper, metaclass).__new__(metaclass,
530 name, bases, dict)
531 # Name mangling for __super removes leading underscores
532 while name[:1] == "_":
533 name = name[1:]
534 if name:
535 name = "_%s__super" % name
536 else:
537 name = "__super"
538 setattr(cls, name, super(cls))
539 return cls
540 class A:
541 __metaclass__ = autosuper
542 def meth(self):
543 return "A"
544 class B(A):
545 def meth(self):
546 return "B" + self.__super.meth()
547 class C(A):
548 def meth(self):
549 return "C" + self.__super.meth()
550 class D(C, B):
551 def meth(self):
552 return "D" + self.__super.meth()
553 self.assertEqual(D().meth(), "DCBA")
554 class E(B, C):
555 def meth(self):
556 return "E" + self.__super.meth()
557 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000558
Georg Brandl48545522008-02-02 10:12:36 +0000559 class autoproperty(type):
560 # Automatically create property attributes when methods
561 # named _get_x and/or _set_x are found
562 def __new__(metaclass, name, bases, dict):
563 hits = {}
564 for key, val in dict.iteritems():
565 if key.startswith("_get_"):
566 key = key[5:]
567 get, set = hits.get(key, (None, None))
568 get = val
569 hits[key] = get, set
570 elif key.startswith("_set_"):
571 key = key[5:]
572 get, set = hits.get(key, (None, None))
573 set = val
574 hits[key] = get, set
575 for key, (get, set) in hits.iteritems():
576 dict[key] = property(get, set)
577 return super(autoproperty, metaclass).__new__(metaclass,
578 name, bases, dict)
579 class A:
580 __metaclass__ = autoproperty
581 def _get_x(self):
582 return -self.__x
583 def _set_x(self, x):
584 self.__x = -x
585 a = A()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000586 self.assertTrue(not hasattr(a, "x"))
Georg Brandl48545522008-02-02 10:12:36 +0000587 a.x = 12
588 self.assertEqual(a.x, 12)
589 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000590
Georg Brandl48545522008-02-02 10:12:36 +0000591 class multimetaclass(autoproperty, autosuper):
592 # Merge of multiple cooperating metaclasses
593 pass
594 class A:
595 __metaclass__ = multimetaclass
596 def _get_x(self):
597 return "A"
598 class B(A):
599 def _get_x(self):
600 return "B" + self.__super._get_x()
601 class C(A):
602 def _get_x(self):
603 return "C" + self.__super._get_x()
604 class D(C, B):
605 def _get_x(self):
606 return "D" + self.__super._get_x()
607 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000608
Georg Brandl48545522008-02-02 10:12:36 +0000609 # Make sure type(x) doesn't call x.__class__.__init__
610 class T(type):
611 counter = 0
612 def __init__(self, *args):
613 T.counter += 1
614 class C:
615 __metaclass__ = T
616 self.assertEqual(T.counter, 1)
617 a = C()
618 self.assertEqual(type(a), C)
619 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000620
Georg Brandl48545522008-02-02 10:12:36 +0000621 class C(object): pass
622 c = C()
623 try: c()
624 except TypeError: pass
625 else: self.fail("calling object w/o call method should raise "
626 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000627
Georg Brandl48545522008-02-02 10:12:36 +0000628 # Testing code to find most derived baseclass
629 class A(type):
630 def __new__(*args, **kwargs):
631 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632
Georg Brandl48545522008-02-02 10:12:36 +0000633 class B(object):
634 pass
635
636 class C(object):
637 __metaclass__ = A
638
639 # The most derived metaclass of D is A rather than type.
640 class D(B, C):
641 pass
642
643 def test_module_subclasses(self):
644 # Testing Python subclass of module...
645 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000646 MT = type(sys)
647 class MM(MT):
648 def __init__(self, name):
649 MT.__init__(self, name)
650 def __getattribute__(self, name):
651 log.append(("getattr", name))
652 return MT.__getattribute__(self, name)
653 def __setattr__(self, name, value):
654 log.append(("setattr", name, value))
655 MT.__setattr__(self, name, value)
656 def __delattr__(self, name):
657 log.append(("delattr", name))
658 MT.__delattr__(self, name)
659 a = MM("a")
660 a.foo = 12
661 x = a.foo
662 del a.foo
663 self.assertEqual(log, [("setattr", "foo", 12),
664 ("getattr", "foo"),
665 ("delattr", "foo")])
666
667 # http://python.org/sf/1174712
668 try:
669 class Module(types.ModuleType, str):
670 pass
671 except TypeError:
672 pass
673 else:
674 self.fail("inheriting from ModuleType and str at the same time "
675 "should fail")
676
677 def test_multiple_inheritence(self):
678 # Testing multiple inheritance...
679 class C(object):
680 def __init__(self):
681 self.__state = 0
682 def getstate(self):
683 return self.__state
684 def setstate(self, state):
685 self.__state = state
686 a = C()
687 self.assertEqual(a.getstate(), 0)
688 a.setstate(10)
689 self.assertEqual(a.getstate(), 10)
690 class D(dict, C):
691 def __init__(self):
692 type({}).__init__(self)
693 C.__init__(self)
694 d = D()
695 self.assertEqual(d.keys(), [])
696 d["hello"] = "world"
697 self.assertEqual(d.items(), [("hello", "world")])
698 self.assertEqual(d["hello"], "world")
699 self.assertEqual(d.getstate(), 0)
700 d.setstate(10)
701 self.assertEqual(d.getstate(), 10)
702 self.assertEqual(D.__mro__, (D, dict, C, object))
703
704 # SF bug #442833
705 class Node(object):
706 def __int__(self):
707 return int(self.foo())
708 def foo(self):
709 return "23"
710 class Frag(Node, list):
711 def foo(self):
712 return "42"
713 self.assertEqual(Node().__int__(), 23)
714 self.assertEqual(int(Node()), 23)
715 self.assertEqual(Frag().__int__(), 42)
716 self.assertEqual(int(Frag()), 42)
717
718 # MI mixing classic and new-style classes.
719
720 class A:
721 x = 1
722
723 class B(A):
724 pass
725
726 class C(A):
727 x = 2
728
729 class D(B, C):
730 pass
731 self.assertEqual(D.x, 1)
732
733 # Classic MRO is preserved for a classic base class.
734 class E(D, object):
735 pass
736 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
737 self.assertEqual(E.x, 1)
738
739 # But with a mix of classic bases, their MROs are combined using
740 # new-style MRO.
741 class F(B, C, object):
742 pass
743 self.assertEqual(F.__mro__, (F, B, C, A, object))
744 self.assertEqual(F.x, 2)
745
746 # Try something else.
747 class C:
748 def cmethod(self):
749 return "C a"
750 def all_method(self):
751 return "C b"
752
753 class M1(C, object):
754 def m1method(self):
755 return "M1 a"
756 def all_method(self):
757 return "M1 b"
758
759 self.assertEqual(M1.__mro__, (M1, C, object))
760 m = M1()
761 self.assertEqual(m.cmethod(), "C a")
762 self.assertEqual(m.m1method(), "M1 a")
763 self.assertEqual(m.all_method(), "M1 b")
764
765 class D(C):
766 def dmethod(self):
767 return "D a"
768 def all_method(self):
769 return "D b"
770
771 class M2(D, object):
772 def m2method(self):
773 return "M2 a"
774 def all_method(self):
775 return "M2 b"
776
777 self.assertEqual(M2.__mro__, (M2, D, C, object))
778 m = M2()
779 self.assertEqual(m.cmethod(), "C a")
780 self.assertEqual(m.dmethod(), "D a")
781 self.assertEqual(m.m2method(), "M2 a")
782 self.assertEqual(m.all_method(), "M2 b")
783
784 class M3(M1, M2, object):
785 def m3method(self):
786 return "M3 a"
787 def all_method(self):
788 return "M3 b"
789 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
790 m = M3()
791 self.assertEqual(m.cmethod(), "C a")
792 self.assertEqual(m.dmethod(), "D a")
793 self.assertEqual(m.m1method(), "M1 a")
794 self.assertEqual(m.m2method(), "M2 a")
795 self.assertEqual(m.m3method(), "M3 a")
796 self.assertEqual(m.all_method(), "M3 b")
797
798 class Classic:
799 pass
800 try:
801 class New(Classic):
802 __metaclass__ = type
803 except TypeError:
804 pass
805 else:
806 self.fail("new class with only classic bases - shouldn't be")
807
808 def test_diamond_inheritence(self):
809 # Testing multiple inheritance special cases...
810 class A(object):
811 def spam(self): return "A"
812 self.assertEqual(A().spam(), "A")
813 class B(A):
814 def boo(self): return "B"
815 def spam(self): return "B"
816 self.assertEqual(B().spam(), "B")
817 self.assertEqual(B().boo(), "B")
818 class C(A):
819 def boo(self): return "C"
820 self.assertEqual(C().spam(), "A")
821 self.assertEqual(C().boo(), "C")
822 class D(B, C): pass
823 self.assertEqual(D().spam(), "B")
824 self.assertEqual(D().boo(), "B")
825 self.assertEqual(D.__mro__, (D, B, C, A, object))
826 class E(C, B): pass
827 self.assertEqual(E().spam(), "B")
828 self.assertEqual(E().boo(), "C")
829 self.assertEqual(E.__mro__, (E, C, B, A, object))
830 # MRO order disagreement
831 try:
832 class F(D, E): pass
833 except TypeError:
834 pass
835 else:
836 self.fail("expected MRO order disagreement (F)")
837 try:
838 class G(E, D): pass
839 except TypeError:
840 pass
841 else:
842 self.fail("expected MRO order disagreement (G)")
843
844 # see thread python-dev/2002-October/029035.html
845 def test_ex5_from_c3_switch(self):
846 # Testing ex5 from C3 switch discussion...
847 class A(object): pass
848 class B(object): pass
849 class C(object): pass
850 class X(A): pass
851 class Y(A): pass
852 class Z(X,B,Y,C): pass
853 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
854
855 # see "A Monotonic Superclass Linearization for Dylan",
856 # by Kim Barrett et al. (OOPSLA 1996)
857 def test_monotonicity(self):
858 # Testing MRO monotonicity...
859 class Boat(object): pass
860 class DayBoat(Boat): pass
861 class WheelBoat(Boat): pass
862 class EngineLess(DayBoat): pass
863 class SmallMultihull(DayBoat): pass
864 class PedalWheelBoat(EngineLess,WheelBoat): pass
865 class SmallCatamaran(SmallMultihull): pass
866 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
867
868 self.assertEqual(PedalWheelBoat.__mro__,
869 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
870 self.assertEqual(SmallCatamaran.__mro__,
871 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
872 self.assertEqual(Pedalo.__mro__,
873 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
874 SmallMultihull, DayBoat, WheelBoat, Boat, object))
875
876 # see "A Monotonic Superclass Linearization for Dylan",
877 # by Kim Barrett et al. (OOPSLA 1996)
878 def test_consistency_with_epg(self):
879 # Testing consistentcy with EPG...
880 class Pane(object): pass
881 class ScrollingMixin(object): pass
882 class EditingMixin(object): pass
883 class ScrollablePane(Pane,ScrollingMixin): pass
884 class EditablePane(Pane,EditingMixin): pass
885 class EditableScrollablePane(ScrollablePane,EditablePane): pass
886
887 self.assertEqual(EditableScrollablePane.__mro__,
888 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
889 ScrollingMixin, EditingMixin, object))
890
891 def test_mro_disagreement(self):
892 # Testing error messages for MRO disagreement...
893 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000894order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000895
Georg Brandl48545522008-02-02 10:12:36 +0000896 def raises(exc, expected, callable, *args):
897 try:
898 callable(*args)
899 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000900 # the exact msg is generally considered an impl detail
901 if test_support.check_impl_detail():
902 if not str(msg).startswith(expected):
903 self.fail("Message %r, expected %r" %
904 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000905 else:
906 self.fail("Expected %s" % exc)
907
908 class A(object): pass
909 class B(A): pass
910 class C(object): pass
911
912 # Test some very simple errors
913 raises(TypeError, "duplicate base class A",
914 type, "X", (A, A), {})
915 raises(TypeError, mro_err_msg,
916 type, "X", (A, B), {})
917 raises(TypeError, mro_err_msg,
918 type, "X", (A, C, B), {})
919 # Test a slightly more complex error
920 class GridLayout(object): pass
921 class HorizontalGrid(GridLayout): pass
922 class VerticalGrid(GridLayout): pass
923 class HVGrid(HorizontalGrid, VerticalGrid): pass
924 class VHGrid(VerticalGrid, HorizontalGrid): pass
925 raises(TypeError, mro_err_msg,
926 type, "ConfusedGrid", (HVGrid, VHGrid), {})
927
928 def test_object_class(self):
929 # Testing object class...
930 a = object()
931 self.assertEqual(a.__class__, object)
932 self.assertEqual(type(a), object)
933 b = object()
934 self.assertNotEqual(a, b)
935 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000936 try:
Georg Brandl48545522008-02-02 10:12:36 +0000937 a.foo = 12
938 except (AttributeError, TypeError):
939 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000940 else:
Georg Brandl48545522008-02-02 10:12:36 +0000941 self.fail("object() should not allow setting a foo attribute")
942 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000943
Georg Brandl48545522008-02-02 10:12:36 +0000944 class Cdict(object):
945 pass
946 x = Cdict()
947 self.assertEqual(x.__dict__, {})
948 x.foo = 1
949 self.assertEqual(x.foo, 1)
950 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000951
Georg Brandl48545522008-02-02 10:12:36 +0000952 def test_slots(self):
953 # Testing __slots__...
954 class C0(object):
955 __slots__ = []
956 x = C0()
957 self.assertFalse(hasattr(x, "__dict__"))
958 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000959
Georg Brandl48545522008-02-02 10:12:36 +0000960 class C1(object):
961 __slots__ = ['a']
962 x = C1()
963 self.assertFalse(hasattr(x, "__dict__"))
964 self.assertFalse(hasattr(x, "a"))
965 x.a = 1
966 self.assertEqual(x.a, 1)
967 x.a = None
968 self.assertEqual(x.a, None)
969 del x.a
970 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971
Georg Brandl48545522008-02-02 10:12:36 +0000972 class C3(object):
973 __slots__ = ['a', 'b', 'c']
974 x = C3()
975 self.assertFalse(hasattr(x, "__dict__"))
976 self.assertFalse(hasattr(x, 'a'))
977 self.assertFalse(hasattr(x, 'b'))
978 self.assertFalse(hasattr(x, 'c'))
979 x.a = 1
980 x.b = 2
981 x.c = 3
982 self.assertEqual(x.a, 1)
983 self.assertEqual(x.b, 2)
984 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985
Georg Brandl48545522008-02-02 10:12:36 +0000986 class C4(object):
987 """Validate name mangling"""
988 __slots__ = ['__a']
989 def __init__(self, value):
990 self.__a = value
991 def get(self):
992 return self.__a
993 x = C4(5)
994 self.assertFalse(hasattr(x, '__dict__'))
995 self.assertFalse(hasattr(x, '__a'))
996 self.assertEqual(x.get(), 5)
997 try:
998 x.__a = 6
999 except AttributeError:
1000 pass
1001 else:
1002 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003
Georg Brandl48545522008-02-02 10:12:36 +00001004 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001005 try:
1006 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001007 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001008 except TypeError:
1009 pass
1010 else:
Georg Brandl48545522008-02-02 10:12:36 +00001011 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001012 try:
Georg Brandl48545522008-02-02 10:12:36 +00001013 class C(object):
1014 __slots__ = ["foo bar"]
1015 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001016 pass
Georg Brandl48545522008-02-02 10:12:36 +00001017 else:
1018 self.fail("['foo bar'] slots not caught")
1019 try:
1020 class C(object):
1021 __slots__ = ["foo\0bar"]
1022 except TypeError:
1023 pass
1024 else:
1025 self.fail("['foo\\0bar'] slots not caught")
1026 try:
1027 class C(object):
1028 __slots__ = ["1"]
1029 except TypeError:
1030 pass
1031 else:
1032 self.fail("['1'] slots not caught")
1033 try:
1034 class C(object):
1035 __slots__ = [""]
1036 except TypeError:
1037 pass
1038 else:
1039 self.fail("[''] slots not caught")
1040 class C(object):
1041 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1042 # XXX(nnorwitz): was there supposed to be something tested
1043 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001044
Georg Brandl48545522008-02-02 10:12:36 +00001045 # Test a single string is not expanded as a sequence.
1046 class C(object):
1047 __slots__ = "abc"
1048 c = C()
1049 c.abc = 5
1050 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001051
Georg Brandl48545522008-02-02 10:12:36 +00001052 # Test unicode slot names
1053 try:
1054 unicode
1055 except NameError:
1056 pass
1057 else:
1058 # Test a single unicode string is not expanded as a sequence.
1059 class C(object):
1060 __slots__ = unicode("abc")
1061 c = C()
1062 c.abc = 5
1063 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001064
Georg Brandl48545522008-02-02 10:12:36 +00001065 # _unicode_to_string used to modify slots in certain circumstances
1066 slots = (unicode("foo"), unicode("bar"))
1067 class C(object):
1068 __slots__ = slots
1069 x = C()
1070 x.foo = 5
1071 self.assertEqual(x.foo, 5)
1072 self.assertEqual(type(slots[0]), unicode)
1073 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001074 try:
Georg Brandl48545522008-02-02 10:12:36 +00001075 class C(object):
1076 __slots__ = [unichr(128)]
1077 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001078 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001079 else:
Georg Brandl48545522008-02-02 10:12:36 +00001080 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001081
Georg Brandl48545522008-02-02 10:12:36 +00001082 # Test leaks
1083 class Counted(object):
1084 counter = 0 # counts the number of instances alive
1085 def __init__(self):
1086 Counted.counter += 1
1087 def __del__(self):
1088 Counted.counter -= 1
1089 class C(object):
1090 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001091 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001092 x.a = Counted()
1093 x.b = Counted()
1094 x.c = Counted()
1095 self.assertEqual(Counted.counter, 3)
1096 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001097 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001098 self.assertEqual(Counted.counter, 0)
1099 class D(C):
1100 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001101 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001102 x.a = Counted()
1103 x.z = Counted()
1104 self.assertEqual(Counted.counter, 2)
1105 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001106 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001107 self.assertEqual(Counted.counter, 0)
1108 class E(D):
1109 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001110 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001111 x.a = Counted()
1112 x.z = Counted()
1113 x.e = Counted()
1114 self.assertEqual(Counted.counter, 3)
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)
Guido van Rossum8c842552002-03-14 23:05:54 +00001118
Georg Brandl48545522008-02-02 10:12:36 +00001119 # Test cyclical leaks [SF bug 519621]
1120 class F(object):
1121 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001122 s = F()
1123 s.a = [Counted(), s]
1124 self.assertEqual(Counted.counter, 1)
1125 s = None
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 Rossum6cef6d52001-09-28 18:13:29 +00001128
Georg Brandl48545522008-02-02 10:12:36 +00001129 # Test lookup leaks [SF bug 572567]
Georg Brandla4f46e12010-02-07 17:03:15 +00001130 import gc
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001131 if hasattr(gc, 'get_objects'):
1132 class G(object):
1133 def __cmp__(self, other):
1134 return 0
1135 __hash__ = None # Silence Py3k warning
1136 g = G()
1137 orig_objects = len(gc.get_objects())
1138 for i in xrange(10):
1139 g==g
1140 new_objects = len(gc.get_objects())
1141 self.assertEqual(orig_objects, new_objects)
1142
Georg Brandl48545522008-02-02 10:12:36 +00001143 class H(object):
1144 __slots__ = ['a', 'b']
1145 def __init__(self):
1146 self.a = 1
1147 self.b = 2
1148 def __del__(self_):
1149 self.assertEqual(self_.a, 1)
1150 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001151 with test_support.captured_output('stderr') as s:
1152 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001153 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001154 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001155
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001156 class X(object):
1157 __slots__ = "a"
1158 with self.assertRaises(AttributeError):
1159 del X().a
1160
Georg Brandl48545522008-02-02 10:12:36 +00001161 def test_slots_special(self):
1162 # Testing __dict__ and __weakref__ in __slots__...
1163 class D(object):
1164 __slots__ = ["__dict__"]
1165 a = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001166 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl48545522008-02-02 10:12:36 +00001167 self.assertFalse(hasattr(a, "__weakref__"))
1168 a.foo = 42
1169 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001170
Georg Brandl48545522008-02-02 10:12:36 +00001171 class W(object):
1172 __slots__ = ["__weakref__"]
1173 a = W()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001174 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001175 self.assertFalse(hasattr(a, "__dict__"))
1176 try:
1177 a.foo = 42
1178 except AttributeError:
1179 pass
1180 else:
1181 self.fail("shouldn't be allowed to set a.foo")
1182
1183 class C1(W, D):
1184 __slots__ = []
1185 a = C1()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001186 self.assertTrue(hasattr(a, "__dict__"))
1187 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001188 a.foo = 42
1189 self.assertEqual(a.__dict__, {"foo": 42})
1190
1191 class C2(D, W):
1192 __slots__ = []
1193 a = C2()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001194 self.assertTrue(hasattr(a, "__dict__"))
1195 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001196 a.foo = 42
1197 self.assertEqual(a.__dict__, {"foo": 42})
1198
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001199 def test_slots_descriptor(self):
1200 # Issue2115: slot descriptors did not correctly check
1201 # the type of the given object
1202 import abc
1203 class MyABC:
1204 __metaclass__ = abc.ABCMeta
1205 __slots__ = "a"
1206
1207 class Unrelated(object):
1208 pass
1209 MyABC.register(Unrelated)
1210
1211 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001212 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001213
1214 # This used to crash
1215 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1216
Benjamin Peterson4895af42009-12-13 16:36:53 +00001217 def test_metaclass_cmp(self):
1218 # See bug 7491.
1219 class M(type):
1220 def __cmp__(self, other):
1221 return -1
1222 class X(object):
1223 __metaclass__ = M
1224 self.assertTrue(X < M)
1225
Georg Brandl48545522008-02-02 10:12:36 +00001226 def test_dynamics(self):
1227 # Testing class attribute propagation...
1228 class D(object):
1229 pass
1230 class E(D):
1231 pass
1232 class F(D):
1233 pass
1234 D.foo = 1
1235 self.assertEqual(D.foo, 1)
1236 # Test that dynamic attributes are inherited
1237 self.assertEqual(E.foo, 1)
1238 self.assertEqual(F.foo, 1)
1239 # Test dynamic instances
1240 class C(object):
1241 pass
1242 a = C()
1243 self.assertFalse(hasattr(a, "foobar"))
1244 C.foobar = 2
1245 self.assertEqual(a.foobar, 2)
1246 C.method = lambda self: 42
1247 self.assertEqual(a.method(), 42)
1248 C.__repr__ = lambda self: "C()"
1249 self.assertEqual(repr(a), "C()")
1250 C.__int__ = lambda self: 100
1251 self.assertEqual(int(a), 100)
1252 self.assertEqual(a.foobar, 2)
1253 self.assertFalse(hasattr(a, "spam"))
1254 def mygetattr(self, name):
1255 if name == "spam":
1256 return "spam"
1257 raise AttributeError
1258 C.__getattr__ = mygetattr
1259 self.assertEqual(a.spam, "spam")
1260 a.new = 12
1261 self.assertEqual(a.new, 12)
1262 def mysetattr(self, name, value):
1263 if name == "spam":
1264 raise AttributeError
1265 return object.__setattr__(self, name, value)
1266 C.__setattr__ = mysetattr
1267 try:
1268 a.spam = "not spam"
1269 except AttributeError:
1270 pass
1271 else:
1272 self.fail("expected AttributeError")
1273 self.assertEqual(a.spam, "spam")
1274 class D(C):
1275 pass
1276 d = D()
1277 d.foo = 1
1278 self.assertEqual(d.foo, 1)
1279
1280 # Test handling of int*seq and seq*int
1281 class I(int):
1282 pass
1283 self.assertEqual("a"*I(2), "aa")
1284 self.assertEqual(I(2)*"a", "aa")
1285 self.assertEqual(2*I(3), 6)
1286 self.assertEqual(I(3)*2, 6)
1287 self.assertEqual(I(3)*I(2), 6)
1288
1289 # Test handling of long*seq and seq*long
1290 class L(long):
1291 pass
1292 self.assertEqual("a"*L(2L), "aa")
1293 self.assertEqual(L(2L)*"a", "aa")
1294 self.assertEqual(2*L(3), 6)
1295 self.assertEqual(L(3)*2, 6)
1296 self.assertEqual(L(3)*L(2), 6)
1297
1298 # Test comparison of classes with dynamic metaclasses
1299 class dynamicmetaclass(type):
1300 pass
1301 class someclass:
1302 __metaclass__ = dynamicmetaclass
1303 self.assertNotEqual(someclass, object)
1304
1305 def test_errors(self):
1306 # Testing errors...
1307 try:
1308 class C(list, dict):
1309 pass
1310 except TypeError:
1311 pass
1312 else:
1313 self.fail("inheritance from both list and dict should be illegal")
1314
1315 try:
1316 class C(object, None):
1317 pass
1318 except TypeError:
1319 pass
1320 else:
1321 self.fail("inheritance from non-type should be illegal")
1322 class Classic:
1323 pass
1324
1325 try:
1326 class C(type(len)):
1327 pass
1328 except TypeError:
1329 pass
1330 else:
1331 self.fail("inheritance from CFunction should be illegal")
1332
1333 try:
1334 class C(object):
1335 __slots__ = 1
1336 except TypeError:
1337 pass
1338 else:
1339 self.fail("__slots__ = 1 should be illegal")
1340
1341 try:
1342 class C(object):
1343 __slots__ = [1]
1344 except TypeError:
1345 pass
1346 else:
1347 self.fail("__slots__ = [1] should be illegal")
1348
1349 class M1(type):
1350 pass
1351 class M2(type):
1352 pass
1353 class A1(object):
1354 __metaclass__ = M1
1355 class A2(object):
1356 __metaclass__ = M2
1357 try:
1358 class B(A1, A2):
1359 pass
1360 except TypeError:
1361 pass
1362 else:
1363 self.fail("finding the most derived metaclass should have failed")
1364
1365 def test_classmethods(self):
1366 # Testing class methods...
1367 class C(object):
1368 def foo(*a): return a
1369 goo = classmethod(foo)
1370 c = C()
1371 self.assertEqual(C.goo(1), (C, 1))
1372 self.assertEqual(c.goo(1), (C, 1))
1373 self.assertEqual(c.foo(1), (c, 1))
1374 class D(C):
1375 pass
1376 d = D()
1377 self.assertEqual(D.goo(1), (D, 1))
1378 self.assertEqual(d.goo(1), (D, 1))
1379 self.assertEqual(d.foo(1), (d, 1))
1380 self.assertEqual(D.foo(d, 1), (d, 1))
1381 # Test for a specific crash (SF bug 528132)
1382 def f(cls, arg): return (cls, arg)
1383 ff = classmethod(f)
1384 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1385 self.assertEqual(ff.__get__(0)(42), (int, 42))
1386
1387 # Test super() with classmethods (SF bug 535444)
1388 self.assertEqual(C.goo.im_self, C)
1389 self.assertEqual(D.goo.im_self, D)
1390 self.assertEqual(super(D,D).goo.im_self, D)
1391 self.assertEqual(super(D,d).goo.im_self, D)
1392 self.assertEqual(super(D,D).goo(), (D,))
1393 self.assertEqual(super(D,d).goo(), (D,))
1394
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001395 # Verify that a non-callable will raise
1396 meth = classmethod(1).__get__(1)
1397 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001398
1399 # Verify that classmethod() doesn't allow keyword args
1400 try:
1401 classmethod(f, kw=1)
1402 except TypeError:
1403 pass
1404 else:
1405 self.fail("classmethod shouldn't accept keyword args")
1406
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001407 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001408 def test_classmethods_in_c(self):
1409 # Testing C-based class methods...
1410 import xxsubtype as spam
1411 a = (1, 2, 3)
1412 d = {'abc': 123}
1413 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1414 self.assertEqual(x, spam.spamlist)
1415 self.assertEqual(a, a1)
1416 self.assertEqual(d, d1)
1417 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1418 self.assertEqual(x, spam.spamlist)
1419 self.assertEqual(a, a1)
1420 self.assertEqual(d, d1)
1421
1422 def test_staticmethods(self):
1423 # Testing static methods...
1424 class C(object):
1425 def foo(*a): return a
1426 goo = staticmethod(foo)
1427 c = C()
1428 self.assertEqual(C.goo(1), (1,))
1429 self.assertEqual(c.goo(1), (1,))
1430 self.assertEqual(c.foo(1), (c, 1,))
1431 class D(C):
1432 pass
1433 d = D()
1434 self.assertEqual(D.goo(1), (1,))
1435 self.assertEqual(d.goo(1), (1,))
1436 self.assertEqual(d.foo(1), (d, 1))
1437 self.assertEqual(D.foo(d, 1), (d, 1))
1438
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001439 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001440 def test_staticmethods_in_c(self):
1441 # Testing C-based static methods...
1442 import xxsubtype as spam
1443 a = (1, 2, 3)
1444 d = {"abc": 123}
1445 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1446 self.assertEqual(x, None)
1447 self.assertEqual(a, a1)
1448 self.assertEqual(d, d1)
1449 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1450 self.assertEqual(x, None)
1451 self.assertEqual(a, a1)
1452 self.assertEqual(d, d1)
1453
1454 def test_classic(self):
1455 # Testing classic classes...
1456 class C:
1457 def foo(*a): return a
1458 goo = classmethod(foo)
1459 c = C()
1460 self.assertEqual(C.goo(1), (C, 1))
1461 self.assertEqual(c.goo(1), (C, 1))
1462 self.assertEqual(c.foo(1), (c, 1))
1463 class D(C):
1464 pass
1465 d = D()
1466 self.assertEqual(D.goo(1), (D, 1))
1467 self.assertEqual(d.goo(1), (D, 1))
1468 self.assertEqual(d.foo(1), (d, 1))
1469 self.assertEqual(D.foo(d, 1), (d, 1))
1470 class E: # *not* subclassing from C
1471 foo = C.foo
1472 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001473 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001474
1475 def test_compattr(self):
1476 # Testing computed attributes...
1477 class C(object):
1478 class computed_attribute(object):
1479 def __init__(self, get, set=None, delete=None):
1480 self.__get = get
1481 self.__set = set
1482 self.__delete = delete
1483 def __get__(self, obj, type=None):
1484 return self.__get(obj)
1485 def __set__(self, obj, value):
1486 return self.__set(obj, value)
1487 def __delete__(self, obj):
1488 return self.__delete(obj)
1489 def __init__(self):
1490 self.__x = 0
1491 def __get_x(self):
1492 x = self.__x
1493 self.__x = x+1
1494 return x
1495 def __set_x(self, x):
1496 self.__x = x
1497 def __delete_x(self):
1498 del self.__x
1499 x = computed_attribute(__get_x, __set_x, __delete_x)
1500 a = C()
1501 self.assertEqual(a.x, 0)
1502 self.assertEqual(a.x, 1)
1503 a.x = 10
1504 self.assertEqual(a.x, 10)
1505 self.assertEqual(a.x, 11)
1506 del a.x
1507 self.assertEqual(hasattr(a, 'x'), 0)
1508
1509 def test_newslots(self):
1510 # Testing __new__ slot override...
1511 class C(list):
1512 def __new__(cls):
1513 self = list.__new__(cls)
1514 self.foo = 1
1515 return self
1516 def __init__(self):
1517 self.foo = self.foo + 2
1518 a = C()
1519 self.assertEqual(a.foo, 3)
1520 self.assertEqual(a.__class__, C)
1521 class D(C):
1522 pass
1523 b = D()
1524 self.assertEqual(b.foo, 3)
1525 self.assertEqual(b.__class__, D)
1526
1527 def test_altmro(self):
1528 # Testing mro() and overriding it...
1529 class A(object):
1530 def f(self): return "A"
1531 class B(A):
1532 pass
1533 class C(A):
1534 def f(self): return "C"
1535 class D(B, C):
1536 pass
1537 self.assertEqual(D.mro(), [D, B, C, A, object])
1538 self.assertEqual(D.__mro__, (D, B, C, A, object))
1539 self.assertEqual(D().f(), "C")
1540
1541 class PerverseMetaType(type):
1542 def mro(cls):
1543 L = type.mro(cls)
1544 L.reverse()
1545 return L
1546 class X(D,B,C,A):
1547 __metaclass__ = PerverseMetaType
1548 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1549 self.assertEqual(X().f(), "A")
1550
1551 try:
1552 class X(object):
1553 class __metaclass__(type):
1554 def mro(self):
1555 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001556 # In CPython, the class creation above already raises
1557 # TypeError, as a protection against the fact that
1558 # instances of X would segfault it. In other Python
1559 # implementations it would be ok to let the class X
1560 # be created, but instead get a clean TypeError on the
1561 # __setitem__ below.
1562 x = object.__new__(X)
1563 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001564 except TypeError:
1565 pass
1566 else:
1567 self.fail("devious mro() return not caught")
1568
1569 try:
1570 class X(object):
1571 class __metaclass__(type):
1572 def mro(self):
1573 return [1]
1574 except TypeError:
1575 pass
1576 else:
1577 self.fail("non-class 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-sequence mro() return not caught")
1588
1589 def test_overloading(self):
1590 # Testing operator overloading...
1591
1592 class B(object):
1593 "Intermediate class because object doesn't have a __setattr__"
1594
1595 class C(B):
1596 def __getattr__(self, name):
1597 if name == "foo":
1598 return ("getattr", name)
1599 else:
1600 raise AttributeError
1601 def __setattr__(self, name, value):
1602 if name == "foo":
1603 self.setattr = (name, value)
1604 else:
1605 return B.__setattr__(self, name, value)
1606 def __delattr__(self, name):
1607 if name == "foo":
1608 self.delattr = name
1609 else:
1610 return B.__delattr__(self, name)
1611
1612 def __getitem__(self, key):
1613 return ("getitem", key)
1614 def __setitem__(self, key, value):
1615 self.setitem = (key, value)
1616 def __delitem__(self, key):
1617 self.delitem = key
1618
1619 def __getslice__(self, i, j):
1620 return ("getslice", i, j)
1621 def __setslice__(self, i, j, value):
1622 self.setslice = (i, j, value)
1623 def __delslice__(self, i, j):
1624 self.delslice = (i, j)
1625
1626 a = C()
1627 self.assertEqual(a.foo, ("getattr", "foo"))
1628 a.foo = 12
1629 self.assertEqual(a.setattr, ("foo", 12))
1630 del a.foo
1631 self.assertEqual(a.delattr, "foo")
1632
1633 self.assertEqual(a[12], ("getitem", 12))
1634 a[12] = 21
1635 self.assertEqual(a.setitem, (12, 21))
1636 del a[12]
1637 self.assertEqual(a.delitem, 12)
1638
1639 self.assertEqual(a[0:10], ("getslice", 0, 10))
1640 a[0:10] = "foo"
1641 self.assertEqual(a.setslice, (0, 10, "foo"))
1642 del a[0:10]
1643 self.assertEqual(a.delslice, (0, 10))
1644
1645 def test_methods(self):
1646 # Testing methods...
1647 class C(object):
1648 def __init__(self, x):
1649 self.x = x
1650 def foo(self):
1651 return self.x
1652 c1 = C(1)
1653 self.assertEqual(c1.foo(), 1)
1654 class D(C):
1655 boo = C.foo
1656 goo = c1.foo
1657 d2 = D(2)
1658 self.assertEqual(d2.foo(), 2)
1659 self.assertEqual(d2.boo(), 2)
1660 self.assertEqual(d2.goo(), 1)
1661 class E(object):
1662 foo = C.foo
1663 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001664 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001665
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001666 def test_special_method_lookup(self):
1667 # The lookup of special methods bypasses __getattr__ and
1668 # __getattribute__, but they still can be descriptors.
1669
1670 def run_context(manager):
1671 with manager:
1672 pass
1673 def iden(self):
1674 return self
1675 def hello(self):
1676 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001677 def empty_seq(self):
1678 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001679 def zero(self):
1680 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001681 def complex_num(self):
1682 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001683 def stop(self):
1684 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001685 def return_true(self, thing=None):
1686 return True
1687 def do_isinstance(obj):
1688 return isinstance(int, obj)
1689 def do_issubclass(obj):
1690 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001691 def swallow(*args):
1692 pass
1693 def do_dict_missing(checker):
1694 class DictSub(checker.__class__, dict):
1695 pass
1696 self.assertEqual(DictSub()["hi"], 4)
1697 def some_number(self_, key):
1698 self.assertEqual(key, "hi")
1699 return 4
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001700
1701 # It would be nice to have every special method tested here, but I'm
1702 # only listing the ones I can remember outside of typeobject.c, since it
1703 # does it right.
1704 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001705 ("__unicode__", unicode, hello, set(), {}),
1706 ("__reversed__", reversed, empty_seq, set(), {}),
1707 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001708 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001709 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1710 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001711 ("__missing__", do_dict_missing, some_number,
1712 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001713 ("__subclasscheck__", do_issubclass, return_true,
1714 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001715 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1716 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001717 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001718 ]
1719
1720 class Checker(object):
1721 def __getattr__(self, attr, test=self):
1722 test.fail("__getattr__ called with {0}".format(attr))
1723 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001724 if attr not in ok:
1725 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001726 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001727 class SpecialDescr(object):
1728 def __init__(self, impl):
1729 self.impl = impl
1730 def __get__(self, obj, owner):
1731 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001732 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001733 class MyException(Exception):
1734 pass
1735 class ErrDescr(object):
1736 def __get__(self, obj, owner):
1737 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001738
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001739 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001740 class X(Checker):
1741 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001742 for attr, obj in env.iteritems():
1743 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001744 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001745 runner(X())
1746
1747 record = []
1748 class X(Checker):
1749 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001750 for attr, obj in env.iteritems():
1751 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001752 setattr(X, name, SpecialDescr(meth_impl))
1753 runner(X())
1754 self.assertEqual(record, [1], name)
1755
Benjamin Peterson87e50062009-05-25 02:40:21 +00001756 class X(Checker):
1757 pass
1758 for attr, obj in env.iteritems():
1759 setattr(X, attr, obj)
1760 setattr(X, name, ErrDescr())
1761 try:
1762 runner(X())
1763 except MyException:
1764 pass
1765 else:
1766 self.fail("{0!r} didn't raise".format(name))
1767
Georg Brandl48545522008-02-02 10:12:36 +00001768 def test_specials(self):
1769 # Testing special operators...
1770 # Test operators like __hash__ for which a built-in default exists
1771
1772 # Test the default behavior for static classes
1773 class C(object):
1774 def __getitem__(self, i):
1775 if 0 <= i < 10: return i
1776 raise IndexError
1777 c1 = C()
1778 c2 = C()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001779 self.assertTrue(not not c1) # What?
Georg Brandl48545522008-02-02 10:12:36 +00001780 self.assertNotEqual(id(c1), id(c2))
1781 hash(c1)
1782 hash(c2)
1783 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1784 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001785 self.assertTrue(c1 != c2)
1786 self.assertTrue(not c1 != c1)
1787 self.assertTrue(not c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001788 # Note that the module name appears in str/repr, and that varies
1789 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001790 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001791 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001792 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001793 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001794 self.assertIn(i, c1)
1795 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001796 # Test the default behavior for dynamic classes
1797 class D(object):
1798 def __getitem__(self, i):
1799 if 0 <= i < 10: return i
1800 raise IndexError
1801 d1 = D()
1802 d2 = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001803 self.assertTrue(not not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001804 self.assertNotEqual(id(d1), id(d2))
1805 hash(d1)
1806 hash(d2)
1807 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1808 self.assertEqual(d1, d1)
1809 self.assertNotEqual(d1, d2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001810 self.assertTrue(not d1 != d1)
1811 self.assertTrue(not d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001812 # Note that the module name appears in str/repr, and that varies
1813 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001814 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001815 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001816 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001817 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001818 self.assertIn(i, d1)
1819 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001820 # Test overridden behavior for static classes
1821 class Proxy(object):
1822 def __init__(self, x):
1823 self.x = x
1824 def __nonzero__(self):
1825 return not not self.x
1826 def __hash__(self):
1827 return hash(self.x)
1828 def __eq__(self, other):
1829 return self.x == other
1830 def __ne__(self, other):
1831 return self.x != other
1832 def __cmp__(self, other):
1833 return cmp(self.x, other.x)
1834 def __str__(self):
1835 return "Proxy:%s" % self.x
1836 def __repr__(self):
1837 return "Proxy(%r)" % self.x
1838 def __contains__(self, value):
1839 return value in self.x
1840 p0 = Proxy(0)
1841 p1 = Proxy(1)
1842 p_1 = Proxy(-1)
1843 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001844 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001845 self.assertEqual(hash(p0), hash(0))
1846 self.assertEqual(p0, p0)
1847 self.assertNotEqual(p0, p1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001848 self.assertTrue(not p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001849 self.assertEqual(not p0, p1)
1850 self.assertEqual(cmp(p0, p1), -1)
1851 self.assertEqual(cmp(p0, p0), 0)
1852 self.assertEqual(cmp(p0, p_1), 1)
1853 self.assertEqual(str(p0), "Proxy:0")
1854 self.assertEqual(repr(p0), "Proxy(0)")
1855 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001856 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001857 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001858 self.assertIn(i, p10)
1859 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001860 # Test overridden behavior for dynamic classes
1861 class DProxy(object):
1862 def __init__(self, x):
1863 self.x = x
1864 def __nonzero__(self):
1865 return not not self.x
1866 def __hash__(self):
1867 return hash(self.x)
1868 def __eq__(self, other):
1869 return self.x == other
1870 def __ne__(self, other):
1871 return self.x != other
1872 def __cmp__(self, other):
1873 return cmp(self.x, other.x)
1874 def __str__(self):
1875 return "DProxy:%s" % self.x
1876 def __repr__(self):
1877 return "DProxy(%r)" % self.x
1878 def __contains__(self, value):
1879 return value in self.x
1880 p0 = DProxy(0)
1881 p1 = DProxy(1)
1882 p_1 = DProxy(-1)
1883 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001884 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001885 self.assertEqual(hash(p0), hash(0))
1886 self.assertEqual(p0, p0)
1887 self.assertNotEqual(p0, p1)
1888 self.assertNotEqual(not p0, p0)
1889 self.assertEqual(not p0, p1)
1890 self.assertEqual(cmp(p0, p1), -1)
1891 self.assertEqual(cmp(p0, p0), 0)
1892 self.assertEqual(cmp(p0, p_1), 1)
1893 self.assertEqual(str(p0), "DProxy:0")
1894 self.assertEqual(repr(p0), "DProxy(0)")
1895 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001896 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001897 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001898 self.assertIn(i, p10)
1899 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001900
1901 # Safety test for __cmp__
1902 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001903 if not hasattr(a, '__cmp__'):
1904 return # some types don't have a __cmp__ any more (so the
1905 # test doesn't make sense any more), or maybe they
1906 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001907 try:
1908 a.__class__.__cmp__(a, b)
1909 except TypeError:
1910 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001911 else:
Georg Brandl48545522008-02-02 10:12:36 +00001912 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1913 a.__class__, a, b))
1914
1915 unsafecmp(u"123", "123")
1916 unsafecmp("123", u"123")
1917 unsafecmp(1, 1.0)
1918 unsafecmp(1.0, 1)
1919 unsafecmp(1, 1L)
1920 unsafecmp(1L, 1)
1921
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001922 @test_support.impl_detail("custom logic for printing to real file objects")
1923 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001924 # Testing recursion checks ...
1925 class Letter(str):
1926 def __new__(cls, letter):
1927 if letter == 'EPS':
1928 return str.__new__(cls)
1929 return str.__new__(cls, letter)
1930 def __str__(self):
1931 if not self:
1932 return 'EPS'
1933 return self
1934 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00001935 test_stdout = sys.stdout
1936 sys.stdout = test_support.get_original_stdout()
1937 try:
1938 # nothing should actually be printed, this should raise an exception
1939 print Letter('w')
1940 except RuntimeError:
1941 pass
1942 else:
1943 self.fail("expected a RuntimeError for print recursion")
1944 finally:
1945 sys.stdout = test_stdout
1946
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001947 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001948 # Bug #1202533.
1949 class A(object):
1950 pass
1951 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1952 try:
1953 A()*2
1954 except RuntimeError:
1955 pass
1956 else:
1957 self.fail("expected a RuntimeError")
1958
1959 def test_weakrefs(self):
1960 # Testing weak references...
1961 import weakref
1962 class C(object):
1963 pass
1964 c = C()
1965 r = weakref.ref(c)
1966 self.assertEqual(r(), c)
1967 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001968 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001969 self.assertEqual(r(), None)
1970 del r
1971 class NoWeak(object):
1972 __slots__ = ['foo']
1973 no = NoWeak()
1974 try:
1975 weakref.ref(no)
1976 except TypeError, msg:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001977 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001978 else:
1979 self.fail("weakref.ref(no) should be illegal")
1980 class Weak(object):
1981 __slots__ = ['foo', '__weakref__']
1982 yes = Weak()
1983 r = weakref.ref(yes)
1984 self.assertEqual(r(), yes)
1985 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001986 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001987 self.assertEqual(r(), None)
1988 del r
1989
1990 def test_properties(self):
1991 # Testing property...
1992 class C(object):
1993 def getx(self):
1994 return self.__x
1995 def setx(self, value):
1996 self.__x = value
1997 def delx(self):
1998 del self.__x
1999 x = property(getx, setx, delx, doc="I'm the x property.")
2000 a = C()
2001 self.assertFalse(hasattr(a, "x"))
2002 a.x = 42
2003 self.assertEqual(a._C__x, 42)
2004 self.assertEqual(a.x, 42)
2005 del a.x
2006 self.assertFalse(hasattr(a, "x"))
2007 self.assertFalse(hasattr(a, "_C__x"))
2008 C.x.__set__(a, 100)
2009 self.assertEqual(C.x.__get__(a), 100)
2010 C.x.__delete__(a)
2011 self.assertFalse(hasattr(a, "x"))
2012
2013 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002014 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002015
2016 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002017 self.assertIn("__doc__", attrs)
2018 self.assertIn("fget", attrs)
2019 self.assertIn("fset", attrs)
2020 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002021
2022 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002023 self.assertTrue(raw.fget is C.__dict__['getx'])
2024 self.assertTrue(raw.fset is C.__dict__['setx'])
2025 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002026
2027 for attr in "__doc__", "fget", "fset", "fdel":
2028 try:
2029 setattr(raw, attr, 42)
2030 except TypeError, msg:
2031 if str(msg).find('readonly') < 0:
2032 self.fail("when setting readonly attr %r on a property, "
2033 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002034 else:
Georg Brandl48545522008-02-02 10:12:36 +00002035 self.fail("expected TypeError from trying to set readonly %r "
2036 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002037
Georg Brandl48545522008-02-02 10:12:36 +00002038 class D(object):
2039 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002040
Georg Brandl48545522008-02-02 10:12:36 +00002041 d = D()
2042 try:
2043 for i in d:
2044 str(i)
2045 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002046 pass
Georg Brandl48545522008-02-02 10:12:36 +00002047 else:
2048 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002049
R. David Murrayf28fd242010-02-23 00:24:49 +00002050 @unittest.skipIf(sys.flags.optimize >= 2,
2051 "Docstrings are omitted with -O2 and above")
2052 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002053 class E(object):
2054 def getter(self):
2055 "getter method"
2056 return 0
2057 def setter(self_, value):
2058 "setter method"
2059 pass
2060 prop = property(getter)
2061 self.assertEqual(prop.__doc__, "getter method")
2062 prop2 = property(fset=setter)
2063 self.assertEqual(prop2.__doc__, None)
2064
R. David Murrayf28fd242010-02-23 00:24:49 +00002065 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002066 # this segfaulted in 2.5b2
2067 try:
2068 import _testcapi
2069 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002070 pass
Georg Brandl48545522008-02-02 10:12:36 +00002071 else:
2072 class X(object):
2073 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002074
Georg Brandl48545522008-02-02 10:12:36 +00002075 def test_properties_plus(self):
2076 class C(object):
2077 foo = property(doc="hello")
2078 @foo.getter
2079 def foo(self):
2080 return self._foo
2081 @foo.setter
2082 def foo(self, value):
2083 self._foo = abs(value)
2084 @foo.deleter
2085 def foo(self):
2086 del self._foo
2087 c = C()
2088 self.assertEqual(C.foo.__doc__, "hello")
2089 self.assertFalse(hasattr(c, "foo"))
2090 c.foo = -42
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002091 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl48545522008-02-02 10:12:36 +00002092 self.assertEqual(c._foo, 42)
2093 self.assertEqual(c.foo, 42)
2094 del c.foo
2095 self.assertFalse(hasattr(c, '_foo'))
2096 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002097
Georg Brandl48545522008-02-02 10:12:36 +00002098 class D(C):
2099 @C.foo.deleter
2100 def foo(self):
2101 try:
2102 del self._foo
2103 except AttributeError:
2104 pass
2105 d = D()
2106 d.foo = 24
2107 self.assertEqual(d.foo, 24)
2108 del d.foo
2109 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002110
Georg Brandl48545522008-02-02 10:12:36 +00002111 class E(object):
2112 @property
2113 def foo(self):
2114 return self._foo
2115 @foo.setter
2116 def foo(self, value):
2117 raise RuntimeError
2118 @foo.setter
2119 def foo(self, value):
2120 self._foo = abs(value)
2121 @foo.deleter
2122 def foo(self, value=None):
2123 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002124
Georg Brandl48545522008-02-02 10:12:36 +00002125 e = E()
2126 e.foo = -42
2127 self.assertEqual(e.foo, 42)
2128 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002129
Georg Brandl48545522008-02-02 10:12:36 +00002130 class F(E):
2131 @E.foo.deleter
2132 def foo(self):
2133 del self._foo
2134 @foo.setter
2135 def foo(self, value):
2136 self._foo = max(0, value)
2137 f = F()
2138 f.foo = -10
2139 self.assertEqual(f.foo, 0)
2140 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002141
Georg Brandl48545522008-02-02 10:12:36 +00002142 def test_dict_constructors(self):
2143 # Testing dict constructor ...
2144 d = dict()
2145 self.assertEqual(d, {})
2146 d = dict({})
2147 self.assertEqual(d, {})
2148 d = dict({1: 2, 'a': 'b'})
2149 self.assertEqual(d, {1: 2, 'a': 'b'})
2150 self.assertEqual(d, dict(d.items()))
2151 self.assertEqual(d, dict(d.iteritems()))
2152 d = dict({'one':1, 'two':2})
2153 self.assertEqual(d, dict(one=1, two=2))
2154 self.assertEqual(d, dict(**d))
2155 self.assertEqual(d, dict({"one": 1}, two=2))
2156 self.assertEqual(d, dict([("two", 2)], one=1))
2157 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2158 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002159
Georg Brandl48545522008-02-02 10:12:36 +00002160 for badarg in 0, 0L, 0j, "0", [0], (0,):
2161 try:
2162 dict(badarg)
2163 except TypeError:
2164 pass
2165 except ValueError:
2166 if badarg == "0":
2167 # It's a sequence, and its elements are also sequences (gotta
2168 # love strings <wink>), but they aren't of length 2, so this
2169 # one seemed better as a ValueError than a TypeError.
2170 pass
2171 else:
2172 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002173 else:
Georg Brandl48545522008-02-02 10:12:36 +00002174 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002175
Georg Brandl48545522008-02-02 10:12:36 +00002176 try:
2177 dict({}, {})
2178 except TypeError:
2179 pass
2180 else:
2181 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002182
Georg Brandl48545522008-02-02 10:12:36 +00002183 class Mapping:
2184 # Lacks a .keys() method; will be added later.
2185 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002186
Georg Brandl48545522008-02-02 10:12:36 +00002187 try:
2188 dict(Mapping())
2189 except TypeError:
2190 pass
2191 else:
2192 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002193
Georg Brandl48545522008-02-02 10:12:36 +00002194 Mapping.keys = lambda self: self.dict.keys()
2195 Mapping.__getitem__ = lambda self, i: self.dict[i]
2196 d = dict(Mapping())
2197 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002198
Georg Brandl48545522008-02-02 10:12:36 +00002199 # Init from sequence of iterable objects, each producing a 2-sequence.
2200 class AddressBookEntry:
2201 def __init__(self, first, last):
2202 self.first = first
2203 self.last = last
2204 def __iter__(self):
2205 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002206
Georg Brandl48545522008-02-02 10:12:36 +00002207 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2208 AddressBookEntry('Barry', 'Peters'),
2209 AddressBookEntry('Tim', 'Peters'),
2210 AddressBookEntry('Barry', 'Warsaw')])
2211 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002212
Georg Brandl48545522008-02-02 10:12:36 +00002213 d = dict(zip(range(4), range(1, 5)))
2214 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002215
Georg Brandl48545522008-02-02 10:12:36 +00002216 # Bad sequence lengths.
2217 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2218 try:
2219 dict(bad)
2220 except ValueError:
2221 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002222 else:
Georg Brandl48545522008-02-02 10:12:36 +00002223 self.fail("no ValueError from dict(%r)" % bad)
2224
2225 def test_dir(self):
2226 # Testing dir() ...
2227 junk = 12
2228 self.assertEqual(dir(), ['junk', 'self'])
2229 del junk
2230
2231 # Just make sure these don't blow up!
2232 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2233 dir(arg)
2234
2235 # Try classic classes.
2236 class C:
2237 Cdata = 1
2238 def Cmethod(self): pass
2239
2240 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2241 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002242 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002243
2244 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2245 self.assertEqual(dir(c), cstuff)
2246
2247 c.cdata = 2
2248 c.cmethod = lambda self: 0
2249 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002250 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002251
2252 class A(C):
2253 Adata = 1
2254 def Amethod(self): pass
2255
2256 astuff = ['Adata', 'Amethod'] + cstuff
2257 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002258 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002259 a = A()
2260 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002261 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002262 a.adata = 42
2263 a.amethod = lambda self: 3
2264 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2265
2266 # The same, but with new-style classes. Since these have object as a
2267 # base class, a lot more gets sucked in.
2268 def interesting(strings):
2269 return [s for s in strings if not s.startswith('_')]
2270
2271 class C(object):
2272 Cdata = 1
2273 def Cmethod(self): pass
2274
2275 cstuff = ['Cdata', 'Cmethod']
2276 self.assertEqual(interesting(dir(C)), cstuff)
2277
2278 c = C()
2279 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002280 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002281
2282 c.cdata = 2
2283 c.cmethod = lambda self: 0
2284 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002285 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002286
2287 class A(C):
2288 Adata = 1
2289 def Amethod(self): pass
2290
2291 astuff = ['Adata', 'Amethod'] + cstuff
2292 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002293 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002294 a = A()
2295 self.assertEqual(interesting(dir(a)), astuff)
2296 a.adata = 42
2297 a.amethod = lambda self: 3
2298 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002299 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002300
2301 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002302 class M(type(sys)):
2303 pass
2304 minstance = M("m")
2305 minstance.b = 2
2306 minstance.a = 1
2307 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2308 self.assertEqual(names, ['a', 'b'])
2309
2310 class M2(M):
2311 def getdict(self):
2312 return "Not a dict!"
2313 __dict__ = property(getdict)
2314
2315 m2instance = M2("m2")
2316 m2instance.b = 2
2317 m2instance.a = 1
2318 self.assertEqual(m2instance.__dict__, "Not a dict!")
2319 try:
2320 dir(m2instance)
2321 except TypeError:
2322 pass
2323
2324 # Two essentially featureless objects, just inheriting stuff from
2325 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002326 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2327 if test_support.check_impl_detail():
2328 # None differs in PyPy: it has a __nonzero__
2329 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002330
2331 # Nasty test case for proxied objects
2332 class Wrapper(object):
2333 def __init__(self, obj):
2334 self.__obj = obj
2335 def __repr__(self):
2336 return "Wrapper(%s)" % repr(self.__obj)
2337 def __getitem__(self, key):
2338 return Wrapper(self.__obj[key])
2339 def __len__(self):
2340 return len(self.__obj)
2341 def __getattr__(self, name):
2342 return Wrapper(getattr(self.__obj, name))
2343
2344 class C(object):
2345 def __getclass(self):
2346 return Wrapper(type(self))
2347 __class__ = property(__getclass)
2348
2349 dir(C()) # This used to segfault
2350
2351 def test_supers(self):
2352 # Testing super...
2353
2354 class A(object):
2355 def meth(self, a):
2356 return "A(%r)" % a
2357
2358 self.assertEqual(A().meth(1), "A(1)")
2359
2360 class B(A):
2361 def __init__(self):
2362 self.__super = super(B, self)
2363 def meth(self, a):
2364 return "B(%r)" % a + self.__super.meth(a)
2365
2366 self.assertEqual(B().meth(2), "B(2)A(2)")
2367
2368 class C(A):
2369 def meth(self, a):
2370 return "C(%r)" % a + self.__super.meth(a)
2371 C._C__super = super(C)
2372
2373 self.assertEqual(C().meth(3), "C(3)A(3)")
2374
2375 class D(C, B):
2376 def meth(self, a):
2377 return "D(%r)" % a + super(D, self).meth(a)
2378
2379 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2380
2381 # Test for subclassing super
2382
2383 class mysuper(super):
2384 def __init__(self, *args):
2385 return super(mysuper, self).__init__(*args)
2386
2387 class E(D):
2388 def meth(self, a):
2389 return "E(%r)" % a + mysuper(E, self).meth(a)
2390
2391 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2392
2393 class F(E):
2394 def meth(self, a):
2395 s = self.__super # == mysuper(F, self)
2396 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2397 F._F__super = mysuper(F)
2398
2399 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2400
2401 # Make sure certain errors are raised
2402
2403 try:
2404 super(D, 42)
2405 except TypeError:
2406 pass
2407 else:
2408 self.fail("shouldn't allow super(D, 42)")
2409
2410 try:
2411 super(D, C())
2412 except TypeError:
2413 pass
2414 else:
2415 self.fail("shouldn't allow super(D, C())")
2416
2417 try:
2418 super(D).__get__(12)
2419 except TypeError:
2420 pass
2421 else:
2422 self.fail("shouldn't allow super(D).__get__(12)")
2423
2424 try:
2425 super(D).__get__(C())
2426 except TypeError:
2427 pass
2428 else:
2429 self.fail("shouldn't allow super(D).__get__(C())")
2430
2431 # Make sure data descriptors can be overridden and accessed via super
2432 # (new feature in Python 2.3)
2433
2434 class DDbase(object):
2435 def getx(self): return 42
2436 x = property(getx)
2437
2438 class DDsub(DDbase):
2439 def getx(self): return "hello"
2440 x = property(getx)
2441
2442 dd = DDsub()
2443 self.assertEqual(dd.x, "hello")
2444 self.assertEqual(super(DDsub, dd).x, 42)
2445
2446 # Ensure that super() lookup of descriptor from classmethod
2447 # works (SF ID# 743627)
2448
2449 class Base(object):
2450 aProp = property(lambda self: "foo")
2451
2452 class Sub(Base):
2453 @classmethod
2454 def test(klass):
2455 return super(Sub,klass).aProp
2456
2457 self.assertEqual(Sub.test(), Base.aProp)
2458
2459 # Verify that super() doesn't allow keyword args
2460 try:
2461 super(Base, kw=1)
2462 except TypeError:
2463 pass
2464 else:
2465 self.assertEqual("super shouldn't accept keyword args")
2466
2467 def test_basic_inheritance(self):
2468 # Testing inheritance from basic types...
2469
2470 class hexint(int):
2471 def __repr__(self):
2472 return hex(self)
2473 def __add__(self, other):
2474 return hexint(int.__add__(self, other))
2475 # (Note that overriding __radd__ doesn't work,
2476 # because the int type gets first dibs.)
2477 self.assertEqual(repr(hexint(7) + 9), "0x10")
2478 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2479 a = hexint(12345)
2480 self.assertEqual(a, 12345)
2481 self.assertEqual(int(a), 12345)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002482 self.assertTrue(int(a).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002483 self.assertEqual(hash(a), hash(12345))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002484 self.assertTrue((+a).__class__ is int)
2485 self.assertTrue((a >> 0).__class__ is int)
2486 self.assertTrue((a << 0).__class__ is int)
2487 self.assertTrue((hexint(0) << 12).__class__ is int)
2488 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002489
2490 class octlong(long):
2491 __slots__ = []
2492 def __str__(self):
2493 s = oct(self)
2494 if s[-1] == 'L':
2495 s = s[:-1]
2496 return s
2497 def __add__(self, other):
2498 return self.__class__(super(octlong, self).__add__(other))
2499 __radd__ = __add__
2500 self.assertEqual(str(octlong(3) + 5), "010")
2501 # (Note that overriding __radd__ here only seems to work
2502 # because the example uses a short int left argument.)
2503 self.assertEqual(str(5 + octlong(3000)), "05675")
2504 a = octlong(12345)
2505 self.assertEqual(a, 12345L)
2506 self.assertEqual(long(a), 12345L)
2507 self.assertEqual(hash(a), hash(12345L))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002508 self.assertTrue(long(a).__class__ is long)
2509 self.assertTrue((+a).__class__ is long)
2510 self.assertTrue((-a).__class__ is long)
2511 self.assertTrue((-octlong(0)).__class__ is long)
2512 self.assertTrue((a >> 0).__class__ is long)
2513 self.assertTrue((a << 0).__class__ is long)
2514 self.assertTrue((a - 0).__class__ is long)
2515 self.assertTrue((a * 1).__class__ is long)
2516 self.assertTrue((a ** 1).__class__ is long)
2517 self.assertTrue((a // 1).__class__ is long)
2518 self.assertTrue((1 * a).__class__ is long)
2519 self.assertTrue((a | 0).__class__ is long)
2520 self.assertTrue((a ^ 0).__class__ is long)
2521 self.assertTrue((a & -1L).__class__ is long)
2522 self.assertTrue((octlong(0) << 12).__class__ is long)
2523 self.assertTrue((octlong(0) >> 12).__class__ is long)
2524 self.assertTrue(abs(octlong(0)).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002525
2526 # Because octlong overrides __add__, we can't check the absence of +0
2527 # optimizations using octlong.
2528 class longclone(long):
2529 pass
2530 a = longclone(1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002531 self.assertTrue((a + 0).__class__ is long)
2532 self.assertTrue((0 + a).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002533
2534 # Check that negative clones don't segfault
2535 a = longclone(-1)
2536 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002537 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002538
2539 class precfloat(float):
2540 __slots__ = ['prec']
2541 def __init__(self, value=0.0, prec=12):
2542 self.prec = int(prec)
2543 def __repr__(self):
2544 return "%.*g" % (self.prec, self)
2545 self.assertEqual(repr(precfloat(1.1)), "1.1")
2546 a = precfloat(12345)
2547 self.assertEqual(a, 12345.0)
2548 self.assertEqual(float(a), 12345.0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002549 self.assertTrue(float(a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002550 self.assertEqual(hash(a), hash(12345.0))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002551 self.assertTrue((+a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002552
2553 class madcomplex(complex):
2554 def __repr__(self):
2555 return "%.17gj%+.17g" % (self.imag, self.real)
2556 a = madcomplex(-3, 4)
2557 self.assertEqual(repr(a), "4j-3")
2558 base = complex(-3, 4)
2559 self.assertEqual(base.__class__, complex)
2560 self.assertEqual(a, base)
2561 self.assertEqual(complex(a), base)
2562 self.assertEqual(complex(a).__class__, complex)
2563 a = madcomplex(a) # just trying another form of the constructor
2564 self.assertEqual(repr(a), "4j-3")
2565 self.assertEqual(a, base)
2566 self.assertEqual(complex(a), base)
2567 self.assertEqual(complex(a).__class__, complex)
2568 self.assertEqual(hash(a), hash(base))
2569 self.assertEqual((+a).__class__, complex)
2570 self.assertEqual((a + 0).__class__, complex)
2571 self.assertEqual(a + 0, base)
2572 self.assertEqual((a - 0).__class__, complex)
2573 self.assertEqual(a - 0, base)
2574 self.assertEqual((a * 1).__class__, complex)
2575 self.assertEqual(a * 1, base)
2576 self.assertEqual((a / 1).__class__, complex)
2577 self.assertEqual(a / 1, base)
2578
2579 class madtuple(tuple):
2580 _rev = None
2581 def rev(self):
2582 if self._rev is not None:
2583 return self._rev
2584 L = list(self)
2585 L.reverse()
2586 self._rev = self.__class__(L)
2587 return self._rev
2588 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2589 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2590 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2591 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2592 for i in range(512):
2593 t = madtuple(range(i))
2594 u = t.rev()
2595 v = u.rev()
2596 self.assertEqual(v, t)
2597 a = madtuple((1,2,3,4,5))
2598 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002599 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002600 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002601 self.assertTrue(a[:].__class__ is tuple)
2602 self.assertTrue((a * 1).__class__ is tuple)
2603 self.assertTrue((a * 0).__class__ is tuple)
2604 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002605 a = madtuple(())
2606 self.assertEqual(tuple(a), ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002607 self.assertTrue(tuple(a).__class__ is tuple)
2608 self.assertTrue((a + a).__class__ is tuple)
2609 self.assertTrue((a * 0).__class__ is tuple)
2610 self.assertTrue((a * 1).__class__ is tuple)
2611 self.assertTrue((a * 2).__class__ is tuple)
2612 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002613
2614 class madstring(str):
2615 _rev = None
2616 def rev(self):
2617 if self._rev is not None:
2618 return self._rev
2619 L = list(self)
2620 L.reverse()
2621 self._rev = self.__class__("".join(L))
2622 return self._rev
2623 s = madstring("abcdefghijklmnopqrstuvwxyz")
2624 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2625 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2626 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2627 for i in range(256):
2628 s = madstring("".join(map(chr, range(i))))
2629 t = s.rev()
2630 u = t.rev()
2631 self.assertEqual(u, s)
2632 s = madstring("12345")
2633 self.assertEqual(str(s), "12345")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002634 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002635
2636 base = "\x00" * 5
2637 s = madstring(base)
2638 self.assertEqual(s, base)
2639 self.assertEqual(str(s), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002640 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002641 self.assertEqual(hash(s), hash(base))
2642 self.assertEqual({s: 1}[base], 1)
2643 self.assertEqual({base: 1}[s], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002644 self.assertTrue((s + "").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002645 self.assertEqual(s + "", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002646 self.assertTrue(("" + s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002647 self.assertEqual("" + s, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002648 self.assertTrue((s * 0).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002649 self.assertEqual(s * 0, "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002650 self.assertTrue((s * 1).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002651 self.assertEqual(s * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002652 self.assertTrue((s * 2).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002653 self.assertEqual(s * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002654 self.assertTrue(s[:].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002655 self.assertEqual(s[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002656 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002657 self.assertEqual(s[0:0], "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002658 self.assertTrue(s.strip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002659 self.assertEqual(s.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002660 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002661 self.assertEqual(s.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002662 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002663 self.assertEqual(s.rstrip(), base)
2664 identitytab = ''.join([chr(i) for i in range(256)])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002665 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002666 self.assertEqual(s.translate(identitytab), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002667 self.assertTrue(s.translate(identitytab, "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002668 self.assertEqual(s.translate(identitytab, "x"), base)
2669 self.assertEqual(s.translate(identitytab, "\x00"), "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002670 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002671 self.assertEqual(s.replace("x", "x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002672 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002673 self.assertEqual(s.ljust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002674 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002675 self.assertEqual(s.rjust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002676 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002677 self.assertEqual(s.center(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002678 self.assertTrue(s.lower().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002679 self.assertEqual(s.lower(), base)
2680
2681 class madunicode(unicode):
2682 _rev = None
2683 def rev(self):
2684 if self._rev is not None:
2685 return self._rev
2686 L = list(self)
2687 L.reverse()
2688 self._rev = self.__class__(u"".join(L))
2689 return self._rev
2690 u = madunicode("ABCDEF")
2691 self.assertEqual(u, u"ABCDEF")
2692 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2693 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2694 base = u"12345"
2695 u = madunicode(base)
2696 self.assertEqual(unicode(u), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002697 self.assertTrue(unicode(u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002698 self.assertEqual(hash(u), hash(base))
2699 self.assertEqual({u: 1}[base], 1)
2700 self.assertEqual({base: 1}[u], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002701 self.assertTrue(u.strip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002702 self.assertEqual(u.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002703 self.assertTrue(u.lstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002704 self.assertEqual(u.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002705 self.assertTrue(u.rstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002706 self.assertEqual(u.rstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002707 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002708 self.assertEqual(u.replace(u"x", u"x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002709 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002710 self.assertEqual(u.replace(u"xy", u"xy"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002711 self.assertTrue(u.center(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002712 self.assertEqual(u.center(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002713 self.assertTrue(u.ljust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002714 self.assertEqual(u.ljust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002715 self.assertTrue(u.rjust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002716 self.assertEqual(u.rjust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002717 self.assertTrue(u.lower().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002718 self.assertEqual(u.lower(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002719 self.assertTrue(u.upper().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002720 self.assertEqual(u.upper(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002721 self.assertTrue(u.capitalize().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002722 self.assertEqual(u.capitalize(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002723 self.assertTrue(u.title().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002724 self.assertEqual(u.title(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002725 self.assertTrue((u + u"").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002726 self.assertEqual(u + u"", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002727 self.assertTrue((u"" + u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002728 self.assertEqual(u"" + u, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002729 self.assertTrue((u * 0).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002730 self.assertEqual(u * 0, u"")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002731 self.assertTrue((u * 1).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002732 self.assertEqual(u * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002733 self.assertTrue((u * 2).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002734 self.assertEqual(u * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002735 self.assertTrue(u[:].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002736 self.assertEqual(u[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002737 self.assertTrue(u[0:0].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002738 self.assertEqual(u[0:0], u"")
2739
2740 class sublist(list):
2741 pass
2742 a = sublist(range(5))
2743 self.assertEqual(a, range(5))
2744 a.append("hello")
2745 self.assertEqual(a, range(5) + ["hello"])
2746 a[5] = 5
2747 self.assertEqual(a, range(6))
2748 a.extend(range(6, 20))
2749 self.assertEqual(a, range(20))
2750 a[-5:] = []
2751 self.assertEqual(a, range(15))
2752 del a[10:15]
2753 self.assertEqual(len(a), 10)
2754 self.assertEqual(a, range(10))
2755 self.assertEqual(list(a), range(10))
2756 self.assertEqual(a[0], 0)
2757 self.assertEqual(a[9], 9)
2758 self.assertEqual(a[-10], 0)
2759 self.assertEqual(a[-1], 9)
2760 self.assertEqual(a[:5], range(5))
2761
2762 class CountedInput(file):
2763 """Counts lines read by self.readline().
2764
2765 self.lineno is the 0-based ordinal of the last line read, up to
2766 a maximum of one greater than the number of lines in the file.
2767
2768 self.ateof is true if and only if the final "" line has been read,
2769 at which point self.lineno stops incrementing, and further calls
2770 to readline() continue to return "".
2771 """
2772
2773 lineno = 0
2774 ateof = 0
2775 def readline(self):
2776 if self.ateof:
2777 return ""
2778 s = file.readline(self)
2779 # Next line works too.
2780 # s = super(CountedInput, self).readline()
2781 self.lineno += 1
2782 if s == "":
2783 self.ateof = 1
2784 return s
2785
2786 f = file(name=test_support.TESTFN, mode='w')
2787 lines = ['a\n', 'b\n', 'c\n']
2788 try:
2789 f.writelines(lines)
2790 f.close()
2791 f = CountedInput(test_support.TESTFN)
2792 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2793 got = f.readline()
2794 self.assertEqual(expected, got)
2795 self.assertEqual(f.lineno, i)
2796 self.assertEqual(f.ateof, (i > len(lines)))
2797 f.close()
2798 finally:
2799 try:
2800 f.close()
2801 except:
2802 pass
2803 test_support.unlink(test_support.TESTFN)
2804
2805 def test_keywords(self):
2806 # Testing keyword args to basic type constructors ...
2807 self.assertEqual(int(x=1), 1)
2808 self.assertEqual(float(x=2), 2.0)
2809 self.assertEqual(long(x=3), 3L)
2810 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2811 self.assertEqual(str(object=500), '500')
2812 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2813 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2814 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2815 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2816
2817 for constructor in (int, float, long, complex, str, unicode,
2818 tuple, list, file):
2819 try:
2820 constructor(bogus_keyword_arg=1)
2821 except TypeError:
2822 pass
2823 else:
2824 self.fail("expected TypeError from bogus keyword argument to %r"
2825 % constructor)
2826
2827 def test_str_subclass_as_dict_key(self):
2828 # Testing a str subclass used as dict key ..
2829
2830 class cistr(str):
2831 """Sublcass of str that computes __eq__ case-insensitively.
2832
2833 Also computes a hash code of the string in canonical form.
2834 """
2835
2836 def __init__(self, value):
2837 self.canonical = value.lower()
2838 self.hashcode = hash(self.canonical)
2839
2840 def __eq__(self, other):
2841 if not isinstance(other, cistr):
2842 other = cistr(other)
2843 return self.canonical == other.canonical
2844
2845 def __hash__(self):
2846 return self.hashcode
2847
2848 self.assertEqual(cistr('ABC'), 'abc')
2849 self.assertEqual('aBc', cistr('ABC'))
2850 self.assertEqual(str(cistr('ABC')), 'ABC')
2851
2852 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2853 self.assertEqual(d[cistr('one')], 1)
2854 self.assertEqual(d[cistr('tWo')], 2)
2855 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002856 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002857 self.assertEqual(d.get(cistr('thrEE')), 3)
2858
2859 def test_classic_comparisons(self):
2860 # Testing classic comparisons...
2861 class classic:
2862 pass
2863
2864 for base in (classic, int, object):
2865 class C(base):
2866 def __init__(self, value):
2867 self.value = int(value)
2868 def __cmp__(self, other):
2869 if isinstance(other, C):
2870 return cmp(self.value, other.value)
2871 if isinstance(other, int) or isinstance(other, long):
2872 return cmp(self.value, other)
2873 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002874 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002875
2876 c1 = C(1)
2877 c2 = C(2)
2878 c3 = C(3)
2879 self.assertEqual(c1, 1)
2880 c = {1: c1, 2: c2, 3: c3}
2881 for x in 1, 2, 3:
2882 for y in 1, 2, 3:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002883 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002884 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002885 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002886 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002887 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2888 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002889
2890 def test_rich_comparisons(self):
2891 # Testing rich comparisons...
2892 class Z(complex):
2893 pass
2894 z = Z(1)
2895 self.assertEqual(z, 1+0j)
2896 self.assertEqual(1+0j, z)
2897 class ZZ(complex):
2898 def __eq__(self, other):
2899 try:
2900 return abs(self - other) <= 1e-6
2901 except:
2902 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002903 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002904 zz = ZZ(1.0000003)
2905 self.assertEqual(zz, 1+0j)
2906 self.assertEqual(1+0j, zz)
2907
2908 class classic:
2909 pass
2910 for base in (classic, int, object, list):
2911 class C(base):
2912 def __init__(self, value):
2913 self.value = int(value)
2914 def __cmp__(self_, other):
2915 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002916 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002917 def __eq__(self, other):
2918 if isinstance(other, C):
2919 return self.value == other.value
2920 if isinstance(other, int) or isinstance(other, long):
2921 return self.value == other
2922 return NotImplemented
2923 def __ne__(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 __lt__(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 __le__(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 __gt__(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 __ge__(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 c1 = C(1)
2954 c2 = C(2)
2955 c3 = C(3)
2956 self.assertEqual(c1, 1)
2957 c = {1: c1, 2: c2, 3: c3}
2958 for x in 1, 2, 3:
2959 for y in 1, 2, 3:
2960 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002961 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002962 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002963 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002964 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002965 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002966 "x=%d, y=%d" % (x, y))
2967
2968 def test_coercions(self):
2969 # Testing coercions...
2970 class I(int): pass
2971 coerce(I(0), 0)
2972 coerce(0, I(0))
2973 class L(long): pass
2974 coerce(L(0), 0)
2975 coerce(L(0), 0L)
2976 coerce(0, L(0))
2977 coerce(0L, L(0))
2978 class F(float): pass
2979 coerce(F(0), 0)
2980 coerce(F(0), 0L)
2981 coerce(F(0), 0.)
2982 coerce(0, F(0))
2983 coerce(0L, F(0))
2984 coerce(0., F(0))
2985 class C(complex): pass
2986 coerce(C(0), 0)
2987 coerce(C(0), 0L)
2988 coerce(C(0), 0.)
2989 coerce(C(0), 0j)
2990 coerce(0, C(0))
2991 coerce(0L, C(0))
2992 coerce(0., C(0))
2993 coerce(0j, C(0))
2994
2995 def test_descrdoc(self):
2996 # Testing descriptor doc strings...
2997 def check(descr, what):
2998 self.assertEqual(descr.__doc__, what)
2999 check(file.closed, "True if the file is closed") # getset descriptor
3000 check(file.name, "file name") # member descriptor
3001
3002 def test_doc_descriptor(self):
3003 # Testing __doc__ descriptor...
3004 # SF bug 542984
3005 class DocDescr(object):
3006 def __get__(self, object, otype):
3007 if object:
3008 object = object.__class__.__name__ + ' instance'
3009 if otype:
3010 otype = otype.__name__
3011 return 'object=%s; type=%s' % (object, otype)
3012 class OldClass:
3013 __doc__ = DocDescr()
3014 class NewClass(object):
3015 __doc__ = DocDescr()
3016 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3017 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3018 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3019 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3020
3021 def test_set_class(self):
3022 # Testing __class__ assignment...
3023 class C(object): pass
3024 class D(object): pass
3025 class E(object): pass
3026 class F(D, E): pass
3027 for cls in C, D, E, F:
3028 for cls2 in C, D, E, F:
3029 x = cls()
3030 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003031 self.assertTrue(x.__class__ is cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003032 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003033 self.assertTrue(x.__class__ is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003034 def cant(x, C):
3035 try:
3036 x.__class__ = C
3037 except TypeError:
3038 pass
3039 else:
3040 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3041 try:
3042 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003043 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003044 pass
3045 else:
3046 self.fail("shouldn't allow del %r.__class__" % x)
3047 cant(C(), list)
3048 cant(list(), C)
3049 cant(C(), 1)
3050 cant(C(), object)
3051 cant(object(), list)
3052 cant(list(), object)
3053 class Int(int): __slots__ = []
3054 cant(2, Int)
3055 cant(Int(), int)
3056 cant(True, int)
3057 cant(2, bool)
3058 o = object()
3059 cant(o, type(1))
3060 cant(o, type(None))
3061 del o
3062 class G(object):
3063 __slots__ = ["a", "b"]
3064 class H(object):
3065 __slots__ = ["b", "a"]
3066 try:
3067 unicode
3068 except NameError:
3069 class I(object):
3070 __slots__ = ["a", "b"]
3071 else:
3072 class I(object):
3073 __slots__ = [unicode("a"), unicode("b")]
3074 class J(object):
3075 __slots__ = ["c", "b"]
3076 class K(object):
3077 __slots__ = ["a", "b", "d"]
3078 class L(H):
3079 __slots__ = ["e"]
3080 class M(I):
3081 __slots__ = ["e"]
3082 class N(J):
3083 __slots__ = ["__weakref__"]
3084 class P(J):
3085 __slots__ = ["__dict__"]
3086 class Q(J):
3087 pass
3088 class R(J):
3089 __slots__ = ["__dict__", "__weakref__"]
3090
3091 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3092 x = cls()
3093 x.a = 1
3094 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003095 self.assertTrue(x.__class__ is cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003096 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3097 self.assertEqual(x.a, 1)
3098 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003099 self.assertTrue(x.__class__ is cls,
Georg Brandl48545522008-02-02 10:12:36 +00003100 "assigning %r as __class__ for %r silently failed" % (cls, x))
3101 self.assertEqual(x.a, 1)
3102 for cls in G, J, K, L, M, N, P, R, list, Int:
3103 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3104 if cls is cls2:
3105 continue
3106 cant(cls(), cls2)
3107
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003108 # Issue5283: when __class__ changes in __del__, the wrong
3109 # type gets DECREF'd.
3110 class O(object):
3111 pass
3112 class A(object):
3113 def __del__(self):
3114 self.__class__ = O
3115 l = [A() for x in range(100)]
3116 del l
3117
Georg Brandl48545522008-02-02 10:12:36 +00003118 def test_set_dict(self):
3119 # Testing __dict__ assignment...
3120 class C(object): pass
3121 a = C()
3122 a.__dict__ = {'b': 1}
3123 self.assertEqual(a.b, 1)
3124 def cant(x, dict):
3125 try:
3126 x.__dict__ = dict
3127 except (AttributeError, TypeError):
3128 pass
3129 else:
3130 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3131 cant(a, None)
3132 cant(a, [])
3133 cant(a, 1)
3134 del a.__dict__ # Deleting __dict__ is allowed
3135
3136 class Base(object):
3137 pass
3138 def verify_dict_readonly(x):
3139 """
3140 x has to be an instance of a class inheriting from Base.
3141 """
3142 cant(x, {})
3143 try:
3144 del x.__dict__
3145 except (AttributeError, TypeError):
3146 pass
3147 else:
3148 self.fail("shouldn't allow del %r.__dict__" % x)
3149 dict_descr = Base.__dict__["__dict__"]
3150 try:
3151 dict_descr.__set__(x, {})
3152 except (AttributeError, TypeError):
3153 pass
3154 else:
3155 self.fail("dict_descr allowed access to %r's dict" % x)
3156
3157 # Classes don't allow __dict__ assignment and have readonly dicts
3158 class Meta1(type, Base):
3159 pass
3160 class Meta2(Base, type):
3161 pass
3162 class D(object):
3163 __metaclass__ = Meta1
3164 class E(object):
3165 __metaclass__ = Meta2
3166 for cls in C, D, E:
3167 verify_dict_readonly(cls)
3168 class_dict = cls.__dict__
3169 try:
3170 class_dict["spam"] = "eggs"
3171 except TypeError:
3172 pass
3173 else:
3174 self.fail("%r's __dict__ can be modified" % cls)
3175
3176 # Modules also disallow __dict__ assignment
3177 class Module1(types.ModuleType, Base):
3178 pass
3179 class Module2(Base, types.ModuleType):
3180 pass
3181 for ModuleType in Module1, Module2:
3182 mod = ModuleType("spam")
3183 verify_dict_readonly(mod)
3184 mod.__dict__["spam"] = "eggs"
3185
3186 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003187 # (at least not any more than regular exception's __dict__ can
3188 # be deleted; on CPython it is not the case, whereas on PyPy they
3189 # can, just like any other new-style instance's __dict__.)
3190 def can_delete_dict(e):
3191 try:
3192 del e.__dict__
3193 except (TypeError, AttributeError):
3194 return False
3195 else:
3196 return True
Georg Brandl48545522008-02-02 10:12:36 +00003197 class Exception1(Exception, Base):
3198 pass
3199 class Exception2(Base, Exception):
3200 pass
3201 for ExceptionType in Exception, Exception1, Exception2:
3202 e = ExceptionType()
3203 e.__dict__ = {"a": 1}
3204 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003205 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003206
3207 def test_pickles(self):
3208 # Testing pickling and copying new-style classes and objects...
3209 import pickle, cPickle
3210
3211 def sorteditems(d):
3212 L = d.items()
3213 L.sort()
3214 return L
3215
3216 global C
3217 class C(object):
3218 def __init__(self, a, b):
3219 super(C, self).__init__()
3220 self.a = a
3221 self.b = b
3222 def __repr__(self):
3223 return "C(%r, %r)" % (self.a, self.b)
3224
3225 global C1
3226 class C1(list):
3227 def __new__(cls, a, b):
3228 return super(C1, cls).__new__(cls)
3229 def __getnewargs__(self):
3230 return (self.a, self.b)
3231 def __init__(self, a, b):
3232 self.a = a
3233 self.b = b
3234 def __repr__(self):
3235 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3236
3237 global C2
3238 class C2(int):
3239 def __new__(cls, a, b, val=0):
3240 return super(C2, cls).__new__(cls, val)
3241 def __getnewargs__(self):
3242 return (self.a, self.b, int(self))
3243 def __init__(self, a, b, val=0):
3244 self.a = a
3245 self.b = b
3246 def __repr__(self):
3247 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3248
3249 global C3
3250 class C3(object):
3251 def __init__(self, foo):
3252 self.foo = foo
3253 def __getstate__(self):
3254 return self.foo
3255 def __setstate__(self, foo):
3256 self.foo = foo
3257
3258 global C4classic, C4
3259 class C4classic: # classic
3260 pass
3261 class C4(C4classic, object): # mixed inheritance
3262 pass
3263
3264 for p in pickle, cPickle:
3265 for bin in 0, 1:
3266 for cls in C, C1, C2:
3267 s = p.dumps(cls, bin)
3268 cls2 = p.loads(s)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003269 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003270
3271 a = C1(1, 2); a.append(42); a.append(24)
3272 b = C2("hello", "world", 42)
3273 s = p.dumps((a, b), bin)
3274 x, y = p.loads(s)
3275 self.assertEqual(x.__class__, a.__class__)
3276 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3277 self.assertEqual(y.__class__, b.__class__)
3278 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3279 self.assertEqual(repr(x), repr(a))
3280 self.assertEqual(repr(y), repr(b))
3281 # Test for __getstate__ and __setstate__ on new style class
3282 u = C3(42)
3283 s = p.dumps(u, bin)
3284 v = p.loads(s)
3285 self.assertEqual(u.__class__, v.__class__)
3286 self.assertEqual(u.foo, v.foo)
3287 # Test for picklability of hybrid class
3288 u = C4()
3289 u.foo = 42
3290 s = p.dumps(u, bin)
3291 v = p.loads(s)
3292 self.assertEqual(u.__class__, v.__class__)
3293 self.assertEqual(u.foo, v.foo)
3294
3295 # Testing copy.deepcopy()
3296 import copy
3297 for cls in C, C1, C2:
3298 cls2 = copy.deepcopy(cls)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003299 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003300
3301 a = C1(1, 2); a.append(42); a.append(24)
3302 b = C2("hello", "world", 42)
3303 x, y = copy.deepcopy((a, b))
3304 self.assertEqual(x.__class__, a.__class__)
3305 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3306 self.assertEqual(y.__class__, b.__class__)
3307 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3308 self.assertEqual(repr(x), repr(a))
3309 self.assertEqual(repr(y), repr(b))
3310
3311 def test_pickle_slots(self):
3312 # Testing pickling of classes with __slots__ ...
3313 import pickle, cPickle
3314 # Pickling of classes with __slots__ but without __getstate__ should fail
3315 global B, C, D, E
3316 class B(object):
3317 pass
3318 for base in [object, B]:
3319 class C(base):
3320 __slots__ = ['a']
3321 class D(C):
3322 pass
3323 try:
3324 pickle.dumps(C())
3325 except TypeError:
3326 pass
3327 else:
3328 self.fail("should fail: pickle C instance - %s" % base)
3329 try:
3330 cPickle.dumps(C())
3331 except TypeError:
3332 pass
3333 else:
3334 self.fail("should fail: cPickle C instance - %s" % base)
3335 try:
3336 pickle.dumps(C())
3337 except TypeError:
3338 pass
3339 else:
3340 self.fail("should fail: pickle D instance - %s" % base)
3341 try:
3342 cPickle.dumps(D())
3343 except TypeError:
3344 pass
3345 else:
3346 self.fail("should fail: cPickle D instance - %s" % base)
3347 # Give C a nice generic __getstate__ and __setstate__
3348 class C(base):
3349 __slots__ = ['a']
3350 def __getstate__(self):
3351 try:
3352 d = self.__dict__.copy()
3353 except AttributeError:
3354 d = {}
3355 for cls in self.__class__.__mro__:
3356 for sn in cls.__dict__.get('__slots__', ()):
3357 try:
3358 d[sn] = getattr(self, sn)
3359 except AttributeError:
3360 pass
3361 return d
3362 def __setstate__(self, d):
3363 for k, v in d.items():
3364 setattr(self, k, v)
3365 class D(C):
3366 pass
3367 # Now it should work
3368 x = C()
3369 y = pickle.loads(pickle.dumps(x))
3370 self.assertEqual(hasattr(y, 'a'), 0)
3371 y = cPickle.loads(cPickle.dumps(x))
3372 self.assertEqual(hasattr(y, 'a'), 0)
3373 x.a = 42
3374 y = pickle.loads(pickle.dumps(x))
3375 self.assertEqual(y.a, 42)
3376 y = cPickle.loads(cPickle.dumps(x))
3377 self.assertEqual(y.a, 42)
3378 x = D()
3379 x.a = 42
3380 x.b = 100
3381 y = pickle.loads(pickle.dumps(x))
3382 self.assertEqual(y.a + y.b, 142)
3383 y = cPickle.loads(cPickle.dumps(x))
3384 self.assertEqual(y.a + y.b, 142)
3385 # A subclass that adds a slot should also work
3386 class E(C):
3387 __slots__ = ['b']
3388 x = E()
3389 x.a = 42
3390 x.b = "foo"
3391 y = pickle.loads(pickle.dumps(x))
3392 self.assertEqual(y.a, x.a)
3393 self.assertEqual(y.b, x.b)
3394 y = cPickle.loads(cPickle.dumps(x))
3395 self.assertEqual(y.a, x.a)
3396 self.assertEqual(y.b, x.b)
3397
3398 def test_binary_operator_override(self):
3399 # Testing overrides of binary operations...
3400 class I(int):
3401 def __repr__(self):
3402 return "I(%r)" % int(self)
3403 def __add__(self, other):
3404 return I(int(self) + int(other))
3405 __radd__ = __add__
3406 def __pow__(self, other, mod=None):
3407 if mod is None:
3408 return I(pow(int(self), int(other)))
3409 else:
3410 return I(pow(int(self), int(other), int(mod)))
3411 def __rpow__(self, other, mod=None):
3412 if mod is None:
3413 return I(pow(int(other), int(self), mod))
3414 else:
3415 return I(pow(int(other), int(self), int(mod)))
3416
3417 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3418 self.assertEqual(repr(I(1) + 2), "I(3)")
3419 self.assertEqual(repr(1 + I(2)), "I(3)")
3420 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3421 self.assertEqual(repr(2 ** I(3)), "I(8)")
3422 self.assertEqual(repr(I(2) ** 3), "I(8)")
3423 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3424 class S(str):
3425 def __eq__(self, other):
3426 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003427 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003428
3429 def test_subclass_propagation(self):
3430 # Testing propagation of slot functions to subclasses...
3431 class A(object):
3432 pass
3433 class B(A):
3434 pass
3435 class C(A):
3436 pass
3437 class D(B, C):
3438 pass
3439 d = D()
3440 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3441 A.__hash__ = lambda self: 42
3442 self.assertEqual(hash(d), 42)
3443 C.__hash__ = lambda self: 314
3444 self.assertEqual(hash(d), 314)
3445 B.__hash__ = lambda self: 144
3446 self.assertEqual(hash(d), 144)
3447 D.__hash__ = lambda self: 100
3448 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003449 D.__hash__ = None
3450 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003451 del D.__hash__
3452 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003453 B.__hash__ = None
3454 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003455 del B.__hash__
3456 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003457 C.__hash__ = None
3458 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003459 del C.__hash__
3460 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003461 A.__hash__ = None
3462 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003463 del A.__hash__
3464 self.assertEqual(hash(d), orig_hash)
3465 d.foo = 42
3466 d.bar = 42
3467 self.assertEqual(d.foo, 42)
3468 self.assertEqual(d.bar, 42)
3469 def __getattribute__(self, name):
3470 if name == "foo":
3471 return 24
3472 return object.__getattribute__(self, name)
3473 A.__getattribute__ = __getattribute__
3474 self.assertEqual(d.foo, 24)
3475 self.assertEqual(d.bar, 42)
3476 def __getattr__(self, name):
3477 if name in ("spam", "foo", "bar"):
3478 return "hello"
3479 raise AttributeError, name
3480 B.__getattr__ = __getattr__
3481 self.assertEqual(d.spam, "hello")
3482 self.assertEqual(d.foo, 24)
3483 self.assertEqual(d.bar, 42)
3484 del A.__getattribute__
3485 self.assertEqual(d.foo, 42)
3486 del d.foo
3487 self.assertEqual(d.foo, "hello")
3488 self.assertEqual(d.bar, 42)
3489 del B.__getattr__
3490 try:
3491 d.foo
3492 except AttributeError:
3493 pass
3494 else:
3495 self.fail("d.foo should be undefined now")
3496
3497 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003498 class A(object):
3499 pass
3500 class B(A):
3501 pass
3502 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003503 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003504 A.__setitem__ = lambda *a: None # crash
3505
3506 def test_buffer_inheritance(self):
3507 # Testing that buffer interface is inherited ...
3508
3509 import binascii
3510 # SF bug [#470040] ParseTuple t# vs subclasses.
3511
3512 class MyStr(str):
3513 pass
3514 base = 'abc'
3515 m = MyStr(base)
3516 # b2a_hex uses the buffer interface to get its argument's value, via
3517 # PyArg_ParseTuple 't#' code.
3518 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3519
3520 # It's not clear that unicode will continue to support the character
3521 # buffer interface, and this test will fail if that's taken away.
3522 class MyUni(unicode):
3523 pass
3524 base = u'abc'
3525 m = MyUni(base)
3526 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3527
3528 class MyInt(int):
3529 pass
3530 m = MyInt(42)
3531 try:
3532 binascii.b2a_hex(m)
3533 self.fail('subclass of int should not have a buffer interface')
3534 except TypeError:
3535 pass
3536
3537 def test_str_of_str_subclass(self):
3538 # Testing __str__ defined in subclass of str ...
3539 import binascii
3540 import cStringIO
3541
3542 class octetstring(str):
3543 def __str__(self):
3544 return binascii.b2a_hex(self)
3545 def __repr__(self):
3546 return self + " repr"
3547
3548 o = octetstring('A')
3549 self.assertEqual(type(o), octetstring)
3550 self.assertEqual(type(str(o)), str)
3551 self.assertEqual(type(repr(o)), str)
3552 self.assertEqual(ord(o), 0x41)
3553 self.assertEqual(str(o), '41')
3554 self.assertEqual(repr(o), 'A repr')
3555 self.assertEqual(o.__str__(), '41')
3556 self.assertEqual(o.__repr__(), 'A repr')
3557
3558 capture = cStringIO.StringIO()
3559 # Calling str() or not exercises different internal paths.
3560 print >> capture, o
3561 print >> capture, str(o)
3562 self.assertEqual(capture.getvalue(), '41\n41\n')
3563 capture.close()
3564
3565 def test_keyword_arguments(self):
3566 # Testing keyword arguments to __init__, __call__...
3567 def f(a): return a
3568 self.assertEqual(f.__call__(a=42), 42)
3569 a = []
3570 list.__init__(a, sequence=[0, 1, 2])
3571 self.assertEqual(a, [0, 1, 2])
3572
3573 def test_recursive_call(self):
3574 # Testing recursive __call__() by setting to instance of class...
3575 class A(object):
3576 pass
3577
3578 A.__call__ = A()
3579 try:
3580 A()()
3581 except RuntimeError:
3582 pass
3583 else:
3584 self.fail("Recursion limit should have been reached for __call__()")
3585
3586 def test_delete_hook(self):
3587 # Testing __del__ hook...
3588 log = []
3589 class C(object):
3590 def __del__(self):
3591 log.append(1)
3592 c = C()
3593 self.assertEqual(log, [])
3594 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003595 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003596 self.assertEqual(log, [1])
3597
3598 class D(object): pass
3599 d = D()
3600 try: del d[0]
3601 except TypeError: pass
3602 else: self.fail("invalid del() didn't raise TypeError")
3603
3604 def test_hash_inheritance(self):
3605 # Testing hash of mutable subclasses...
3606
3607 class mydict(dict):
3608 pass
3609 d = mydict()
3610 try:
3611 hash(d)
3612 except TypeError:
3613 pass
3614 else:
3615 self.fail("hash() of dict subclass should fail")
3616
3617 class mylist(list):
3618 pass
3619 d = mylist()
3620 try:
3621 hash(d)
3622 except TypeError:
3623 pass
3624 else:
3625 self.fail("hash() of list subclass should fail")
3626
3627 def test_str_operations(self):
3628 try: 'a' + 5
3629 except TypeError: pass
3630 else: self.fail("'' + 5 doesn't raise TypeError")
3631
3632 try: ''.split('')
3633 except ValueError: pass
3634 else: self.fail("''.split('') doesn't raise ValueError")
3635
3636 try: ''.join([0])
3637 except TypeError: pass
3638 else: self.fail("''.join([0]) doesn't raise TypeError")
3639
3640 try: ''.rindex('5')
3641 except ValueError: pass
3642 else: self.fail("''.rindex('5') doesn't raise ValueError")
3643
3644 try: '%(n)s' % None
3645 except TypeError: pass
3646 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3647
3648 try: '%(n' % {}
3649 except ValueError: pass
3650 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3651
3652 try: '%*s' % ('abc')
3653 except TypeError: pass
3654 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3655
3656 try: '%*.*s' % ('abc', 5)
3657 except TypeError: pass
3658 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3659
3660 try: '%s' % (1, 2)
3661 except TypeError: pass
3662 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3663
3664 try: '%' % None
3665 except ValueError: pass
3666 else: self.fail("'%' % None doesn't raise ValueError")
3667
3668 self.assertEqual('534253'.isdigit(), 1)
3669 self.assertEqual('534253x'.isdigit(), 0)
3670 self.assertEqual('%c' % 5, '\x05')
3671 self.assertEqual('%c' % '5', '5')
3672
3673 def test_deepcopy_recursive(self):
3674 # Testing deepcopy of recursive objects...
3675 class Node:
3676 pass
3677 a = Node()
3678 b = Node()
3679 a.b = b
3680 b.a = a
3681 z = deepcopy(a) # This blew up before
3682
3683 def test_unintialized_modules(self):
3684 # Testing uninitialized module objects...
3685 from types import ModuleType as M
3686 m = M.__new__(M)
3687 str(m)
3688 self.assertEqual(hasattr(m, "__name__"), 0)
3689 self.assertEqual(hasattr(m, "__file__"), 0)
3690 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003691 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003692 m.foo = 1
3693 self.assertEqual(m.__dict__, {"foo": 1})
3694
3695 def test_funny_new(self):
3696 # Testing __new__ returning something unexpected...
3697 class C(object):
3698 def __new__(cls, arg):
3699 if isinstance(arg, str): return [1, 2, 3]
3700 elif isinstance(arg, int): return object.__new__(D)
3701 else: return object.__new__(cls)
3702 class D(C):
3703 def __init__(self, arg):
3704 self.foo = arg
3705 self.assertEqual(C("1"), [1, 2, 3])
3706 self.assertEqual(D("1"), [1, 2, 3])
3707 d = D(None)
3708 self.assertEqual(d.foo, None)
3709 d = C(1)
3710 self.assertEqual(isinstance(d, D), True)
3711 self.assertEqual(d.foo, 1)
3712 d = D(1)
3713 self.assertEqual(isinstance(d, D), True)
3714 self.assertEqual(d.foo, 1)
3715
3716 def test_imul_bug(self):
3717 # Testing for __imul__ problems...
3718 # SF bug 544647
3719 class C(object):
3720 def __imul__(self, other):
3721 return (self, other)
3722 x = C()
3723 y = x
3724 y *= 1.0
3725 self.assertEqual(y, (x, 1.0))
3726 y = x
3727 y *= 2
3728 self.assertEqual(y, (x, 2))
3729 y = x
3730 y *= 3L
3731 self.assertEqual(y, (x, 3L))
3732 y = x
3733 y *= 1L<<100
3734 self.assertEqual(y, (x, 1L<<100))
3735 y = x
3736 y *= None
3737 self.assertEqual(y, (x, None))
3738 y = x
3739 y *= "foo"
3740 self.assertEqual(y, (x, "foo"))
3741
3742 def test_copy_setstate(self):
3743 # Testing that copy.*copy() correctly uses __setstate__...
3744 import copy
3745 class C(object):
3746 def __init__(self, foo=None):
3747 self.foo = foo
3748 self.__foo = foo
3749 def setfoo(self, foo=None):
3750 self.foo = foo
3751 def getfoo(self):
3752 return self.__foo
3753 def __getstate__(self):
3754 return [self.foo]
3755 def __setstate__(self_, lst):
3756 self.assertEqual(len(lst), 1)
3757 self_.__foo = self_.foo = lst[0]
3758 a = C(42)
3759 a.setfoo(24)
3760 self.assertEqual(a.foo, 24)
3761 self.assertEqual(a.getfoo(), 42)
3762 b = copy.copy(a)
3763 self.assertEqual(b.foo, 24)
3764 self.assertEqual(b.getfoo(), 24)
3765 b = copy.deepcopy(a)
3766 self.assertEqual(b.foo, 24)
3767 self.assertEqual(b.getfoo(), 24)
3768
3769 def test_slices(self):
3770 # Testing cases with slices and overridden __getitem__ ...
3771
3772 # Strings
3773 self.assertEqual("hello"[:4], "hell")
3774 self.assertEqual("hello"[slice(4)], "hell")
3775 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3776 class S(str):
3777 def __getitem__(self, x):
3778 return str.__getitem__(self, x)
3779 self.assertEqual(S("hello")[:4], "hell")
3780 self.assertEqual(S("hello")[slice(4)], "hell")
3781 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3782 # Tuples
3783 self.assertEqual((1,2,3)[:2], (1,2))
3784 self.assertEqual((1,2,3)[slice(2)], (1,2))
3785 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3786 class T(tuple):
3787 def __getitem__(self, x):
3788 return tuple.__getitem__(self, x)
3789 self.assertEqual(T((1,2,3))[:2], (1,2))
3790 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3791 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3792 # Lists
3793 self.assertEqual([1,2,3][:2], [1,2])
3794 self.assertEqual([1,2,3][slice(2)], [1,2])
3795 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3796 class L(list):
3797 def __getitem__(self, x):
3798 return list.__getitem__(self, x)
3799 self.assertEqual(L([1,2,3])[:2], [1,2])
3800 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3801 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3802 # Now do lists and __setitem__
3803 a = L([1,2,3])
3804 a[slice(1, 3)] = [3,2]
3805 self.assertEqual(a, [1,3,2])
3806 a[slice(0, 2, 1)] = [3,1]
3807 self.assertEqual(a, [3,1,2])
3808 a.__setitem__(slice(1, 3), [2,1])
3809 self.assertEqual(a, [3,2,1])
3810 a.__setitem__(slice(0, 2, 1), [2,3])
3811 self.assertEqual(a, [2,3,1])
3812
3813 def test_subtype_resurrection(self):
3814 # Testing resurrection of new-style instance...
3815
3816 class C(object):
3817 container = []
3818
3819 def __del__(self):
3820 # resurrect the instance
3821 C.container.append(self)
3822
3823 c = C()
3824 c.attr = 42
3825
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003826 # The most interesting thing here is whether this blows up, due to
3827 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3828 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003829 del c
3830
3831 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003832 # the last container slot works: that will attempt to delete c again,
3833 # which will cause c to get appended back to the container again
3834 # "during" the del. (On non-CPython implementations, however, __del__
3835 # is typically not called again.)
3836 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003837 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003838 del C.container[-1]
3839 if test_support.check_impl_detail():
3840 test_support.gc_collect()
3841 self.assertEqual(len(C.container), 1)
3842 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003843
3844 # Make c mortal again, so that the test framework with -l doesn't report
3845 # it as a leak.
3846 del C.__del__
3847
3848 def test_slots_trash(self):
3849 # Testing slot trash...
3850 # Deallocating deeply nested slotted trash caused stack overflows
3851 class trash(object):
3852 __slots__ = ['x']
3853 def __init__(self, x):
3854 self.x = x
3855 o = None
3856 for i in xrange(50000):
3857 o = trash(o)
3858 del o
3859
3860 def test_slots_multiple_inheritance(self):
3861 # SF bug 575229, multiple inheritance w/ slots dumps core
3862 class A(object):
3863 __slots__=()
3864 class B(object):
3865 pass
3866 class C(A,B) :
3867 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003868 if test_support.check_impl_detail():
3869 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003870 self.assertTrue(hasattr(C, '__dict__'))
3871 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl48545522008-02-02 10:12:36 +00003872 C().x = 2
3873
3874 def test_rmul(self):
3875 # Testing correct invocation of __rmul__...
3876 # SF patch 592646
3877 class C(object):
3878 def __mul__(self, other):
3879 return "mul"
3880 def __rmul__(self, other):
3881 return "rmul"
3882 a = C()
3883 self.assertEqual(a*2, "mul")
3884 self.assertEqual(a*2.2, "mul")
3885 self.assertEqual(2*a, "rmul")
3886 self.assertEqual(2.2*a, "rmul")
3887
3888 def test_ipow(self):
3889 # Testing correct invocation of __ipow__...
3890 # [SF bug 620179]
3891 class C(object):
3892 def __ipow__(self, other):
3893 pass
3894 a = C()
3895 a **= 2
3896
3897 def test_mutable_bases(self):
3898 # Testing mutable bases...
3899
3900 # stuff that should work:
3901 class C(object):
3902 pass
3903 class C2(object):
3904 def __getattribute__(self, attr):
3905 if attr == 'a':
3906 return 2
3907 else:
3908 return super(C2, self).__getattribute__(attr)
3909 def meth(self):
3910 return 1
3911 class D(C):
3912 pass
3913 class E(D):
3914 pass
3915 d = D()
3916 e = E()
3917 D.__bases__ = (C,)
3918 D.__bases__ = (C2,)
3919 self.assertEqual(d.meth(), 1)
3920 self.assertEqual(e.meth(), 1)
3921 self.assertEqual(d.a, 2)
3922 self.assertEqual(e.a, 2)
3923 self.assertEqual(C2.__subclasses__(), [D])
3924
Georg Brandl48545522008-02-02 10:12:36 +00003925 try:
3926 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003927 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003928 pass
3929 else:
3930 self.fail("shouldn't be able to delete .__bases__")
3931
3932 try:
3933 D.__bases__ = ()
3934 except TypeError, msg:
3935 if str(msg) == "a new-style class can't have only classic bases":
3936 self.fail("wrong error message for .__bases__ = ()")
3937 else:
3938 self.fail("shouldn't be able to set .__bases__ to ()")
3939
3940 try:
3941 D.__bases__ = (D,)
3942 except TypeError:
3943 pass
3944 else:
3945 # actually, we'll have crashed by here...
3946 self.fail("shouldn't be able to create inheritance cycles")
3947
3948 try:
3949 D.__bases__ = (C, C)
3950 except TypeError:
3951 pass
3952 else:
3953 self.fail("didn't detect repeated base classes")
3954
3955 try:
3956 D.__bases__ = (E,)
3957 except TypeError:
3958 pass
3959 else:
3960 self.fail("shouldn't be able to create inheritance cycles")
3961
3962 # let's throw a classic class into the mix:
3963 class Classic:
3964 def meth2(self):
3965 return 3
3966
3967 D.__bases__ = (C, Classic)
3968
3969 self.assertEqual(d.meth2(), 3)
3970 self.assertEqual(e.meth2(), 3)
3971 try:
3972 d.a
3973 except AttributeError:
3974 pass
3975 else:
3976 self.fail("attribute should have vanished")
3977
3978 try:
3979 D.__bases__ = (Classic,)
3980 except TypeError:
3981 pass
3982 else:
3983 self.fail("new-style class must have a new-style base")
3984
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003985 def test_builtin_bases(self):
3986 # Make sure all the builtin types can have their base queried without
3987 # segfaulting. See issue #5787.
3988 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3989 if isinstance(tp, type)]
3990 for tp in builtin_types:
3991 object.__getattribute__(tp, "__bases__")
3992 if tp is not object:
3993 self.assertEqual(len(tp.__bases__), 1, tp)
3994
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003995 class L(list):
3996 pass
3997
3998 class C(object):
3999 pass
4000
4001 class D(C):
4002 pass
4003
4004 try:
4005 L.__bases__ = (dict,)
4006 except TypeError:
4007 pass
4008 else:
4009 self.fail("shouldn't turn list subclass into dict subclass")
4010
4011 try:
4012 list.__bases__ = (dict,)
4013 except TypeError:
4014 pass
4015 else:
4016 self.fail("shouldn't be able to assign to list.__bases__")
4017
4018 try:
4019 D.__bases__ = (C, list)
4020 except TypeError:
4021 pass
4022 else:
4023 assert 0, "best_base calculation found wanting"
4024
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004025
Georg Brandl48545522008-02-02 10:12:36 +00004026 def test_mutable_bases_with_failing_mro(self):
4027 # Testing mutable bases with failing mro...
4028 class WorkOnce(type):
4029 def __new__(self, name, bases, ns):
4030 self.flag = 0
4031 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4032 def mro(self):
4033 if self.flag > 0:
4034 raise RuntimeError, "bozo"
4035 else:
4036 self.flag += 1
4037 return type.mro(self)
4038
4039 class WorkAlways(type):
4040 def mro(self):
4041 # this is here to make sure that .mro()s aren't called
4042 # with an exception set (which was possible at one point).
4043 # An error message will be printed in a debug build.
4044 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004045 return type.mro(self)
4046
Georg Brandl48545522008-02-02 10:12:36 +00004047 class C(object):
4048 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004049
Georg Brandl48545522008-02-02 10:12:36 +00004050 class C2(object):
4051 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004052
Georg Brandl48545522008-02-02 10:12:36 +00004053 class D(C):
4054 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004055
Georg Brandl48545522008-02-02 10:12:36 +00004056 class E(D):
4057 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004058
Georg Brandl48545522008-02-02 10:12:36 +00004059 class F(D):
4060 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004061
Georg Brandl48545522008-02-02 10:12:36 +00004062 class G(D):
4063 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004064
Georg Brandl48545522008-02-02 10:12:36 +00004065 # Immediate subclasses have their mro's adjusted in alphabetical
4066 # order, so E's will get adjusted before adjusting F's fails. We
4067 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004068
Georg Brandl48545522008-02-02 10:12:36 +00004069 E_mro_before = E.__mro__
4070 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004071
Armin Rigofd163f92005-12-29 15:59:19 +00004072 try:
Georg Brandl48545522008-02-02 10:12:36 +00004073 D.__bases__ = (C2,)
4074 except RuntimeError:
4075 self.assertEqual(E.__mro__, E_mro_before)
4076 self.assertEqual(D.__mro__, D_mro_before)
4077 else:
4078 self.fail("exception not propagated")
4079
4080 def test_mutable_bases_catch_mro_conflict(self):
4081 # Testing mutable bases catch mro conflict...
4082 class A(object):
4083 pass
4084
4085 class B(object):
4086 pass
4087
4088 class C(A, B):
4089 pass
4090
4091 class D(A, B):
4092 pass
4093
4094 class E(C, D):
4095 pass
4096
4097 try:
4098 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004099 except TypeError:
4100 pass
4101 else:
Georg Brandl48545522008-02-02 10:12:36 +00004102 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004103
Georg Brandl48545522008-02-02 10:12:36 +00004104 def test_mutable_names(self):
4105 # Testing mutable names...
4106 class C(object):
4107 pass
4108
4109 # C.__module__ could be 'test_descr' or '__main__'
4110 mod = C.__module__
4111
4112 C.__name__ = 'D'
4113 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4114
4115 C.__name__ = 'D.E'
4116 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4117
4118 def test_subclass_right_op(self):
4119 # Testing correct dispatch of subclass overloading __r<op>__...
4120
4121 # This code tests various cases where right-dispatch of a subclass
4122 # should be preferred over left-dispatch of a base class.
4123
4124 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4125
4126 class B(int):
4127 def __floordiv__(self, other):
4128 return "B.__floordiv__"
4129 def __rfloordiv__(self, other):
4130 return "B.__rfloordiv__"
4131
4132 self.assertEqual(B(1) // 1, "B.__floordiv__")
4133 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4134
4135 # Case 2: subclass of object; this is just the baseline for case 3
4136
4137 class C(object):
4138 def __floordiv__(self, other):
4139 return "C.__floordiv__"
4140 def __rfloordiv__(self, other):
4141 return "C.__rfloordiv__"
4142
4143 self.assertEqual(C() // 1, "C.__floordiv__")
4144 self.assertEqual(1 // C(), "C.__rfloordiv__")
4145
4146 # Case 3: subclass of new-style class; here it gets interesting
4147
4148 class D(C):
4149 def __floordiv__(self, other):
4150 return "D.__floordiv__"
4151 def __rfloordiv__(self, other):
4152 return "D.__rfloordiv__"
4153
4154 self.assertEqual(D() // C(), "D.__floordiv__")
4155 self.assertEqual(C() // D(), "D.__rfloordiv__")
4156
4157 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4158
4159 class E(C):
4160 pass
4161
4162 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4163
4164 self.assertEqual(E() // 1, "C.__floordiv__")
4165 self.assertEqual(1 // E(), "C.__rfloordiv__")
4166 self.assertEqual(E() // C(), "C.__floordiv__")
4167 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4168
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004169 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004170 def test_meth_class_get(self):
4171 # Testing __get__ method of METH_CLASS C methods...
4172 # Full coverage of descrobject.c::classmethod_get()
4173
4174 # Baseline
4175 arg = [1, 2, 3]
4176 res = {1: None, 2: None, 3: None}
4177 self.assertEqual(dict.fromkeys(arg), res)
4178 self.assertEqual({}.fromkeys(arg), res)
4179
4180 # Now get the descriptor
4181 descr = dict.__dict__["fromkeys"]
4182
4183 # More baseline using the descriptor directly
4184 self.assertEqual(descr.__get__(None, dict)(arg), res)
4185 self.assertEqual(descr.__get__({})(arg), res)
4186
4187 # Now check various error cases
4188 try:
4189 descr.__get__(None, None)
4190 except TypeError:
4191 pass
4192 else:
4193 self.fail("shouldn't have allowed descr.__get__(None, None)")
4194 try:
4195 descr.__get__(42)
4196 except TypeError:
4197 pass
4198 else:
4199 self.fail("shouldn't have allowed descr.__get__(42)")
4200 try:
4201 descr.__get__(None, 42)
4202 except TypeError:
4203 pass
4204 else:
4205 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4206 try:
4207 descr.__get__(None, int)
4208 except TypeError:
4209 pass
4210 else:
4211 self.fail("shouldn't have allowed descr.__get__(None, int)")
4212
4213 def test_isinst_isclass(self):
4214 # Testing proxy isinstance() and isclass()...
4215 class Proxy(object):
4216 def __init__(self, obj):
4217 self.__obj = obj
4218 def __getattribute__(self, name):
4219 if name.startswith("_Proxy__"):
4220 return object.__getattribute__(self, name)
4221 else:
4222 return getattr(self.__obj, name)
4223 # Test with a classic class
4224 class C:
4225 pass
4226 a = C()
4227 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004228 self.assertIsInstance(a, C) # Baseline
4229 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004230 # Test with a classic subclass
4231 class D(C):
4232 pass
4233 a = D()
4234 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004235 self.assertIsInstance(a, C) # Baseline
4236 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004237 # Test with a new-style class
4238 class C(object):
4239 pass
4240 a = C()
4241 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004242 self.assertIsInstance(a, C) # Baseline
4243 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004244 # Test with a new-style subclass
4245 class D(C):
4246 pass
4247 a = D()
4248 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004249 self.assertIsInstance(a, C) # Baseline
4250 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004251
4252 def test_proxy_super(self):
4253 # Testing super() for a proxy object...
4254 class Proxy(object):
4255 def __init__(self, obj):
4256 self.__obj = obj
4257 def __getattribute__(self, name):
4258 if name.startswith("_Proxy__"):
4259 return object.__getattribute__(self, name)
4260 else:
4261 return getattr(self.__obj, name)
4262
4263 class B(object):
4264 def f(self):
4265 return "B.f"
4266
4267 class C(B):
4268 def f(self):
4269 return super(C, self).f() + "->C.f"
4270
4271 obj = C()
4272 p = Proxy(obj)
4273 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4274
4275 def test_carloverre(self):
4276 # Testing prohibition of Carlo Verre's hack...
4277 try:
4278 object.__setattr__(str, "foo", 42)
4279 except TypeError:
4280 pass
4281 else:
4282 self.fail("Carlo Verre __setattr__ suceeded!")
4283 try:
4284 object.__delattr__(str, "lower")
4285 except TypeError:
4286 pass
4287 else:
4288 self.fail("Carlo Verre __delattr__ succeeded!")
4289
4290 def test_weakref_segfault(self):
4291 # Testing weakref segfault...
4292 # SF 742911
4293 import weakref
4294
4295 class Provoker:
4296 def __init__(self, referrent):
4297 self.ref = weakref.ref(referrent)
4298
4299 def __del__(self):
4300 x = self.ref()
4301
4302 class Oops(object):
4303 pass
4304
4305 o = Oops()
4306 o.whatever = Provoker(o)
4307 del o
4308
4309 def test_wrapper_segfault(self):
4310 # SF 927248: deeply nested wrappers could cause stack overflow
4311 f = lambda:None
4312 for i in xrange(1000000):
4313 f = f.__call__
4314 f = None
4315
4316 def test_file_fault(self):
4317 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004318 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004319 class StdoutGuard:
4320 def __getattr__(self, attr):
4321 sys.stdout = sys.__stdout__
4322 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4323 sys.stdout = StdoutGuard()
4324 try:
4325 print "Oops!"
4326 except RuntimeError:
4327 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004328 finally:
4329 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004330
4331 def test_vicious_descriptor_nonsense(self):
4332 # Testing vicious_descriptor_nonsense...
4333
4334 # A potential segfault spotted by Thomas Wouters in mail to
4335 # python-dev 2003-04-17, turned into an example & fixed by Michael
4336 # Hudson just less than four months later...
4337
4338 class Evil(object):
4339 def __hash__(self):
4340 return hash('attr')
4341 def __eq__(self, other):
4342 del C.attr
4343 return 0
4344
4345 class Descr(object):
4346 def __get__(self, ob, type=None):
4347 return 1
4348
4349 class C(object):
4350 attr = Descr()
4351
4352 c = C()
4353 c.__dict__[Evil()] = 0
4354
4355 self.assertEqual(c.attr, 1)
4356 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004357 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004358 self.assertEqual(hasattr(c, 'attr'), False)
4359
4360 def test_init(self):
4361 # SF 1155938
4362 class Foo(object):
4363 def __init__(self):
4364 return 10
4365 try:
4366 Foo()
4367 except TypeError:
4368 pass
4369 else:
4370 self.fail("did not test __init__() for None return")
4371
4372 def test_method_wrapper(self):
4373 # Testing method-wrapper objects...
4374 # <type 'method-wrapper'> did not support any reflection before 2.5
4375
4376 l = []
4377 self.assertEqual(l.__add__, l.__add__)
4378 self.assertEqual(l.__add__, [].__add__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004379 self.assertTrue(l.__add__ != [5].__add__)
4380 self.assertTrue(l.__add__ != l.__mul__)
4381 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004382 if hasattr(l.__add__, '__self__'):
4383 # CPython
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004384 self.assertTrue(l.__add__.__self__ is l)
4385 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004386 else:
4387 # Python implementations where [].__add__ is a normal bound method
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004388 self.assertTrue(l.__add__.im_self is l)
4389 self.assertTrue(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004390 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4391 try:
4392 hash(l.__add__)
4393 except TypeError:
4394 pass
4395 else:
4396 self.fail("no TypeError from hash([].__add__)")
4397
4398 t = ()
4399 t += (7,)
4400 self.assertEqual(t.__add__, (7,).__add__)
4401 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4402
4403 def test_not_implemented(self):
4404 # Testing NotImplemented...
4405 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004406 import operator
4407
4408 def specialmethod(self, other):
4409 return NotImplemented
4410
4411 def check(expr, x, y):
4412 try:
4413 exec expr in {'x': x, 'y': y, 'operator': operator}
4414 except TypeError:
4415 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004416 else:
Georg Brandl48545522008-02-02 10:12:36 +00004417 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004418
Georg Brandl48545522008-02-02 10:12:36 +00004419 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4420 # TypeErrors
4421 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4422 # ValueErrors instead of TypeErrors
4423 for metaclass in [type, types.ClassType]:
4424 for name, expr, iexpr in [
4425 ('__add__', 'x + y', 'x += y'),
4426 ('__sub__', 'x - y', 'x -= y'),
4427 ('__mul__', 'x * y', 'x *= y'),
4428 ('__truediv__', 'operator.truediv(x, y)', None),
4429 ('__floordiv__', 'operator.floordiv(x, y)', None),
4430 ('__div__', 'x / y', 'x /= y'),
4431 ('__mod__', 'x % y', 'x %= y'),
4432 ('__divmod__', 'divmod(x, y)', None),
4433 ('__pow__', 'x ** y', 'x **= y'),
4434 ('__lshift__', 'x << y', 'x <<= y'),
4435 ('__rshift__', 'x >> y', 'x >>= y'),
4436 ('__and__', 'x & y', 'x &= y'),
4437 ('__or__', 'x | y', 'x |= y'),
4438 ('__xor__', 'x ^ y', 'x ^= y'),
4439 ('__coerce__', 'coerce(x, y)', None)]:
4440 if name == '__coerce__':
4441 rname = name
4442 else:
4443 rname = '__r' + name[2:]
4444 A = metaclass('A', (), {name: specialmethod})
4445 B = metaclass('B', (), {rname: specialmethod})
4446 a = A()
4447 b = B()
4448 check(expr, a, a)
4449 check(expr, a, b)
4450 check(expr, b, a)
4451 check(expr, b, b)
4452 check(expr, a, N1)
4453 check(expr, a, N2)
4454 check(expr, N1, b)
4455 check(expr, N2, b)
4456 if iexpr:
4457 check(iexpr, a, a)
4458 check(iexpr, a, b)
4459 check(iexpr, b, a)
4460 check(iexpr, b, b)
4461 check(iexpr, a, N1)
4462 check(iexpr, a, N2)
4463 iname = '__i' + name[2:]
4464 C = metaclass('C', (), {iname: specialmethod})
4465 c = C()
4466 check(iexpr, c, a)
4467 check(iexpr, c, b)
4468 check(iexpr, c, N1)
4469 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004470
Georg Brandl48545522008-02-02 10:12:36 +00004471 def test_assign_slice(self):
4472 # ceval.c's assign_slice used to check for
4473 # tp->tp_as_sequence->sq_slice instead of
4474 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004475
Georg Brandl48545522008-02-02 10:12:36 +00004476 class C(object):
4477 def __setslice__(self, start, stop, value):
4478 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004479
Georg Brandl48545522008-02-02 10:12:36 +00004480 c = C()
4481 c[1:2] = 3
4482 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004483
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004484 def test_set_and_no_get(self):
4485 # See
4486 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4487 class Descr(object):
4488
4489 def __init__(self, name):
4490 self.name = name
4491
4492 def __set__(self, obj, value):
4493 obj.__dict__[self.name] = value
4494 descr = Descr("a")
4495
4496 class X(object):
4497 a = descr
4498
4499 x = X()
4500 self.assertIs(x.a, descr)
4501 x.a = 42
4502 self.assertEqual(x.a, 42)
4503
Benjamin Peterson42d59472010-02-06 20:14:10 +00004504 # Also check type_getattro for correctness.
4505 class Meta(type):
4506 pass
4507 class X(object):
4508 __metaclass__ = Meta
4509 X.a = 42
4510 Meta.a = Descr("a")
4511 self.assertEqual(X.a, 42)
4512
Benjamin Peterson273c2332008-11-17 22:39:09 +00004513 def test_getattr_hooks(self):
4514 # issue 4230
4515
4516 class Descriptor(object):
4517 counter = 0
4518 def __get__(self, obj, objtype=None):
4519 def getter(name):
4520 self.counter += 1
4521 raise AttributeError(name)
4522 return getter
4523
4524 descr = Descriptor()
4525 class A(object):
4526 __getattribute__ = descr
4527 class B(object):
4528 __getattr__ = descr
4529 class C(object):
4530 __getattribute__ = descr
4531 __getattr__ = descr
4532
4533 self.assertRaises(AttributeError, getattr, A(), "attr")
4534 self.assertEquals(descr.counter, 1)
4535 self.assertRaises(AttributeError, getattr, B(), "attr")
4536 self.assertEquals(descr.counter, 2)
4537 self.assertRaises(AttributeError, getattr, C(), "attr")
4538 self.assertEquals(descr.counter, 4)
4539
4540 import gc
4541 class EvilGetattribute(object):
4542 # This used to segfault
4543 def __getattr__(self, name):
4544 raise AttributeError(name)
4545 def __getattribute__(self, name):
4546 del EvilGetattribute.__getattr__
4547 for i in range(5):
4548 gc.collect()
4549 raise AttributeError(name)
4550
4551 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4552
Guido van Rossum9acc3872008-01-23 23:23:43 +00004553
Georg Brandl48545522008-02-02 10:12:36 +00004554class DictProxyTests(unittest.TestCase):
4555 def setUp(self):
4556 class C(object):
4557 def meth(self):
4558 pass
4559 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004560
Georg Brandl48545522008-02-02 10:12:36 +00004561 def test_iter_keys(self):
4562 # Testing dict-proxy iterkeys...
4563 keys = [ key for key in self.C.__dict__.iterkeys() ]
4564 keys.sort()
4565 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4566 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004567
Georg Brandl48545522008-02-02 10:12:36 +00004568 def test_iter_values(self):
4569 # Testing dict-proxy itervalues...
4570 values = [ values for values in self.C.__dict__.itervalues() ]
4571 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004572
Georg Brandl48545522008-02-02 10:12:36 +00004573 def test_iter_items(self):
4574 # Testing dict-proxy iteritems...
4575 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4576 keys.sort()
4577 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4578 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004579
Georg Brandl48545522008-02-02 10:12:36 +00004580 def test_dict_type_with_metaclass(self):
4581 # Testing type of __dict__ when __metaclass__ set...
4582 class B(object):
4583 pass
4584 class M(type):
4585 pass
4586 class C:
4587 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4588 __metaclass__ = M
4589 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004590
Guido van Rossum9acc3872008-01-23 23:23:43 +00004591
Georg Brandl48545522008-02-02 10:12:36 +00004592class PTypesLongInitTest(unittest.TestCase):
4593 # This is in its own TestCase so that it can be run before any other tests.
4594 def test_pytype_long_ready(self):
4595 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004596
Georg Brandl48545522008-02-02 10:12:36 +00004597 # This dumps core when SF bug 551412 isn't fixed --
4598 # but only when test_descr.py is run separately.
4599 # (That can't be helped -- as soon as PyType_Ready()
4600 # is called for PyLong_Type, the bug is gone.)
4601 class UserLong(object):
4602 def __pow__(self, *args):
4603 pass
4604 try:
4605 pow(0L, UserLong(), 0L)
4606 except:
4607 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004608
Georg Brandl48545522008-02-02 10:12:36 +00004609 # Another segfault only when run early
4610 # (before PyType_Ready(tuple) is called)
4611 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004612
4613
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004614def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004615 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4616 DeprecationWarning)]
4617 if sys.py3kwarning:
4618 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004619 ("classic (int|long) division", DeprecationWarning),
4620 ("coerce.. not supported", DeprecationWarning),
4621 ("Overriding __cmp__ ", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004622 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4623 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004624 # Run all local test cases, with PTypesLongInitTest first.
4625 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4626 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004628if __name__ == "__main__":
4629 test_main()