blob: 28dfbffe2d881aab8a8744c97e87c0cb7ca41a10 [file] [log] [blame]
Benjamin Petersond4d400c2009-04-18 20:12:47 +00001import __builtin__
Benjamin Petersona8d45852012-03-07 18:41:11 -06002import gc
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00003import sys
Armin Rigo9790a272007-05-02 19:23:31 +00004import types
Georg Brandl48545522008-02-02 10:12:36 +00005import unittest
Benjamin Petersona8d45852012-03-07 18:41:11 -06006import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +00007
Georg Brandl48545522008-02-02 10:12:36 +00008from copy import deepcopy
9from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Guido van Rossum875eeaa2001-10-11 18:33:53 +000011
Georg Brandl48545522008-02-02 10:12:36 +000012class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000013
Georg Brandl48545522008-02-02 10:12:36 +000014 def __init__(self, *args, **kwargs):
15 unittest.TestCase.__init__(self, *args, **kwargs)
16 self.binops = {
17 'add': '+',
18 'sub': '-',
19 'mul': '*',
20 'div': '/',
21 'divmod': 'divmod',
22 'pow': '**',
23 'lshift': '<<',
24 'rshift': '>>',
25 'and': '&',
26 'xor': '^',
27 'or': '|',
28 'cmp': 'cmp',
29 'lt': '<',
30 'le': '<=',
31 'eq': '==',
32 'ne': '!=',
33 'gt': '>',
34 'ge': '>=',
35 }
Tim Peters3caca232001-12-06 06:23:26 +000036
Georg Brandl48545522008-02-02 10:12:36 +000037 for name, expr in self.binops.items():
38 if expr.islower():
39 expr = expr + "(a, b)"
40 else:
41 expr = 'a %s b' % expr
42 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000043
Georg Brandl48545522008-02-02 10:12:36 +000044 self.unops = {
45 'pos': '+',
46 'neg': '-',
47 'abs': 'abs',
48 'invert': '~',
49 'int': 'int',
50 'long': 'long',
51 'float': 'float',
52 'oct': 'oct',
53 'hex': 'hex',
54 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000055
Georg Brandl48545522008-02-02 10:12:36 +000056 for name, expr in self.unops.items():
57 if expr.islower():
58 expr = expr + "(a)"
59 else:
60 expr = '%s a' % expr
61 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000062
Georg Brandl48545522008-02-02 10:12:36 +000063 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
64 d = {'a': a}
65 self.assertEqual(eval(expr, d), res)
66 t = type(a)
67 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000068
Georg Brandl48545522008-02-02 10:12:36 +000069 # Find method in parent class
70 while meth not in t.__dict__:
71 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000072 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
73 # method object; the getattr() below obtains its underlying function.
74 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000075 self.assertEqual(m(a), res)
76 bm = getattr(a, meth)
77 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000078
Georg Brandl48545522008-02-02 10:12:36 +000079 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
80 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000081
Georg Brandl48545522008-02-02 10:12:36 +000082 # XXX Hack so this passes before 2.3 when -Qnew is specified.
83 if meth == "__div__" and 1/2 == 0.5:
84 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl48545522008-02-02 10:12:36 +000086 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000087
Georg Brandl48545522008-02-02 10:12:36 +000088 self.assertEqual(eval(expr, d), res)
89 t = type(a)
90 m = getattr(t, meth)
91 while meth not in t.__dict__:
92 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000093 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
94 # method object; the getattr() below obtains its underlying function.
95 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000096 self.assertEqual(m(a, b), res)
97 bm = getattr(a, meth)
98 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000099
Georg Brandl48545522008-02-02 10:12:36 +0000100 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
101 d = {'a': a, 'b': b, 'c': c}
102 self.assertEqual(eval(expr, d), res)
103 t = type(a)
104 m = getattr(t, meth)
105 while meth not in t.__dict__:
106 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000107 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
108 # method object; the getattr() below obtains its underlying function.
109 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000110 self.assertEqual(m(a, b, c), res)
111 bm = getattr(a, meth)
112 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000113
Georg Brandl48545522008-02-02 10:12:36 +0000114 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
115 d = {'a': deepcopy(a), 'b': b}
116 exec stmt in d
117 self.assertEqual(d['a'], res)
118 t = type(a)
119 m = getattr(t, meth)
120 while meth not in t.__dict__:
121 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000122 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
123 # method object; the getattr() below obtains its underlying function.
124 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000125 d['a'] = deepcopy(a)
126 m(d['a'], b)
127 self.assertEqual(d['a'], res)
128 d['a'] = deepcopy(a)
129 bm = getattr(d['a'], meth)
130 bm(b)
131 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000132
Georg Brandl48545522008-02-02 10:12:36 +0000133 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
134 d = {'a': deepcopy(a), 'b': b, 'c': c}
135 exec stmt in d
136 self.assertEqual(d['a'], res)
137 t = type(a)
138 m = getattr(t, meth)
139 while meth not in t.__dict__:
140 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000141 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
142 # method object; the getattr() below obtains its underlying function.
143 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000144 d['a'] = deepcopy(a)
145 m(d['a'], b, c)
146 self.assertEqual(d['a'], res)
147 d['a'] = deepcopy(a)
148 bm = getattr(d['a'], meth)
149 bm(b, c)
150 self.assertEqual(d['a'], res)
151
152 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
153 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
154 exec stmt in dictionary
155 self.assertEqual(dictionary['a'], res)
156 t = type(a)
157 while meth not in t.__dict__:
158 t = t.__bases__[0]
159 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000160 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
161 # method object; the getattr() below obtains its underlying function.
162 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000163 dictionary['a'] = deepcopy(a)
164 m(dictionary['a'], b, c, d)
165 self.assertEqual(dictionary['a'], res)
166 dictionary['a'] = deepcopy(a)
167 bm = getattr(dictionary['a'], meth)
168 bm(b, c, d)
169 self.assertEqual(dictionary['a'], res)
170
171 def test_lists(self):
172 # Testing list operations...
173 # Asserts are within individual test methods
174 self.binop_test([1], [2], [1,2], "a+b", "__add__")
175 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
176 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
177 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
178 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
179 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
180 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
181 self.unop_test([1,2,3], 3, "len(a)", "__len__")
182 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
183 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
184 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
185 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
186 "__setslice__")
187
188 def test_dicts(self):
189 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000190 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
191 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
192 else:
193 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000194 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
195 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
196 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
197
198 d = {1:2, 3:4}
199 l1 = []
200 for i in d.keys():
201 l1.append(i)
202 l = []
203 for i in iter(d):
204 l.append(i)
205 self.assertEqual(l, l1)
206 l = []
207 for i in d.__iter__():
208 l.append(i)
209 self.assertEqual(l, l1)
210 l = []
211 for i in dict.__iter__(d):
212 l.append(i)
213 self.assertEqual(l, l1)
214 d = {1:2, 3:4}
215 self.unop_test(d, 2, "len(a)", "__len__")
216 self.assertEqual(eval(repr(d), {}), d)
217 self.assertEqual(eval(d.__repr__(), {}), d)
218 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
219 "__setitem__")
220
221 # Tests for unary and binary operators
222 def number_operators(self, a, b, skip=[]):
223 dict = {'a': a, 'b': b}
224
225 for name, expr in self.binops.items():
226 if name not in skip:
227 name = "__%s__" % name
228 if hasattr(a, name):
229 res = eval(expr, dict)
230 self.binop_test(a, b, res, expr, name)
231
232 for name, expr in self.unops.items():
233 if name not in skip:
234 name = "__%s__" % name
235 if hasattr(a, name):
236 res = eval(expr, dict)
237 self.unop_test(a, res, expr, name)
238
239 def test_ints(self):
240 # Testing int operations...
241 self.number_operators(100, 3)
242 # The following crashes in Python 2.2
243 self.assertEqual((1).__nonzero__(), 1)
244 self.assertEqual((0).__nonzero__(), 0)
245 # This returns 'NotImplemented' in Python 2.2
246 class C(int):
247 def __add__(self, other):
248 return NotImplemented
249 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000250 try:
Georg Brandl48545522008-02-02 10:12:36 +0000251 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000252 except TypeError:
253 pass
254 else:
Georg Brandl48545522008-02-02 10:12:36 +0000255 self.fail("NotImplemented should have caused TypeError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000256 try:
Georg Brandl48545522008-02-02 10:12:36 +0000257 C(sys.maxint+1)
258 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000259 pass
260 else:
Georg Brandl48545522008-02-02 10:12:36 +0000261 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000262
Georg Brandl48545522008-02-02 10:12:36 +0000263 def test_longs(self):
264 # Testing long operations...
265 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000266
Georg Brandl48545522008-02-02 10:12:36 +0000267 def test_floats(self):
268 # Testing float operations...
269 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000270
Georg Brandl48545522008-02-02 10:12:36 +0000271 def test_complexes(self):
272 # Testing complex operations...
273 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
274 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275
Georg Brandl48545522008-02-02 10:12:36 +0000276 class Number(complex):
277 __slots__ = ['prec']
278 def __new__(cls, *args, **kwds):
279 result = complex.__new__(cls, *args)
280 result.prec = kwds.get('prec', 12)
281 return result
282 def __repr__(self):
283 prec = self.prec
284 if self.imag == 0.0:
285 return "%.*g" % (prec, self.real)
286 if self.real == 0.0:
287 return "%.*gj" % (prec, self.imag)
288 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
289 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000290
Georg Brandl48545522008-02-02 10:12:36 +0000291 a = Number(3.14, prec=6)
292 self.assertEqual(repr(a), "3.14")
293 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000294
Georg Brandl48545522008-02-02 10:12:36 +0000295 a = Number(a, prec=2)
296 self.assertEqual(repr(a), "3.1")
297 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000298
Georg Brandl48545522008-02-02 10:12:36 +0000299 a = Number(234.5)
300 self.assertEqual(repr(a), "234.5")
301 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000302
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000303 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000304 def test_spam_lists(self):
305 # Testing spamlist operations...
306 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000307
Georg Brandl48545522008-02-02 10:12:36 +0000308 def spamlist(l, memo=None):
309 import xxsubtype as spam
310 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000311
Georg Brandl48545522008-02-02 10:12:36 +0000312 # This is an ugly hack:
313 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000314
Georg Brandl48545522008-02-02 10:12:36 +0000315 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
316 "__add__")
317 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
318 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
319 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
320 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
321 "__getslice__")
322 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
323 "__iadd__")
324 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
325 "__imul__")
326 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
327 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
328 "__mul__")
329 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
330 "__rmul__")
331 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
332 "__setitem__")
333 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
334 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
335 # Test subclassing
336 class C(spam.spamlist):
337 def foo(self): return 1
338 a = C()
339 self.assertEqual(a, [])
340 self.assertEqual(a.foo(), 1)
341 a.append(100)
342 self.assertEqual(a, [100])
343 self.assertEqual(a.getstate(), 0)
344 a.setstate(42)
345 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000346
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000347 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000348 def test_spam_dicts(self):
349 # Testing spamdict operations...
350 import copy, xxsubtype as spam
351 def spamdict(d, memo=None):
352 import xxsubtype as spam
353 sd = spam.spamdict()
354 for k, v in d.items():
355 sd[k] = v
356 return sd
357 # This is an ugly hack:
358 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000359
Georg Brandl48545522008-02-02 10:12:36 +0000360 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
361 "__cmp__")
362 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
363 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
364 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
365 d = spamdict({1:2,3:4})
366 l1 = []
367 for i in d.keys():
368 l1.append(i)
369 l = []
370 for i in iter(d):
371 l.append(i)
372 self.assertEqual(l, l1)
373 l = []
374 for i in d.__iter__():
375 l.append(i)
376 self.assertEqual(l, l1)
377 l = []
378 for i in type(spamdict({})).__iter__(d):
379 l.append(i)
380 self.assertEqual(l, l1)
381 straightd = {1:2, 3:4}
382 spamd = spamdict(straightd)
383 self.unop_test(spamd, 2, "len(a)", "__len__")
384 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
385 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
386 "a[b]=c", "__setitem__")
387 # Test subclassing
388 class C(spam.spamdict):
389 def foo(self): return 1
390 a = C()
391 self.assertEqual(a.items(), [])
392 self.assertEqual(a.foo(), 1)
393 a['foo'] = 'bar'
394 self.assertEqual(a.items(), [('foo', 'bar')])
395 self.assertEqual(a.getstate(), 0)
396 a.setstate(100)
397 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000398
Georg Brandl48545522008-02-02 10:12:36 +0000399class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000400
Georg Brandl48545522008-02-02 10:12:36 +0000401 def test_python_dicts(self):
402 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000403 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000404 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000405 d = dict()
406 self.assertEqual(d, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000407 self.assertTrue(d.__class__ is dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000408 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000409 class C(dict):
410 state = -1
411 def __init__(self_local, *a, **kw):
412 if a:
413 self.assertEqual(len(a), 1)
414 self_local.state = a[0]
415 if kw:
416 for k, v in kw.items():
417 self_local[v] = k
418 def __getitem__(self, key):
419 return self.get(key, 0)
420 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000421 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000422 dict.__setitem__(self_local, key, value)
423 def setstate(self, state):
424 self.state = state
425 def getstate(self):
426 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000427 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000428 a1 = C(12)
429 self.assertEqual(a1.state, 12)
430 a2 = C(foo=1, bar=2)
431 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
432 a = C()
433 self.assertEqual(a.state, -1)
434 self.assertEqual(a.getstate(), -1)
435 a.setstate(0)
436 self.assertEqual(a.state, 0)
437 self.assertEqual(a.getstate(), 0)
438 a.setstate(10)
439 self.assertEqual(a.state, 10)
440 self.assertEqual(a.getstate(), 10)
441 self.assertEqual(a[42], 0)
442 a[42] = 24
443 self.assertEqual(a[42], 24)
444 N = 50
445 for i in range(N):
446 a[i] = C()
447 for j in range(N):
448 a[i][j] = i*j
449 for i in range(N):
450 for j in range(N):
451 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000452
Georg Brandl48545522008-02-02 10:12:36 +0000453 def test_python_lists(self):
454 # Testing Python subclass of list...
455 class C(list):
456 def __getitem__(self, i):
457 return list.__getitem__(self, i) + 100
458 def __getslice__(self, i, j):
459 return (i, j)
460 a = C()
461 a.extend([0,1,2])
462 self.assertEqual(a[0], 100)
463 self.assertEqual(a[1], 101)
464 self.assertEqual(a[2], 102)
465 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000466
Georg Brandl48545522008-02-02 10:12:36 +0000467 def test_metaclass(self):
468 # Testing __metaclass__...
469 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000470 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000471 def __init__(self):
472 self.__state = 0
473 def getstate(self):
474 return self.__state
475 def setstate(self, state):
476 self.__state = state
477 a = C()
478 self.assertEqual(a.getstate(), 0)
479 a.setstate(10)
480 self.assertEqual(a.getstate(), 10)
481 class D:
482 class __metaclass__(type):
483 def myself(cls): return cls
484 self.assertEqual(D.myself(), D)
485 d = D()
486 self.assertEqual(d.__class__, D)
487 class M1(type):
488 def __new__(cls, name, bases, dict):
489 dict['__spam__'] = 1
490 return type.__new__(cls, name, bases, dict)
491 class C:
492 __metaclass__ = M1
493 self.assertEqual(C.__spam__, 1)
494 c = C()
495 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000496
Georg Brandl48545522008-02-02 10:12:36 +0000497 class _instance(object):
498 pass
499 class M2(object):
500 @staticmethod
501 def __new__(cls, name, bases, dict):
502 self = object.__new__(cls)
503 self.name = name
504 self.bases = bases
505 self.dict = dict
506 return self
507 def __call__(self):
508 it = _instance()
509 # Early binding of methods
510 for key in self.dict:
511 if key.startswith("__"):
512 continue
513 setattr(it, key, self.dict[key].__get__(it, self))
514 return it
515 class C:
516 __metaclass__ = M2
517 def spam(self):
518 return 42
519 self.assertEqual(C.name, 'C')
520 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000521 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000522 c = C()
523 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000524
Georg Brandl48545522008-02-02 10:12:36 +0000525 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000526
Georg Brandl48545522008-02-02 10:12:36 +0000527 class autosuper(type):
528 # Automatically add __super to the class
529 # This trick only works for dynamic classes
530 def __new__(metaclass, name, bases, dict):
531 cls = super(autosuper, metaclass).__new__(metaclass,
532 name, bases, dict)
533 # Name mangling for __super removes leading underscores
534 while name[:1] == "_":
535 name = name[1:]
536 if name:
537 name = "_%s__super" % name
538 else:
539 name = "__super"
540 setattr(cls, name, super(cls))
541 return cls
542 class A:
543 __metaclass__ = autosuper
544 def meth(self):
545 return "A"
546 class B(A):
547 def meth(self):
548 return "B" + self.__super.meth()
549 class C(A):
550 def meth(self):
551 return "C" + self.__super.meth()
552 class D(C, B):
553 def meth(self):
554 return "D" + self.__super.meth()
555 self.assertEqual(D().meth(), "DCBA")
556 class E(B, C):
557 def meth(self):
558 return "E" + self.__super.meth()
559 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000560
Georg Brandl48545522008-02-02 10:12:36 +0000561 class autoproperty(type):
562 # Automatically create property attributes when methods
563 # named _get_x and/or _set_x are found
564 def __new__(metaclass, name, bases, dict):
565 hits = {}
566 for key, val in dict.iteritems():
567 if key.startswith("_get_"):
568 key = key[5:]
569 get, set = hits.get(key, (None, None))
570 get = val
571 hits[key] = get, set
572 elif key.startswith("_set_"):
573 key = key[5:]
574 get, set = hits.get(key, (None, None))
575 set = val
576 hits[key] = get, set
577 for key, (get, set) in hits.iteritems():
578 dict[key] = property(get, set)
579 return super(autoproperty, metaclass).__new__(metaclass,
580 name, bases, dict)
581 class A:
582 __metaclass__ = autoproperty
583 def _get_x(self):
584 return -self.__x
585 def _set_x(self, x):
586 self.__x = -x
587 a = A()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000588 self.assertTrue(not hasattr(a, "x"))
Georg Brandl48545522008-02-02 10:12:36 +0000589 a.x = 12
590 self.assertEqual(a.x, 12)
591 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000592
Georg Brandl48545522008-02-02 10:12:36 +0000593 class multimetaclass(autoproperty, autosuper):
594 # Merge of multiple cooperating metaclasses
595 pass
596 class A:
597 __metaclass__ = multimetaclass
598 def _get_x(self):
599 return "A"
600 class B(A):
601 def _get_x(self):
602 return "B" + self.__super._get_x()
603 class C(A):
604 def _get_x(self):
605 return "C" + self.__super._get_x()
606 class D(C, B):
607 def _get_x(self):
608 return "D" + self.__super._get_x()
609 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000610
Georg Brandl48545522008-02-02 10:12:36 +0000611 # Make sure type(x) doesn't call x.__class__.__init__
612 class T(type):
613 counter = 0
614 def __init__(self, *args):
615 T.counter += 1
616 class C:
617 __metaclass__ = T
618 self.assertEqual(T.counter, 1)
619 a = C()
620 self.assertEqual(type(a), C)
621 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000622
Georg Brandl48545522008-02-02 10:12:36 +0000623 class C(object): pass
624 c = C()
625 try: c()
626 except TypeError: pass
627 else: self.fail("calling object w/o call method should raise "
628 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000629
Georg Brandl48545522008-02-02 10:12:36 +0000630 # Testing code to find most derived baseclass
631 class A(type):
632 def __new__(*args, **kwargs):
633 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000634
Georg Brandl48545522008-02-02 10:12:36 +0000635 class B(object):
636 pass
637
638 class C(object):
639 __metaclass__ = A
640
641 # The most derived metaclass of D is A rather than type.
642 class D(B, C):
643 pass
644
645 def test_module_subclasses(self):
646 # Testing Python subclass of module...
647 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000648 MT = type(sys)
649 class MM(MT):
650 def __init__(self, name):
651 MT.__init__(self, name)
652 def __getattribute__(self, name):
653 log.append(("getattr", name))
654 return MT.__getattribute__(self, name)
655 def __setattr__(self, name, value):
656 log.append(("setattr", name, value))
657 MT.__setattr__(self, name, value)
658 def __delattr__(self, name):
659 log.append(("delattr", name))
660 MT.__delattr__(self, name)
661 a = MM("a")
662 a.foo = 12
663 x = a.foo
664 del a.foo
665 self.assertEqual(log, [("setattr", "foo", 12),
666 ("getattr", "foo"),
667 ("delattr", "foo")])
668
669 # http://python.org/sf/1174712
670 try:
671 class Module(types.ModuleType, str):
672 pass
673 except TypeError:
674 pass
675 else:
676 self.fail("inheriting from ModuleType and str at the same time "
677 "should fail")
678
679 def test_multiple_inheritence(self):
680 # Testing multiple inheritance...
681 class C(object):
682 def __init__(self):
683 self.__state = 0
684 def getstate(self):
685 return self.__state
686 def setstate(self, state):
687 self.__state = state
688 a = C()
689 self.assertEqual(a.getstate(), 0)
690 a.setstate(10)
691 self.assertEqual(a.getstate(), 10)
692 class D(dict, C):
693 def __init__(self):
694 type({}).__init__(self)
695 C.__init__(self)
696 d = D()
697 self.assertEqual(d.keys(), [])
698 d["hello"] = "world"
699 self.assertEqual(d.items(), [("hello", "world")])
700 self.assertEqual(d["hello"], "world")
701 self.assertEqual(d.getstate(), 0)
702 d.setstate(10)
703 self.assertEqual(d.getstate(), 10)
704 self.assertEqual(D.__mro__, (D, dict, C, object))
705
706 # SF bug #442833
707 class Node(object):
708 def __int__(self):
709 return int(self.foo())
710 def foo(self):
711 return "23"
712 class Frag(Node, list):
713 def foo(self):
714 return "42"
715 self.assertEqual(Node().__int__(), 23)
716 self.assertEqual(int(Node()), 23)
717 self.assertEqual(Frag().__int__(), 42)
718 self.assertEqual(int(Frag()), 42)
719
720 # MI mixing classic and new-style classes.
721
722 class A:
723 x = 1
724
725 class B(A):
726 pass
727
728 class C(A):
729 x = 2
730
731 class D(B, C):
732 pass
733 self.assertEqual(D.x, 1)
734
735 # Classic MRO is preserved for a classic base class.
736 class E(D, object):
737 pass
738 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
739 self.assertEqual(E.x, 1)
740
741 # But with a mix of classic bases, their MROs are combined using
742 # new-style MRO.
743 class F(B, C, object):
744 pass
745 self.assertEqual(F.__mro__, (F, B, C, A, object))
746 self.assertEqual(F.x, 2)
747
748 # Try something else.
749 class C:
750 def cmethod(self):
751 return "C a"
752 def all_method(self):
753 return "C b"
754
755 class M1(C, object):
756 def m1method(self):
757 return "M1 a"
758 def all_method(self):
759 return "M1 b"
760
761 self.assertEqual(M1.__mro__, (M1, C, object))
762 m = M1()
763 self.assertEqual(m.cmethod(), "C a")
764 self.assertEqual(m.m1method(), "M1 a")
765 self.assertEqual(m.all_method(), "M1 b")
766
767 class D(C):
768 def dmethod(self):
769 return "D a"
770 def all_method(self):
771 return "D b"
772
773 class M2(D, object):
774 def m2method(self):
775 return "M2 a"
776 def all_method(self):
777 return "M2 b"
778
779 self.assertEqual(M2.__mro__, (M2, D, C, object))
780 m = M2()
781 self.assertEqual(m.cmethod(), "C a")
782 self.assertEqual(m.dmethod(), "D a")
783 self.assertEqual(m.m2method(), "M2 a")
784 self.assertEqual(m.all_method(), "M2 b")
785
786 class M3(M1, M2, object):
787 def m3method(self):
788 return "M3 a"
789 def all_method(self):
790 return "M3 b"
791 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
792 m = M3()
793 self.assertEqual(m.cmethod(), "C a")
794 self.assertEqual(m.dmethod(), "D a")
795 self.assertEqual(m.m1method(), "M1 a")
796 self.assertEqual(m.m2method(), "M2 a")
797 self.assertEqual(m.m3method(), "M3 a")
798 self.assertEqual(m.all_method(), "M3 b")
799
800 class Classic:
801 pass
802 try:
803 class New(Classic):
804 __metaclass__ = type
805 except TypeError:
806 pass
807 else:
808 self.fail("new class with only classic bases - shouldn't be")
809
810 def test_diamond_inheritence(self):
811 # Testing multiple inheritance special cases...
812 class A(object):
813 def spam(self): return "A"
814 self.assertEqual(A().spam(), "A")
815 class B(A):
816 def boo(self): return "B"
817 def spam(self): return "B"
818 self.assertEqual(B().spam(), "B")
819 self.assertEqual(B().boo(), "B")
820 class C(A):
821 def boo(self): return "C"
822 self.assertEqual(C().spam(), "A")
823 self.assertEqual(C().boo(), "C")
824 class D(B, C): pass
825 self.assertEqual(D().spam(), "B")
826 self.assertEqual(D().boo(), "B")
827 self.assertEqual(D.__mro__, (D, B, C, A, object))
828 class E(C, B): pass
829 self.assertEqual(E().spam(), "B")
830 self.assertEqual(E().boo(), "C")
831 self.assertEqual(E.__mro__, (E, C, B, A, object))
832 # MRO order disagreement
833 try:
834 class F(D, E): pass
835 except TypeError:
836 pass
837 else:
838 self.fail("expected MRO order disagreement (F)")
839 try:
840 class G(E, D): pass
841 except TypeError:
842 pass
843 else:
844 self.fail("expected MRO order disagreement (G)")
845
846 # see thread python-dev/2002-October/029035.html
847 def test_ex5_from_c3_switch(self):
848 # Testing ex5 from C3 switch discussion...
849 class A(object): pass
850 class B(object): pass
851 class C(object): pass
852 class X(A): pass
853 class Y(A): pass
854 class Z(X,B,Y,C): pass
855 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
856
857 # see "A Monotonic Superclass Linearization for Dylan",
858 # by Kim Barrett et al. (OOPSLA 1996)
859 def test_monotonicity(self):
860 # Testing MRO monotonicity...
861 class Boat(object): pass
862 class DayBoat(Boat): pass
863 class WheelBoat(Boat): pass
864 class EngineLess(DayBoat): pass
865 class SmallMultihull(DayBoat): pass
866 class PedalWheelBoat(EngineLess,WheelBoat): pass
867 class SmallCatamaran(SmallMultihull): pass
868 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
869
870 self.assertEqual(PedalWheelBoat.__mro__,
871 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
872 self.assertEqual(SmallCatamaran.__mro__,
873 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
874 self.assertEqual(Pedalo.__mro__,
875 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
876 SmallMultihull, DayBoat, WheelBoat, Boat, object))
877
878 # see "A Monotonic Superclass Linearization for Dylan",
879 # by Kim Barrett et al. (OOPSLA 1996)
880 def test_consistency_with_epg(self):
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200881 # Testing consistency with EPG...
Georg Brandl48545522008-02-02 10:12:36 +0000882 class Pane(object): pass
883 class ScrollingMixin(object): pass
884 class EditingMixin(object): pass
885 class ScrollablePane(Pane,ScrollingMixin): pass
886 class EditablePane(Pane,EditingMixin): pass
887 class EditableScrollablePane(ScrollablePane,EditablePane): pass
888
889 self.assertEqual(EditableScrollablePane.__mro__,
890 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
891 ScrollingMixin, EditingMixin, object))
892
893 def test_mro_disagreement(self):
894 # Testing error messages for MRO disagreement...
895 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000896order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000897
Georg Brandl48545522008-02-02 10:12:36 +0000898 def raises(exc, expected, callable, *args):
899 try:
900 callable(*args)
901 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000902 # the exact msg is generally considered an impl detail
903 if test_support.check_impl_detail():
904 if not str(msg).startswith(expected):
905 self.fail("Message %r, expected %r" %
906 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000907 else:
908 self.fail("Expected %s" % exc)
909
910 class A(object): pass
911 class B(A): pass
912 class C(object): pass
913
914 # Test some very simple errors
915 raises(TypeError, "duplicate base class A",
916 type, "X", (A, A), {})
917 raises(TypeError, mro_err_msg,
918 type, "X", (A, B), {})
919 raises(TypeError, mro_err_msg,
920 type, "X", (A, C, B), {})
921 # Test a slightly more complex error
922 class GridLayout(object): pass
923 class HorizontalGrid(GridLayout): pass
924 class VerticalGrid(GridLayout): pass
925 class HVGrid(HorizontalGrid, VerticalGrid): pass
926 class VHGrid(VerticalGrid, HorizontalGrid): pass
927 raises(TypeError, mro_err_msg,
928 type, "ConfusedGrid", (HVGrid, VHGrid), {})
929
930 def test_object_class(self):
931 # Testing object class...
932 a = object()
933 self.assertEqual(a.__class__, object)
934 self.assertEqual(type(a), object)
935 b = object()
936 self.assertNotEqual(a, b)
937 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000938 try:
Georg Brandl48545522008-02-02 10:12:36 +0000939 a.foo = 12
940 except (AttributeError, TypeError):
941 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000942 else:
Georg Brandl48545522008-02-02 10:12:36 +0000943 self.fail("object() should not allow setting a foo attribute")
944 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000945
Georg Brandl48545522008-02-02 10:12:36 +0000946 class Cdict(object):
947 pass
948 x = Cdict()
949 self.assertEqual(x.__dict__, {})
950 x.foo = 1
951 self.assertEqual(x.foo, 1)
952 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000953
Georg Brandl48545522008-02-02 10:12:36 +0000954 def test_slots(self):
955 # Testing __slots__...
956 class C0(object):
957 __slots__ = []
958 x = C0()
959 self.assertFalse(hasattr(x, "__dict__"))
960 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000961
Georg Brandl48545522008-02-02 10:12:36 +0000962 class C1(object):
963 __slots__ = ['a']
964 x = C1()
965 self.assertFalse(hasattr(x, "__dict__"))
966 self.assertFalse(hasattr(x, "a"))
967 x.a = 1
968 self.assertEqual(x.a, 1)
969 x.a = None
970 self.assertEqual(x.a, None)
971 del x.a
972 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000973
Georg Brandl48545522008-02-02 10:12:36 +0000974 class C3(object):
975 __slots__ = ['a', 'b', 'c']
976 x = C3()
977 self.assertFalse(hasattr(x, "__dict__"))
978 self.assertFalse(hasattr(x, 'a'))
979 self.assertFalse(hasattr(x, 'b'))
980 self.assertFalse(hasattr(x, 'c'))
981 x.a = 1
982 x.b = 2
983 x.c = 3
984 self.assertEqual(x.a, 1)
985 self.assertEqual(x.b, 2)
986 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000987
Georg Brandl48545522008-02-02 10:12:36 +0000988 class C4(object):
989 """Validate name mangling"""
990 __slots__ = ['__a']
991 def __init__(self, value):
992 self.__a = value
993 def get(self):
994 return self.__a
995 x = C4(5)
996 self.assertFalse(hasattr(x, '__dict__'))
997 self.assertFalse(hasattr(x, '__a'))
998 self.assertEqual(x.get(), 5)
999 try:
1000 x.__a = 6
1001 except AttributeError:
1002 pass
1003 else:
1004 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005
Georg Brandl48545522008-02-02 10:12:36 +00001006 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001007 try:
1008 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001009 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001010 except TypeError:
1011 pass
1012 else:
Georg Brandl48545522008-02-02 10:12:36 +00001013 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001014 try:
Georg Brandl48545522008-02-02 10:12:36 +00001015 class C(object):
1016 __slots__ = ["foo bar"]
1017 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001018 pass
Georg Brandl48545522008-02-02 10:12:36 +00001019 else:
1020 self.fail("['foo bar'] slots not caught")
1021 try:
1022 class C(object):
1023 __slots__ = ["foo\0bar"]
1024 except TypeError:
1025 pass
1026 else:
1027 self.fail("['foo\\0bar'] slots not caught")
1028 try:
1029 class C(object):
1030 __slots__ = ["1"]
1031 except TypeError:
1032 pass
1033 else:
1034 self.fail("['1'] slots not caught")
1035 try:
1036 class C(object):
1037 __slots__ = [""]
1038 except TypeError:
1039 pass
1040 else:
1041 self.fail("[''] slots not caught")
1042 class C(object):
1043 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1044 # XXX(nnorwitz): was there supposed to be something tested
1045 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001046
Georg Brandl48545522008-02-02 10:12:36 +00001047 # Test a single string is not expanded as a sequence.
1048 class C(object):
1049 __slots__ = "abc"
1050 c = C()
1051 c.abc = 5
1052 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001053
Georg Brandl48545522008-02-02 10:12:36 +00001054 # Test unicode slot names
1055 try:
1056 unicode
1057 except NameError:
1058 pass
1059 else:
1060 # Test a single unicode string is not expanded as a sequence.
1061 class C(object):
1062 __slots__ = unicode("abc")
1063 c = C()
1064 c.abc = 5
1065 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001066
Georg Brandl48545522008-02-02 10:12:36 +00001067 # _unicode_to_string used to modify slots in certain circumstances
1068 slots = (unicode("foo"), unicode("bar"))
1069 class C(object):
1070 __slots__ = slots
1071 x = C()
1072 x.foo = 5
1073 self.assertEqual(x.foo, 5)
1074 self.assertEqual(type(slots[0]), unicode)
1075 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001076 try:
Georg Brandl48545522008-02-02 10:12:36 +00001077 class C(object):
1078 __slots__ = [unichr(128)]
1079 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001080 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001081 else:
Georg Brandl48545522008-02-02 10:12:36 +00001082 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001083
Georg Brandl48545522008-02-02 10:12:36 +00001084 # Test leaks
1085 class Counted(object):
1086 counter = 0 # counts the number of instances alive
1087 def __init__(self):
1088 Counted.counter += 1
1089 def __del__(self):
1090 Counted.counter -= 1
1091 class C(object):
1092 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001093 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001094 x.a = Counted()
1095 x.b = Counted()
1096 x.c = Counted()
1097 self.assertEqual(Counted.counter, 3)
1098 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001099 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001100 self.assertEqual(Counted.counter, 0)
1101 class D(C):
1102 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001103 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001104 x.a = Counted()
1105 x.z = Counted()
1106 self.assertEqual(Counted.counter, 2)
1107 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001108 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001109 self.assertEqual(Counted.counter, 0)
1110 class E(D):
1111 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001112 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001113 x.a = Counted()
1114 x.z = Counted()
1115 x.e = Counted()
1116 self.assertEqual(Counted.counter, 3)
1117 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001118 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001119 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001120
Georg Brandl48545522008-02-02 10:12:36 +00001121 # Test cyclical leaks [SF bug 519621]
1122 class F(object):
1123 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001124 s = F()
1125 s.a = [Counted(), s]
1126 self.assertEqual(Counted.counter, 1)
1127 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001128 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001129 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001130
Georg Brandl48545522008-02-02 10:12:36 +00001131 # Test lookup leaks [SF bug 572567]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001132 if hasattr(gc, 'get_objects'):
1133 class G(object):
1134 def __cmp__(self, other):
1135 return 0
1136 __hash__ = None # Silence Py3k warning
1137 g = G()
1138 orig_objects = len(gc.get_objects())
1139 for i in xrange(10):
1140 g==g
1141 new_objects = len(gc.get_objects())
1142 self.assertEqual(orig_objects, new_objects)
1143
Georg Brandl48545522008-02-02 10:12:36 +00001144 class H(object):
1145 __slots__ = ['a', 'b']
1146 def __init__(self):
1147 self.a = 1
1148 self.b = 2
1149 def __del__(self_):
1150 self.assertEqual(self_.a, 1)
1151 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001152 with test_support.captured_output('stderr') as s:
1153 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001154 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001155 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001156
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001157 class X(object):
1158 __slots__ = "a"
1159 with self.assertRaises(AttributeError):
1160 del X().a
1161
Georg Brandl48545522008-02-02 10:12:36 +00001162 def test_slots_special(self):
1163 # Testing __dict__ and __weakref__ in __slots__...
1164 class D(object):
1165 __slots__ = ["__dict__"]
1166 a = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001167 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl48545522008-02-02 10:12:36 +00001168 self.assertFalse(hasattr(a, "__weakref__"))
1169 a.foo = 42
1170 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001171
Georg Brandl48545522008-02-02 10:12:36 +00001172 class W(object):
1173 __slots__ = ["__weakref__"]
1174 a = W()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001175 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001176 self.assertFalse(hasattr(a, "__dict__"))
1177 try:
1178 a.foo = 42
1179 except AttributeError:
1180 pass
1181 else:
1182 self.fail("shouldn't be allowed to set a.foo")
1183
1184 class C1(W, D):
1185 __slots__ = []
1186 a = C1()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001187 self.assertTrue(hasattr(a, "__dict__"))
1188 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001189 a.foo = 42
1190 self.assertEqual(a.__dict__, {"foo": 42})
1191
1192 class C2(D, W):
1193 __slots__ = []
1194 a = C2()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001195 self.assertTrue(hasattr(a, "__dict__"))
1196 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001197 a.foo = 42
1198 self.assertEqual(a.__dict__, {"foo": 42})
1199
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001200 def test_slots_descriptor(self):
1201 # Issue2115: slot descriptors did not correctly check
1202 # the type of the given object
1203 import abc
1204 class MyABC:
1205 __metaclass__ = abc.ABCMeta
1206 __slots__ = "a"
1207
1208 class Unrelated(object):
1209 pass
1210 MyABC.register(Unrelated)
1211
1212 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001213 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001214
1215 # This used to crash
1216 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1217
Benjamin Peterson4895af42009-12-13 16:36:53 +00001218 def test_metaclass_cmp(self):
1219 # See bug 7491.
1220 class M(type):
1221 def __cmp__(self, other):
1222 return -1
1223 class X(object):
1224 __metaclass__ = M
1225 self.assertTrue(X < M)
1226
Georg Brandl48545522008-02-02 10:12:36 +00001227 def test_dynamics(self):
1228 # Testing class attribute propagation...
1229 class D(object):
1230 pass
1231 class E(D):
1232 pass
1233 class F(D):
1234 pass
1235 D.foo = 1
1236 self.assertEqual(D.foo, 1)
1237 # Test that dynamic attributes are inherited
1238 self.assertEqual(E.foo, 1)
1239 self.assertEqual(F.foo, 1)
1240 # Test dynamic instances
1241 class C(object):
1242 pass
1243 a = C()
1244 self.assertFalse(hasattr(a, "foobar"))
1245 C.foobar = 2
1246 self.assertEqual(a.foobar, 2)
1247 C.method = lambda self: 42
1248 self.assertEqual(a.method(), 42)
1249 C.__repr__ = lambda self: "C()"
1250 self.assertEqual(repr(a), "C()")
1251 C.__int__ = lambda self: 100
1252 self.assertEqual(int(a), 100)
1253 self.assertEqual(a.foobar, 2)
1254 self.assertFalse(hasattr(a, "spam"))
1255 def mygetattr(self, name):
1256 if name == "spam":
1257 return "spam"
1258 raise AttributeError
1259 C.__getattr__ = mygetattr
1260 self.assertEqual(a.spam, "spam")
1261 a.new = 12
1262 self.assertEqual(a.new, 12)
1263 def mysetattr(self, name, value):
1264 if name == "spam":
1265 raise AttributeError
1266 return object.__setattr__(self, name, value)
1267 C.__setattr__ = mysetattr
1268 try:
1269 a.spam = "not spam"
1270 except AttributeError:
1271 pass
1272 else:
1273 self.fail("expected AttributeError")
1274 self.assertEqual(a.spam, "spam")
1275 class D(C):
1276 pass
1277 d = D()
1278 d.foo = 1
1279 self.assertEqual(d.foo, 1)
1280
1281 # Test handling of int*seq and seq*int
1282 class I(int):
1283 pass
1284 self.assertEqual("a"*I(2), "aa")
1285 self.assertEqual(I(2)*"a", "aa")
1286 self.assertEqual(2*I(3), 6)
1287 self.assertEqual(I(3)*2, 6)
1288 self.assertEqual(I(3)*I(2), 6)
1289
1290 # Test handling of long*seq and seq*long
1291 class L(long):
1292 pass
1293 self.assertEqual("a"*L(2L), "aa")
1294 self.assertEqual(L(2L)*"a", "aa")
1295 self.assertEqual(2*L(3), 6)
1296 self.assertEqual(L(3)*2, 6)
1297 self.assertEqual(L(3)*L(2), 6)
1298
1299 # Test comparison of classes with dynamic metaclasses
1300 class dynamicmetaclass(type):
1301 pass
1302 class someclass:
1303 __metaclass__ = dynamicmetaclass
1304 self.assertNotEqual(someclass, object)
1305
1306 def test_errors(self):
1307 # Testing errors...
1308 try:
1309 class C(list, dict):
1310 pass
1311 except TypeError:
1312 pass
1313 else:
1314 self.fail("inheritance from both list and dict should be illegal")
1315
1316 try:
1317 class C(object, None):
1318 pass
1319 except TypeError:
1320 pass
1321 else:
1322 self.fail("inheritance from non-type should be illegal")
1323 class Classic:
1324 pass
1325
1326 try:
1327 class C(type(len)):
1328 pass
1329 except TypeError:
1330 pass
1331 else:
1332 self.fail("inheritance from CFunction should be illegal")
1333
1334 try:
1335 class C(object):
1336 __slots__ = 1
1337 except TypeError:
1338 pass
1339 else:
1340 self.fail("__slots__ = 1 should be illegal")
1341
1342 try:
1343 class C(object):
1344 __slots__ = [1]
1345 except TypeError:
1346 pass
1347 else:
1348 self.fail("__slots__ = [1] should be illegal")
1349
1350 class M1(type):
1351 pass
1352 class M2(type):
1353 pass
1354 class A1(object):
1355 __metaclass__ = M1
1356 class A2(object):
1357 __metaclass__ = M2
1358 try:
1359 class B(A1, A2):
1360 pass
1361 except TypeError:
1362 pass
1363 else:
1364 self.fail("finding the most derived metaclass should have failed")
1365
1366 def test_classmethods(self):
1367 # Testing class methods...
1368 class C(object):
1369 def foo(*a): return a
1370 goo = classmethod(foo)
1371 c = C()
1372 self.assertEqual(C.goo(1), (C, 1))
1373 self.assertEqual(c.goo(1), (C, 1))
1374 self.assertEqual(c.foo(1), (c, 1))
1375 class D(C):
1376 pass
1377 d = D()
1378 self.assertEqual(D.goo(1), (D, 1))
1379 self.assertEqual(d.goo(1), (D, 1))
1380 self.assertEqual(d.foo(1), (d, 1))
1381 self.assertEqual(D.foo(d, 1), (d, 1))
1382 # Test for a specific crash (SF bug 528132)
1383 def f(cls, arg): return (cls, arg)
1384 ff = classmethod(f)
1385 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1386 self.assertEqual(ff.__get__(0)(42), (int, 42))
1387
1388 # Test super() with classmethods (SF bug 535444)
1389 self.assertEqual(C.goo.im_self, C)
1390 self.assertEqual(D.goo.im_self, D)
1391 self.assertEqual(super(D,D).goo.im_self, D)
1392 self.assertEqual(super(D,d).goo.im_self, D)
1393 self.assertEqual(super(D,D).goo(), (D,))
1394 self.assertEqual(super(D,d).goo(), (D,))
1395
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001396 # Verify that a non-callable will raise
1397 meth = classmethod(1).__get__(1)
1398 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001399
1400 # Verify that classmethod() doesn't allow keyword args
1401 try:
1402 classmethod(f, kw=1)
1403 except TypeError:
1404 pass
1405 else:
1406 self.fail("classmethod shouldn't accept keyword args")
1407
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001408 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001409 def test_classmethods_in_c(self):
1410 # Testing C-based class methods...
1411 import xxsubtype as spam
1412 a = (1, 2, 3)
1413 d = {'abc': 123}
1414 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1415 self.assertEqual(x, spam.spamlist)
1416 self.assertEqual(a, a1)
1417 self.assertEqual(d, d1)
1418 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1419 self.assertEqual(x, spam.spamlist)
1420 self.assertEqual(a, a1)
1421 self.assertEqual(d, d1)
1422
1423 def test_staticmethods(self):
1424 # Testing static methods...
1425 class C(object):
1426 def foo(*a): return a
1427 goo = staticmethod(foo)
1428 c = C()
1429 self.assertEqual(C.goo(1), (1,))
1430 self.assertEqual(c.goo(1), (1,))
1431 self.assertEqual(c.foo(1), (c, 1,))
1432 class D(C):
1433 pass
1434 d = D()
1435 self.assertEqual(D.goo(1), (1,))
1436 self.assertEqual(d.goo(1), (1,))
1437 self.assertEqual(d.foo(1), (d, 1))
1438 self.assertEqual(D.foo(d, 1), (d, 1))
1439
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001440 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001441 def test_staticmethods_in_c(self):
1442 # Testing C-based static methods...
1443 import xxsubtype as spam
1444 a = (1, 2, 3)
1445 d = {"abc": 123}
1446 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1447 self.assertEqual(x, None)
1448 self.assertEqual(a, a1)
1449 self.assertEqual(d, d1)
1450 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1451 self.assertEqual(x, None)
1452 self.assertEqual(a, a1)
1453 self.assertEqual(d, d1)
1454
1455 def test_classic(self):
1456 # Testing classic classes...
1457 class C:
1458 def foo(*a): return a
1459 goo = classmethod(foo)
1460 c = C()
1461 self.assertEqual(C.goo(1), (C, 1))
1462 self.assertEqual(c.goo(1), (C, 1))
1463 self.assertEqual(c.foo(1), (c, 1))
1464 class D(C):
1465 pass
1466 d = D()
1467 self.assertEqual(D.goo(1), (D, 1))
1468 self.assertEqual(d.goo(1), (D, 1))
1469 self.assertEqual(d.foo(1), (d, 1))
1470 self.assertEqual(D.foo(d, 1), (d, 1))
1471 class E: # *not* subclassing from C
1472 foo = C.foo
1473 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001474 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001475
1476 def test_compattr(self):
1477 # Testing computed attributes...
1478 class C(object):
1479 class computed_attribute(object):
1480 def __init__(self, get, set=None, delete=None):
1481 self.__get = get
1482 self.__set = set
1483 self.__delete = delete
1484 def __get__(self, obj, type=None):
1485 return self.__get(obj)
1486 def __set__(self, obj, value):
1487 return self.__set(obj, value)
1488 def __delete__(self, obj):
1489 return self.__delete(obj)
1490 def __init__(self):
1491 self.__x = 0
1492 def __get_x(self):
1493 x = self.__x
1494 self.__x = x+1
1495 return x
1496 def __set_x(self, x):
1497 self.__x = x
1498 def __delete_x(self):
1499 del self.__x
1500 x = computed_attribute(__get_x, __set_x, __delete_x)
1501 a = C()
1502 self.assertEqual(a.x, 0)
1503 self.assertEqual(a.x, 1)
1504 a.x = 10
1505 self.assertEqual(a.x, 10)
1506 self.assertEqual(a.x, 11)
1507 del a.x
1508 self.assertEqual(hasattr(a, 'x'), 0)
1509
1510 def test_newslots(self):
1511 # Testing __new__ slot override...
1512 class C(list):
1513 def __new__(cls):
1514 self = list.__new__(cls)
1515 self.foo = 1
1516 return self
1517 def __init__(self):
1518 self.foo = self.foo + 2
1519 a = C()
1520 self.assertEqual(a.foo, 3)
1521 self.assertEqual(a.__class__, C)
1522 class D(C):
1523 pass
1524 b = D()
1525 self.assertEqual(b.foo, 3)
1526 self.assertEqual(b.__class__, D)
1527
1528 def test_altmro(self):
1529 # Testing mro() and overriding it...
1530 class A(object):
1531 def f(self): return "A"
1532 class B(A):
1533 pass
1534 class C(A):
1535 def f(self): return "C"
1536 class D(B, C):
1537 pass
1538 self.assertEqual(D.mro(), [D, B, C, A, object])
1539 self.assertEqual(D.__mro__, (D, B, C, A, object))
1540 self.assertEqual(D().f(), "C")
1541
1542 class PerverseMetaType(type):
1543 def mro(cls):
1544 L = type.mro(cls)
1545 L.reverse()
1546 return L
1547 class X(D,B,C,A):
1548 __metaclass__ = PerverseMetaType
1549 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1550 self.assertEqual(X().f(), "A")
1551
1552 try:
1553 class X(object):
1554 class __metaclass__(type):
1555 def mro(self):
1556 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001557 # In CPython, the class creation above already raises
1558 # TypeError, as a protection against the fact that
1559 # instances of X would segfault it. In other Python
1560 # implementations it would be ok to let the class X
1561 # be created, but instead get a clean TypeError on the
1562 # __setitem__ below.
1563 x = object.__new__(X)
1564 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001565 except TypeError:
1566 pass
1567 else:
1568 self.fail("devious mro() return not caught")
1569
1570 try:
1571 class X(object):
1572 class __metaclass__(type):
1573 def mro(self):
1574 return [1]
1575 except TypeError:
1576 pass
1577 else:
1578 self.fail("non-class mro() return not caught")
1579
1580 try:
1581 class X(object):
1582 class __metaclass__(type):
1583 def mro(self):
1584 return 1
1585 except TypeError:
1586 pass
1587 else:
1588 self.fail("non-sequence mro() return not caught")
1589
1590 def test_overloading(self):
1591 # Testing operator overloading...
1592
1593 class B(object):
1594 "Intermediate class because object doesn't have a __setattr__"
1595
1596 class C(B):
1597 def __getattr__(self, name):
1598 if name == "foo":
1599 return ("getattr", name)
1600 else:
1601 raise AttributeError
1602 def __setattr__(self, name, value):
1603 if name == "foo":
1604 self.setattr = (name, value)
1605 else:
1606 return B.__setattr__(self, name, value)
1607 def __delattr__(self, name):
1608 if name == "foo":
1609 self.delattr = name
1610 else:
1611 return B.__delattr__(self, name)
1612
1613 def __getitem__(self, key):
1614 return ("getitem", key)
1615 def __setitem__(self, key, value):
1616 self.setitem = (key, value)
1617 def __delitem__(self, key):
1618 self.delitem = key
1619
1620 def __getslice__(self, i, j):
1621 return ("getslice", i, j)
1622 def __setslice__(self, i, j, value):
1623 self.setslice = (i, j, value)
1624 def __delslice__(self, i, j):
1625 self.delslice = (i, j)
1626
1627 a = C()
1628 self.assertEqual(a.foo, ("getattr", "foo"))
1629 a.foo = 12
1630 self.assertEqual(a.setattr, ("foo", 12))
1631 del a.foo
1632 self.assertEqual(a.delattr, "foo")
1633
1634 self.assertEqual(a[12], ("getitem", 12))
1635 a[12] = 21
1636 self.assertEqual(a.setitem, (12, 21))
1637 del a[12]
1638 self.assertEqual(a.delitem, 12)
1639
1640 self.assertEqual(a[0:10], ("getslice", 0, 10))
1641 a[0:10] = "foo"
1642 self.assertEqual(a.setslice, (0, 10, "foo"))
1643 del a[0:10]
1644 self.assertEqual(a.delslice, (0, 10))
1645
1646 def test_methods(self):
1647 # Testing methods...
1648 class C(object):
1649 def __init__(self, x):
1650 self.x = x
1651 def foo(self):
1652 return self.x
1653 c1 = C(1)
1654 self.assertEqual(c1.foo(), 1)
1655 class D(C):
1656 boo = C.foo
1657 goo = c1.foo
1658 d2 = D(2)
1659 self.assertEqual(d2.foo(), 2)
1660 self.assertEqual(d2.boo(), 2)
1661 self.assertEqual(d2.goo(), 1)
1662 class E(object):
1663 foo = C.foo
1664 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001665 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001666
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001667 def test_special_method_lookup(self):
1668 # The lookup of special methods bypasses __getattr__ and
1669 # __getattribute__, but they still can be descriptors.
1670
1671 def run_context(manager):
1672 with manager:
1673 pass
1674 def iden(self):
1675 return self
1676 def hello(self):
1677 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001678 def empty_seq(self):
1679 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001680 def zero(self):
1681 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001682 def complex_num(self):
1683 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001684 def stop(self):
1685 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001686 def return_true(self, thing=None):
1687 return True
1688 def do_isinstance(obj):
1689 return isinstance(int, obj)
1690 def do_issubclass(obj):
1691 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001692 def swallow(*args):
1693 pass
1694 def do_dict_missing(checker):
1695 class DictSub(checker.__class__, dict):
1696 pass
1697 self.assertEqual(DictSub()["hi"], 4)
1698 def some_number(self_, key):
1699 self.assertEqual(key, "hi")
1700 return 4
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001701 def format_impl(self, spec):
1702 return "hello"
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001703
1704 # It would be nice to have every special method tested here, but I'm
1705 # only listing the ones I can remember outside of typeobject.c, since it
1706 # does it right.
1707 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001708 ("__unicode__", unicode, hello, set(), {}),
1709 ("__reversed__", reversed, empty_seq, set(), {}),
1710 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001711 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001712 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1713 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001714 ("__missing__", do_dict_missing, some_number,
1715 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001716 ("__subclasscheck__", do_issubclass, return_true,
1717 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001718 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1719 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001720 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001721 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001722 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001723 ]
1724
1725 class Checker(object):
1726 def __getattr__(self, attr, test=self):
1727 test.fail("__getattr__ called with {0}".format(attr))
1728 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001729 if attr not in ok:
1730 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001731 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001732 class SpecialDescr(object):
1733 def __init__(self, impl):
1734 self.impl = impl
1735 def __get__(self, obj, owner):
1736 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001737 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001738 class MyException(Exception):
1739 pass
1740 class ErrDescr(object):
1741 def __get__(self, obj, owner):
1742 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001743
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001744 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001745 class X(Checker):
1746 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001747 for attr, obj in env.iteritems():
1748 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001749 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001750 runner(X())
1751
1752 record = []
1753 class X(Checker):
1754 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001755 for attr, obj in env.iteritems():
1756 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001757 setattr(X, name, SpecialDescr(meth_impl))
1758 runner(X())
1759 self.assertEqual(record, [1], name)
1760
Benjamin Peterson87e50062009-05-25 02:40:21 +00001761 class X(Checker):
1762 pass
1763 for attr, obj in env.iteritems():
1764 setattr(X, attr, obj)
1765 setattr(X, name, ErrDescr())
1766 try:
1767 runner(X())
1768 except MyException:
1769 pass
1770 else:
1771 self.fail("{0!r} didn't raise".format(name))
1772
Georg Brandl48545522008-02-02 10:12:36 +00001773 def test_specials(self):
1774 # Testing special operators...
1775 # Test operators like __hash__ for which a built-in default exists
1776
1777 # Test the default behavior for static classes
1778 class C(object):
1779 def __getitem__(self, i):
1780 if 0 <= i < 10: return i
1781 raise IndexError
1782 c1 = C()
1783 c2 = C()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001784 self.assertTrue(not not c1) # What?
Georg Brandl48545522008-02-02 10:12:36 +00001785 self.assertNotEqual(id(c1), id(c2))
1786 hash(c1)
1787 hash(c2)
1788 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1789 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001790 self.assertTrue(c1 != c2)
1791 self.assertTrue(not c1 != c1)
1792 self.assertTrue(not c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001793 # Note that the module name appears in str/repr, and that varies
1794 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001795 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001796 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001797 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001798 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001799 self.assertIn(i, c1)
1800 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001801 # Test the default behavior for dynamic classes
1802 class D(object):
1803 def __getitem__(self, i):
1804 if 0 <= i < 10: return i
1805 raise IndexError
1806 d1 = D()
1807 d2 = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001808 self.assertTrue(not not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001809 self.assertNotEqual(id(d1), id(d2))
1810 hash(d1)
1811 hash(d2)
1812 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1813 self.assertEqual(d1, d1)
1814 self.assertNotEqual(d1, d2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001815 self.assertTrue(not d1 != d1)
1816 self.assertTrue(not d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001817 # Note that the module name appears in str/repr, and that varies
1818 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001819 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001820 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001821 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001822 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001823 self.assertIn(i, d1)
1824 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001825 # Test overridden behavior for static classes
1826 class Proxy(object):
1827 def __init__(self, x):
1828 self.x = x
1829 def __nonzero__(self):
1830 return not not self.x
1831 def __hash__(self):
1832 return hash(self.x)
1833 def __eq__(self, other):
1834 return self.x == other
1835 def __ne__(self, other):
1836 return self.x != other
1837 def __cmp__(self, other):
1838 return cmp(self.x, other.x)
1839 def __str__(self):
1840 return "Proxy:%s" % self.x
1841 def __repr__(self):
1842 return "Proxy(%r)" % self.x
1843 def __contains__(self, value):
1844 return value in self.x
1845 p0 = Proxy(0)
1846 p1 = Proxy(1)
1847 p_1 = Proxy(-1)
1848 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001849 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001850 self.assertEqual(hash(p0), hash(0))
1851 self.assertEqual(p0, p0)
1852 self.assertNotEqual(p0, p1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001853 self.assertTrue(not p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001854 self.assertEqual(not p0, p1)
1855 self.assertEqual(cmp(p0, p1), -1)
1856 self.assertEqual(cmp(p0, p0), 0)
1857 self.assertEqual(cmp(p0, p_1), 1)
1858 self.assertEqual(str(p0), "Proxy:0")
1859 self.assertEqual(repr(p0), "Proxy(0)")
1860 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001861 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001862 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001863 self.assertIn(i, p10)
1864 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001865 # Test overridden behavior for dynamic classes
1866 class DProxy(object):
1867 def __init__(self, x):
1868 self.x = x
1869 def __nonzero__(self):
1870 return not not self.x
1871 def __hash__(self):
1872 return hash(self.x)
1873 def __eq__(self, other):
1874 return self.x == other
1875 def __ne__(self, other):
1876 return self.x != other
1877 def __cmp__(self, other):
1878 return cmp(self.x, other.x)
1879 def __str__(self):
1880 return "DProxy:%s" % self.x
1881 def __repr__(self):
1882 return "DProxy(%r)" % self.x
1883 def __contains__(self, value):
1884 return value in self.x
1885 p0 = DProxy(0)
1886 p1 = DProxy(1)
1887 p_1 = DProxy(-1)
1888 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001889 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001890 self.assertEqual(hash(p0), hash(0))
1891 self.assertEqual(p0, p0)
1892 self.assertNotEqual(p0, p1)
1893 self.assertNotEqual(not p0, p0)
1894 self.assertEqual(not p0, p1)
1895 self.assertEqual(cmp(p0, p1), -1)
1896 self.assertEqual(cmp(p0, p0), 0)
1897 self.assertEqual(cmp(p0, p_1), 1)
1898 self.assertEqual(str(p0), "DProxy:0")
1899 self.assertEqual(repr(p0), "DProxy(0)")
1900 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001901 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001902 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001903 self.assertIn(i, p10)
1904 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001905
1906 # Safety test for __cmp__
1907 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001908 if not hasattr(a, '__cmp__'):
1909 return # some types don't have a __cmp__ any more (so the
1910 # test doesn't make sense any more), or maybe they
1911 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001912 try:
1913 a.__class__.__cmp__(a, b)
1914 except TypeError:
1915 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001916 else:
Georg Brandl48545522008-02-02 10:12:36 +00001917 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1918 a.__class__, a, b))
1919
1920 unsafecmp(u"123", "123")
1921 unsafecmp("123", u"123")
1922 unsafecmp(1, 1.0)
1923 unsafecmp(1.0, 1)
1924 unsafecmp(1, 1L)
1925 unsafecmp(1L, 1)
1926
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001927 @test_support.impl_detail("custom logic for printing to real file objects")
1928 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001929 # Testing recursion checks ...
1930 class Letter(str):
1931 def __new__(cls, letter):
1932 if letter == 'EPS':
1933 return str.__new__(cls)
1934 return str.__new__(cls, letter)
1935 def __str__(self):
1936 if not self:
1937 return 'EPS'
1938 return self
1939 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00001940 test_stdout = sys.stdout
1941 sys.stdout = test_support.get_original_stdout()
1942 try:
1943 # nothing should actually be printed, this should raise an exception
1944 print Letter('w')
1945 except RuntimeError:
1946 pass
1947 else:
1948 self.fail("expected a RuntimeError for print recursion")
1949 finally:
1950 sys.stdout = test_stdout
1951
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001952 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001953 # Bug #1202533.
1954 class A(object):
1955 pass
1956 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1957 try:
1958 A()*2
1959 except RuntimeError:
1960 pass
1961 else:
1962 self.fail("expected a RuntimeError")
1963
1964 def test_weakrefs(self):
1965 # Testing weak references...
1966 import weakref
1967 class C(object):
1968 pass
1969 c = C()
1970 r = weakref.ref(c)
1971 self.assertEqual(r(), c)
1972 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001973 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001974 self.assertEqual(r(), None)
1975 del r
1976 class NoWeak(object):
1977 __slots__ = ['foo']
1978 no = NoWeak()
1979 try:
1980 weakref.ref(no)
1981 except TypeError, msg:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001982 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001983 else:
1984 self.fail("weakref.ref(no) should be illegal")
1985 class Weak(object):
1986 __slots__ = ['foo', '__weakref__']
1987 yes = Weak()
1988 r = weakref.ref(yes)
1989 self.assertEqual(r(), yes)
1990 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001991 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001992 self.assertEqual(r(), None)
1993 del r
1994
1995 def test_properties(self):
1996 # Testing property...
1997 class C(object):
1998 def getx(self):
1999 return self.__x
2000 def setx(self, value):
2001 self.__x = value
2002 def delx(self):
2003 del self.__x
2004 x = property(getx, setx, delx, doc="I'm the x property.")
2005 a = C()
2006 self.assertFalse(hasattr(a, "x"))
2007 a.x = 42
2008 self.assertEqual(a._C__x, 42)
2009 self.assertEqual(a.x, 42)
2010 del a.x
2011 self.assertFalse(hasattr(a, "x"))
2012 self.assertFalse(hasattr(a, "_C__x"))
2013 C.x.__set__(a, 100)
2014 self.assertEqual(C.x.__get__(a), 100)
2015 C.x.__delete__(a)
2016 self.assertFalse(hasattr(a, "x"))
2017
2018 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002019 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002020
2021 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002022 self.assertIn("__doc__", attrs)
2023 self.assertIn("fget", attrs)
2024 self.assertIn("fset", attrs)
2025 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002026
2027 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002028 self.assertTrue(raw.fget is C.__dict__['getx'])
2029 self.assertTrue(raw.fset is C.__dict__['setx'])
2030 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002031
2032 for attr in "__doc__", "fget", "fset", "fdel":
2033 try:
2034 setattr(raw, attr, 42)
2035 except TypeError, msg:
2036 if str(msg).find('readonly') < 0:
2037 self.fail("when setting readonly attr %r on a property, "
2038 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002039 else:
Georg Brandl48545522008-02-02 10:12:36 +00002040 self.fail("expected TypeError from trying to set readonly %r "
2041 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002042
Georg Brandl48545522008-02-02 10:12:36 +00002043 class D(object):
2044 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002045
Georg Brandl48545522008-02-02 10:12:36 +00002046 d = D()
2047 try:
2048 for i in d:
2049 str(i)
2050 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002051 pass
Georg Brandl48545522008-02-02 10:12:36 +00002052 else:
2053 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002054
R. David Murrayf28fd242010-02-23 00:24:49 +00002055 @unittest.skipIf(sys.flags.optimize >= 2,
2056 "Docstrings are omitted with -O2 and above")
2057 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002058 class E(object):
2059 def getter(self):
2060 "getter method"
2061 return 0
2062 def setter(self_, value):
2063 "setter method"
2064 pass
2065 prop = property(getter)
2066 self.assertEqual(prop.__doc__, "getter method")
2067 prop2 = property(fset=setter)
2068 self.assertEqual(prop2.__doc__, None)
2069
R. David Murrayf28fd242010-02-23 00:24:49 +00002070 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002071 # this segfaulted in 2.5b2
2072 try:
2073 import _testcapi
2074 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002075 pass
Georg Brandl48545522008-02-02 10:12:36 +00002076 else:
2077 class X(object):
2078 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002079
Georg Brandl48545522008-02-02 10:12:36 +00002080 def test_properties_plus(self):
2081 class C(object):
2082 foo = property(doc="hello")
2083 @foo.getter
2084 def foo(self):
2085 return self._foo
2086 @foo.setter
2087 def foo(self, value):
2088 self._foo = abs(value)
2089 @foo.deleter
2090 def foo(self):
2091 del self._foo
2092 c = C()
2093 self.assertEqual(C.foo.__doc__, "hello")
2094 self.assertFalse(hasattr(c, "foo"))
2095 c.foo = -42
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002096 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl48545522008-02-02 10:12:36 +00002097 self.assertEqual(c._foo, 42)
2098 self.assertEqual(c.foo, 42)
2099 del c.foo
2100 self.assertFalse(hasattr(c, '_foo'))
2101 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002102
Georg Brandl48545522008-02-02 10:12:36 +00002103 class D(C):
2104 @C.foo.deleter
2105 def foo(self):
2106 try:
2107 del self._foo
2108 except AttributeError:
2109 pass
2110 d = D()
2111 d.foo = 24
2112 self.assertEqual(d.foo, 24)
2113 del d.foo
2114 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002115
Georg Brandl48545522008-02-02 10:12:36 +00002116 class E(object):
2117 @property
2118 def foo(self):
2119 return self._foo
2120 @foo.setter
2121 def foo(self, value):
2122 raise RuntimeError
2123 @foo.setter
2124 def foo(self, value):
2125 self._foo = abs(value)
2126 @foo.deleter
2127 def foo(self, value=None):
2128 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002129
Georg Brandl48545522008-02-02 10:12:36 +00002130 e = E()
2131 e.foo = -42
2132 self.assertEqual(e.foo, 42)
2133 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002134
Georg Brandl48545522008-02-02 10:12:36 +00002135 class F(E):
2136 @E.foo.deleter
2137 def foo(self):
2138 del self._foo
2139 @foo.setter
2140 def foo(self, value):
2141 self._foo = max(0, value)
2142 f = F()
2143 f.foo = -10
2144 self.assertEqual(f.foo, 0)
2145 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002146
Georg Brandl48545522008-02-02 10:12:36 +00002147 def test_dict_constructors(self):
2148 # Testing dict constructor ...
2149 d = dict()
2150 self.assertEqual(d, {})
2151 d = dict({})
2152 self.assertEqual(d, {})
2153 d = dict({1: 2, 'a': 'b'})
2154 self.assertEqual(d, {1: 2, 'a': 'b'})
2155 self.assertEqual(d, dict(d.items()))
2156 self.assertEqual(d, dict(d.iteritems()))
2157 d = dict({'one':1, 'two':2})
2158 self.assertEqual(d, dict(one=1, two=2))
2159 self.assertEqual(d, dict(**d))
2160 self.assertEqual(d, dict({"one": 1}, two=2))
2161 self.assertEqual(d, dict([("two", 2)], one=1))
2162 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2163 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002164
Georg Brandl48545522008-02-02 10:12:36 +00002165 for badarg in 0, 0L, 0j, "0", [0], (0,):
2166 try:
2167 dict(badarg)
2168 except TypeError:
2169 pass
2170 except ValueError:
2171 if badarg == "0":
2172 # It's a sequence, and its elements are also sequences (gotta
2173 # love strings <wink>), but they aren't of length 2, so this
2174 # one seemed better as a ValueError than a TypeError.
2175 pass
2176 else:
2177 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002178 else:
Georg Brandl48545522008-02-02 10:12:36 +00002179 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002180
Georg Brandl48545522008-02-02 10:12:36 +00002181 try:
2182 dict({}, {})
2183 except TypeError:
2184 pass
2185 else:
2186 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002187
Georg Brandl48545522008-02-02 10:12:36 +00002188 class Mapping:
2189 # Lacks a .keys() method; will be added later.
2190 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002191
Georg Brandl48545522008-02-02 10:12:36 +00002192 try:
2193 dict(Mapping())
2194 except TypeError:
2195 pass
2196 else:
2197 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002198
Georg Brandl48545522008-02-02 10:12:36 +00002199 Mapping.keys = lambda self: self.dict.keys()
2200 Mapping.__getitem__ = lambda self, i: self.dict[i]
2201 d = dict(Mapping())
2202 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002203
Georg Brandl48545522008-02-02 10:12:36 +00002204 # Init from sequence of iterable objects, each producing a 2-sequence.
2205 class AddressBookEntry:
2206 def __init__(self, first, last):
2207 self.first = first
2208 self.last = last
2209 def __iter__(self):
2210 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002211
Georg Brandl48545522008-02-02 10:12:36 +00002212 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2213 AddressBookEntry('Barry', 'Peters'),
2214 AddressBookEntry('Tim', 'Peters'),
2215 AddressBookEntry('Barry', 'Warsaw')])
2216 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002217
Georg Brandl48545522008-02-02 10:12:36 +00002218 d = dict(zip(range(4), range(1, 5)))
2219 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002220
Georg Brandl48545522008-02-02 10:12:36 +00002221 # Bad sequence lengths.
2222 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2223 try:
2224 dict(bad)
2225 except ValueError:
2226 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002227 else:
Georg Brandl48545522008-02-02 10:12:36 +00002228 self.fail("no ValueError from dict(%r)" % bad)
2229
2230 def test_dir(self):
2231 # Testing dir() ...
2232 junk = 12
2233 self.assertEqual(dir(), ['junk', 'self'])
2234 del junk
2235
2236 # Just make sure these don't blow up!
2237 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2238 dir(arg)
2239
2240 # Try classic classes.
2241 class C:
2242 Cdata = 1
2243 def Cmethod(self): pass
2244
2245 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2246 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002247 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002248
2249 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2250 self.assertEqual(dir(c), cstuff)
2251
2252 c.cdata = 2
2253 c.cmethod = lambda self: 0
2254 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002255 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002256
2257 class A(C):
2258 Adata = 1
2259 def Amethod(self): pass
2260
2261 astuff = ['Adata', 'Amethod'] + cstuff
2262 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002263 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002264 a = A()
2265 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002266 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002267 a.adata = 42
2268 a.amethod = lambda self: 3
2269 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2270
2271 # The same, but with new-style classes. Since these have object as a
2272 # base class, a lot more gets sucked in.
2273 def interesting(strings):
2274 return [s for s in strings if not s.startswith('_')]
2275
2276 class C(object):
2277 Cdata = 1
2278 def Cmethod(self): pass
2279
2280 cstuff = ['Cdata', 'Cmethod']
2281 self.assertEqual(interesting(dir(C)), cstuff)
2282
2283 c = C()
2284 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002285 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002286
2287 c.cdata = 2
2288 c.cmethod = lambda self: 0
2289 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002290 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002291
2292 class A(C):
2293 Adata = 1
2294 def Amethod(self): pass
2295
2296 astuff = ['Adata', 'Amethod'] + cstuff
2297 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002298 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002299 a = A()
2300 self.assertEqual(interesting(dir(a)), astuff)
2301 a.adata = 42
2302 a.amethod = lambda self: 3
2303 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002304 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002305
2306 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002307 class M(type(sys)):
2308 pass
2309 minstance = M("m")
2310 minstance.b = 2
2311 minstance.a = 1
2312 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2313 self.assertEqual(names, ['a', 'b'])
2314
2315 class M2(M):
2316 def getdict(self):
2317 return "Not a dict!"
2318 __dict__ = property(getdict)
2319
2320 m2instance = M2("m2")
2321 m2instance.b = 2
2322 m2instance.a = 1
2323 self.assertEqual(m2instance.__dict__, "Not a dict!")
2324 try:
2325 dir(m2instance)
2326 except TypeError:
2327 pass
2328
2329 # Two essentially featureless objects, just inheriting stuff from
2330 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002331 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2332 if test_support.check_impl_detail():
2333 # None differs in PyPy: it has a __nonzero__
2334 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002335
2336 # Nasty test case for proxied objects
2337 class Wrapper(object):
2338 def __init__(self, obj):
2339 self.__obj = obj
2340 def __repr__(self):
2341 return "Wrapper(%s)" % repr(self.__obj)
2342 def __getitem__(self, key):
2343 return Wrapper(self.__obj[key])
2344 def __len__(self):
2345 return len(self.__obj)
2346 def __getattr__(self, name):
2347 return Wrapper(getattr(self.__obj, name))
2348
2349 class C(object):
2350 def __getclass(self):
2351 return Wrapper(type(self))
2352 __class__ = property(__getclass)
2353
2354 dir(C()) # This used to segfault
2355
2356 def test_supers(self):
2357 # Testing super...
2358
2359 class A(object):
2360 def meth(self, a):
2361 return "A(%r)" % a
2362
2363 self.assertEqual(A().meth(1), "A(1)")
2364
2365 class B(A):
2366 def __init__(self):
2367 self.__super = super(B, self)
2368 def meth(self, a):
2369 return "B(%r)" % a + self.__super.meth(a)
2370
2371 self.assertEqual(B().meth(2), "B(2)A(2)")
2372
2373 class C(A):
2374 def meth(self, a):
2375 return "C(%r)" % a + self.__super.meth(a)
2376 C._C__super = super(C)
2377
2378 self.assertEqual(C().meth(3), "C(3)A(3)")
2379
2380 class D(C, B):
2381 def meth(self, a):
2382 return "D(%r)" % a + super(D, self).meth(a)
2383
2384 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2385
2386 # Test for subclassing super
2387
2388 class mysuper(super):
2389 def __init__(self, *args):
2390 return super(mysuper, self).__init__(*args)
2391
2392 class E(D):
2393 def meth(self, a):
2394 return "E(%r)" % a + mysuper(E, self).meth(a)
2395
2396 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2397
2398 class F(E):
2399 def meth(self, a):
2400 s = self.__super # == mysuper(F, self)
2401 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2402 F._F__super = mysuper(F)
2403
2404 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2405
2406 # Make sure certain errors are raised
2407
2408 try:
2409 super(D, 42)
2410 except TypeError:
2411 pass
2412 else:
2413 self.fail("shouldn't allow super(D, 42)")
2414
2415 try:
2416 super(D, C())
2417 except TypeError:
2418 pass
2419 else:
2420 self.fail("shouldn't allow super(D, C())")
2421
2422 try:
2423 super(D).__get__(12)
2424 except TypeError:
2425 pass
2426 else:
2427 self.fail("shouldn't allow super(D).__get__(12)")
2428
2429 try:
2430 super(D).__get__(C())
2431 except TypeError:
2432 pass
2433 else:
2434 self.fail("shouldn't allow super(D).__get__(C())")
2435
2436 # Make sure data descriptors can be overridden and accessed via super
2437 # (new feature in Python 2.3)
2438
2439 class DDbase(object):
2440 def getx(self): return 42
2441 x = property(getx)
2442
2443 class DDsub(DDbase):
2444 def getx(self): return "hello"
2445 x = property(getx)
2446
2447 dd = DDsub()
2448 self.assertEqual(dd.x, "hello")
2449 self.assertEqual(super(DDsub, dd).x, 42)
2450
2451 # Ensure that super() lookup of descriptor from classmethod
2452 # works (SF ID# 743627)
2453
2454 class Base(object):
2455 aProp = property(lambda self: "foo")
2456
2457 class Sub(Base):
2458 @classmethod
2459 def test(klass):
2460 return super(Sub,klass).aProp
2461
2462 self.assertEqual(Sub.test(), Base.aProp)
2463
2464 # Verify that super() doesn't allow keyword args
2465 try:
2466 super(Base, kw=1)
2467 except TypeError:
2468 pass
2469 else:
2470 self.assertEqual("super shouldn't accept keyword args")
2471
2472 def test_basic_inheritance(self):
2473 # Testing inheritance from basic types...
2474
2475 class hexint(int):
2476 def __repr__(self):
2477 return hex(self)
2478 def __add__(self, other):
2479 return hexint(int.__add__(self, other))
2480 # (Note that overriding __radd__ doesn't work,
2481 # because the int type gets first dibs.)
2482 self.assertEqual(repr(hexint(7) + 9), "0x10")
2483 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2484 a = hexint(12345)
2485 self.assertEqual(a, 12345)
2486 self.assertEqual(int(a), 12345)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002487 self.assertTrue(int(a).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002488 self.assertEqual(hash(a), hash(12345))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002489 self.assertTrue((+a).__class__ is int)
2490 self.assertTrue((a >> 0).__class__ is int)
2491 self.assertTrue((a << 0).__class__ is int)
2492 self.assertTrue((hexint(0) << 12).__class__ is int)
2493 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002494
2495 class octlong(long):
2496 __slots__ = []
2497 def __str__(self):
2498 s = oct(self)
2499 if s[-1] == 'L':
2500 s = s[:-1]
2501 return s
2502 def __add__(self, other):
2503 return self.__class__(super(octlong, self).__add__(other))
2504 __radd__ = __add__
2505 self.assertEqual(str(octlong(3) + 5), "010")
2506 # (Note that overriding __radd__ here only seems to work
2507 # because the example uses a short int left argument.)
2508 self.assertEqual(str(5 + octlong(3000)), "05675")
2509 a = octlong(12345)
2510 self.assertEqual(a, 12345L)
2511 self.assertEqual(long(a), 12345L)
2512 self.assertEqual(hash(a), hash(12345L))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002513 self.assertTrue(long(a).__class__ is long)
2514 self.assertTrue((+a).__class__ is long)
2515 self.assertTrue((-a).__class__ is long)
2516 self.assertTrue((-octlong(0)).__class__ is long)
2517 self.assertTrue((a >> 0).__class__ is long)
2518 self.assertTrue((a << 0).__class__ is long)
2519 self.assertTrue((a - 0).__class__ is long)
2520 self.assertTrue((a * 1).__class__ is long)
2521 self.assertTrue((a ** 1).__class__ is long)
2522 self.assertTrue((a // 1).__class__ is long)
2523 self.assertTrue((1 * a).__class__ is long)
2524 self.assertTrue((a | 0).__class__ is long)
2525 self.assertTrue((a ^ 0).__class__ is long)
2526 self.assertTrue((a & -1L).__class__ is long)
2527 self.assertTrue((octlong(0) << 12).__class__ is long)
2528 self.assertTrue((octlong(0) >> 12).__class__ is long)
2529 self.assertTrue(abs(octlong(0)).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002530
2531 # Because octlong overrides __add__, we can't check the absence of +0
2532 # optimizations using octlong.
2533 class longclone(long):
2534 pass
2535 a = longclone(1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002536 self.assertTrue((a + 0).__class__ is long)
2537 self.assertTrue((0 + a).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002538
2539 # Check that negative clones don't segfault
2540 a = longclone(-1)
2541 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002542 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002543
2544 class precfloat(float):
2545 __slots__ = ['prec']
2546 def __init__(self, value=0.0, prec=12):
2547 self.prec = int(prec)
2548 def __repr__(self):
2549 return "%.*g" % (self.prec, self)
2550 self.assertEqual(repr(precfloat(1.1)), "1.1")
2551 a = precfloat(12345)
2552 self.assertEqual(a, 12345.0)
2553 self.assertEqual(float(a), 12345.0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002554 self.assertTrue(float(a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002555 self.assertEqual(hash(a), hash(12345.0))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002556 self.assertTrue((+a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002557
2558 class madcomplex(complex):
2559 def __repr__(self):
2560 return "%.17gj%+.17g" % (self.imag, self.real)
2561 a = madcomplex(-3, 4)
2562 self.assertEqual(repr(a), "4j-3")
2563 base = complex(-3, 4)
2564 self.assertEqual(base.__class__, complex)
2565 self.assertEqual(a, base)
2566 self.assertEqual(complex(a), base)
2567 self.assertEqual(complex(a).__class__, complex)
2568 a = madcomplex(a) # just trying another form of the constructor
2569 self.assertEqual(repr(a), "4j-3")
2570 self.assertEqual(a, base)
2571 self.assertEqual(complex(a), base)
2572 self.assertEqual(complex(a).__class__, complex)
2573 self.assertEqual(hash(a), hash(base))
2574 self.assertEqual((+a).__class__, complex)
2575 self.assertEqual((a + 0).__class__, complex)
2576 self.assertEqual(a + 0, base)
2577 self.assertEqual((a - 0).__class__, complex)
2578 self.assertEqual(a - 0, base)
2579 self.assertEqual((a * 1).__class__, complex)
2580 self.assertEqual(a * 1, base)
2581 self.assertEqual((a / 1).__class__, complex)
2582 self.assertEqual(a / 1, base)
2583
2584 class madtuple(tuple):
2585 _rev = None
2586 def rev(self):
2587 if self._rev is not None:
2588 return self._rev
2589 L = list(self)
2590 L.reverse()
2591 self._rev = self.__class__(L)
2592 return self._rev
2593 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2594 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2595 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2596 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2597 for i in range(512):
2598 t = madtuple(range(i))
2599 u = t.rev()
2600 v = u.rev()
2601 self.assertEqual(v, t)
2602 a = madtuple((1,2,3,4,5))
2603 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002604 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002605 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002606 self.assertTrue(a[:].__class__ is tuple)
2607 self.assertTrue((a * 1).__class__ is tuple)
2608 self.assertTrue((a * 0).__class__ is tuple)
2609 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002610 a = madtuple(())
2611 self.assertEqual(tuple(a), ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002612 self.assertTrue(tuple(a).__class__ is tuple)
2613 self.assertTrue((a + a).__class__ is tuple)
2614 self.assertTrue((a * 0).__class__ is tuple)
2615 self.assertTrue((a * 1).__class__ is tuple)
2616 self.assertTrue((a * 2).__class__ is tuple)
2617 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002618
2619 class madstring(str):
2620 _rev = None
2621 def rev(self):
2622 if self._rev is not None:
2623 return self._rev
2624 L = list(self)
2625 L.reverse()
2626 self._rev = self.__class__("".join(L))
2627 return self._rev
2628 s = madstring("abcdefghijklmnopqrstuvwxyz")
2629 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2630 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2631 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2632 for i in range(256):
2633 s = madstring("".join(map(chr, range(i))))
2634 t = s.rev()
2635 u = t.rev()
2636 self.assertEqual(u, s)
2637 s = madstring("12345")
2638 self.assertEqual(str(s), "12345")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002639 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002640
2641 base = "\x00" * 5
2642 s = madstring(base)
2643 self.assertEqual(s, base)
2644 self.assertEqual(str(s), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002645 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002646 self.assertEqual(hash(s), hash(base))
2647 self.assertEqual({s: 1}[base], 1)
2648 self.assertEqual({base: 1}[s], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002649 self.assertTrue((s + "").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002650 self.assertEqual(s + "", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002651 self.assertTrue(("" + s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002652 self.assertEqual("" + s, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002653 self.assertTrue((s * 0).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002654 self.assertEqual(s * 0, "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002655 self.assertTrue((s * 1).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002656 self.assertEqual(s * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002657 self.assertTrue((s * 2).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002658 self.assertEqual(s * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002659 self.assertTrue(s[:].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002660 self.assertEqual(s[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002661 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002662 self.assertEqual(s[0:0], "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002663 self.assertTrue(s.strip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002664 self.assertEqual(s.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002665 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002666 self.assertEqual(s.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002667 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002668 self.assertEqual(s.rstrip(), base)
2669 identitytab = ''.join([chr(i) for i in range(256)])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002670 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002671 self.assertEqual(s.translate(identitytab), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002672 self.assertTrue(s.translate(identitytab, "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002673 self.assertEqual(s.translate(identitytab, "x"), base)
2674 self.assertEqual(s.translate(identitytab, "\x00"), "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002675 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002676 self.assertEqual(s.replace("x", "x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002677 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002678 self.assertEqual(s.ljust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002679 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002680 self.assertEqual(s.rjust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002681 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002682 self.assertEqual(s.center(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002683 self.assertTrue(s.lower().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002684 self.assertEqual(s.lower(), base)
2685
2686 class madunicode(unicode):
2687 _rev = None
2688 def rev(self):
2689 if self._rev is not None:
2690 return self._rev
2691 L = list(self)
2692 L.reverse()
2693 self._rev = self.__class__(u"".join(L))
2694 return self._rev
2695 u = madunicode("ABCDEF")
2696 self.assertEqual(u, u"ABCDEF")
2697 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2698 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2699 base = u"12345"
2700 u = madunicode(base)
2701 self.assertEqual(unicode(u), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002702 self.assertTrue(unicode(u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002703 self.assertEqual(hash(u), hash(base))
2704 self.assertEqual({u: 1}[base], 1)
2705 self.assertEqual({base: 1}[u], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002706 self.assertTrue(u.strip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002707 self.assertEqual(u.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002708 self.assertTrue(u.lstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002709 self.assertEqual(u.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002710 self.assertTrue(u.rstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002711 self.assertEqual(u.rstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002712 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002713 self.assertEqual(u.replace(u"x", u"x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002714 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002715 self.assertEqual(u.replace(u"xy", u"xy"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002716 self.assertTrue(u.center(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002717 self.assertEqual(u.center(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002718 self.assertTrue(u.ljust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002719 self.assertEqual(u.ljust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002720 self.assertTrue(u.rjust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002721 self.assertEqual(u.rjust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002722 self.assertTrue(u.lower().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002723 self.assertEqual(u.lower(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002724 self.assertTrue(u.upper().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002725 self.assertEqual(u.upper(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002726 self.assertTrue(u.capitalize().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002727 self.assertEqual(u.capitalize(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002728 self.assertTrue(u.title().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002729 self.assertEqual(u.title(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002730 self.assertTrue((u + u"").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002731 self.assertEqual(u + u"", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002732 self.assertTrue((u"" + u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002733 self.assertEqual(u"" + u, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002734 self.assertTrue((u * 0).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002735 self.assertEqual(u * 0, u"")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002736 self.assertTrue((u * 1).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002737 self.assertEqual(u * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002738 self.assertTrue((u * 2).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002739 self.assertEqual(u * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002740 self.assertTrue(u[:].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002741 self.assertEqual(u[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002742 self.assertTrue(u[0:0].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002743 self.assertEqual(u[0:0], u"")
2744
2745 class sublist(list):
2746 pass
2747 a = sublist(range(5))
2748 self.assertEqual(a, range(5))
2749 a.append("hello")
2750 self.assertEqual(a, range(5) + ["hello"])
2751 a[5] = 5
2752 self.assertEqual(a, range(6))
2753 a.extend(range(6, 20))
2754 self.assertEqual(a, range(20))
2755 a[-5:] = []
2756 self.assertEqual(a, range(15))
2757 del a[10:15]
2758 self.assertEqual(len(a), 10)
2759 self.assertEqual(a, range(10))
2760 self.assertEqual(list(a), range(10))
2761 self.assertEqual(a[0], 0)
2762 self.assertEqual(a[9], 9)
2763 self.assertEqual(a[-10], 0)
2764 self.assertEqual(a[-1], 9)
2765 self.assertEqual(a[:5], range(5))
2766
2767 class CountedInput(file):
2768 """Counts lines read by self.readline().
2769
2770 self.lineno is the 0-based ordinal of the last line read, up to
2771 a maximum of one greater than the number of lines in the file.
2772
2773 self.ateof is true if and only if the final "" line has been read,
2774 at which point self.lineno stops incrementing, and further calls
2775 to readline() continue to return "".
2776 """
2777
2778 lineno = 0
2779 ateof = 0
2780 def readline(self):
2781 if self.ateof:
2782 return ""
2783 s = file.readline(self)
2784 # Next line works too.
2785 # s = super(CountedInput, self).readline()
2786 self.lineno += 1
2787 if s == "":
2788 self.ateof = 1
2789 return s
2790
2791 f = file(name=test_support.TESTFN, mode='w')
2792 lines = ['a\n', 'b\n', 'c\n']
2793 try:
2794 f.writelines(lines)
2795 f.close()
2796 f = CountedInput(test_support.TESTFN)
2797 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2798 got = f.readline()
2799 self.assertEqual(expected, got)
2800 self.assertEqual(f.lineno, i)
2801 self.assertEqual(f.ateof, (i > len(lines)))
2802 f.close()
2803 finally:
2804 try:
2805 f.close()
2806 except:
2807 pass
2808 test_support.unlink(test_support.TESTFN)
2809
2810 def test_keywords(self):
2811 # Testing keyword args to basic type constructors ...
2812 self.assertEqual(int(x=1), 1)
2813 self.assertEqual(float(x=2), 2.0)
2814 self.assertEqual(long(x=3), 3L)
2815 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2816 self.assertEqual(str(object=500), '500')
2817 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2818 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2819 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2820 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2821
2822 for constructor in (int, float, long, complex, str, unicode,
2823 tuple, list, file):
2824 try:
2825 constructor(bogus_keyword_arg=1)
2826 except TypeError:
2827 pass
2828 else:
2829 self.fail("expected TypeError from bogus keyword argument to %r"
2830 % constructor)
2831
2832 def test_str_subclass_as_dict_key(self):
2833 # Testing a str subclass used as dict key ..
2834
2835 class cistr(str):
2836 """Sublcass of str that computes __eq__ case-insensitively.
2837
2838 Also computes a hash code of the string in canonical form.
2839 """
2840
2841 def __init__(self, value):
2842 self.canonical = value.lower()
2843 self.hashcode = hash(self.canonical)
2844
2845 def __eq__(self, other):
2846 if not isinstance(other, cistr):
2847 other = cistr(other)
2848 return self.canonical == other.canonical
2849
2850 def __hash__(self):
2851 return self.hashcode
2852
2853 self.assertEqual(cistr('ABC'), 'abc')
2854 self.assertEqual('aBc', cistr('ABC'))
2855 self.assertEqual(str(cistr('ABC')), 'ABC')
2856
2857 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2858 self.assertEqual(d[cistr('one')], 1)
2859 self.assertEqual(d[cistr('tWo')], 2)
2860 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002861 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002862 self.assertEqual(d.get(cistr('thrEE')), 3)
2863
2864 def test_classic_comparisons(self):
2865 # Testing classic comparisons...
2866 class classic:
2867 pass
2868
2869 for base in (classic, int, object):
2870 class C(base):
2871 def __init__(self, value):
2872 self.value = int(value)
2873 def __cmp__(self, other):
2874 if isinstance(other, C):
2875 return cmp(self.value, other.value)
2876 if isinstance(other, int) or isinstance(other, long):
2877 return cmp(self.value, other)
2878 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002879 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002880
2881 c1 = C(1)
2882 c2 = C(2)
2883 c3 = C(3)
2884 self.assertEqual(c1, 1)
2885 c = {1: c1, 2: c2, 3: c3}
2886 for x in 1, 2, 3:
2887 for y in 1, 2, 3:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002888 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002889 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002890 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002891 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002892 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2893 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002894
2895 def test_rich_comparisons(self):
2896 # Testing rich comparisons...
2897 class Z(complex):
2898 pass
2899 z = Z(1)
2900 self.assertEqual(z, 1+0j)
2901 self.assertEqual(1+0j, z)
2902 class ZZ(complex):
2903 def __eq__(self, other):
2904 try:
2905 return abs(self - other) <= 1e-6
2906 except:
2907 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002908 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002909 zz = ZZ(1.0000003)
2910 self.assertEqual(zz, 1+0j)
2911 self.assertEqual(1+0j, zz)
2912
2913 class classic:
2914 pass
2915 for base in (classic, int, object, list):
2916 class C(base):
2917 def __init__(self, value):
2918 self.value = int(value)
2919 def __cmp__(self_, other):
2920 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002921 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002922 def __eq__(self, other):
2923 if isinstance(other, C):
2924 return self.value == other.value
2925 if isinstance(other, int) or isinstance(other, long):
2926 return self.value == other
2927 return NotImplemented
2928 def __ne__(self, other):
2929 if isinstance(other, C):
2930 return self.value != other.value
2931 if isinstance(other, int) or isinstance(other, long):
2932 return self.value != other
2933 return NotImplemented
2934 def __lt__(self, other):
2935 if isinstance(other, C):
2936 return self.value < other.value
2937 if isinstance(other, int) or isinstance(other, long):
2938 return self.value < other
2939 return NotImplemented
2940 def __le__(self, other):
2941 if isinstance(other, C):
2942 return self.value <= other.value
2943 if isinstance(other, int) or isinstance(other, long):
2944 return self.value <= other
2945 return NotImplemented
2946 def __gt__(self, other):
2947 if isinstance(other, C):
2948 return self.value > other.value
2949 if isinstance(other, int) or isinstance(other, long):
2950 return self.value > other
2951 return NotImplemented
2952 def __ge__(self, other):
2953 if isinstance(other, C):
2954 return self.value >= other.value
2955 if isinstance(other, int) or isinstance(other, long):
2956 return self.value >= other
2957 return NotImplemented
2958 c1 = C(1)
2959 c2 = C(2)
2960 c3 = C(3)
2961 self.assertEqual(c1, 1)
2962 c = {1: c1, 2: c2, 3: c3}
2963 for x in 1, 2, 3:
2964 for y in 1, 2, 3:
2965 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002966 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002967 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002968 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002969 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002970 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002971 "x=%d, y=%d" % (x, y))
2972
2973 def test_coercions(self):
2974 # Testing coercions...
2975 class I(int): pass
2976 coerce(I(0), 0)
2977 coerce(0, I(0))
2978 class L(long): pass
2979 coerce(L(0), 0)
2980 coerce(L(0), 0L)
2981 coerce(0, L(0))
2982 coerce(0L, L(0))
2983 class F(float): pass
2984 coerce(F(0), 0)
2985 coerce(F(0), 0L)
2986 coerce(F(0), 0.)
2987 coerce(0, F(0))
2988 coerce(0L, F(0))
2989 coerce(0., F(0))
2990 class C(complex): pass
2991 coerce(C(0), 0)
2992 coerce(C(0), 0L)
2993 coerce(C(0), 0.)
2994 coerce(C(0), 0j)
2995 coerce(0, C(0))
2996 coerce(0L, C(0))
2997 coerce(0., C(0))
2998 coerce(0j, C(0))
2999
3000 def test_descrdoc(self):
3001 # Testing descriptor doc strings...
3002 def check(descr, what):
3003 self.assertEqual(descr.__doc__, what)
3004 check(file.closed, "True if the file is closed") # getset descriptor
3005 check(file.name, "file name") # member descriptor
3006
3007 def test_doc_descriptor(self):
3008 # Testing __doc__ descriptor...
3009 # SF bug 542984
3010 class DocDescr(object):
3011 def __get__(self, object, otype):
3012 if object:
3013 object = object.__class__.__name__ + ' instance'
3014 if otype:
3015 otype = otype.__name__
3016 return 'object=%s; type=%s' % (object, otype)
3017 class OldClass:
3018 __doc__ = DocDescr()
3019 class NewClass(object):
3020 __doc__ = DocDescr()
3021 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3022 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3023 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3024 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3025
3026 def test_set_class(self):
3027 # Testing __class__ assignment...
3028 class C(object): pass
3029 class D(object): pass
3030 class E(object): pass
3031 class F(D, E): pass
3032 for cls in C, D, E, F:
3033 for cls2 in C, D, E, F:
3034 x = cls()
3035 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003036 self.assertTrue(x.__class__ is cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003037 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003038 self.assertTrue(x.__class__ is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003039 def cant(x, C):
3040 try:
3041 x.__class__ = C
3042 except TypeError:
3043 pass
3044 else:
3045 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3046 try:
3047 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003048 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003049 pass
3050 else:
3051 self.fail("shouldn't allow del %r.__class__" % x)
3052 cant(C(), list)
3053 cant(list(), C)
3054 cant(C(), 1)
3055 cant(C(), object)
3056 cant(object(), list)
3057 cant(list(), object)
3058 class Int(int): __slots__ = []
3059 cant(2, Int)
3060 cant(Int(), int)
3061 cant(True, int)
3062 cant(2, bool)
3063 o = object()
3064 cant(o, type(1))
3065 cant(o, type(None))
3066 del o
3067 class G(object):
3068 __slots__ = ["a", "b"]
3069 class H(object):
3070 __slots__ = ["b", "a"]
3071 try:
3072 unicode
3073 except NameError:
3074 class I(object):
3075 __slots__ = ["a", "b"]
3076 else:
3077 class I(object):
3078 __slots__ = [unicode("a"), unicode("b")]
3079 class J(object):
3080 __slots__ = ["c", "b"]
3081 class K(object):
3082 __slots__ = ["a", "b", "d"]
3083 class L(H):
3084 __slots__ = ["e"]
3085 class M(I):
3086 __slots__ = ["e"]
3087 class N(J):
3088 __slots__ = ["__weakref__"]
3089 class P(J):
3090 __slots__ = ["__dict__"]
3091 class Q(J):
3092 pass
3093 class R(J):
3094 __slots__ = ["__dict__", "__weakref__"]
3095
3096 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3097 x = cls()
3098 x.a = 1
3099 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003100 self.assertTrue(x.__class__ is cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003101 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3102 self.assertEqual(x.a, 1)
3103 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003104 self.assertTrue(x.__class__ is cls,
Georg Brandl48545522008-02-02 10:12:36 +00003105 "assigning %r as __class__ for %r silently failed" % (cls, x))
3106 self.assertEqual(x.a, 1)
3107 for cls in G, J, K, L, M, N, P, R, list, Int:
3108 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3109 if cls is cls2:
3110 continue
3111 cant(cls(), cls2)
3112
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003113 # Issue5283: when __class__ changes in __del__, the wrong
3114 # type gets DECREF'd.
3115 class O(object):
3116 pass
3117 class A(object):
3118 def __del__(self):
3119 self.__class__ = O
3120 l = [A() for x in range(100)]
3121 del l
3122
Georg Brandl48545522008-02-02 10:12:36 +00003123 def test_set_dict(self):
3124 # Testing __dict__ assignment...
3125 class C(object): pass
3126 a = C()
3127 a.__dict__ = {'b': 1}
3128 self.assertEqual(a.b, 1)
3129 def cant(x, dict):
3130 try:
3131 x.__dict__ = dict
3132 except (AttributeError, TypeError):
3133 pass
3134 else:
3135 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3136 cant(a, None)
3137 cant(a, [])
3138 cant(a, 1)
3139 del a.__dict__ # Deleting __dict__ is allowed
3140
3141 class Base(object):
3142 pass
3143 def verify_dict_readonly(x):
3144 """
3145 x has to be an instance of a class inheriting from Base.
3146 """
3147 cant(x, {})
3148 try:
3149 del x.__dict__
3150 except (AttributeError, TypeError):
3151 pass
3152 else:
3153 self.fail("shouldn't allow del %r.__dict__" % x)
3154 dict_descr = Base.__dict__["__dict__"]
3155 try:
3156 dict_descr.__set__(x, {})
3157 except (AttributeError, TypeError):
3158 pass
3159 else:
3160 self.fail("dict_descr allowed access to %r's dict" % x)
3161
3162 # Classes don't allow __dict__ assignment and have readonly dicts
3163 class Meta1(type, Base):
3164 pass
3165 class Meta2(Base, type):
3166 pass
3167 class D(object):
3168 __metaclass__ = Meta1
3169 class E(object):
3170 __metaclass__ = Meta2
3171 for cls in C, D, E:
3172 verify_dict_readonly(cls)
3173 class_dict = cls.__dict__
3174 try:
3175 class_dict["spam"] = "eggs"
3176 except TypeError:
3177 pass
3178 else:
3179 self.fail("%r's __dict__ can be modified" % cls)
3180
3181 # Modules also disallow __dict__ assignment
3182 class Module1(types.ModuleType, Base):
3183 pass
3184 class Module2(Base, types.ModuleType):
3185 pass
3186 for ModuleType in Module1, Module2:
3187 mod = ModuleType("spam")
3188 verify_dict_readonly(mod)
3189 mod.__dict__["spam"] = "eggs"
3190
3191 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003192 # (at least not any more than regular exception's __dict__ can
3193 # be deleted; on CPython it is not the case, whereas on PyPy they
3194 # can, just like any other new-style instance's __dict__.)
3195 def can_delete_dict(e):
3196 try:
3197 del e.__dict__
3198 except (TypeError, AttributeError):
3199 return False
3200 else:
3201 return True
Georg Brandl48545522008-02-02 10:12:36 +00003202 class Exception1(Exception, Base):
3203 pass
3204 class Exception2(Base, Exception):
3205 pass
3206 for ExceptionType in Exception, Exception1, Exception2:
3207 e = ExceptionType()
3208 e.__dict__ = {"a": 1}
3209 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003210 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003211
3212 def test_pickles(self):
3213 # Testing pickling and copying new-style classes and objects...
3214 import pickle, cPickle
3215
3216 def sorteditems(d):
3217 L = d.items()
3218 L.sort()
3219 return L
3220
3221 global C
3222 class C(object):
3223 def __init__(self, a, b):
3224 super(C, self).__init__()
3225 self.a = a
3226 self.b = b
3227 def __repr__(self):
3228 return "C(%r, %r)" % (self.a, self.b)
3229
3230 global C1
3231 class C1(list):
3232 def __new__(cls, a, b):
3233 return super(C1, cls).__new__(cls)
3234 def __getnewargs__(self):
3235 return (self.a, self.b)
3236 def __init__(self, a, b):
3237 self.a = a
3238 self.b = b
3239 def __repr__(self):
3240 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3241
3242 global C2
3243 class C2(int):
3244 def __new__(cls, a, b, val=0):
3245 return super(C2, cls).__new__(cls, val)
3246 def __getnewargs__(self):
3247 return (self.a, self.b, int(self))
3248 def __init__(self, a, b, val=0):
3249 self.a = a
3250 self.b = b
3251 def __repr__(self):
3252 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3253
3254 global C3
3255 class C3(object):
3256 def __init__(self, foo):
3257 self.foo = foo
3258 def __getstate__(self):
3259 return self.foo
3260 def __setstate__(self, foo):
3261 self.foo = foo
3262
3263 global C4classic, C4
3264 class C4classic: # classic
3265 pass
3266 class C4(C4classic, object): # mixed inheritance
3267 pass
3268
3269 for p in pickle, cPickle:
3270 for bin in 0, 1:
3271 for cls in C, C1, C2:
3272 s = p.dumps(cls, bin)
3273 cls2 = p.loads(s)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003274 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003275
3276 a = C1(1, 2); a.append(42); a.append(24)
3277 b = C2("hello", "world", 42)
3278 s = p.dumps((a, b), bin)
3279 x, y = p.loads(s)
3280 self.assertEqual(x.__class__, a.__class__)
3281 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3282 self.assertEqual(y.__class__, b.__class__)
3283 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3284 self.assertEqual(repr(x), repr(a))
3285 self.assertEqual(repr(y), repr(b))
3286 # Test for __getstate__ and __setstate__ on new style class
3287 u = C3(42)
3288 s = p.dumps(u, bin)
3289 v = p.loads(s)
3290 self.assertEqual(u.__class__, v.__class__)
3291 self.assertEqual(u.foo, v.foo)
3292 # Test for picklability of hybrid class
3293 u = C4()
3294 u.foo = 42
3295 s = p.dumps(u, bin)
3296 v = p.loads(s)
3297 self.assertEqual(u.__class__, v.__class__)
3298 self.assertEqual(u.foo, v.foo)
3299
3300 # Testing copy.deepcopy()
3301 import copy
3302 for cls in C, C1, C2:
3303 cls2 = copy.deepcopy(cls)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003304 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003305
3306 a = C1(1, 2); a.append(42); a.append(24)
3307 b = C2("hello", "world", 42)
3308 x, y = copy.deepcopy((a, b))
3309 self.assertEqual(x.__class__, a.__class__)
3310 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3311 self.assertEqual(y.__class__, b.__class__)
3312 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3313 self.assertEqual(repr(x), repr(a))
3314 self.assertEqual(repr(y), repr(b))
3315
3316 def test_pickle_slots(self):
3317 # Testing pickling of classes with __slots__ ...
3318 import pickle, cPickle
3319 # Pickling of classes with __slots__ but without __getstate__ should fail
3320 global B, C, D, E
3321 class B(object):
3322 pass
3323 for base in [object, B]:
3324 class C(base):
3325 __slots__ = ['a']
3326 class D(C):
3327 pass
3328 try:
3329 pickle.dumps(C())
3330 except TypeError:
3331 pass
3332 else:
3333 self.fail("should fail: pickle C instance - %s" % base)
3334 try:
3335 cPickle.dumps(C())
3336 except TypeError:
3337 pass
3338 else:
3339 self.fail("should fail: cPickle C instance - %s" % base)
3340 try:
3341 pickle.dumps(C())
3342 except TypeError:
3343 pass
3344 else:
3345 self.fail("should fail: pickle D instance - %s" % base)
3346 try:
3347 cPickle.dumps(D())
3348 except TypeError:
3349 pass
3350 else:
3351 self.fail("should fail: cPickle D instance - %s" % base)
3352 # Give C a nice generic __getstate__ and __setstate__
3353 class C(base):
3354 __slots__ = ['a']
3355 def __getstate__(self):
3356 try:
3357 d = self.__dict__.copy()
3358 except AttributeError:
3359 d = {}
3360 for cls in self.__class__.__mro__:
3361 for sn in cls.__dict__.get('__slots__', ()):
3362 try:
3363 d[sn] = getattr(self, sn)
3364 except AttributeError:
3365 pass
3366 return d
3367 def __setstate__(self, d):
3368 for k, v in d.items():
3369 setattr(self, k, v)
3370 class D(C):
3371 pass
3372 # Now it should work
3373 x = C()
3374 y = pickle.loads(pickle.dumps(x))
3375 self.assertEqual(hasattr(y, 'a'), 0)
3376 y = cPickle.loads(cPickle.dumps(x))
3377 self.assertEqual(hasattr(y, 'a'), 0)
3378 x.a = 42
3379 y = pickle.loads(pickle.dumps(x))
3380 self.assertEqual(y.a, 42)
3381 y = cPickle.loads(cPickle.dumps(x))
3382 self.assertEqual(y.a, 42)
3383 x = D()
3384 x.a = 42
3385 x.b = 100
3386 y = pickle.loads(pickle.dumps(x))
3387 self.assertEqual(y.a + y.b, 142)
3388 y = cPickle.loads(cPickle.dumps(x))
3389 self.assertEqual(y.a + y.b, 142)
3390 # A subclass that adds a slot should also work
3391 class E(C):
3392 __slots__ = ['b']
3393 x = E()
3394 x.a = 42
3395 x.b = "foo"
3396 y = pickle.loads(pickle.dumps(x))
3397 self.assertEqual(y.a, x.a)
3398 self.assertEqual(y.b, x.b)
3399 y = cPickle.loads(cPickle.dumps(x))
3400 self.assertEqual(y.a, x.a)
3401 self.assertEqual(y.b, x.b)
3402
3403 def test_binary_operator_override(self):
3404 # Testing overrides of binary operations...
3405 class I(int):
3406 def __repr__(self):
3407 return "I(%r)" % int(self)
3408 def __add__(self, other):
3409 return I(int(self) + int(other))
3410 __radd__ = __add__
3411 def __pow__(self, other, mod=None):
3412 if mod is None:
3413 return I(pow(int(self), int(other)))
3414 else:
3415 return I(pow(int(self), int(other), int(mod)))
3416 def __rpow__(self, other, mod=None):
3417 if mod is None:
3418 return I(pow(int(other), int(self), mod))
3419 else:
3420 return I(pow(int(other), int(self), int(mod)))
3421
3422 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3423 self.assertEqual(repr(I(1) + 2), "I(3)")
3424 self.assertEqual(repr(1 + I(2)), "I(3)")
3425 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3426 self.assertEqual(repr(2 ** I(3)), "I(8)")
3427 self.assertEqual(repr(I(2) ** 3), "I(8)")
3428 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3429 class S(str):
3430 def __eq__(self, other):
3431 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003432 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003433
3434 def test_subclass_propagation(self):
3435 # Testing propagation of slot functions to subclasses...
3436 class A(object):
3437 pass
3438 class B(A):
3439 pass
3440 class C(A):
3441 pass
3442 class D(B, C):
3443 pass
3444 d = D()
3445 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3446 A.__hash__ = lambda self: 42
3447 self.assertEqual(hash(d), 42)
3448 C.__hash__ = lambda self: 314
3449 self.assertEqual(hash(d), 314)
3450 B.__hash__ = lambda self: 144
3451 self.assertEqual(hash(d), 144)
3452 D.__hash__ = lambda self: 100
3453 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003454 D.__hash__ = None
3455 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003456 del D.__hash__
3457 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003458 B.__hash__ = None
3459 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003460 del B.__hash__
3461 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003462 C.__hash__ = None
3463 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003464 del C.__hash__
3465 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003466 A.__hash__ = None
3467 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003468 del A.__hash__
3469 self.assertEqual(hash(d), orig_hash)
3470 d.foo = 42
3471 d.bar = 42
3472 self.assertEqual(d.foo, 42)
3473 self.assertEqual(d.bar, 42)
3474 def __getattribute__(self, name):
3475 if name == "foo":
3476 return 24
3477 return object.__getattribute__(self, name)
3478 A.__getattribute__ = __getattribute__
3479 self.assertEqual(d.foo, 24)
3480 self.assertEqual(d.bar, 42)
3481 def __getattr__(self, name):
3482 if name in ("spam", "foo", "bar"):
3483 return "hello"
3484 raise AttributeError, name
3485 B.__getattr__ = __getattr__
3486 self.assertEqual(d.spam, "hello")
3487 self.assertEqual(d.foo, 24)
3488 self.assertEqual(d.bar, 42)
3489 del A.__getattribute__
3490 self.assertEqual(d.foo, 42)
3491 del d.foo
3492 self.assertEqual(d.foo, "hello")
3493 self.assertEqual(d.bar, 42)
3494 del B.__getattr__
3495 try:
3496 d.foo
3497 except AttributeError:
3498 pass
3499 else:
3500 self.fail("d.foo should be undefined now")
3501
3502 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003503 class A(object):
3504 pass
3505 class B(A):
3506 pass
3507 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003508 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003509 A.__setitem__ = lambda *a: None # crash
3510
3511 def test_buffer_inheritance(self):
3512 # Testing that buffer interface is inherited ...
3513
3514 import binascii
3515 # SF bug [#470040] ParseTuple t# vs subclasses.
3516
3517 class MyStr(str):
3518 pass
3519 base = 'abc'
3520 m = MyStr(base)
3521 # b2a_hex uses the buffer interface to get its argument's value, via
3522 # PyArg_ParseTuple 't#' code.
3523 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3524
3525 # It's not clear that unicode will continue to support the character
3526 # buffer interface, and this test will fail if that's taken away.
3527 class MyUni(unicode):
3528 pass
3529 base = u'abc'
3530 m = MyUni(base)
3531 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3532
3533 class MyInt(int):
3534 pass
3535 m = MyInt(42)
3536 try:
3537 binascii.b2a_hex(m)
3538 self.fail('subclass of int should not have a buffer interface')
3539 except TypeError:
3540 pass
3541
3542 def test_str_of_str_subclass(self):
3543 # Testing __str__ defined in subclass of str ...
3544 import binascii
3545 import cStringIO
3546
3547 class octetstring(str):
3548 def __str__(self):
3549 return binascii.b2a_hex(self)
3550 def __repr__(self):
3551 return self + " repr"
3552
3553 o = octetstring('A')
3554 self.assertEqual(type(o), octetstring)
3555 self.assertEqual(type(str(o)), str)
3556 self.assertEqual(type(repr(o)), str)
3557 self.assertEqual(ord(o), 0x41)
3558 self.assertEqual(str(o), '41')
3559 self.assertEqual(repr(o), 'A repr')
3560 self.assertEqual(o.__str__(), '41')
3561 self.assertEqual(o.__repr__(), 'A repr')
3562
3563 capture = cStringIO.StringIO()
3564 # Calling str() or not exercises different internal paths.
3565 print >> capture, o
3566 print >> capture, str(o)
3567 self.assertEqual(capture.getvalue(), '41\n41\n')
3568 capture.close()
3569
3570 def test_keyword_arguments(self):
3571 # Testing keyword arguments to __init__, __call__...
3572 def f(a): return a
3573 self.assertEqual(f.__call__(a=42), 42)
3574 a = []
3575 list.__init__(a, sequence=[0, 1, 2])
3576 self.assertEqual(a, [0, 1, 2])
3577
3578 def test_recursive_call(self):
3579 # Testing recursive __call__() by setting to instance of class...
3580 class A(object):
3581 pass
3582
3583 A.__call__ = A()
3584 try:
3585 A()()
3586 except RuntimeError:
3587 pass
3588 else:
3589 self.fail("Recursion limit should have been reached for __call__()")
3590
3591 def test_delete_hook(self):
3592 # Testing __del__ hook...
3593 log = []
3594 class C(object):
3595 def __del__(self):
3596 log.append(1)
3597 c = C()
3598 self.assertEqual(log, [])
3599 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003600 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003601 self.assertEqual(log, [1])
3602
3603 class D(object): pass
3604 d = D()
3605 try: del d[0]
3606 except TypeError: pass
3607 else: self.fail("invalid del() didn't raise TypeError")
3608
3609 def test_hash_inheritance(self):
3610 # Testing hash of mutable subclasses...
3611
3612 class mydict(dict):
3613 pass
3614 d = mydict()
3615 try:
3616 hash(d)
3617 except TypeError:
3618 pass
3619 else:
3620 self.fail("hash() of dict subclass should fail")
3621
3622 class mylist(list):
3623 pass
3624 d = mylist()
3625 try:
3626 hash(d)
3627 except TypeError:
3628 pass
3629 else:
3630 self.fail("hash() of list subclass should fail")
3631
3632 def test_str_operations(self):
3633 try: 'a' + 5
3634 except TypeError: pass
3635 else: self.fail("'' + 5 doesn't raise TypeError")
3636
3637 try: ''.split('')
3638 except ValueError: pass
3639 else: self.fail("''.split('') doesn't raise ValueError")
3640
3641 try: ''.join([0])
3642 except TypeError: pass
3643 else: self.fail("''.join([0]) doesn't raise TypeError")
3644
3645 try: ''.rindex('5')
3646 except ValueError: pass
3647 else: self.fail("''.rindex('5') doesn't raise ValueError")
3648
3649 try: '%(n)s' % None
3650 except TypeError: pass
3651 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3652
3653 try: '%(n' % {}
3654 except ValueError: pass
3655 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3656
3657 try: '%*s' % ('abc')
3658 except TypeError: pass
3659 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3660
3661 try: '%*.*s' % ('abc', 5)
3662 except TypeError: pass
3663 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3664
3665 try: '%s' % (1, 2)
3666 except TypeError: pass
3667 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3668
3669 try: '%' % None
3670 except ValueError: pass
3671 else: self.fail("'%' % None doesn't raise ValueError")
3672
3673 self.assertEqual('534253'.isdigit(), 1)
3674 self.assertEqual('534253x'.isdigit(), 0)
3675 self.assertEqual('%c' % 5, '\x05')
3676 self.assertEqual('%c' % '5', '5')
3677
3678 def test_deepcopy_recursive(self):
3679 # Testing deepcopy of recursive objects...
3680 class Node:
3681 pass
3682 a = Node()
3683 b = Node()
3684 a.b = b
3685 b.a = a
3686 z = deepcopy(a) # This blew up before
3687
3688 def test_unintialized_modules(self):
3689 # Testing uninitialized module objects...
3690 from types import ModuleType as M
3691 m = M.__new__(M)
3692 str(m)
3693 self.assertEqual(hasattr(m, "__name__"), 0)
3694 self.assertEqual(hasattr(m, "__file__"), 0)
3695 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003696 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003697 m.foo = 1
3698 self.assertEqual(m.__dict__, {"foo": 1})
3699
3700 def test_funny_new(self):
3701 # Testing __new__ returning something unexpected...
3702 class C(object):
3703 def __new__(cls, arg):
3704 if isinstance(arg, str): return [1, 2, 3]
3705 elif isinstance(arg, int): return object.__new__(D)
3706 else: return object.__new__(cls)
3707 class D(C):
3708 def __init__(self, arg):
3709 self.foo = arg
3710 self.assertEqual(C("1"), [1, 2, 3])
3711 self.assertEqual(D("1"), [1, 2, 3])
3712 d = D(None)
3713 self.assertEqual(d.foo, None)
3714 d = C(1)
3715 self.assertEqual(isinstance(d, D), True)
3716 self.assertEqual(d.foo, 1)
3717 d = D(1)
3718 self.assertEqual(isinstance(d, D), True)
3719 self.assertEqual(d.foo, 1)
3720
3721 def test_imul_bug(self):
3722 # Testing for __imul__ problems...
3723 # SF bug 544647
3724 class C(object):
3725 def __imul__(self, other):
3726 return (self, other)
3727 x = C()
3728 y = x
3729 y *= 1.0
3730 self.assertEqual(y, (x, 1.0))
3731 y = x
3732 y *= 2
3733 self.assertEqual(y, (x, 2))
3734 y = x
3735 y *= 3L
3736 self.assertEqual(y, (x, 3L))
3737 y = x
3738 y *= 1L<<100
3739 self.assertEqual(y, (x, 1L<<100))
3740 y = x
3741 y *= None
3742 self.assertEqual(y, (x, None))
3743 y = x
3744 y *= "foo"
3745 self.assertEqual(y, (x, "foo"))
3746
3747 def test_copy_setstate(self):
3748 # Testing that copy.*copy() correctly uses __setstate__...
3749 import copy
3750 class C(object):
3751 def __init__(self, foo=None):
3752 self.foo = foo
3753 self.__foo = foo
3754 def setfoo(self, foo=None):
3755 self.foo = foo
3756 def getfoo(self):
3757 return self.__foo
3758 def __getstate__(self):
3759 return [self.foo]
3760 def __setstate__(self_, lst):
3761 self.assertEqual(len(lst), 1)
3762 self_.__foo = self_.foo = lst[0]
3763 a = C(42)
3764 a.setfoo(24)
3765 self.assertEqual(a.foo, 24)
3766 self.assertEqual(a.getfoo(), 42)
3767 b = copy.copy(a)
3768 self.assertEqual(b.foo, 24)
3769 self.assertEqual(b.getfoo(), 24)
3770 b = copy.deepcopy(a)
3771 self.assertEqual(b.foo, 24)
3772 self.assertEqual(b.getfoo(), 24)
3773
3774 def test_slices(self):
3775 # Testing cases with slices and overridden __getitem__ ...
3776
3777 # Strings
3778 self.assertEqual("hello"[:4], "hell")
3779 self.assertEqual("hello"[slice(4)], "hell")
3780 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3781 class S(str):
3782 def __getitem__(self, x):
3783 return str.__getitem__(self, x)
3784 self.assertEqual(S("hello")[:4], "hell")
3785 self.assertEqual(S("hello")[slice(4)], "hell")
3786 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3787 # Tuples
3788 self.assertEqual((1,2,3)[:2], (1,2))
3789 self.assertEqual((1,2,3)[slice(2)], (1,2))
3790 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3791 class T(tuple):
3792 def __getitem__(self, x):
3793 return tuple.__getitem__(self, x)
3794 self.assertEqual(T((1,2,3))[:2], (1,2))
3795 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3796 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3797 # Lists
3798 self.assertEqual([1,2,3][:2], [1,2])
3799 self.assertEqual([1,2,3][slice(2)], [1,2])
3800 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3801 class L(list):
3802 def __getitem__(self, x):
3803 return list.__getitem__(self, x)
3804 self.assertEqual(L([1,2,3])[:2], [1,2])
3805 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3806 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3807 # Now do lists and __setitem__
3808 a = L([1,2,3])
3809 a[slice(1, 3)] = [3,2]
3810 self.assertEqual(a, [1,3,2])
3811 a[slice(0, 2, 1)] = [3,1]
3812 self.assertEqual(a, [3,1,2])
3813 a.__setitem__(slice(1, 3), [2,1])
3814 self.assertEqual(a, [3,2,1])
3815 a.__setitem__(slice(0, 2, 1), [2,3])
3816 self.assertEqual(a, [2,3,1])
3817
3818 def test_subtype_resurrection(self):
3819 # Testing resurrection of new-style instance...
3820
3821 class C(object):
3822 container = []
3823
3824 def __del__(self):
3825 # resurrect the instance
3826 C.container.append(self)
3827
3828 c = C()
3829 c.attr = 42
3830
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003831 # The most interesting thing here is whether this blows up, due to
3832 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3833 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003834 del c
3835
3836 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003837 # the last container slot works: that will attempt to delete c again,
3838 # which will cause c to get appended back to the container again
3839 # "during" the del. (On non-CPython implementations, however, __del__
3840 # is typically not called again.)
3841 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003842 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003843 del C.container[-1]
3844 if test_support.check_impl_detail():
3845 test_support.gc_collect()
3846 self.assertEqual(len(C.container), 1)
3847 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003848
3849 # Make c mortal again, so that the test framework with -l doesn't report
3850 # it as a leak.
3851 del C.__del__
3852
3853 def test_slots_trash(self):
3854 # Testing slot trash...
3855 # Deallocating deeply nested slotted trash caused stack overflows
3856 class trash(object):
3857 __slots__ = ['x']
3858 def __init__(self, x):
3859 self.x = x
3860 o = None
3861 for i in xrange(50000):
3862 o = trash(o)
3863 del o
3864
3865 def test_slots_multiple_inheritance(self):
3866 # SF bug 575229, multiple inheritance w/ slots dumps core
3867 class A(object):
3868 __slots__=()
3869 class B(object):
3870 pass
3871 class C(A,B) :
3872 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003873 if test_support.check_impl_detail():
3874 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003875 self.assertTrue(hasattr(C, '__dict__'))
3876 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl48545522008-02-02 10:12:36 +00003877 C().x = 2
3878
3879 def test_rmul(self):
3880 # Testing correct invocation of __rmul__...
3881 # SF patch 592646
3882 class C(object):
3883 def __mul__(self, other):
3884 return "mul"
3885 def __rmul__(self, other):
3886 return "rmul"
3887 a = C()
3888 self.assertEqual(a*2, "mul")
3889 self.assertEqual(a*2.2, "mul")
3890 self.assertEqual(2*a, "rmul")
3891 self.assertEqual(2.2*a, "rmul")
3892
3893 def test_ipow(self):
3894 # Testing correct invocation of __ipow__...
3895 # [SF bug 620179]
3896 class C(object):
3897 def __ipow__(self, other):
3898 pass
3899 a = C()
3900 a **= 2
3901
3902 def test_mutable_bases(self):
3903 # Testing mutable bases...
3904
3905 # stuff that should work:
3906 class C(object):
3907 pass
3908 class C2(object):
3909 def __getattribute__(self, attr):
3910 if attr == 'a':
3911 return 2
3912 else:
3913 return super(C2, self).__getattribute__(attr)
3914 def meth(self):
3915 return 1
3916 class D(C):
3917 pass
3918 class E(D):
3919 pass
3920 d = D()
3921 e = E()
3922 D.__bases__ = (C,)
3923 D.__bases__ = (C2,)
3924 self.assertEqual(d.meth(), 1)
3925 self.assertEqual(e.meth(), 1)
3926 self.assertEqual(d.a, 2)
3927 self.assertEqual(e.a, 2)
3928 self.assertEqual(C2.__subclasses__(), [D])
3929
Georg Brandl48545522008-02-02 10:12:36 +00003930 try:
3931 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003932 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003933 pass
3934 else:
3935 self.fail("shouldn't be able to delete .__bases__")
3936
3937 try:
3938 D.__bases__ = ()
3939 except TypeError, msg:
3940 if str(msg) == "a new-style class can't have only classic bases":
3941 self.fail("wrong error message for .__bases__ = ()")
3942 else:
3943 self.fail("shouldn't be able to set .__bases__ to ()")
3944
3945 try:
3946 D.__bases__ = (D,)
3947 except TypeError:
3948 pass
3949 else:
3950 # actually, we'll have crashed by here...
3951 self.fail("shouldn't be able to create inheritance cycles")
3952
3953 try:
3954 D.__bases__ = (C, C)
3955 except TypeError:
3956 pass
3957 else:
3958 self.fail("didn't detect repeated base classes")
3959
3960 try:
3961 D.__bases__ = (E,)
3962 except TypeError:
3963 pass
3964 else:
3965 self.fail("shouldn't be able to create inheritance cycles")
3966
3967 # let's throw a classic class into the mix:
3968 class Classic:
3969 def meth2(self):
3970 return 3
3971
3972 D.__bases__ = (C, Classic)
3973
3974 self.assertEqual(d.meth2(), 3)
3975 self.assertEqual(e.meth2(), 3)
3976 try:
3977 d.a
3978 except AttributeError:
3979 pass
3980 else:
3981 self.fail("attribute should have vanished")
3982
3983 try:
3984 D.__bases__ = (Classic,)
3985 except TypeError:
3986 pass
3987 else:
3988 self.fail("new-style class must have a new-style base")
3989
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003990 def test_builtin_bases(self):
3991 # Make sure all the builtin types can have their base queried without
3992 # segfaulting. See issue #5787.
3993 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3994 if isinstance(tp, type)]
3995 for tp in builtin_types:
3996 object.__getattribute__(tp, "__bases__")
3997 if tp is not object:
3998 self.assertEqual(len(tp.__bases__), 1, tp)
3999
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00004000 class L(list):
4001 pass
4002
4003 class C(object):
4004 pass
4005
4006 class D(C):
4007 pass
4008
4009 try:
4010 L.__bases__ = (dict,)
4011 except TypeError:
4012 pass
4013 else:
4014 self.fail("shouldn't turn list subclass into dict subclass")
4015
4016 try:
4017 list.__bases__ = (dict,)
4018 except TypeError:
4019 pass
4020 else:
4021 self.fail("shouldn't be able to assign to list.__bases__")
4022
4023 try:
4024 D.__bases__ = (C, list)
4025 except TypeError:
4026 pass
4027 else:
4028 assert 0, "best_base calculation found wanting"
4029
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004030
Georg Brandl48545522008-02-02 10:12:36 +00004031 def test_mutable_bases_with_failing_mro(self):
4032 # Testing mutable bases with failing mro...
4033 class WorkOnce(type):
4034 def __new__(self, name, bases, ns):
4035 self.flag = 0
4036 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4037 def mro(self):
4038 if self.flag > 0:
4039 raise RuntimeError, "bozo"
4040 else:
4041 self.flag += 1
4042 return type.mro(self)
4043
4044 class WorkAlways(type):
4045 def mro(self):
4046 # this is here to make sure that .mro()s aren't called
4047 # with an exception set (which was possible at one point).
4048 # An error message will be printed in a debug build.
4049 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004050 return type.mro(self)
4051
Georg Brandl48545522008-02-02 10:12:36 +00004052 class C(object):
4053 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004054
Georg Brandl48545522008-02-02 10:12:36 +00004055 class C2(object):
4056 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004057
Georg Brandl48545522008-02-02 10:12:36 +00004058 class D(C):
4059 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004060
Georg Brandl48545522008-02-02 10:12:36 +00004061 class E(D):
4062 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004063
Georg Brandl48545522008-02-02 10:12:36 +00004064 class F(D):
4065 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004066
Georg Brandl48545522008-02-02 10:12:36 +00004067 class G(D):
4068 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004069
Georg Brandl48545522008-02-02 10:12:36 +00004070 # Immediate subclasses have their mro's adjusted in alphabetical
4071 # order, so E's will get adjusted before adjusting F's fails. We
4072 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004073
Georg Brandl48545522008-02-02 10:12:36 +00004074 E_mro_before = E.__mro__
4075 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004076
Armin Rigofd163f92005-12-29 15:59:19 +00004077 try:
Georg Brandl48545522008-02-02 10:12:36 +00004078 D.__bases__ = (C2,)
4079 except RuntimeError:
4080 self.assertEqual(E.__mro__, E_mro_before)
4081 self.assertEqual(D.__mro__, D_mro_before)
4082 else:
4083 self.fail("exception not propagated")
4084
4085 def test_mutable_bases_catch_mro_conflict(self):
4086 # Testing mutable bases catch mro conflict...
4087 class A(object):
4088 pass
4089
4090 class B(object):
4091 pass
4092
4093 class C(A, B):
4094 pass
4095
4096 class D(A, B):
4097 pass
4098
4099 class E(C, D):
4100 pass
4101
4102 try:
4103 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004104 except TypeError:
4105 pass
4106 else:
Georg Brandl48545522008-02-02 10:12:36 +00004107 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004108
Georg Brandl48545522008-02-02 10:12:36 +00004109 def test_mutable_names(self):
4110 # Testing mutable names...
4111 class C(object):
4112 pass
4113
4114 # C.__module__ could be 'test_descr' or '__main__'
4115 mod = C.__module__
4116
4117 C.__name__ = 'D'
4118 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4119
4120 C.__name__ = 'D.E'
4121 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4122
4123 def test_subclass_right_op(self):
4124 # Testing correct dispatch of subclass overloading __r<op>__...
4125
4126 # This code tests various cases where right-dispatch of a subclass
4127 # should be preferred over left-dispatch of a base class.
4128
4129 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4130
4131 class B(int):
4132 def __floordiv__(self, other):
4133 return "B.__floordiv__"
4134 def __rfloordiv__(self, other):
4135 return "B.__rfloordiv__"
4136
4137 self.assertEqual(B(1) // 1, "B.__floordiv__")
4138 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4139
4140 # Case 2: subclass of object; this is just the baseline for case 3
4141
4142 class C(object):
4143 def __floordiv__(self, other):
4144 return "C.__floordiv__"
4145 def __rfloordiv__(self, other):
4146 return "C.__rfloordiv__"
4147
4148 self.assertEqual(C() // 1, "C.__floordiv__")
4149 self.assertEqual(1 // C(), "C.__rfloordiv__")
4150
4151 # Case 3: subclass of new-style class; here it gets interesting
4152
4153 class D(C):
4154 def __floordiv__(self, other):
4155 return "D.__floordiv__"
4156 def __rfloordiv__(self, other):
4157 return "D.__rfloordiv__"
4158
4159 self.assertEqual(D() // C(), "D.__floordiv__")
4160 self.assertEqual(C() // D(), "D.__rfloordiv__")
4161
4162 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4163
4164 class E(C):
4165 pass
4166
4167 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4168
4169 self.assertEqual(E() // 1, "C.__floordiv__")
4170 self.assertEqual(1 // E(), "C.__rfloordiv__")
4171 self.assertEqual(E() // C(), "C.__floordiv__")
4172 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4173
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004174 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004175 def test_meth_class_get(self):
4176 # Testing __get__ method of METH_CLASS C methods...
4177 # Full coverage of descrobject.c::classmethod_get()
4178
4179 # Baseline
4180 arg = [1, 2, 3]
4181 res = {1: None, 2: None, 3: None}
4182 self.assertEqual(dict.fromkeys(arg), res)
4183 self.assertEqual({}.fromkeys(arg), res)
4184
4185 # Now get the descriptor
4186 descr = dict.__dict__["fromkeys"]
4187
4188 # More baseline using the descriptor directly
4189 self.assertEqual(descr.__get__(None, dict)(arg), res)
4190 self.assertEqual(descr.__get__({})(arg), res)
4191
4192 # Now check various error cases
4193 try:
4194 descr.__get__(None, None)
4195 except TypeError:
4196 pass
4197 else:
4198 self.fail("shouldn't have allowed descr.__get__(None, None)")
4199 try:
4200 descr.__get__(42)
4201 except TypeError:
4202 pass
4203 else:
4204 self.fail("shouldn't have allowed descr.__get__(42)")
4205 try:
4206 descr.__get__(None, 42)
4207 except TypeError:
4208 pass
4209 else:
4210 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4211 try:
4212 descr.__get__(None, int)
4213 except TypeError:
4214 pass
4215 else:
4216 self.fail("shouldn't have allowed descr.__get__(None, int)")
4217
4218 def test_isinst_isclass(self):
4219 # Testing proxy isinstance() and isclass()...
4220 class Proxy(object):
4221 def __init__(self, obj):
4222 self.__obj = obj
4223 def __getattribute__(self, name):
4224 if name.startswith("_Proxy__"):
4225 return object.__getattribute__(self, name)
4226 else:
4227 return getattr(self.__obj, name)
4228 # Test with a classic class
4229 class C:
4230 pass
4231 a = C()
4232 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004233 self.assertIsInstance(a, C) # Baseline
4234 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004235 # Test with a classic subclass
4236 class D(C):
4237 pass
4238 a = D()
4239 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004240 self.assertIsInstance(a, C) # Baseline
4241 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004242 # Test with a new-style class
4243 class C(object):
4244 pass
4245 a = C()
4246 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004247 self.assertIsInstance(a, C) # Baseline
4248 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004249 # Test with a new-style subclass
4250 class D(C):
4251 pass
4252 a = D()
4253 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004254 self.assertIsInstance(a, C) # Baseline
4255 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004256
4257 def test_proxy_super(self):
4258 # Testing super() for a proxy object...
4259 class Proxy(object):
4260 def __init__(self, obj):
4261 self.__obj = obj
4262 def __getattribute__(self, name):
4263 if name.startswith("_Proxy__"):
4264 return object.__getattribute__(self, name)
4265 else:
4266 return getattr(self.__obj, name)
4267
4268 class B(object):
4269 def f(self):
4270 return "B.f"
4271
4272 class C(B):
4273 def f(self):
4274 return super(C, self).f() + "->C.f"
4275
4276 obj = C()
4277 p = Proxy(obj)
4278 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4279
4280 def test_carloverre(self):
4281 # Testing prohibition of Carlo Verre's hack...
4282 try:
4283 object.__setattr__(str, "foo", 42)
4284 except TypeError:
4285 pass
4286 else:
Ezio Melottic2077b02011-03-16 12:34:31 +02004287 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl48545522008-02-02 10:12:36 +00004288 try:
4289 object.__delattr__(str, "lower")
4290 except TypeError:
4291 pass
4292 else:
4293 self.fail("Carlo Verre __delattr__ succeeded!")
4294
4295 def test_weakref_segfault(self):
4296 # Testing weakref segfault...
4297 # SF 742911
4298 import weakref
4299
4300 class Provoker:
4301 def __init__(self, referrent):
4302 self.ref = weakref.ref(referrent)
4303
4304 def __del__(self):
4305 x = self.ref()
4306
4307 class Oops(object):
4308 pass
4309
4310 o = Oops()
4311 o.whatever = Provoker(o)
4312 del o
4313
4314 def test_wrapper_segfault(self):
4315 # SF 927248: deeply nested wrappers could cause stack overflow
4316 f = lambda:None
4317 for i in xrange(1000000):
4318 f = f.__call__
4319 f = None
4320
4321 def test_file_fault(self):
4322 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004323 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004324 class StdoutGuard:
4325 def __getattr__(self, attr):
4326 sys.stdout = sys.__stdout__
4327 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4328 sys.stdout = StdoutGuard()
4329 try:
4330 print "Oops!"
4331 except RuntimeError:
4332 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004333 finally:
4334 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004335
4336 def test_vicious_descriptor_nonsense(self):
4337 # Testing vicious_descriptor_nonsense...
4338
4339 # A potential segfault spotted by Thomas Wouters in mail to
4340 # python-dev 2003-04-17, turned into an example & fixed by Michael
4341 # Hudson just less than four months later...
4342
4343 class Evil(object):
4344 def __hash__(self):
4345 return hash('attr')
4346 def __eq__(self, other):
4347 del C.attr
4348 return 0
4349
4350 class Descr(object):
4351 def __get__(self, ob, type=None):
4352 return 1
4353
4354 class C(object):
4355 attr = Descr()
4356
4357 c = C()
4358 c.__dict__[Evil()] = 0
4359
4360 self.assertEqual(c.attr, 1)
4361 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004362 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004363 self.assertEqual(hasattr(c, 'attr'), False)
4364
4365 def test_init(self):
4366 # SF 1155938
4367 class Foo(object):
4368 def __init__(self):
4369 return 10
4370 try:
4371 Foo()
4372 except TypeError:
4373 pass
4374 else:
4375 self.fail("did not test __init__() for None return")
4376
4377 def test_method_wrapper(self):
4378 # Testing method-wrapper objects...
4379 # <type 'method-wrapper'> did not support any reflection before 2.5
4380
4381 l = []
4382 self.assertEqual(l.__add__, l.__add__)
4383 self.assertEqual(l.__add__, [].__add__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004384 self.assertTrue(l.__add__ != [5].__add__)
4385 self.assertTrue(l.__add__ != l.__mul__)
4386 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004387 if hasattr(l.__add__, '__self__'):
4388 # CPython
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004389 self.assertTrue(l.__add__.__self__ is l)
4390 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004391 else:
4392 # Python implementations where [].__add__ is a normal bound method
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004393 self.assertTrue(l.__add__.im_self is l)
4394 self.assertTrue(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004395 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4396 try:
4397 hash(l.__add__)
4398 except TypeError:
4399 pass
4400 else:
4401 self.fail("no TypeError from hash([].__add__)")
4402
4403 t = ()
4404 t += (7,)
4405 self.assertEqual(t.__add__, (7,).__add__)
4406 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4407
4408 def test_not_implemented(self):
4409 # Testing NotImplemented...
4410 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004411 import operator
4412
4413 def specialmethod(self, other):
4414 return NotImplemented
4415
4416 def check(expr, x, y):
4417 try:
4418 exec expr in {'x': x, 'y': y, 'operator': operator}
4419 except TypeError:
4420 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004421 else:
Georg Brandl48545522008-02-02 10:12:36 +00004422 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004423
Georg Brandl48545522008-02-02 10:12:36 +00004424 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4425 # TypeErrors
4426 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4427 # ValueErrors instead of TypeErrors
4428 for metaclass in [type, types.ClassType]:
4429 for name, expr, iexpr in [
4430 ('__add__', 'x + y', 'x += y'),
4431 ('__sub__', 'x - y', 'x -= y'),
4432 ('__mul__', 'x * y', 'x *= y'),
4433 ('__truediv__', 'operator.truediv(x, y)', None),
4434 ('__floordiv__', 'operator.floordiv(x, y)', None),
4435 ('__div__', 'x / y', 'x /= y'),
4436 ('__mod__', 'x % y', 'x %= y'),
4437 ('__divmod__', 'divmod(x, y)', None),
4438 ('__pow__', 'x ** y', 'x **= y'),
4439 ('__lshift__', 'x << y', 'x <<= y'),
4440 ('__rshift__', 'x >> y', 'x >>= y'),
4441 ('__and__', 'x & y', 'x &= y'),
4442 ('__or__', 'x | y', 'x |= y'),
4443 ('__xor__', 'x ^ y', 'x ^= y'),
4444 ('__coerce__', 'coerce(x, y)', None)]:
4445 if name == '__coerce__':
4446 rname = name
4447 else:
4448 rname = '__r' + name[2:]
4449 A = metaclass('A', (), {name: specialmethod})
4450 B = metaclass('B', (), {rname: specialmethod})
4451 a = A()
4452 b = B()
4453 check(expr, a, a)
4454 check(expr, a, b)
4455 check(expr, b, a)
4456 check(expr, b, b)
4457 check(expr, a, N1)
4458 check(expr, a, N2)
4459 check(expr, N1, b)
4460 check(expr, N2, b)
4461 if iexpr:
4462 check(iexpr, a, a)
4463 check(iexpr, a, b)
4464 check(iexpr, b, a)
4465 check(iexpr, b, b)
4466 check(iexpr, a, N1)
4467 check(iexpr, a, N2)
4468 iname = '__i' + name[2:]
4469 C = metaclass('C', (), {iname: specialmethod})
4470 c = C()
4471 check(iexpr, c, a)
4472 check(iexpr, c, b)
4473 check(iexpr, c, N1)
4474 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004475
Georg Brandl48545522008-02-02 10:12:36 +00004476 def test_assign_slice(self):
4477 # ceval.c's assign_slice used to check for
4478 # tp->tp_as_sequence->sq_slice instead of
4479 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004480
Georg Brandl48545522008-02-02 10:12:36 +00004481 class C(object):
4482 def __setslice__(self, start, stop, value):
4483 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004484
Georg Brandl48545522008-02-02 10:12:36 +00004485 c = C()
4486 c[1:2] = 3
4487 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004488
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004489 def test_set_and_no_get(self):
4490 # See
4491 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4492 class Descr(object):
4493
4494 def __init__(self, name):
4495 self.name = name
4496
4497 def __set__(self, obj, value):
4498 obj.__dict__[self.name] = value
4499 descr = Descr("a")
4500
4501 class X(object):
4502 a = descr
4503
4504 x = X()
4505 self.assertIs(x.a, descr)
4506 x.a = 42
4507 self.assertEqual(x.a, 42)
4508
Benjamin Peterson42d59472010-02-06 20:14:10 +00004509 # Also check type_getattro for correctness.
4510 class Meta(type):
4511 pass
4512 class X(object):
4513 __metaclass__ = Meta
4514 X.a = 42
4515 Meta.a = Descr("a")
4516 self.assertEqual(X.a, 42)
4517
Benjamin Peterson273c2332008-11-17 22:39:09 +00004518 def test_getattr_hooks(self):
4519 # issue 4230
4520
4521 class Descriptor(object):
4522 counter = 0
4523 def __get__(self, obj, objtype=None):
4524 def getter(name):
4525 self.counter += 1
4526 raise AttributeError(name)
4527 return getter
4528
4529 descr = Descriptor()
4530 class A(object):
4531 __getattribute__ = descr
4532 class B(object):
4533 __getattr__ = descr
4534 class C(object):
4535 __getattribute__ = descr
4536 __getattr__ = descr
4537
4538 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004539 self.assertEqual(descr.counter, 1)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004540 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004541 self.assertEqual(descr.counter, 2)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004542 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004543 self.assertEqual(descr.counter, 4)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004544
Benjamin Peterson273c2332008-11-17 22:39:09 +00004545 class EvilGetattribute(object):
4546 # This used to segfault
4547 def __getattr__(self, name):
4548 raise AttributeError(name)
4549 def __getattribute__(self, name):
4550 del EvilGetattribute.__getattr__
4551 for i in range(5):
4552 gc.collect()
4553 raise AttributeError(name)
4554
4555 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4556
Benjamin Peterson6e7832b2012-03-16 09:32:59 -05004557 def test_type___getattribute__(self):
4558 self.assertRaises(TypeError, type.__getattribute__, list, type)
4559
Benjamin Peterson9b911ca2011-01-12 15:49:47 +00004560 def test_abstractmethods(self):
4561 # type pretends not to have __abstractmethods__.
4562 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4563 class meta(type):
4564 pass
4565 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4566 class X(object):
4567 pass
4568 with self.assertRaises(AttributeError):
4569 del X.__abstractmethods__
4570
Victor Stinnere363ec12011-05-01 23:43:37 +02004571 def test_proxy_call(self):
4572 class FakeStr(object):
4573 __class__ = str
4574
4575 fake_str = FakeStr()
4576 # isinstance() reads __class__ on new style classes
4577 self.assertTrue(isinstance(fake_str, str))
4578
4579 # call a method descriptor
4580 with self.assertRaises(TypeError):
4581 str.split(fake_str)
4582
4583 # call a slot wrapper descriptor
4584 with self.assertRaises(TypeError):
4585 str.__add__(fake_str, "abc")
4586
Antoine Pitrou304f0f92011-07-15 21:22:50 +02004587 def test_repr_as_str(self):
4588 # Issue #11603: crash or infinite loop when rebinding __str__ as
4589 # __repr__.
4590 class Foo(object):
4591 pass
4592 Foo.__repr__ = Foo.__str__
4593 foo = Foo()
4594 str(foo)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004595
Benjamin Petersona8d45852012-03-07 18:41:11 -06004596 def test_cycle_through_dict(self):
4597 # See bug #1469629
4598 class X(dict):
4599 def __init__(self):
4600 dict.__init__(self)
4601 self.__dict__ = self
4602 x = X()
4603 x.attr = 42
4604 wr = weakref.ref(x)
4605 del x
4606 test_support.gc_collect()
4607 self.assertIsNone(wr())
4608 for o in gc.get_objects():
4609 self.assertIsNot(type(o), X)
4610
Georg Brandl48545522008-02-02 10:12:36 +00004611class DictProxyTests(unittest.TestCase):
4612 def setUp(self):
4613 class C(object):
4614 def meth(self):
4615 pass
4616 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004617
Raymond Hettingerbf7a2662011-06-30 00:44:36 +01004618 def test_repr(self):
4619 self.assertIn('dict_proxy({', repr(vars(self.C)))
4620 self.assertIn("'meth':", repr(vars(self.C)))
4621
Georg Brandl48545522008-02-02 10:12:36 +00004622 def test_iter_keys(self):
4623 # Testing dict-proxy iterkeys...
4624 keys = [ key for key in self.C.__dict__.iterkeys() ]
4625 keys.sort()
Ezio Melotti2623a372010-11-21 13:34:58 +00004626 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl48545522008-02-02 10:12:36 +00004627 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004628
Georg Brandl48545522008-02-02 10:12:36 +00004629 def test_iter_values(self):
4630 # Testing dict-proxy itervalues...
4631 values = [ values for values in self.C.__dict__.itervalues() ]
4632 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004633
Georg Brandl48545522008-02-02 10:12:36 +00004634 def test_iter_items(self):
4635 # Testing dict-proxy iteritems...
4636 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4637 keys.sort()
4638 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4639 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004640
Georg Brandl48545522008-02-02 10:12:36 +00004641 def test_dict_type_with_metaclass(self):
4642 # Testing type of __dict__ when __metaclass__ set...
4643 class B(object):
4644 pass
4645 class M(type):
4646 pass
4647 class C:
4648 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4649 __metaclass__ = M
4650 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004651
Guido van Rossum9acc3872008-01-23 23:23:43 +00004652
Georg Brandl48545522008-02-02 10:12:36 +00004653class PTypesLongInitTest(unittest.TestCase):
4654 # This is in its own TestCase so that it can be run before any other tests.
4655 def test_pytype_long_ready(self):
4656 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004657
Georg Brandl48545522008-02-02 10:12:36 +00004658 # This dumps core when SF bug 551412 isn't fixed --
4659 # but only when test_descr.py is run separately.
4660 # (That can't be helped -- as soon as PyType_Ready()
4661 # is called for PyLong_Type, the bug is gone.)
4662 class UserLong(object):
4663 def __pow__(self, *args):
4664 pass
4665 try:
4666 pow(0L, UserLong(), 0L)
4667 except:
4668 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004669
Georg Brandl48545522008-02-02 10:12:36 +00004670 # Another segfault only when run early
4671 # (before PyType_Ready(tuple) is called)
4672 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004673
4674
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004675def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004676 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4677 DeprecationWarning)]
4678 if sys.py3kwarning:
4679 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004680 ("classic (int|long) division", DeprecationWarning),
4681 ("coerce.. not supported", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004682 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4683 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004684 # Run all local test cases, with PTypesLongInitTest first.
4685 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4686 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004687
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004688if __name__ == "__main__":
4689 test_main()