blob: 63a06cd164af55acea6c8330de78c4503805f716 [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
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200401 def assertHasAttr(self, obj, name):
402 self.assertTrue(hasattr(obj, name),
403 '%r has no attribute %r' % (obj, name))
404
405 def assertNotHasAttr(self, obj, name):
406 self.assertFalse(hasattr(obj, name),
407 '%r has unexpected attribute %r' % (obj, name))
408
Georg Brandl48545522008-02-02 10:12:36 +0000409 def test_python_dicts(self):
410 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000411 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000412 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000413 d = dict()
414 self.assertEqual(d, {})
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200415 self.assertIs(d.__class__, dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000416 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000417 class C(dict):
418 state = -1
419 def __init__(self_local, *a, **kw):
420 if a:
421 self.assertEqual(len(a), 1)
422 self_local.state = a[0]
423 if kw:
424 for k, v in kw.items():
425 self_local[v] = k
426 def __getitem__(self, key):
427 return self.get(key, 0)
428 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000429 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000430 dict.__setitem__(self_local, key, value)
431 def setstate(self, state):
432 self.state = state
433 def getstate(self):
434 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000435 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000436 a1 = C(12)
437 self.assertEqual(a1.state, 12)
438 a2 = C(foo=1, bar=2)
439 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
440 a = C()
441 self.assertEqual(a.state, -1)
442 self.assertEqual(a.getstate(), -1)
443 a.setstate(0)
444 self.assertEqual(a.state, 0)
445 self.assertEqual(a.getstate(), 0)
446 a.setstate(10)
447 self.assertEqual(a.state, 10)
448 self.assertEqual(a.getstate(), 10)
449 self.assertEqual(a[42], 0)
450 a[42] = 24
451 self.assertEqual(a[42], 24)
452 N = 50
453 for i in range(N):
454 a[i] = C()
455 for j in range(N):
456 a[i][j] = i*j
457 for i in range(N):
458 for j in range(N):
459 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000460
Georg Brandl48545522008-02-02 10:12:36 +0000461 def test_python_lists(self):
462 # Testing Python subclass of list...
463 class C(list):
464 def __getitem__(self, i):
465 return list.__getitem__(self, i) + 100
466 def __getslice__(self, i, j):
467 return (i, j)
468 a = C()
469 a.extend([0,1,2])
470 self.assertEqual(a[0], 100)
471 self.assertEqual(a[1], 101)
472 self.assertEqual(a[2], 102)
473 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000474
Georg Brandl48545522008-02-02 10:12:36 +0000475 def test_metaclass(self):
476 # Testing __metaclass__...
477 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000478 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000479 def __init__(self):
480 self.__state = 0
481 def getstate(self):
482 return self.__state
483 def setstate(self, state):
484 self.__state = state
485 a = C()
486 self.assertEqual(a.getstate(), 0)
487 a.setstate(10)
488 self.assertEqual(a.getstate(), 10)
489 class D:
490 class __metaclass__(type):
491 def myself(cls): return cls
492 self.assertEqual(D.myself(), D)
493 d = D()
494 self.assertEqual(d.__class__, D)
495 class M1(type):
496 def __new__(cls, name, bases, dict):
497 dict['__spam__'] = 1
498 return type.__new__(cls, name, bases, dict)
499 class C:
500 __metaclass__ = M1
501 self.assertEqual(C.__spam__, 1)
502 c = C()
503 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000504
Georg Brandl48545522008-02-02 10:12:36 +0000505 class _instance(object):
506 pass
507 class M2(object):
508 @staticmethod
509 def __new__(cls, name, bases, dict):
510 self = object.__new__(cls)
511 self.name = name
512 self.bases = bases
513 self.dict = dict
514 return self
515 def __call__(self):
516 it = _instance()
517 # Early binding of methods
518 for key in self.dict:
519 if key.startswith("__"):
520 continue
521 setattr(it, key, self.dict[key].__get__(it, self))
522 return it
523 class C:
524 __metaclass__ = M2
525 def spam(self):
526 return 42
527 self.assertEqual(C.name, 'C')
528 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000529 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000530 c = C()
531 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000532
Georg Brandl48545522008-02-02 10:12:36 +0000533 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000534
Georg Brandl48545522008-02-02 10:12:36 +0000535 class autosuper(type):
536 # Automatically add __super to the class
537 # This trick only works for dynamic classes
538 def __new__(metaclass, name, bases, dict):
539 cls = super(autosuper, metaclass).__new__(metaclass,
540 name, bases, dict)
541 # Name mangling for __super removes leading underscores
542 while name[:1] == "_":
543 name = name[1:]
544 if name:
545 name = "_%s__super" % name
546 else:
547 name = "__super"
548 setattr(cls, name, super(cls))
549 return cls
550 class A:
551 __metaclass__ = autosuper
552 def meth(self):
553 return "A"
554 class B(A):
555 def meth(self):
556 return "B" + self.__super.meth()
557 class C(A):
558 def meth(self):
559 return "C" + self.__super.meth()
560 class D(C, B):
561 def meth(self):
562 return "D" + self.__super.meth()
563 self.assertEqual(D().meth(), "DCBA")
564 class E(B, C):
565 def meth(self):
566 return "E" + self.__super.meth()
567 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000568
Georg Brandl48545522008-02-02 10:12:36 +0000569 class autoproperty(type):
570 # Automatically create property attributes when methods
571 # named _get_x and/or _set_x are found
572 def __new__(metaclass, name, bases, dict):
573 hits = {}
574 for key, val in dict.iteritems():
575 if key.startswith("_get_"):
576 key = key[5:]
577 get, set = hits.get(key, (None, None))
578 get = val
579 hits[key] = get, set
580 elif key.startswith("_set_"):
581 key = key[5:]
582 get, set = hits.get(key, (None, None))
583 set = val
584 hits[key] = get, set
585 for key, (get, set) in hits.iteritems():
586 dict[key] = property(get, set)
587 return super(autoproperty, metaclass).__new__(metaclass,
588 name, bases, dict)
589 class A:
590 __metaclass__ = autoproperty
591 def _get_x(self):
592 return -self.__x
593 def _set_x(self, x):
594 self.__x = -x
595 a = A()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200596 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +0000597 a.x = 12
598 self.assertEqual(a.x, 12)
599 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000600
Georg Brandl48545522008-02-02 10:12:36 +0000601 class multimetaclass(autoproperty, autosuper):
602 # Merge of multiple cooperating metaclasses
603 pass
604 class A:
605 __metaclass__ = multimetaclass
606 def _get_x(self):
607 return "A"
608 class B(A):
609 def _get_x(self):
610 return "B" + self.__super._get_x()
611 class C(A):
612 def _get_x(self):
613 return "C" + self.__super._get_x()
614 class D(C, B):
615 def _get_x(self):
616 return "D" + self.__super._get_x()
617 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000618
Georg Brandl48545522008-02-02 10:12:36 +0000619 # Make sure type(x) doesn't call x.__class__.__init__
620 class T(type):
621 counter = 0
622 def __init__(self, *args):
623 T.counter += 1
624 class C:
625 __metaclass__ = T
626 self.assertEqual(T.counter, 1)
627 a = C()
628 self.assertEqual(type(a), C)
629 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000630
Georg Brandl48545522008-02-02 10:12:36 +0000631 class C(object): pass
632 c = C()
633 try: c()
634 except TypeError: pass
635 else: self.fail("calling object w/o call method should raise "
636 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000637
Georg Brandl48545522008-02-02 10:12:36 +0000638 # Testing code to find most derived baseclass
639 class A(type):
640 def __new__(*args, **kwargs):
641 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642
Georg Brandl48545522008-02-02 10:12:36 +0000643 class B(object):
644 pass
645
646 class C(object):
647 __metaclass__ = A
648
649 # The most derived metaclass of D is A rather than type.
650 class D(B, C):
651 pass
652
653 def test_module_subclasses(self):
654 # Testing Python subclass of module...
655 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000656 MT = type(sys)
657 class MM(MT):
658 def __init__(self, name):
659 MT.__init__(self, name)
660 def __getattribute__(self, name):
661 log.append(("getattr", name))
662 return MT.__getattribute__(self, name)
663 def __setattr__(self, name, value):
664 log.append(("setattr", name, value))
665 MT.__setattr__(self, name, value)
666 def __delattr__(self, name):
667 log.append(("delattr", name))
668 MT.__delattr__(self, name)
669 a = MM("a")
670 a.foo = 12
671 x = a.foo
672 del a.foo
673 self.assertEqual(log, [("setattr", "foo", 12),
674 ("getattr", "foo"),
675 ("delattr", "foo")])
676
677 # http://python.org/sf/1174712
678 try:
679 class Module(types.ModuleType, str):
680 pass
681 except TypeError:
682 pass
683 else:
684 self.fail("inheriting from ModuleType and str at the same time "
685 "should fail")
686
687 def test_multiple_inheritence(self):
688 # Testing multiple inheritance...
689 class C(object):
690 def __init__(self):
691 self.__state = 0
692 def getstate(self):
693 return self.__state
694 def setstate(self, state):
695 self.__state = state
696 a = C()
697 self.assertEqual(a.getstate(), 0)
698 a.setstate(10)
699 self.assertEqual(a.getstate(), 10)
700 class D(dict, C):
701 def __init__(self):
702 type({}).__init__(self)
703 C.__init__(self)
704 d = D()
705 self.assertEqual(d.keys(), [])
706 d["hello"] = "world"
707 self.assertEqual(d.items(), [("hello", "world")])
708 self.assertEqual(d["hello"], "world")
709 self.assertEqual(d.getstate(), 0)
710 d.setstate(10)
711 self.assertEqual(d.getstate(), 10)
712 self.assertEqual(D.__mro__, (D, dict, C, object))
713
714 # SF bug #442833
715 class Node(object):
716 def __int__(self):
717 return int(self.foo())
718 def foo(self):
719 return "23"
720 class Frag(Node, list):
721 def foo(self):
722 return "42"
723 self.assertEqual(Node().__int__(), 23)
724 self.assertEqual(int(Node()), 23)
725 self.assertEqual(Frag().__int__(), 42)
726 self.assertEqual(int(Frag()), 42)
727
728 # MI mixing classic and new-style classes.
729
730 class A:
731 x = 1
732
733 class B(A):
734 pass
735
736 class C(A):
737 x = 2
738
739 class D(B, C):
740 pass
741 self.assertEqual(D.x, 1)
742
743 # Classic MRO is preserved for a classic base class.
744 class E(D, object):
745 pass
746 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
747 self.assertEqual(E.x, 1)
748
749 # But with a mix of classic bases, their MROs are combined using
750 # new-style MRO.
751 class F(B, C, object):
752 pass
753 self.assertEqual(F.__mro__, (F, B, C, A, object))
754 self.assertEqual(F.x, 2)
755
756 # Try something else.
757 class C:
758 def cmethod(self):
759 return "C a"
760 def all_method(self):
761 return "C b"
762
763 class M1(C, object):
764 def m1method(self):
765 return "M1 a"
766 def all_method(self):
767 return "M1 b"
768
769 self.assertEqual(M1.__mro__, (M1, C, object))
770 m = M1()
771 self.assertEqual(m.cmethod(), "C a")
772 self.assertEqual(m.m1method(), "M1 a")
773 self.assertEqual(m.all_method(), "M1 b")
774
775 class D(C):
776 def dmethod(self):
777 return "D a"
778 def all_method(self):
779 return "D b"
780
781 class M2(D, object):
782 def m2method(self):
783 return "M2 a"
784 def all_method(self):
785 return "M2 b"
786
787 self.assertEqual(M2.__mro__, (M2, D, C, object))
788 m = M2()
789 self.assertEqual(m.cmethod(), "C a")
790 self.assertEqual(m.dmethod(), "D a")
791 self.assertEqual(m.m2method(), "M2 a")
792 self.assertEqual(m.all_method(), "M2 b")
793
794 class M3(M1, M2, object):
795 def m3method(self):
796 return "M3 a"
797 def all_method(self):
798 return "M3 b"
799 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
800 m = M3()
801 self.assertEqual(m.cmethod(), "C a")
802 self.assertEqual(m.dmethod(), "D a")
803 self.assertEqual(m.m1method(), "M1 a")
804 self.assertEqual(m.m2method(), "M2 a")
805 self.assertEqual(m.m3method(), "M3 a")
806 self.assertEqual(m.all_method(), "M3 b")
807
808 class Classic:
809 pass
810 try:
811 class New(Classic):
812 __metaclass__ = type
813 except TypeError:
814 pass
815 else:
816 self.fail("new class with only classic bases - shouldn't be")
817
818 def test_diamond_inheritence(self):
819 # Testing multiple inheritance special cases...
820 class A(object):
821 def spam(self): return "A"
822 self.assertEqual(A().spam(), "A")
823 class B(A):
824 def boo(self): return "B"
825 def spam(self): return "B"
826 self.assertEqual(B().spam(), "B")
827 self.assertEqual(B().boo(), "B")
828 class C(A):
829 def boo(self): return "C"
830 self.assertEqual(C().spam(), "A")
831 self.assertEqual(C().boo(), "C")
832 class D(B, C): pass
833 self.assertEqual(D().spam(), "B")
834 self.assertEqual(D().boo(), "B")
835 self.assertEqual(D.__mro__, (D, B, C, A, object))
836 class E(C, B): pass
837 self.assertEqual(E().spam(), "B")
838 self.assertEqual(E().boo(), "C")
839 self.assertEqual(E.__mro__, (E, C, B, A, object))
840 # MRO order disagreement
841 try:
842 class F(D, E): pass
843 except TypeError:
844 pass
845 else:
846 self.fail("expected MRO order disagreement (F)")
847 try:
848 class G(E, D): pass
849 except TypeError:
850 pass
851 else:
852 self.fail("expected MRO order disagreement (G)")
853
854 # see thread python-dev/2002-October/029035.html
855 def test_ex5_from_c3_switch(self):
856 # Testing ex5 from C3 switch discussion...
857 class A(object): pass
858 class B(object): pass
859 class C(object): pass
860 class X(A): pass
861 class Y(A): pass
862 class Z(X,B,Y,C): pass
863 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
864
865 # see "A Monotonic Superclass Linearization for Dylan",
866 # by Kim Barrett et al. (OOPSLA 1996)
867 def test_monotonicity(self):
868 # Testing MRO monotonicity...
869 class Boat(object): pass
870 class DayBoat(Boat): pass
871 class WheelBoat(Boat): pass
872 class EngineLess(DayBoat): pass
873 class SmallMultihull(DayBoat): pass
874 class PedalWheelBoat(EngineLess,WheelBoat): pass
875 class SmallCatamaran(SmallMultihull): pass
876 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
877
878 self.assertEqual(PedalWheelBoat.__mro__,
879 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
880 self.assertEqual(SmallCatamaran.__mro__,
881 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
882 self.assertEqual(Pedalo.__mro__,
883 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
884 SmallMultihull, DayBoat, WheelBoat, Boat, object))
885
886 # see "A Monotonic Superclass Linearization for Dylan",
887 # by Kim Barrett et al. (OOPSLA 1996)
888 def test_consistency_with_epg(self):
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200889 # Testing consistency with EPG...
Georg Brandl48545522008-02-02 10:12:36 +0000890 class Pane(object): pass
891 class ScrollingMixin(object): pass
892 class EditingMixin(object): pass
893 class ScrollablePane(Pane,ScrollingMixin): pass
894 class EditablePane(Pane,EditingMixin): pass
895 class EditableScrollablePane(ScrollablePane,EditablePane): pass
896
897 self.assertEqual(EditableScrollablePane.__mro__,
898 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
899 ScrollingMixin, EditingMixin, object))
900
901 def test_mro_disagreement(self):
902 # Testing error messages for MRO disagreement...
903 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000904order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000905
Georg Brandl48545522008-02-02 10:12:36 +0000906 def raises(exc, expected, callable, *args):
907 try:
908 callable(*args)
909 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000910 # the exact msg is generally considered an impl detail
911 if test_support.check_impl_detail():
912 if not str(msg).startswith(expected):
913 self.fail("Message %r, expected %r" %
914 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000915 else:
916 self.fail("Expected %s" % exc)
917
918 class A(object): pass
919 class B(A): pass
920 class C(object): pass
921
922 # Test some very simple errors
923 raises(TypeError, "duplicate base class A",
924 type, "X", (A, A), {})
925 raises(TypeError, mro_err_msg,
926 type, "X", (A, B), {})
927 raises(TypeError, mro_err_msg,
928 type, "X", (A, C, B), {})
929 # Test a slightly more complex error
930 class GridLayout(object): pass
931 class HorizontalGrid(GridLayout): pass
932 class VerticalGrid(GridLayout): pass
933 class HVGrid(HorizontalGrid, VerticalGrid): pass
934 class VHGrid(VerticalGrid, HorizontalGrid): pass
935 raises(TypeError, mro_err_msg,
936 type, "ConfusedGrid", (HVGrid, VHGrid), {})
937
938 def test_object_class(self):
939 # Testing object class...
940 a = object()
941 self.assertEqual(a.__class__, object)
942 self.assertEqual(type(a), object)
943 b = object()
944 self.assertNotEqual(a, b)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200945 self.assertNotHasAttr(a, "foo")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000946 try:
Georg Brandl48545522008-02-02 10:12:36 +0000947 a.foo = 12
948 except (AttributeError, TypeError):
949 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000950 else:
Georg Brandl48545522008-02-02 10:12:36 +0000951 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200952 self.assertNotHasAttr(object(), "__dict__")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000953
Georg Brandl48545522008-02-02 10:12:36 +0000954 class Cdict(object):
955 pass
956 x = Cdict()
957 self.assertEqual(x.__dict__, {})
958 x.foo = 1
959 self.assertEqual(x.foo, 1)
960 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000961
Georg Brandl48545522008-02-02 10:12:36 +0000962 def test_slots(self):
963 # Testing __slots__...
964 class C0(object):
965 __slots__ = []
966 x = C0()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200967 self.assertNotHasAttr(x, "__dict__")
968 self.assertNotHasAttr(x, "foo")
Guido van Rossum37202612001-08-09 19:45:21 +0000969
Georg Brandl48545522008-02-02 10:12:36 +0000970 class C1(object):
971 __slots__ = ['a']
972 x = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200973 self.assertNotHasAttr(x, "__dict__")
974 self.assertNotHasAttr(x, "a")
Georg Brandl48545522008-02-02 10:12:36 +0000975 x.a = 1
976 self.assertEqual(x.a, 1)
977 x.a = None
978 self.assertEqual(x.a, None)
979 del x.a
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200980 self.assertNotHasAttr(x, "a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981
Georg Brandl48545522008-02-02 10:12:36 +0000982 class C3(object):
983 __slots__ = ['a', 'b', 'c']
984 x = C3()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200985 self.assertNotHasAttr(x, "__dict__")
986 self.assertNotHasAttr(x, 'a')
987 self.assertNotHasAttr(x, 'b')
988 self.assertNotHasAttr(x, 'c')
Georg Brandl48545522008-02-02 10:12:36 +0000989 x.a = 1
990 x.b = 2
991 x.c = 3
992 self.assertEqual(x.a, 1)
993 self.assertEqual(x.b, 2)
994 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995
Georg Brandl48545522008-02-02 10:12:36 +0000996 class C4(object):
997 """Validate name mangling"""
998 __slots__ = ['__a']
999 def __init__(self, value):
1000 self.__a = value
1001 def get(self):
1002 return self.__a
1003 x = C4(5)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001004 self.assertNotHasAttr(x, '__dict__')
1005 self.assertNotHasAttr(x, '__a')
Georg Brandl48545522008-02-02 10:12:36 +00001006 self.assertEqual(x.get(), 5)
1007 try:
1008 x.__a = 6
1009 except AttributeError:
1010 pass
1011 else:
1012 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013
Georg Brandl48545522008-02-02 10:12:36 +00001014 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001015 try:
1016 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001017 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001018 except TypeError:
1019 pass
1020 else:
Georg Brandl48545522008-02-02 10:12:36 +00001021 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001022 try:
Georg Brandl48545522008-02-02 10:12:36 +00001023 class C(object):
1024 __slots__ = ["foo bar"]
1025 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001026 pass
Georg Brandl48545522008-02-02 10:12:36 +00001027 else:
1028 self.fail("['foo bar'] slots not caught")
1029 try:
1030 class C(object):
1031 __slots__ = ["foo\0bar"]
1032 except TypeError:
1033 pass
1034 else:
1035 self.fail("['foo\\0bar'] slots not caught")
1036 try:
1037 class C(object):
1038 __slots__ = ["1"]
1039 except TypeError:
1040 pass
1041 else:
1042 self.fail("['1'] slots not caught")
1043 try:
1044 class C(object):
1045 __slots__ = [""]
1046 except TypeError:
1047 pass
1048 else:
1049 self.fail("[''] slots not caught")
1050 class C(object):
1051 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1052 # XXX(nnorwitz): was there supposed to be something tested
1053 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001054
Georg Brandl48545522008-02-02 10:12:36 +00001055 # Test a single string is not expanded as a sequence.
1056 class C(object):
1057 __slots__ = "abc"
1058 c = C()
1059 c.abc = 5
1060 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001061
Georg Brandl48545522008-02-02 10:12:36 +00001062 # Test unicode slot names
1063 try:
1064 unicode
1065 except NameError:
1066 pass
1067 else:
1068 # Test a single unicode string is not expanded as a sequence.
1069 class C(object):
1070 __slots__ = unicode("abc")
1071 c = C()
1072 c.abc = 5
1073 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001074
Georg Brandl48545522008-02-02 10:12:36 +00001075 # _unicode_to_string used to modify slots in certain circumstances
1076 slots = (unicode("foo"), unicode("bar"))
1077 class C(object):
1078 __slots__ = slots
1079 x = C()
1080 x.foo = 5
1081 self.assertEqual(x.foo, 5)
1082 self.assertEqual(type(slots[0]), unicode)
1083 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001084 try:
Georg Brandl48545522008-02-02 10:12:36 +00001085 class C(object):
1086 __slots__ = [unichr(128)]
1087 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001088 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001089 else:
Georg Brandl48545522008-02-02 10:12:36 +00001090 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001091
Georg Brandl48545522008-02-02 10:12:36 +00001092 # Test leaks
1093 class Counted(object):
1094 counter = 0 # counts the number of instances alive
1095 def __init__(self):
1096 Counted.counter += 1
1097 def __del__(self):
1098 Counted.counter -= 1
1099 class C(object):
1100 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001101 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001102 x.a = Counted()
1103 x.b = Counted()
1104 x.c = Counted()
1105 self.assertEqual(Counted.counter, 3)
1106 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001107 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001108 self.assertEqual(Counted.counter, 0)
1109 class D(C):
1110 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001111 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001112 x.a = Counted()
1113 x.z = Counted()
1114 self.assertEqual(Counted.counter, 2)
1115 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001116 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001117 self.assertEqual(Counted.counter, 0)
1118 class E(D):
1119 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001120 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001121 x.a = Counted()
1122 x.z = Counted()
1123 x.e = Counted()
1124 self.assertEqual(Counted.counter, 3)
1125 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001126 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001127 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001128
Georg Brandl48545522008-02-02 10:12:36 +00001129 # Test cyclical leaks [SF bug 519621]
1130 class F(object):
1131 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001132 s = F()
1133 s.a = [Counted(), s]
1134 self.assertEqual(Counted.counter, 1)
1135 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001136 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001137 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001138
Georg Brandl48545522008-02-02 10:12:36 +00001139 # Test lookup leaks [SF bug 572567]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001140 if hasattr(gc, 'get_objects'):
1141 class G(object):
1142 def __cmp__(self, other):
1143 return 0
1144 __hash__ = None # Silence Py3k warning
1145 g = G()
1146 orig_objects = len(gc.get_objects())
1147 for i in xrange(10):
1148 g==g
1149 new_objects = len(gc.get_objects())
1150 self.assertEqual(orig_objects, new_objects)
1151
Georg Brandl48545522008-02-02 10:12:36 +00001152 class H(object):
1153 __slots__ = ['a', 'b']
1154 def __init__(self):
1155 self.a = 1
1156 self.b = 2
1157 def __del__(self_):
1158 self.assertEqual(self_.a, 1)
1159 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001160 with test_support.captured_output('stderr') as s:
1161 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001162 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001163 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001164
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001165 class X(object):
1166 __slots__ = "a"
1167 with self.assertRaises(AttributeError):
1168 del X().a
1169
Georg Brandl48545522008-02-02 10:12:36 +00001170 def test_slots_special(self):
1171 # Testing __dict__ and __weakref__ in __slots__...
1172 class D(object):
1173 __slots__ = ["__dict__"]
1174 a = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001175 self.assertHasAttr(a, "__dict__")
1176 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001177 a.foo = 42
1178 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001179
Georg Brandl48545522008-02-02 10:12:36 +00001180 class W(object):
1181 __slots__ = ["__weakref__"]
1182 a = W()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001183 self.assertHasAttr(a, "__weakref__")
1184 self.assertNotHasAttr(a, "__dict__")
Georg Brandl48545522008-02-02 10:12:36 +00001185 try:
1186 a.foo = 42
1187 except AttributeError:
1188 pass
1189 else:
1190 self.fail("shouldn't be allowed to set a.foo")
1191
1192 class C1(W, D):
1193 __slots__ = []
1194 a = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001195 self.assertHasAttr(a, "__dict__")
1196 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001197 a.foo = 42
1198 self.assertEqual(a.__dict__, {"foo": 42})
1199
1200 class C2(D, W):
1201 __slots__ = []
1202 a = C2()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001203 self.assertHasAttr(a, "__dict__")
1204 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001205 a.foo = 42
1206 self.assertEqual(a.__dict__, {"foo": 42})
1207
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001208 def test_slots_descriptor(self):
1209 # Issue2115: slot descriptors did not correctly check
1210 # the type of the given object
1211 import abc
1212 class MyABC:
1213 __metaclass__ = abc.ABCMeta
1214 __slots__ = "a"
1215
1216 class Unrelated(object):
1217 pass
1218 MyABC.register(Unrelated)
1219
1220 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001221 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001222
1223 # This used to crash
1224 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1225
Benjamin Peterson4895af42009-12-13 16:36:53 +00001226 def test_metaclass_cmp(self):
1227 # See bug 7491.
1228 class M(type):
1229 def __cmp__(self, other):
1230 return -1
1231 class X(object):
1232 __metaclass__ = M
1233 self.assertTrue(X < M)
1234
Georg Brandl48545522008-02-02 10:12:36 +00001235 def test_dynamics(self):
1236 # Testing class attribute propagation...
1237 class D(object):
1238 pass
1239 class E(D):
1240 pass
1241 class F(D):
1242 pass
1243 D.foo = 1
1244 self.assertEqual(D.foo, 1)
1245 # Test that dynamic attributes are inherited
1246 self.assertEqual(E.foo, 1)
1247 self.assertEqual(F.foo, 1)
1248 # Test dynamic instances
1249 class C(object):
1250 pass
1251 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001252 self.assertNotHasAttr(a, "foobar")
Georg Brandl48545522008-02-02 10:12:36 +00001253 C.foobar = 2
1254 self.assertEqual(a.foobar, 2)
1255 C.method = lambda self: 42
1256 self.assertEqual(a.method(), 42)
1257 C.__repr__ = lambda self: "C()"
1258 self.assertEqual(repr(a), "C()")
1259 C.__int__ = lambda self: 100
1260 self.assertEqual(int(a), 100)
1261 self.assertEqual(a.foobar, 2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001262 self.assertNotHasAttr(a, "spam")
Georg Brandl48545522008-02-02 10:12:36 +00001263 def mygetattr(self, name):
1264 if name == "spam":
1265 return "spam"
1266 raise AttributeError
1267 C.__getattr__ = mygetattr
1268 self.assertEqual(a.spam, "spam")
1269 a.new = 12
1270 self.assertEqual(a.new, 12)
1271 def mysetattr(self, name, value):
1272 if name == "spam":
1273 raise AttributeError
1274 return object.__setattr__(self, name, value)
1275 C.__setattr__ = mysetattr
1276 try:
1277 a.spam = "not spam"
1278 except AttributeError:
1279 pass
1280 else:
1281 self.fail("expected AttributeError")
1282 self.assertEqual(a.spam, "spam")
1283 class D(C):
1284 pass
1285 d = D()
1286 d.foo = 1
1287 self.assertEqual(d.foo, 1)
1288
1289 # Test handling of int*seq and seq*int
1290 class I(int):
1291 pass
1292 self.assertEqual("a"*I(2), "aa")
1293 self.assertEqual(I(2)*"a", "aa")
1294 self.assertEqual(2*I(3), 6)
1295 self.assertEqual(I(3)*2, 6)
1296 self.assertEqual(I(3)*I(2), 6)
1297
1298 # Test handling of long*seq and seq*long
1299 class L(long):
1300 pass
1301 self.assertEqual("a"*L(2L), "aa")
1302 self.assertEqual(L(2L)*"a", "aa")
1303 self.assertEqual(2*L(3), 6)
1304 self.assertEqual(L(3)*2, 6)
1305 self.assertEqual(L(3)*L(2), 6)
1306
1307 # Test comparison of classes with dynamic metaclasses
1308 class dynamicmetaclass(type):
1309 pass
1310 class someclass:
1311 __metaclass__ = dynamicmetaclass
1312 self.assertNotEqual(someclass, object)
1313
1314 def test_errors(self):
1315 # Testing errors...
1316 try:
1317 class C(list, dict):
1318 pass
1319 except TypeError:
1320 pass
1321 else:
1322 self.fail("inheritance from both list and dict should be illegal")
1323
1324 try:
1325 class C(object, None):
1326 pass
1327 except TypeError:
1328 pass
1329 else:
1330 self.fail("inheritance from non-type should be illegal")
1331 class Classic:
1332 pass
1333
1334 try:
1335 class C(type(len)):
1336 pass
1337 except TypeError:
1338 pass
1339 else:
1340 self.fail("inheritance from CFunction 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 try:
1351 class C(object):
1352 __slots__ = [1]
1353 except TypeError:
1354 pass
1355 else:
1356 self.fail("__slots__ = [1] should be illegal")
1357
1358 class M1(type):
1359 pass
1360 class M2(type):
1361 pass
1362 class A1(object):
1363 __metaclass__ = M1
1364 class A2(object):
1365 __metaclass__ = M2
1366 try:
1367 class B(A1, A2):
1368 pass
1369 except TypeError:
1370 pass
1371 else:
1372 self.fail("finding the most derived metaclass should have failed")
1373
1374 def test_classmethods(self):
1375 # Testing class methods...
1376 class C(object):
1377 def foo(*a): return a
1378 goo = classmethod(foo)
1379 c = C()
1380 self.assertEqual(C.goo(1), (C, 1))
1381 self.assertEqual(c.goo(1), (C, 1))
1382 self.assertEqual(c.foo(1), (c, 1))
1383 class D(C):
1384 pass
1385 d = D()
1386 self.assertEqual(D.goo(1), (D, 1))
1387 self.assertEqual(d.goo(1), (D, 1))
1388 self.assertEqual(d.foo(1), (d, 1))
1389 self.assertEqual(D.foo(d, 1), (d, 1))
1390 # Test for a specific crash (SF bug 528132)
1391 def f(cls, arg): return (cls, arg)
1392 ff = classmethod(f)
1393 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1394 self.assertEqual(ff.__get__(0)(42), (int, 42))
1395
1396 # Test super() with classmethods (SF bug 535444)
1397 self.assertEqual(C.goo.im_self, C)
1398 self.assertEqual(D.goo.im_self, D)
1399 self.assertEqual(super(D,D).goo.im_self, D)
1400 self.assertEqual(super(D,d).goo.im_self, D)
1401 self.assertEqual(super(D,D).goo(), (D,))
1402 self.assertEqual(super(D,d).goo(), (D,))
1403
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001404 # Verify that a non-callable will raise
1405 meth = classmethod(1).__get__(1)
1406 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001407
1408 # Verify that classmethod() doesn't allow keyword args
1409 try:
1410 classmethod(f, kw=1)
1411 except TypeError:
1412 pass
1413 else:
1414 self.fail("classmethod shouldn't accept keyword args")
1415
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001416 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001417 def test_classmethods_in_c(self):
1418 # Testing C-based class methods...
1419 import xxsubtype as spam
1420 a = (1, 2, 3)
1421 d = {'abc': 123}
1422 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1423 self.assertEqual(x, spam.spamlist)
1424 self.assertEqual(a, a1)
1425 self.assertEqual(d, d1)
1426 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1427 self.assertEqual(x, spam.spamlist)
1428 self.assertEqual(a, a1)
1429 self.assertEqual(d, d1)
Benjamin Peterson042c47b2012-05-01 09:51:09 -04001430 spam_cm = spam.spamlist.__dict__['classmeth']
1431 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1432 self.assertEqual(x2, spam.spamlist)
1433 self.assertEqual(a2, a1)
1434 self.assertEqual(d2, d1)
1435 class SubSpam(spam.spamlist): pass
1436 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1437 self.assertEqual(x2, SubSpam)
1438 self.assertEqual(a2, a1)
1439 self.assertEqual(d2, d1)
1440 with self.assertRaises(TypeError):
1441 spam_cm()
1442 with self.assertRaises(TypeError):
1443 spam_cm(spam.spamlist())
1444 with self.assertRaises(TypeError):
1445 spam_cm(list)
Georg Brandl48545522008-02-02 10:12:36 +00001446
1447 def test_staticmethods(self):
1448 # Testing static methods...
1449 class C(object):
1450 def foo(*a): return a
1451 goo = staticmethod(foo)
1452 c = C()
1453 self.assertEqual(C.goo(1), (1,))
1454 self.assertEqual(c.goo(1), (1,))
1455 self.assertEqual(c.foo(1), (c, 1,))
1456 class D(C):
1457 pass
1458 d = D()
1459 self.assertEqual(D.goo(1), (1,))
1460 self.assertEqual(d.goo(1), (1,))
1461 self.assertEqual(d.foo(1), (d, 1))
1462 self.assertEqual(D.foo(d, 1), (d, 1))
1463
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001464 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001465 def test_staticmethods_in_c(self):
1466 # Testing C-based static methods...
1467 import xxsubtype as spam
1468 a = (1, 2, 3)
1469 d = {"abc": 123}
1470 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1471 self.assertEqual(x, None)
1472 self.assertEqual(a, a1)
1473 self.assertEqual(d, d1)
1474 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1475 self.assertEqual(x, None)
1476 self.assertEqual(a, a1)
1477 self.assertEqual(d, d1)
1478
1479 def test_classic(self):
1480 # Testing classic classes...
1481 class C:
1482 def foo(*a): return a
1483 goo = classmethod(foo)
1484 c = C()
1485 self.assertEqual(C.goo(1), (C, 1))
1486 self.assertEqual(c.goo(1), (C, 1))
1487 self.assertEqual(c.foo(1), (c, 1))
1488 class D(C):
1489 pass
1490 d = D()
1491 self.assertEqual(D.goo(1), (D, 1))
1492 self.assertEqual(d.goo(1), (D, 1))
1493 self.assertEqual(d.foo(1), (d, 1))
1494 self.assertEqual(D.foo(d, 1), (d, 1))
1495 class E: # *not* subclassing from C
1496 foo = C.foo
1497 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001498 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001499
1500 def test_compattr(self):
1501 # Testing computed attributes...
1502 class C(object):
1503 class computed_attribute(object):
1504 def __init__(self, get, set=None, delete=None):
1505 self.__get = get
1506 self.__set = set
1507 self.__delete = delete
1508 def __get__(self, obj, type=None):
1509 return self.__get(obj)
1510 def __set__(self, obj, value):
1511 return self.__set(obj, value)
1512 def __delete__(self, obj):
1513 return self.__delete(obj)
1514 def __init__(self):
1515 self.__x = 0
1516 def __get_x(self):
1517 x = self.__x
1518 self.__x = x+1
1519 return x
1520 def __set_x(self, x):
1521 self.__x = x
1522 def __delete_x(self):
1523 del self.__x
1524 x = computed_attribute(__get_x, __set_x, __delete_x)
1525 a = C()
1526 self.assertEqual(a.x, 0)
1527 self.assertEqual(a.x, 1)
1528 a.x = 10
1529 self.assertEqual(a.x, 10)
1530 self.assertEqual(a.x, 11)
1531 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001532 self.assertNotHasAttr(a, 'x')
Georg Brandl48545522008-02-02 10:12:36 +00001533
1534 def test_newslots(self):
1535 # Testing __new__ slot override...
1536 class C(list):
1537 def __new__(cls):
1538 self = list.__new__(cls)
1539 self.foo = 1
1540 return self
1541 def __init__(self):
1542 self.foo = self.foo + 2
1543 a = C()
1544 self.assertEqual(a.foo, 3)
1545 self.assertEqual(a.__class__, C)
1546 class D(C):
1547 pass
1548 b = D()
1549 self.assertEqual(b.foo, 3)
1550 self.assertEqual(b.__class__, D)
1551
1552 def test_altmro(self):
1553 # Testing mro() and overriding it...
1554 class A(object):
1555 def f(self): return "A"
1556 class B(A):
1557 pass
1558 class C(A):
1559 def f(self): return "C"
1560 class D(B, C):
1561 pass
1562 self.assertEqual(D.mro(), [D, B, C, A, object])
1563 self.assertEqual(D.__mro__, (D, B, C, A, object))
1564 self.assertEqual(D().f(), "C")
1565
1566 class PerverseMetaType(type):
1567 def mro(cls):
1568 L = type.mro(cls)
1569 L.reverse()
1570 return L
1571 class X(D,B,C,A):
1572 __metaclass__ = PerverseMetaType
1573 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1574 self.assertEqual(X().f(), "A")
1575
1576 try:
1577 class X(object):
1578 class __metaclass__(type):
1579 def mro(self):
1580 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001581 # In CPython, the class creation above already raises
1582 # TypeError, as a protection against the fact that
1583 # instances of X would segfault it. In other Python
1584 # implementations it would be ok to let the class X
1585 # be created, but instead get a clean TypeError on the
1586 # __setitem__ below.
1587 x = object.__new__(X)
1588 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001589 except TypeError:
1590 pass
1591 else:
1592 self.fail("devious mro() return not caught")
1593
1594 try:
1595 class X(object):
1596 class __metaclass__(type):
1597 def mro(self):
1598 return [1]
1599 except TypeError:
1600 pass
1601 else:
1602 self.fail("non-class mro() return not caught")
1603
1604 try:
1605 class X(object):
1606 class __metaclass__(type):
1607 def mro(self):
1608 return 1
1609 except TypeError:
1610 pass
1611 else:
1612 self.fail("non-sequence mro() return not caught")
1613
1614 def test_overloading(self):
1615 # Testing operator overloading...
1616
1617 class B(object):
1618 "Intermediate class because object doesn't have a __setattr__"
1619
1620 class C(B):
1621 def __getattr__(self, name):
1622 if name == "foo":
1623 return ("getattr", name)
1624 else:
1625 raise AttributeError
1626 def __setattr__(self, name, value):
1627 if name == "foo":
1628 self.setattr = (name, value)
1629 else:
1630 return B.__setattr__(self, name, value)
1631 def __delattr__(self, name):
1632 if name == "foo":
1633 self.delattr = name
1634 else:
1635 return B.__delattr__(self, name)
1636
1637 def __getitem__(self, key):
1638 return ("getitem", key)
1639 def __setitem__(self, key, value):
1640 self.setitem = (key, value)
1641 def __delitem__(self, key):
1642 self.delitem = key
1643
1644 def __getslice__(self, i, j):
1645 return ("getslice", i, j)
1646 def __setslice__(self, i, j, value):
1647 self.setslice = (i, j, value)
1648 def __delslice__(self, i, j):
1649 self.delslice = (i, j)
1650
1651 a = C()
1652 self.assertEqual(a.foo, ("getattr", "foo"))
1653 a.foo = 12
1654 self.assertEqual(a.setattr, ("foo", 12))
1655 del a.foo
1656 self.assertEqual(a.delattr, "foo")
1657
1658 self.assertEqual(a[12], ("getitem", 12))
1659 a[12] = 21
1660 self.assertEqual(a.setitem, (12, 21))
1661 del a[12]
1662 self.assertEqual(a.delitem, 12)
1663
1664 self.assertEqual(a[0:10], ("getslice", 0, 10))
1665 a[0:10] = "foo"
1666 self.assertEqual(a.setslice, (0, 10, "foo"))
1667 del a[0:10]
1668 self.assertEqual(a.delslice, (0, 10))
1669
1670 def test_methods(self):
1671 # Testing methods...
1672 class C(object):
1673 def __init__(self, x):
1674 self.x = x
1675 def foo(self):
1676 return self.x
1677 c1 = C(1)
1678 self.assertEqual(c1.foo(), 1)
1679 class D(C):
1680 boo = C.foo
1681 goo = c1.foo
1682 d2 = D(2)
1683 self.assertEqual(d2.foo(), 2)
1684 self.assertEqual(d2.boo(), 2)
1685 self.assertEqual(d2.goo(), 1)
1686 class E(object):
1687 foo = C.foo
1688 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001689 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001690
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001691 def test_special_method_lookup(self):
1692 # The lookup of special methods bypasses __getattr__ and
1693 # __getattribute__, but they still can be descriptors.
1694
1695 def run_context(manager):
1696 with manager:
1697 pass
1698 def iden(self):
1699 return self
1700 def hello(self):
1701 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001702 def empty_seq(self):
1703 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001704 def zero(self):
1705 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001706 def complex_num(self):
1707 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001708 def stop(self):
1709 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001710 def return_true(self, thing=None):
1711 return True
1712 def do_isinstance(obj):
1713 return isinstance(int, obj)
1714 def do_issubclass(obj):
1715 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001716 def swallow(*args):
1717 pass
1718 def do_dict_missing(checker):
1719 class DictSub(checker.__class__, dict):
1720 pass
1721 self.assertEqual(DictSub()["hi"], 4)
1722 def some_number(self_, key):
1723 self.assertEqual(key, "hi")
1724 return 4
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001725 def format_impl(self, spec):
1726 return "hello"
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001727
1728 # It would be nice to have every special method tested here, but I'm
1729 # only listing the ones I can remember outside of typeobject.c, since it
1730 # does it right.
1731 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001732 ("__unicode__", unicode, hello, set(), {}),
1733 ("__reversed__", reversed, empty_seq, set(), {}),
1734 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001735 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001736 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1737 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001738 ("__missing__", do_dict_missing, some_number,
1739 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001740 ("__subclasscheck__", do_issubclass, return_true,
1741 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001742 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1743 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001744 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001745 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001746 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001747 ]
1748
1749 class Checker(object):
1750 def __getattr__(self, attr, test=self):
1751 test.fail("__getattr__ called with {0}".format(attr))
1752 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001753 if attr not in ok:
1754 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001755 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001756 class SpecialDescr(object):
1757 def __init__(self, impl):
1758 self.impl = impl
1759 def __get__(self, obj, owner):
1760 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001761 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001762 class MyException(Exception):
1763 pass
1764 class ErrDescr(object):
1765 def __get__(self, obj, owner):
1766 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001767
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001768 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001769 class X(Checker):
1770 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001771 for attr, obj in env.iteritems():
1772 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001773 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001774 runner(X())
1775
1776 record = []
1777 class X(Checker):
1778 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001779 for attr, obj in env.iteritems():
1780 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001781 setattr(X, name, SpecialDescr(meth_impl))
1782 runner(X())
1783 self.assertEqual(record, [1], name)
1784
Benjamin Peterson87e50062009-05-25 02:40:21 +00001785 class X(Checker):
1786 pass
1787 for attr, obj in env.iteritems():
1788 setattr(X, attr, obj)
1789 setattr(X, name, ErrDescr())
1790 try:
1791 runner(X())
1792 except MyException:
1793 pass
1794 else:
1795 self.fail("{0!r} didn't raise".format(name))
1796
Georg Brandl48545522008-02-02 10:12:36 +00001797 def test_specials(self):
1798 # Testing special operators...
1799 # Test operators like __hash__ for which a built-in default exists
1800
1801 # Test the default behavior for static classes
1802 class C(object):
1803 def __getitem__(self, i):
1804 if 0 <= i < 10: return i
1805 raise IndexError
1806 c1 = C()
1807 c2 = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001808 self.assertFalse(not c1)
Georg Brandl48545522008-02-02 10:12:36 +00001809 self.assertNotEqual(id(c1), id(c2))
1810 hash(c1)
1811 hash(c2)
1812 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1813 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001814 self.assertTrue(c1 != c2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001815 self.assertFalse(c1 != c1)
1816 self.assertFalse(c1 == c2)
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.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001819 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001820 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001821 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001822 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001823 self.assertIn(i, c1)
1824 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001825 # Test the default behavior for dynamic classes
1826 class D(object):
1827 def __getitem__(self, i):
1828 if 0 <= i < 10: return i
1829 raise IndexError
1830 d1 = D()
1831 d2 = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001832 self.assertFalse(not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001833 self.assertNotEqual(id(d1), id(d2))
1834 hash(d1)
1835 hash(d2)
1836 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1837 self.assertEqual(d1, d1)
1838 self.assertNotEqual(d1, d2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001839 self.assertFalse(d1 != d1)
1840 self.assertFalse(d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001841 # Note that the module name appears in str/repr, and that varies
1842 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001843 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001844 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001845 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001846 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001847 self.assertIn(i, d1)
1848 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001849 # Test overridden behavior for static classes
1850 class Proxy(object):
1851 def __init__(self, x):
1852 self.x = x
1853 def __nonzero__(self):
1854 return not not self.x
1855 def __hash__(self):
1856 return hash(self.x)
1857 def __eq__(self, other):
1858 return self.x == other
1859 def __ne__(self, other):
1860 return self.x != other
1861 def __cmp__(self, other):
1862 return cmp(self.x, other.x)
1863 def __str__(self):
1864 return "Proxy:%s" % self.x
1865 def __repr__(self):
1866 return "Proxy(%r)" % self.x
1867 def __contains__(self, value):
1868 return value in self.x
1869 p0 = Proxy(0)
1870 p1 = Proxy(1)
1871 p_1 = Proxy(-1)
1872 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001873 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001874 self.assertEqual(hash(p0), hash(0))
1875 self.assertEqual(p0, p0)
1876 self.assertNotEqual(p0, p1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001877 self.assertFalse(p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001878 self.assertEqual(not p0, p1)
1879 self.assertEqual(cmp(p0, p1), -1)
1880 self.assertEqual(cmp(p0, p0), 0)
1881 self.assertEqual(cmp(p0, p_1), 1)
1882 self.assertEqual(str(p0), "Proxy:0")
1883 self.assertEqual(repr(p0), "Proxy(0)")
1884 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001885 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001886 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001887 self.assertIn(i, p10)
1888 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001889 # Test overridden behavior for dynamic classes
1890 class DProxy(object):
1891 def __init__(self, x):
1892 self.x = x
1893 def __nonzero__(self):
1894 return not not self.x
1895 def __hash__(self):
1896 return hash(self.x)
1897 def __eq__(self, other):
1898 return self.x == other
1899 def __ne__(self, other):
1900 return self.x != other
1901 def __cmp__(self, other):
1902 return cmp(self.x, other.x)
1903 def __str__(self):
1904 return "DProxy:%s" % self.x
1905 def __repr__(self):
1906 return "DProxy(%r)" % self.x
1907 def __contains__(self, value):
1908 return value in self.x
1909 p0 = DProxy(0)
1910 p1 = DProxy(1)
1911 p_1 = DProxy(-1)
1912 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001913 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001914 self.assertEqual(hash(p0), hash(0))
1915 self.assertEqual(p0, p0)
1916 self.assertNotEqual(p0, p1)
1917 self.assertNotEqual(not p0, p0)
1918 self.assertEqual(not p0, p1)
1919 self.assertEqual(cmp(p0, p1), -1)
1920 self.assertEqual(cmp(p0, p0), 0)
1921 self.assertEqual(cmp(p0, p_1), 1)
1922 self.assertEqual(str(p0), "DProxy:0")
1923 self.assertEqual(repr(p0), "DProxy(0)")
1924 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001925 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001926 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001927 self.assertIn(i, p10)
1928 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001929
1930 # Safety test for __cmp__
1931 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001932 if not hasattr(a, '__cmp__'):
1933 return # some types don't have a __cmp__ any more (so the
1934 # test doesn't make sense any more), or maybe they
1935 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001936 try:
1937 a.__class__.__cmp__(a, b)
1938 except TypeError:
1939 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001940 else:
Georg Brandl48545522008-02-02 10:12:36 +00001941 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1942 a.__class__, a, b))
1943
1944 unsafecmp(u"123", "123")
1945 unsafecmp("123", u"123")
1946 unsafecmp(1, 1.0)
1947 unsafecmp(1.0, 1)
1948 unsafecmp(1, 1L)
1949 unsafecmp(1L, 1)
1950
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001951 @test_support.impl_detail("custom logic for printing to real file objects")
1952 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001953 # Testing recursion checks ...
1954 class Letter(str):
1955 def __new__(cls, letter):
1956 if letter == 'EPS':
1957 return str.__new__(cls)
1958 return str.__new__(cls, letter)
1959 def __str__(self):
1960 if not self:
1961 return 'EPS'
1962 return self
1963 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00001964 test_stdout = sys.stdout
1965 sys.stdout = test_support.get_original_stdout()
1966 try:
1967 # nothing should actually be printed, this should raise an exception
1968 print Letter('w')
1969 except RuntimeError:
1970 pass
1971 else:
1972 self.fail("expected a RuntimeError for print recursion")
1973 finally:
1974 sys.stdout = test_stdout
1975
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001976 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001977 # Bug #1202533.
1978 class A(object):
1979 pass
1980 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1981 try:
1982 A()*2
1983 except RuntimeError:
1984 pass
1985 else:
1986 self.fail("expected a RuntimeError")
1987
1988 def test_weakrefs(self):
1989 # Testing weak references...
1990 import weakref
1991 class C(object):
1992 pass
1993 c = C()
1994 r = weakref.ref(c)
1995 self.assertEqual(r(), c)
1996 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001997 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001998 self.assertEqual(r(), None)
1999 del r
2000 class NoWeak(object):
2001 __slots__ = ['foo']
2002 no = NoWeak()
2003 try:
2004 weakref.ref(no)
2005 except TypeError, msg:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002006 self.assertIn("weak reference", str(msg))
Georg Brandl48545522008-02-02 10:12:36 +00002007 else:
2008 self.fail("weakref.ref(no) should be illegal")
2009 class Weak(object):
2010 __slots__ = ['foo', '__weakref__']
2011 yes = Weak()
2012 r = weakref.ref(yes)
2013 self.assertEqual(r(), yes)
2014 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002015 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00002016 self.assertEqual(r(), None)
2017 del r
2018
2019 def test_properties(self):
2020 # Testing property...
2021 class C(object):
2022 def getx(self):
2023 return self.__x
2024 def setx(self, value):
2025 self.__x = value
2026 def delx(self):
2027 del self.__x
2028 x = property(getx, setx, delx, doc="I'm the x property.")
2029 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002030 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002031 a.x = 42
2032 self.assertEqual(a._C__x, 42)
2033 self.assertEqual(a.x, 42)
2034 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002035 self.assertNotHasAttr(a, "x")
2036 self.assertNotHasAttr(a, "_C__x")
Georg Brandl48545522008-02-02 10:12:36 +00002037 C.x.__set__(a, 100)
2038 self.assertEqual(C.x.__get__(a), 100)
2039 C.x.__delete__(a)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002040 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002041
2042 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002043 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002044
2045 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002046 self.assertIn("__doc__", attrs)
2047 self.assertIn("fget", attrs)
2048 self.assertIn("fset", attrs)
2049 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002050
2051 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002052 self.assertIs(raw.fget, C.__dict__['getx'])
2053 self.assertIs(raw.fset, C.__dict__['setx'])
2054 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002055
2056 for attr in "__doc__", "fget", "fset", "fdel":
2057 try:
2058 setattr(raw, attr, 42)
2059 except TypeError, msg:
2060 if str(msg).find('readonly') < 0:
2061 self.fail("when setting readonly attr %r on a property, "
2062 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002063 else:
Georg Brandl48545522008-02-02 10:12:36 +00002064 self.fail("expected TypeError from trying to set readonly %r "
2065 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002066
Georg Brandl48545522008-02-02 10:12:36 +00002067 class D(object):
2068 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002069
Georg Brandl48545522008-02-02 10:12:36 +00002070 d = D()
2071 try:
2072 for i in d:
2073 str(i)
2074 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002075 pass
Georg Brandl48545522008-02-02 10:12:36 +00002076 else:
2077 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002078
R. David Murrayf28fd242010-02-23 00:24:49 +00002079 @unittest.skipIf(sys.flags.optimize >= 2,
2080 "Docstrings are omitted with -O2 and above")
2081 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002082 class E(object):
2083 def getter(self):
2084 "getter method"
2085 return 0
2086 def setter(self_, value):
2087 "setter method"
2088 pass
2089 prop = property(getter)
2090 self.assertEqual(prop.__doc__, "getter method")
2091 prop2 = property(fset=setter)
2092 self.assertEqual(prop2.__doc__, None)
2093
R. David Murrayf28fd242010-02-23 00:24:49 +00002094 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002095 # this segfaulted in 2.5b2
2096 try:
2097 import _testcapi
2098 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002099 pass
Georg Brandl48545522008-02-02 10:12:36 +00002100 else:
2101 class X(object):
2102 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002103
Georg Brandl48545522008-02-02 10:12:36 +00002104 def test_properties_plus(self):
2105 class C(object):
2106 foo = property(doc="hello")
2107 @foo.getter
2108 def foo(self):
2109 return self._foo
2110 @foo.setter
2111 def foo(self, value):
2112 self._foo = abs(value)
2113 @foo.deleter
2114 def foo(self):
2115 del self._foo
2116 c = C()
2117 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002118 self.assertNotHasAttr(c, "foo")
Georg Brandl48545522008-02-02 10:12:36 +00002119 c.foo = -42
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002120 self.assertHasAttr(c, '_foo')
Georg Brandl48545522008-02-02 10:12:36 +00002121 self.assertEqual(c._foo, 42)
2122 self.assertEqual(c.foo, 42)
2123 del c.foo
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002124 self.assertNotHasAttr(c, '_foo')
2125 self.assertNotHasAttr(c, "foo")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002126
Georg Brandl48545522008-02-02 10:12:36 +00002127 class D(C):
2128 @C.foo.deleter
2129 def foo(self):
2130 try:
2131 del self._foo
2132 except AttributeError:
2133 pass
2134 d = D()
2135 d.foo = 24
2136 self.assertEqual(d.foo, 24)
2137 del d.foo
2138 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002139
Georg Brandl48545522008-02-02 10:12:36 +00002140 class E(object):
2141 @property
2142 def foo(self):
2143 return self._foo
2144 @foo.setter
2145 def foo(self, value):
2146 raise RuntimeError
2147 @foo.setter
2148 def foo(self, value):
2149 self._foo = abs(value)
2150 @foo.deleter
2151 def foo(self, value=None):
2152 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002153
Georg Brandl48545522008-02-02 10:12:36 +00002154 e = E()
2155 e.foo = -42
2156 self.assertEqual(e.foo, 42)
2157 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002158
Georg Brandl48545522008-02-02 10:12:36 +00002159 class F(E):
2160 @E.foo.deleter
2161 def foo(self):
2162 del self._foo
2163 @foo.setter
2164 def foo(self, value):
2165 self._foo = max(0, value)
2166 f = F()
2167 f.foo = -10
2168 self.assertEqual(f.foo, 0)
2169 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002170
Georg Brandl48545522008-02-02 10:12:36 +00002171 def test_dict_constructors(self):
2172 # Testing dict constructor ...
2173 d = dict()
2174 self.assertEqual(d, {})
2175 d = dict({})
2176 self.assertEqual(d, {})
2177 d = dict({1: 2, 'a': 'b'})
2178 self.assertEqual(d, {1: 2, 'a': 'b'})
2179 self.assertEqual(d, dict(d.items()))
2180 self.assertEqual(d, dict(d.iteritems()))
2181 d = dict({'one':1, 'two':2})
2182 self.assertEqual(d, dict(one=1, two=2))
2183 self.assertEqual(d, dict(**d))
2184 self.assertEqual(d, dict({"one": 1}, two=2))
2185 self.assertEqual(d, dict([("two", 2)], one=1))
2186 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2187 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002188
Georg Brandl48545522008-02-02 10:12:36 +00002189 for badarg in 0, 0L, 0j, "0", [0], (0,):
2190 try:
2191 dict(badarg)
2192 except TypeError:
2193 pass
2194 except ValueError:
2195 if badarg == "0":
2196 # It's a sequence, and its elements are also sequences (gotta
2197 # love strings <wink>), but they aren't of length 2, so this
2198 # one seemed better as a ValueError than a TypeError.
2199 pass
2200 else:
2201 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002202 else:
Georg Brandl48545522008-02-02 10:12:36 +00002203 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002204
Georg Brandl48545522008-02-02 10:12:36 +00002205 try:
2206 dict({}, {})
2207 except TypeError:
2208 pass
2209 else:
2210 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002211
Georg Brandl48545522008-02-02 10:12:36 +00002212 class Mapping:
2213 # Lacks a .keys() method; will be added later.
2214 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002215
Georg Brandl48545522008-02-02 10:12:36 +00002216 try:
2217 dict(Mapping())
2218 except TypeError:
2219 pass
2220 else:
2221 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002222
Georg Brandl48545522008-02-02 10:12:36 +00002223 Mapping.keys = lambda self: self.dict.keys()
2224 Mapping.__getitem__ = lambda self, i: self.dict[i]
2225 d = dict(Mapping())
2226 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002227
Georg Brandl48545522008-02-02 10:12:36 +00002228 # Init from sequence of iterable objects, each producing a 2-sequence.
2229 class AddressBookEntry:
2230 def __init__(self, first, last):
2231 self.first = first
2232 self.last = last
2233 def __iter__(self):
2234 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002235
Georg Brandl48545522008-02-02 10:12:36 +00002236 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2237 AddressBookEntry('Barry', 'Peters'),
2238 AddressBookEntry('Tim', 'Peters'),
2239 AddressBookEntry('Barry', 'Warsaw')])
2240 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002241
Georg Brandl48545522008-02-02 10:12:36 +00002242 d = dict(zip(range(4), range(1, 5)))
2243 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002244
Georg Brandl48545522008-02-02 10:12:36 +00002245 # Bad sequence lengths.
2246 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2247 try:
2248 dict(bad)
2249 except ValueError:
2250 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002251 else:
Georg Brandl48545522008-02-02 10:12:36 +00002252 self.fail("no ValueError from dict(%r)" % bad)
2253
2254 def test_dir(self):
2255 # Testing dir() ...
2256 junk = 12
2257 self.assertEqual(dir(), ['junk', 'self'])
2258 del junk
2259
2260 # Just make sure these don't blow up!
2261 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2262 dir(arg)
2263
2264 # Try classic classes.
2265 class C:
2266 Cdata = 1
2267 def Cmethod(self): pass
2268
2269 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2270 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002271 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002272
2273 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2274 self.assertEqual(dir(c), cstuff)
2275
2276 c.cdata = 2
2277 c.cmethod = lambda self: 0
2278 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002279 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002280
2281 class A(C):
2282 Adata = 1
2283 def Amethod(self): pass
2284
2285 astuff = ['Adata', 'Amethod'] + cstuff
2286 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002287 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002288 a = A()
2289 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002290 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002291 a.adata = 42
2292 a.amethod = lambda self: 3
2293 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2294
2295 # The same, but with new-style classes. Since these have object as a
2296 # base class, a lot more gets sucked in.
2297 def interesting(strings):
2298 return [s for s in strings if not s.startswith('_')]
2299
2300 class C(object):
2301 Cdata = 1
2302 def Cmethod(self): pass
2303
2304 cstuff = ['Cdata', 'Cmethod']
2305 self.assertEqual(interesting(dir(C)), cstuff)
2306
2307 c = C()
2308 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002309 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002310
2311 c.cdata = 2
2312 c.cmethod = lambda self: 0
2313 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002314 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002315
2316 class A(C):
2317 Adata = 1
2318 def Amethod(self): pass
2319
2320 astuff = ['Adata', 'Amethod'] + cstuff
2321 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002322 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002323 a = A()
2324 self.assertEqual(interesting(dir(a)), astuff)
2325 a.adata = 42
2326 a.amethod = lambda self: 3
2327 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002328 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002329
2330 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002331 class M(type(sys)):
2332 pass
2333 minstance = M("m")
2334 minstance.b = 2
2335 minstance.a = 1
2336 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2337 self.assertEqual(names, ['a', 'b'])
2338
2339 class M2(M):
2340 def getdict(self):
2341 return "Not a dict!"
2342 __dict__ = property(getdict)
2343
2344 m2instance = M2("m2")
2345 m2instance.b = 2
2346 m2instance.a = 1
2347 self.assertEqual(m2instance.__dict__, "Not a dict!")
2348 try:
2349 dir(m2instance)
2350 except TypeError:
2351 pass
2352
2353 # Two essentially featureless objects, just inheriting stuff from
2354 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002355 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2356 if test_support.check_impl_detail():
2357 # None differs in PyPy: it has a __nonzero__
2358 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002359
2360 # Nasty test case for proxied objects
2361 class Wrapper(object):
2362 def __init__(self, obj):
2363 self.__obj = obj
2364 def __repr__(self):
2365 return "Wrapper(%s)" % repr(self.__obj)
2366 def __getitem__(self, key):
2367 return Wrapper(self.__obj[key])
2368 def __len__(self):
2369 return len(self.__obj)
2370 def __getattr__(self, name):
2371 return Wrapper(getattr(self.__obj, name))
2372
2373 class C(object):
2374 def __getclass(self):
2375 return Wrapper(type(self))
2376 __class__ = property(__getclass)
2377
2378 dir(C()) # This used to segfault
2379
2380 def test_supers(self):
2381 # Testing super...
2382
2383 class A(object):
2384 def meth(self, a):
2385 return "A(%r)" % a
2386
2387 self.assertEqual(A().meth(1), "A(1)")
2388
2389 class B(A):
2390 def __init__(self):
2391 self.__super = super(B, self)
2392 def meth(self, a):
2393 return "B(%r)" % a + self.__super.meth(a)
2394
2395 self.assertEqual(B().meth(2), "B(2)A(2)")
2396
2397 class C(A):
2398 def meth(self, a):
2399 return "C(%r)" % a + self.__super.meth(a)
2400 C._C__super = super(C)
2401
2402 self.assertEqual(C().meth(3), "C(3)A(3)")
2403
2404 class D(C, B):
2405 def meth(self, a):
2406 return "D(%r)" % a + super(D, self).meth(a)
2407
2408 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2409
2410 # Test for subclassing super
2411
2412 class mysuper(super):
2413 def __init__(self, *args):
2414 return super(mysuper, self).__init__(*args)
2415
2416 class E(D):
2417 def meth(self, a):
2418 return "E(%r)" % a + mysuper(E, self).meth(a)
2419
2420 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2421
2422 class F(E):
2423 def meth(self, a):
2424 s = self.__super # == mysuper(F, self)
2425 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2426 F._F__super = mysuper(F)
2427
2428 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2429
2430 # Make sure certain errors are raised
2431
2432 try:
2433 super(D, 42)
2434 except TypeError:
2435 pass
2436 else:
2437 self.fail("shouldn't allow super(D, 42)")
2438
2439 try:
2440 super(D, C())
2441 except TypeError:
2442 pass
2443 else:
2444 self.fail("shouldn't allow super(D, C())")
2445
2446 try:
2447 super(D).__get__(12)
2448 except TypeError:
2449 pass
2450 else:
2451 self.fail("shouldn't allow super(D).__get__(12)")
2452
2453 try:
2454 super(D).__get__(C())
2455 except TypeError:
2456 pass
2457 else:
2458 self.fail("shouldn't allow super(D).__get__(C())")
2459
2460 # Make sure data descriptors can be overridden and accessed via super
2461 # (new feature in Python 2.3)
2462
2463 class DDbase(object):
2464 def getx(self): return 42
2465 x = property(getx)
2466
2467 class DDsub(DDbase):
2468 def getx(self): return "hello"
2469 x = property(getx)
2470
2471 dd = DDsub()
2472 self.assertEqual(dd.x, "hello")
2473 self.assertEqual(super(DDsub, dd).x, 42)
2474
2475 # Ensure that super() lookup of descriptor from classmethod
2476 # works (SF ID# 743627)
2477
2478 class Base(object):
2479 aProp = property(lambda self: "foo")
2480
2481 class Sub(Base):
2482 @classmethod
2483 def test(klass):
2484 return super(Sub,klass).aProp
2485
2486 self.assertEqual(Sub.test(), Base.aProp)
2487
2488 # Verify that super() doesn't allow keyword args
2489 try:
2490 super(Base, kw=1)
2491 except TypeError:
2492 pass
2493 else:
2494 self.assertEqual("super shouldn't accept keyword args")
2495
2496 def test_basic_inheritance(self):
2497 # Testing inheritance from basic types...
2498
2499 class hexint(int):
2500 def __repr__(self):
2501 return hex(self)
2502 def __add__(self, other):
2503 return hexint(int.__add__(self, other))
2504 # (Note that overriding __radd__ doesn't work,
2505 # because the int type gets first dibs.)
2506 self.assertEqual(repr(hexint(7) + 9), "0x10")
2507 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2508 a = hexint(12345)
2509 self.assertEqual(a, 12345)
2510 self.assertEqual(int(a), 12345)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002511 self.assertIs(int(a).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002512 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002513 self.assertIs((+a).__class__, int)
2514 self.assertIs((a >> 0).__class__, int)
2515 self.assertIs((a << 0).__class__, int)
2516 self.assertIs((hexint(0) << 12).__class__, int)
2517 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002518
2519 class octlong(long):
2520 __slots__ = []
2521 def __str__(self):
2522 s = oct(self)
2523 if s[-1] == 'L':
2524 s = s[:-1]
2525 return s
2526 def __add__(self, other):
2527 return self.__class__(super(octlong, self).__add__(other))
2528 __radd__ = __add__
2529 self.assertEqual(str(octlong(3) + 5), "010")
2530 # (Note that overriding __radd__ here only seems to work
2531 # because the example uses a short int left argument.)
2532 self.assertEqual(str(5 + octlong(3000)), "05675")
2533 a = octlong(12345)
2534 self.assertEqual(a, 12345L)
2535 self.assertEqual(long(a), 12345L)
2536 self.assertEqual(hash(a), hash(12345L))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002537 self.assertIs(long(a).__class__, long)
2538 self.assertIs((+a).__class__, long)
2539 self.assertIs((-a).__class__, long)
2540 self.assertIs((-octlong(0)).__class__, long)
2541 self.assertIs((a >> 0).__class__, long)
2542 self.assertIs((a << 0).__class__, long)
2543 self.assertIs((a - 0).__class__, long)
2544 self.assertIs((a * 1).__class__, long)
2545 self.assertIs((a ** 1).__class__, long)
2546 self.assertIs((a // 1).__class__, long)
2547 self.assertIs((1 * a).__class__, long)
2548 self.assertIs((a | 0).__class__, long)
2549 self.assertIs((a ^ 0).__class__, long)
2550 self.assertIs((a & -1L).__class__, long)
2551 self.assertIs((octlong(0) << 12).__class__, long)
2552 self.assertIs((octlong(0) >> 12).__class__, long)
2553 self.assertIs(abs(octlong(0)).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002554
2555 # Because octlong overrides __add__, we can't check the absence of +0
2556 # optimizations using octlong.
2557 class longclone(long):
2558 pass
2559 a = longclone(1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002560 self.assertIs((a + 0).__class__, long)
2561 self.assertIs((0 + a).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002562
2563 # Check that negative clones don't segfault
2564 a = longclone(-1)
2565 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002566 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002567
2568 class precfloat(float):
2569 __slots__ = ['prec']
2570 def __init__(self, value=0.0, prec=12):
2571 self.prec = int(prec)
2572 def __repr__(self):
2573 return "%.*g" % (self.prec, self)
2574 self.assertEqual(repr(precfloat(1.1)), "1.1")
2575 a = precfloat(12345)
2576 self.assertEqual(a, 12345.0)
2577 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002578 self.assertIs(float(a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002579 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002580 self.assertIs((+a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002581
2582 class madcomplex(complex):
2583 def __repr__(self):
2584 return "%.17gj%+.17g" % (self.imag, self.real)
2585 a = madcomplex(-3, 4)
2586 self.assertEqual(repr(a), "4j-3")
2587 base = complex(-3, 4)
2588 self.assertEqual(base.__class__, complex)
2589 self.assertEqual(a, base)
2590 self.assertEqual(complex(a), base)
2591 self.assertEqual(complex(a).__class__, complex)
2592 a = madcomplex(a) # just trying another form of the constructor
2593 self.assertEqual(repr(a), "4j-3")
2594 self.assertEqual(a, base)
2595 self.assertEqual(complex(a), base)
2596 self.assertEqual(complex(a).__class__, complex)
2597 self.assertEqual(hash(a), hash(base))
2598 self.assertEqual((+a).__class__, complex)
2599 self.assertEqual((a + 0).__class__, complex)
2600 self.assertEqual(a + 0, base)
2601 self.assertEqual((a - 0).__class__, complex)
2602 self.assertEqual(a - 0, base)
2603 self.assertEqual((a * 1).__class__, complex)
2604 self.assertEqual(a * 1, base)
2605 self.assertEqual((a / 1).__class__, complex)
2606 self.assertEqual(a / 1, base)
2607
2608 class madtuple(tuple):
2609 _rev = None
2610 def rev(self):
2611 if self._rev is not None:
2612 return self._rev
2613 L = list(self)
2614 L.reverse()
2615 self._rev = self.__class__(L)
2616 return self._rev
2617 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2618 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2619 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2620 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2621 for i in range(512):
2622 t = madtuple(range(i))
2623 u = t.rev()
2624 v = u.rev()
2625 self.assertEqual(v, t)
2626 a = madtuple((1,2,3,4,5))
2627 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002628 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002629 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002630 self.assertIs(a[:].__class__, tuple)
2631 self.assertIs((a * 1).__class__, tuple)
2632 self.assertIs((a * 0).__class__, tuple)
2633 self.assertIs((a + ()).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002634 a = madtuple(())
2635 self.assertEqual(tuple(a), ())
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002636 self.assertIs(tuple(a).__class__, tuple)
2637 self.assertIs((a + a).__class__, tuple)
2638 self.assertIs((a * 0).__class__, tuple)
2639 self.assertIs((a * 1).__class__, tuple)
2640 self.assertIs((a * 2).__class__, tuple)
2641 self.assertIs(a[:].__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002642
2643 class madstring(str):
2644 _rev = None
2645 def rev(self):
2646 if self._rev is not None:
2647 return self._rev
2648 L = list(self)
2649 L.reverse()
2650 self._rev = self.__class__("".join(L))
2651 return self._rev
2652 s = madstring("abcdefghijklmnopqrstuvwxyz")
2653 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2654 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2655 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2656 for i in range(256):
2657 s = madstring("".join(map(chr, range(i))))
2658 t = s.rev()
2659 u = t.rev()
2660 self.assertEqual(u, s)
2661 s = madstring("12345")
2662 self.assertEqual(str(s), "12345")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002663 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002664
2665 base = "\x00" * 5
2666 s = madstring(base)
2667 self.assertEqual(s, base)
2668 self.assertEqual(str(s), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002669 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002670 self.assertEqual(hash(s), hash(base))
2671 self.assertEqual({s: 1}[base], 1)
2672 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002673 self.assertIs((s + "").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002674 self.assertEqual(s + "", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002675 self.assertIs(("" + s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002676 self.assertEqual("" + s, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002677 self.assertIs((s * 0).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002678 self.assertEqual(s * 0, "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002679 self.assertIs((s * 1).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002680 self.assertEqual(s * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002681 self.assertIs((s * 2).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002682 self.assertEqual(s * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002683 self.assertIs(s[:].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002684 self.assertEqual(s[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002685 self.assertIs(s[0:0].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002686 self.assertEqual(s[0:0], "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002687 self.assertIs(s.strip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002688 self.assertEqual(s.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002689 self.assertIs(s.lstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002690 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002691 self.assertIs(s.rstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002692 self.assertEqual(s.rstrip(), base)
2693 identitytab = ''.join([chr(i) for i in range(256)])
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002694 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002695 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002696 self.assertIs(s.translate(identitytab, "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002697 self.assertEqual(s.translate(identitytab, "x"), base)
2698 self.assertEqual(s.translate(identitytab, "\x00"), "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002699 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002700 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002701 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002702 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002703 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002704 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002705 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002706 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002707 self.assertIs(s.lower().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002708 self.assertEqual(s.lower(), base)
2709
2710 class madunicode(unicode):
2711 _rev = None
2712 def rev(self):
2713 if self._rev is not None:
2714 return self._rev
2715 L = list(self)
2716 L.reverse()
2717 self._rev = self.__class__(u"".join(L))
2718 return self._rev
2719 u = madunicode("ABCDEF")
2720 self.assertEqual(u, u"ABCDEF")
2721 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2722 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2723 base = u"12345"
2724 u = madunicode(base)
2725 self.assertEqual(unicode(u), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002726 self.assertIs(unicode(u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002727 self.assertEqual(hash(u), hash(base))
2728 self.assertEqual({u: 1}[base], 1)
2729 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002730 self.assertIs(u.strip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002731 self.assertEqual(u.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002732 self.assertIs(u.lstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002733 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002734 self.assertIs(u.rstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002735 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002736 self.assertIs(u.replace(u"x", u"x").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002737 self.assertEqual(u.replace(u"x", u"x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002738 self.assertIs(u.replace(u"xy", u"xy").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002739 self.assertEqual(u.replace(u"xy", u"xy"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002740 self.assertIs(u.center(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002741 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002742 self.assertIs(u.ljust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002743 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002744 self.assertIs(u.rjust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002745 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002746 self.assertIs(u.lower().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002747 self.assertEqual(u.lower(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002748 self.assertIs(u.upper().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002749 self.assertEqual(u.upper(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002750 self.assertIs(u.capitalize().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002751 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002752 self.assertIs(u.title().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002753 self.assertEqual(u.title(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002754 self.assertIs((u + u"").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002755 self.assertEqual(u + u"", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002756 self.assertIs((u"" + u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002757 self.assertEqual(u"" + u, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002758 self.assertIs((u * 0).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002759 self.assertEqual(u * 0, u"")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002760 self.assertIs((u * 1).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002761 self.assertEqual(u * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002762 self.assertIs((u * 2).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002763 self.assertEqual(u * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002764 self.assertIs(u[:].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002765 self.assertEqual(u[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002766 self.assertIs(u[0:0].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002767 self.assertEqual(u[0:0], u"")
2768
2769 class sublist(list):
2770 pass
2771 a = sublist(range(5))
2772 self.assertEqual(a, range(5))
2773 a.append("hello")
2774 self.assertEqual(a, range(5) + ["hello"])
2775 a[5] = 5
2776 self.assertEqual(a, range(6))
2777 a.extend(range(6, 20))
2778 self.assertEqual(a, range(20))
2779 a[-5:] = []
2780 self.assertEqual(a, range(15))
2781 del a[10:15]
2782 self.assertEqual(len(a), 10)
2783 self.assertEqual(a, range(10))
2784 self.assertEqual(list(a), range(10))
2785 self.assertEqual(a[0], 0)
2786 self.assertEqual(a[9], 9)
2787 self.assertEqual(a[-10], 0)
2788 self.assertEqual(a[-1], 9)
2789 self.assertEqual(a[:5], range(5))
2790
2791 class CountedInput(file):
2792 """Counts lines read by self.readline().
2793
2794 self.lineno is the 0-based ordinal of the last line read, up to
2795 a maximum of one greater than the number of lines in the file.
2796
2797 self.ateof is true if and only if the final "" line has been read,
2798 at which point self.lineno stops incrementing, and further calls
2799 to readline() continue to return "".
2800 """
2801
2802 lineno = 0
2803 ateof = 0
2804 def readline(self):
2805 if self.ateof:
2806 return ""
2807 s = file.readline(self)
2808 # Next line works too.
2809 # s = super(CountedInput, self).readline()
2810 self.lineno += 1
2811 if s == "":
2812 self.ateof = 1
2813 return s
2814
2815 f = file(name=test_support.TESTFN, mode='w')
2816 lines = ['a\n', 'b\n', 'c\n']
2817 try:
2818 f.writelines(lines)
2819 f.close()
2820 f = CountedInput(test_support.TESTFN)
2821 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2822 got = f.readline()
2823 self.assertEqual(expected, got)
2824 self.assertEqual(f.lineno, i)
2825 self.assertEqual(f.ateof, (i > len(lines)))
2826 f.close()
2827 finally:
2828 try:
2829 f.close()
2830 except:
2831 pass
2832 test_support.unlink(test_support.TESTFN)
2833
2834 def test_keywords(self):
2835 # Testing keyword args to basic type constructors ...
2836 self.assertEqual(int(x=1), 1)
2837 self.assertEqual(float(x=2), 2.0)
2838 self.assertEqual(long(x=3), 3L)
2839 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2840 self.assertEqual(str(object=500), '500')
2841 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2842 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2843 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2844 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2845
2846 for constructor in (int, float, long, complex, str, unicode,
2847 tuple, list, file):
2848 try:
2849 constructor(bogus_keyword_arg=1)
2850 except TypeError:
2851 pass
2852 else:
2853 self.fail("expected TypeError from bogus keyword argument to %r"
2854 % constructor)
2855
2856 def test_str_subclass_as_dict_key(self):
2857 # Testing a str subclass used as dict key ..
2858
2859 class cistr(str):
2860 """Sublcass of str that computes __eq__ case-insensitively.
2861
2862 Also computes a hash code of the string in canonical form.
2863 """
2864
2865 def __init__(self, value):
2866 self.canonical = value.lower()
2867 self.hashcode = hash(self.canonical)
2868
2869 def __eq__(self, other):
2870 if not isinstance(other, cistr):
2871 other = cistr(other)
2872 return self.canonical == other.canonical
2873
2874 def __hash__(self):
2875 return self.hashcode
2876
2877 self.assertEqual(cistr('ABC'), 'abc')
2878 self.assertEqual('aBc', cistr('ABC'))
2879 self.assertEqual(str(cistr('ABC')), 'ABC')
2880
2881 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2882 self.assertEqual(d[cistr('one')], 1)
2883 self.assertEqual(d[cistr('tWo')], 2)
2884 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002885 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002886 self.assertEqual(d.get(cistr('thrEE')), 3)
2887
2888 def test_classic_comparisons(self):
2889 # Testing classic comparisons...
2890 class classic:
2891 pass
2892
2893 for base in (classic, int, object):
2894 class C(base):
2895 def __init__(self, value):
2896 self.value = int(value)
2897 def __cmp__(self, other):
2898 if isinstance(other, C):
2899 return cmp(self.value, other.value)
2900 if isinstance(other, int) or isinstance(other, long):
2901 return cmp(self.value, other)
2902 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002903 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002904
2905 c1 = C(1)
2906 c2 = C(2)
2907 c3 = C(3)
2908 self.assertEqual(c1, 1)
2909 c = {1: c1, 2: c2, 3: c3}
2910 for x in 1, 2, 3:
2911 for y in 1, 2, 3:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002912 self.assertEqual(cmp(c[x], c[y]), cmp(x, y),
2913 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002914 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002915 self.assertEqual(eval("c[x] %s c[y]" % op),
2916 eval("x %s y" % op),
2917 "x=%d, y=%d" % (x, y))
2918 self.assertEqual(cmp(c[x], y), cmp(x, y),
2919 "x=%d, y=%d" % (x, y))
2920 self.assertEqual(cmp(x, c[y]), cmp(x, y),
2921 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002922
2923 def test_rich_comparisons(self):
2924 # Testing rich comparisons...
2925 class Z(complex):
2926 pass
2927 z = Z(1)
2928 self.assertEqual(z, 1+0j)
2929 self.assertEqual(1+0j, z)
2930 class ZZ(complex):
2931 def __eq__(self, other):
2932 try:
2933 return abs(self - other) <= 1e-6
2934 except:
2935 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002936 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002937 zz = ZZ(1.0000003)
2938 self.assertEqual(zz, 1+0j)
2939 self.assertEqual(1+0j, zz)
2940
2941 class classic:
2942 pass
2943 for base in (classic, int, object, list):
2944 class C(base):
2945 def __init__(self, value):
2946 self.value = int(value)
2947 def __cmp__(self_, other):
2948 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002949 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002950 def __eq__(self, other):
2951 if isinstance(other, C):
2952 return self.value == other.value
2953 if isinstance(other, int) or isinstance(other, long):
2954 return self.value == other
2955 return NotImplemented
2956 def __ne__(self, other):
2957 if isinstance(other, C):
2958 return self.value != other.value
2959 if isinstance(other, int) or isinstance(other, long):
2960 return self.value != other
2961 return NotImplemented
2962 def __lt__(self, other):
2963 if isinstance(other, C):
2964 return self.value < other.value
2965 if isinstance(other, int) or isinstance(other, long):
2966 return self.value < other
2967 return NotImplemented
2968 def __le__(self, other):
2969 if isinstance(other, C):
2970 return self.value <= other.value
2971 if isinstance(other, int) or isinstance(other, long):
2972 return self.value <= other
2973 return NotImplemented
2974 def __gt__(self, other):
2975 if isinstance(other, C):
2976 return self.value > other.value
2977 if isinstance(other, int) or isinstance(other, long):
2978 return self.value > other
2979 return NotImplemented
2980 def __ge__(self, other):
2981 if isinstance(other, C):
2982 return self.value >= other.value
2983 if isinstance(other, int) or isinstance(other, long):
2984 return self.value >= other
2985 return NotImplemented
2986 c1 = C(1)
2987 c2 = C(2)
2988 c3 = C(3)
2989 self.assertEqual(c1, 1)
2990 c = {1: c1, 2: c2, 3: c3}
2991 for x in 1, 2, 3:
2992 for y in 1, 2, 3:
2993 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002994 self.assertEqual(eval("c[x] %s c[y]" % op),
2995 eval("x %s y" % op),
2996 "x=%d, y=%d" % (x, y))
2997 self.assertEqual(eval("c[x] %s y" % op),
2998 eval("x %s y" % op),
2999 "x=%d, y=%d" % (x, y))
3000 self.assertEqual(eval("x %s c[y]" % op),
3001 eval("x %s y" % op),
3002 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003003
3004 def test_coercions(self):
3005 # Testing coercions...
3006 class I(int): pass
3007 coerce(I(0), 0)
3008 coerce(0, I(0))
3009 class L(long): pass
3010 coerce(L(0), 0)
3011 coerce(L(0), 0L)
3012 coerce(0, L(0))
3013 coerce(0L, L(0))
3014 class F(float): pass
3015 coerce(F(0), 0)
3016 coerce(F(0), 0L)
3017 coerce(F(0), 0.)
3018 coerce(0, F(0))
3019 coerce(0L, F(0))
3020 coerce(0., F(0))
3021 class C(complex): pass
3022 coerce(C(0), 0)
3023 coerce(C(0), 0L)
3024 coerce(C(0), 0.)
3025 coerce(C(0), 0j)
3026 coerce(0, C(0))
3027 coerce(0L, C(0))
3028 coerce(0., C(0))
3029 coerce(0j, C(0))
3030
3031 def test_descrdoc(self):
3032 # Testing descriptor doc strings...
3033 def check(descr, what):
3034 self.assertEqual(descr.__doc__, what)
3035 check(file.closed, "True if the file is closed") # getset descriptor
3036 check(file.name, "file name") # member descriptor
3037
3038 def test_doc_descriptor(self):
3039 # Testing __doc__ descriptor...
3040 # SF bug 542984
3041 class DocDescr(object):
3042 def __get__(self, object, otype):
3043 if object:
3044 object = object.__class__.__name__ + ' instance'
3045 if otype:
3046 otype = otype.__name__
3047 return 'object=%s; type=%s' % (object, otype)
3048 class OldClass:
3049 __doc__ = DocDescr()
3050 class NewClass(object):
3051 __doc__ = DocDescr()
3052 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3053 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3054 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3055 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3056
3057 def test_set_class(self):
3058 # Testing __class__ assignment...
3059 class C(object): pass
3060 class D(object): pass
3061 class E(object): pass
3062 class F(D, E): pass
3063 for cls in C, D, E, F:
3064 for cls2 in C, D, E, F:
3065 x = cls()
3066 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003067 self.assertIs(x.__class__, cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003068 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003069 self.assertIs(x.__class__, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003070 def cant(x, C):
3071 try:
3072 x.__class__ = C
3073 except TypeError:
3074 pass
3075 else:
3076 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3077 try:
3078 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003079 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003080 pass
3081 else:
3082 self.fail("shouldn't allow del %r.__class__" % x)
3083 cant(C(), list)
3084 cant(list(), C)
3085 cant(C(), 1)
3086 cant(C(), object)
3087 cant(object(), list)
3088 cant(list(), object)
3089 class Int(int): __slots__ = []
3090 cant(2, Int)
3091 cant(Int(), int)
3092 cant(True, int)
3093 cant(2, bool)
3094 o = object()
3095 cant(o, type(1))
3096 cant(o, type(None))
3097 del o
3098 class G(object):
3099 __slots__ = ["a", "b"]
3100 class H(object):
3101 __slots__ = ["b", "a"]
3102 try:
3103 unicode
3104 except NameError:
3105 class I(object):
3106 __slots__ = ["a", "b"]
3107 else:
3108 class I(object):
3109 __slots__ = [unicode("a"), unicode("b")]
3110 class J(object):
3111 __slots__ = ["c", "b"]
3112 class K(object):
3113 __slots__ = ["a", "b", "d"]
3114 class L(H):
3115 __slots__ = ["e"]
3116 class M(I):
3117 __slots__ = ["e"]
3118 class N(J):
3119 __slots__ = ["__weakref__"]
3120 class P(J):
3121 __slots__ = ["__dict__"]
3122 class Q(J):
3123 pass
3124 class R(J):
3125 __slots__ = ["__dict__", "__weakref__"]
3126
3127 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3128 x = cls()
3129 x.a = 1
3130 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003131 self.assertIs(x.__class__, cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003132 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3133 self.assertEqual(x.a, 1)
3134 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003135 self.assertIs(x.__class__, cls,
Georg Brandl48545522008-02-02 10:12:36 +00003136 "assigning %r as __class__ for %r silently failed" % (cls, x))
3137 self.assertEqual(x.a, 1)
3138 for cls in G, J, K, L, M, N, P, R, list, Int:
3139 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3140 if cls is cls2:
3141 continue
3142 cant(cls(), cls2)
3143
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003144 # Issue5283: when __class__ changes in __del__, the wrong
3145 # type gets DECREF'd.
3146 class O(object):
3147 pass
3148 class A(object):
3149 def __del__(self):
3150 self.__class__ = O
3151 l = [A() for x in range(100)]
3152 del l
3153
Georg Brandl48545522008-02-02 10:12:36 +00003154 def test_set_dict(self):
3155 # Testing __dict__ assignment...
3156 class C(object): pass
3157 a = C()
3158 a.__dict__ = {'b': 1}
3159 self.assertEqual(a.b, 1)
3160 def cant(x, dict):
3161 try:
3162 x.__dict__ = dict
3163 except (AttributeError, TypeError):
3164 pass
3165 else:
3166 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3167 cant(a, None)
3168 cant(a, [])
3169 cant(a, 1)
3170 del a.__dict__ # Deleting __dict__ is allowed
3171
3172 class Base(object):
3173 pass
3174 def verify_dict_readonly(x):
3175 """
3176 x has to be an instance of a class inheriting from Base.
3177 """
3178 cant(x, {})
3179 try:
3180 del x.__dict__
3181 except (AttributeError, TypeError):
3182 pass
3183 else:
3184 self.fail("shouldn't allow del %r.__dict__" % x)
3185 dict_descr = Base.__dict__["__dict__"]
3186 try:
3187 dict_descr.__set__(x, {})
3188 except (AttributeError, TypeError):
3189 pass
3190 else:
3191 self.fail("dict_descr allowed access to %r's dict" % x)
3192
3193 # Classes don't allow __dict__ assignment and have readonly dicts
3194 class Meta1(type, Base):
3195 pass
3196 class Meta2(Base, type):
3197 pass
3198 class D(object):
3199 __metaclass__ = Meta1
3200 class E(object):
3201 __metaclass__ = Meta2
3202 for cls in C, D, E:
3203 verify_dict_readonly(cls)
3204 class_dict = cls.__dict__
3205 try:
3206 class_dict["spam"] = "eggs"
3207 except TypeError:
3208 pass
3209 else:
3210 self.fail("%r's __dict__ can be modified" % cls)
3211
3212 # Modules also disallow __dict__ assignment
3213 class Module1(types.ModuleType, Base):
3214 pass
3215 class Module2(Base, types.ModuleType):
3216 pass
3217 for ModuleType in Module1, Module2:
3218 mod = ModuleType("spam")
3219 verify_dict_readonly(mod)
3220 mod.__dict__["spam"] = "eggs"
3221
3222 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003223 # (at least not any more than regular exception's __dict__ can
3224 # be deleted; on CPython it is not the case, whereas on PyPy they
3225 # can, just like any other new-style instance's __dict__.)
3226 def can_delete_dict(e):
3227 try:
3228 del e.__dict__
3229 except (TypeError, AttributeError):
3230 return False
3231 else:
3232 return True
Georg Brandl48545522008-02-02 10:12:36 +00003233 class Exception1(Exception, Base):
3234 pass
3235 class Exception2(Base, Exception):
3236 pass
3237 for ExceptionType in Exception, Exception1, Exception2:
3238 e = ExceptionType()
3239 e.__dict__ = {"a": 1}
3240 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003241 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003242
3243 def test_pickles(self):
3244 # Testing pickling and copying new-style classes and objects...
3245 import pickle, cPickle
3246
3247 def sorteditems(d):
3248 L = d.items()
3249 L.sort()
3250 return L
3251
3252 global C
3253 class C(object):
3254 def __init__(self, a, b):
3255 super(C, self).__init__()
3256 self.a = a
3257 self.b = b
3258 def __repr__(self):
3259 return "C(%r, %r)" % (self.a, self.b)
3260
3261 global C1
3262 class C1(list):
3263 def __new__(cls, a, b):
3264 return super(C1, cls).__new__(cls)
3265 def __getnewargs__(self):
3266 return (self.a, self.b)
3267 def __init__(self, a, b):
3268 self.a = a
3269 self.b = b
3270 def __repr__(self):
3271 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3272
3273 global C2
3274 class C2(int):
3275 def __new__(cls, a, b, val=0):
3276 return super(C2, cls).__new__(cls, val)
3277 def __getnewargs__(self):
3278 return (self.a, self.b, int(self))
3279 def __init__(self, a, b, val=0):
3280 self.a = a
3281 self.b = b
3282 def __repr__(self):
3283 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3284
3285 global C3
3286 class C3(object):
3287 def __init__(self, foo):
3288 self.foo = foo
3289 def __getstate__(self):
3290 return self.foo
3291 def __setstate__(self, foo):
3292 self.foo = foo
3293
3294 global C4classic, C4
3295 class C4classic: # classic
3296 pass
3297 class C4(C4classic, object): # mixed inheritance
3298 pass
3299
3300 for p in pickle, cPickle:
3301 for bin in 0, 1:
3302 for cls in C, C1, C2:
3303 s = p.dumps(cls, bin)
3304 cls2 = p.loads(s)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003305 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003306
3307 a = C1(1, 2); a.append(42); a.append(24)
3308 b = C2("hello", "world", 42)
3309 s = p.dumps((a, b), bin)
3310 x, y = p.loads(s)
3311 self.assertEqual(x.__class__, a.__class__)
3312 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3313 self.assertEqual(y.__class__, b.__class__)
3314 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3315 self.assertEqual(repr(x), repr(a))
3316 self.assertEqual(repr(y), repr(b))
3317 # Test for __getstate__ and __setstate__ on new style class
3318 u = C3(42)
3319 s = p.dumps(u, bin)
3320 v = p.loads(s)
3321 self.assertEqual(u.__class__, v.__class__)
3322 self.assertEqual(u.foo, v.foo)
3323 # Test for picklability of hybrid class
3324 u = C4()
3325 u.foo = 42
3326 s = p.dumps(u, bin)
3327 v = p.loads(s)
3328 self.assertEqual(u.__class__, v.__class__)
3329 self.assertEqual(u.foo, v.foo)
3330
3331 # Testing copy.deepcopy()
3332 import copy
3333 for cls in C, C1, C2:
3334 cls2 = copy.deepcopy(cls)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003335 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003336
3337 a = C1(1, 2); a.append(42); a.append(24)
3338 b = C2("hello", "world", 42)
3339 x, y = copy.deepcopy((a, b))
3340 self.assertEqual(x.__class__, a.__class__)
3341 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3342 self.assertEqual(y.__class__, b.__class__)
3343 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3344 self.assertEqual(repr(x), repr(a))
3345 self.assertEqual(repr(y), repr(b))
3346
3347 def test_pickle_slots(self):
3348 # Testing pickling of classes with __slots__ ...
3349 import pickle, cPickle
3350 # Pickling of classes with __slots__ but without __getstate__ should fail
3351 global B, C, D, E
3352 class B(object):
3353 pass
3354 for base in [object, B]:
3355 class C(base):
3356 __slots__ = ['a']
3357 class D(C):
3358 pass
3359 try:
3360 pickle.dumps(C())
3361 except TypeError:
3362 pass
3363 else:
3364 self.fail("should fail: pickle C instance - %s" % base)
3365 try:
3366 cPickle.dumps(C())
3367 except TypeError:
3368 pass
3369 else:
3370 self.fail("should fail: cPickle C instance - %s" % base)
3371 try:
3372 pickle.dumps(C())
3373 except TypeError:
3374 pass
3375 else:
3376 self.fail("should fail: pickle D instance - %s" % base)
3377 try:
3378 cPickle.dumps(D())
3379 except TypeError:
3380 pass
3381 else:
3382 self.fail("should fail: cPickle D instance - %s" % base)
3383 # Give C a nice generic __getstate__ and __setstate__
3384 class C(base):
3385 __slots__ = ['a']
3386 def __getstate__(self):
3387 try:
3388 d = self.__dict__.copy()
3389 except AttributeError:
3390 d = {}
3391 for cls in self.__class__.__mro__:
3392 for sn in cls.__dict__.get('__slots__', ()):
3393 try:
3394 d[sn] = getattr(self, sn)
3395 except AttributeError:
3396 pass
3397 return d
3398 def __setstate__(self, d):
3399 for k, v in d.items():
3400 setattr(self, k, v)
3401 class D(C):
3402 pass
3403 # Now it should work
3404 x = C()
3405 y = pickle.loads(pickle.dumps(x))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003406 self.assertNotHasAttr(y, 'a')
Georg Brandl48545522008-02-02 10:12:36 +00003407 y = cPickle.loads(cPickle.dumps(x))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003408 self.assertNotHasAttr(y, 'a')
Georg Brandl48545522008-02-02 10:12:36 +00003409 x.a = 42
3410 y = pickle.loads(pickle.dumps(x))
3411 self.assertEqual(y.a, 42)
3412 y = cPickle.loads(cPickle.dumps(x))
3413 self.assertEqual(y.a, 42)
3414 x = D()
3415 x.a = 42
3416 x.b = 100
3417 y = pickle.loads(pickle.dumps(x))
3418 self.assertEqual(y.a + y.b, 142)
3419 y = cPickle.loads(cPickle.dumps(x))
3420 self.assertEqual(y.a + y.b, 142)
3421 # A subclass that adds a slot should also work
3422 class E(C):
3423 __slots__ = ['b']
3424 x = E()
3425 x.a = 42
3426 x.b = "foo"
3427 y = pickle.loads(pickle.dumps(x))
3428 self.assertEqual(y.a, x.a)
3429 self.assertEqual(y.b, x.b)
3430 y = cPickle.loads(cPickle.dumps(x))
3431 self.assertEqual(y.a, x.a)
3432 self.assertEqual(y.b, x.b)
3433
3434 def test_binary_operator_override(self):
3435 # Testing overrides of binary operations...
3436 class I(int):
3437 def __repr__(self):
3438 return "I(%r)" % int(self)
3439 def __add__(self, other):
3440 return I(int(self) + int(other))
3441 __radd__ = __add__
3442 def __pow__(self, other, mod=None):
3443 if mod is None:
3444 return I(pow(int(self), int(other)))
3445 else:
3446 return I(pow(int(self), int(other), int(mod)))
3447 def __rpow__(self, other, mod=None):
3448 if mod is None:
3449 return I(pow(int(other), int(self), mod))
3450 else:
3451 return I(pow(int(other), int(self), int(mod)))
3452
3453 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3454 self.assertEqual(repr(I(1) + 2), "I(3)")
3455 self.assertEqual(repr(1 + I(2)), "I(3)")
3456 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3457 self.assertEqual(repr(2 ** I(3)), "I(8)")
3458 self.assertEqual(repr(I(2) ** 3), "I(8)")
3459 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3460 class S(str):
3461 def __eq__(self, other):
3462 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003463 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003464
3465 def test_subclass_propagation(self):
3466 # Testing propagation of slot functions to subclasses...
3467 class A(object):
3468 pass
3469 class B(A):
3470 pass
3471 class C(A):
3472 pass
3473 class D(B, C):
3474 pass
3475 d = D()
3476 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3477 A.__hash__ = lambda self: 42
3478 self.assertEqual(hash(d), 42)
3479 C.__hash__ = lambda self: 314
3480 self.assertEqual(hash(d), 314)
3481 B.__hash__ = lambda self: 144
3482 self.assertEqual(hash(d), 144)
3483 D.__hash__ = lambda self: 100
3484 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003485 D.__hash__ = None
3486 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003487 del D.__hash__
3488 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003489 B.__hash__ = None
3490 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003491 del B.__hash__
3492 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003493 C.__hash__ = None
3494 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003495 del C.__hash__
3496 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003497 A.__hash__ = None
3498 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003499 del A.__hash__
3500 self.assertEqual(hash(d), orig_hash)
3501 d.foo = 42
3502 d.bar = 42
3503 self.assertEqual(d.foo, 42)
3504 self.assertEqual(d.bar, 42)
3505 def __getattribute__(self, name):
3506 if name == "foo":
3507 return 24
3508 return object.__getattribute__(self, name)
3509 A.__getattribute__ = __getattribute__
3510 self.assertEqual(d.foo, 24)
3511 self.assertEqual(d.bar, 42)
3512 def __getattr__(self, name):
3513 if name in ("spam", "foo", "bar"):
3514 return "hello"
3515 raise AttributeError, name
3516 B.__getattr__ = __getattr__
3517 self.assertEqual(d.spam, "hello")
3518 self.assertEqual(d.foo, 24)
3519 self.assertEqual(d.bar, 42)
3520 del A.__getattribute__
3521 self.assertEqual(d.foo, 42)
3522 del d.foo
3523 self.assertEqual(d.foo, "hello")
3524 self.assertEqual(d.bar, 42)
3525 del B.__getattr__
3526 try:
3527 d.foo
3528 except AttributeError:
3529 pass
3530 else:
3531 self.fail("d.foo should be undefined now")
3532
3533 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003534 class A(object):
3535 pass
3536 class B(A):
3537 pass
3538 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003539 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003540 A.__setitem__ = lambda *a: None # crash
3541
3542 def test_buffer_inheritance(self):
3543 # Testing that buffer interface is inherited ...
3544
3545 import binascii
3546 # SF bug [#470040] ParseTuple t# vs subclasses.
3547
3548 class MyStr(str):
3549 pass
3550 base = 'abc'
3551 m = MyStr(base)
3552 # b2a_hex uses the buffer interface to get its argument's value, via
3553 # PyArg_ParseTuple 't#' code.
3554 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3555
3556 # It's not clear that unicode will continue to support the character
3557 # buffer interface, and this test will fail if that's taken away.
3558 class MyUni(unicode):
3559 pass
3560 base = u'abc'
3561 m = MyUni(base)
3562 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3563
3564 class MyInt(int):
3565 pass
3566 m = MyInt(42)
3567 try:
3568 binascii.b2a_hex(m)
3569 self.fail('subclass of int should not have a buffer interface')
3570 except TypeError:
3571 pass
3572
3573 def test_str_of_str_subclass(self):
3574 # Testing __str__ defined in subclass of str ...
3575 import binascii
3576 import cStringIO
3577
3578 class octetstring(str):
3579 def __str__(self):
3580 return binascii.b2a_hex(self)
3581 def __repr__(self):
3582 return self + " repr"
3583
3584 o = octetstring('A')
3585 self.assertEqual(type(o), octetstring)
3586 self.assertEqual(type(str(o)), str)
3587 self.assertEqual(type(repr(o)), str)
3588 self.assertEqual(ord(o), 0x41)
3589 self.assertEqual(str(o), '41')
3590 self.assertEqual(repr(o), 'A repr')
3591 self.assertEqual(o.__str__(), '41')
3592 self.assertEqual(o.__repr__(), 'A repr')
3593
3594 capture = cStringIO.StringIO()
3595 # Calling str() or not exercises different internal paths.
3596 print >> capture, o
3597 print >> capture, str(o)
3598 self.assertEqual(capture.getvalue(), '41\n41\n')
3599 capture.close()
3600
3601 def test_keyword_arguments(self):
3602 # Testing keyword arguments to __init__, __call__...
3603 def f(a): return a
3604 self.assertEqual(f.__call__(a=42), 42)
3605 a = []
3606 list.__init__(a, sequence=[0, 1, 2])
3607 self.assertEqual(a, [0, 1, 2])
3608
3609 def test_recursive_call(self):
3610 # Testing recursive __call__() by setting to instance of class...
3611 class A(object):
3612 pass
3613
3614 A.__call__ = A()
3615 try:
3616 A()()
3617 except RuntimeError:
3618 pass
3619 else:
3620 self.fail("Recursion limit should have been reached for __call__()")
3621
3622 def test_delete_hook(self):
3623 # Testing __del__ hook...
3624 log = []
3625 class C(object):
3626 def __del__(self):
3627 log.append(1)
3628 c = C()
3629 self.assertEqual(log, [])
3630 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003631 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003632 self.assertEqual(log, [1])
3633
3634 class D(object): pass
3635 d = D()
3636 try: del d[0]
3637 except TypeError: pass
3638 else: self.fail("invalid del() didn't raise TypeError")
3639
3640 def test_hash_inheritance(self):
3641 # Testing hash of mutable subclasses...
3642
3643 class mydict(dict):
3644 pass
3645 d = mydict()
3646 try:
3647 hash(d)
3648 except TypeError:
3649 pass
3650 else:
3651 self.fail("hash() of dict subclass should fail")
3652
3653 class mylist(list):
3654 pass
3655 d = mylist()
3656 try:
3657 hash(d)
3658 except TypeError:
3659 pass
3660 else:
3661 self.fail("hash() of list subclass should fail")
3662
3663 def test_str_operations(self):
3664 try: 'a' + 5
3665 except TypeError: pass
3666 else: self.fail("'' + 5 doesn't raise TypeError")
3667
3668 try: ''.split('')
3669 except ValueError: pass
3670 else: self.fail("''.split('') doesn't raise ValueError")
3671
3672 try: ''.join([0])
3673 except TypeError: pass
3674 else: self.fail("''.join([0]) doesn't raise TypeError")
3675
3676 try: ''.rindex('5')
3677 except ValueError: pass
3678 else: self.fail("''.rindex('5') doesn't raise ValueError")
3679
3680 try: '%(n)s' % None
3681 except TypeError: pass
3682 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3683
3684 try: '%(n' % {}
3685 except ValueError: pass
3686 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3687
3688 try: '%*s' % ('abc')
3689 except TypeError: pass
3690 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3691
3692 try: '%*.*s' % ('abc', 5)
3693 except TypeError: pass
3694 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3695
3696 try: '%s' % (1, 2)
3697 except TypeError: pass
3698 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3699
3700 try: '%' % None
3701 except ValueError: pass
3702 else: self.fail("'%' % None doesn't raise ValueError")
3703
3704 self.assertEqual('534253'.isdigit(), 1)
3705 self.assertEqual('534253x'.isdigit(), 0)
3706 self.assertEqual('%c' % 5, '\x05')
3707 self.assertEqual('%c' % '5', '5')
3708
3709 def test_deepcopy_recursive(self):
3710 # Testing deepcopy of recursive objects...
3711 class Node:
3712 pass
3713 a = Node()
3714 b = Node()
3715 a.b = b
3716 b.a = a
3717 z = deepcopy(a) # This blew up before
3718
3719 def test_unintialized_modules(self):
3720 # Testing uninitialized module objects...
3721 from types import ModuleType as M
3722 m = M.__new__(M)
3723 str(m)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003724 self.assertNotHasAttr(m, "__name__")
3725 self.assertNotHasAttr(m, "__file__")
3726 self.assertNotHasAttr(m, "foo")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003727 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003728 m.foo = 1
3729 self.assertEqual(m.__dict__, {"foo": 1})
3730
3731 def test_funny_new(self):
3732 # Testing __new__ returning something unexpected...
3733 class C(object):
3734 def __new__(cls, arg):
3735 if isinstance(arg, str): return [1, 2, 3]
3736 elif isinstance(arg, int): return object.__new__(D)
3737 else: return object.__new__(cls)
3738 class D(C):
3739 def __init__(self, arg):
3740 self.foo = arg
3741 self.assertEqual(C("1"), [1, 2, 3])
3742 self.assertEqual(D("1"), [1, 2, 3])
3743 d = D(None)
3744 self.assertEqual(d.foo, None)
3745 d = C(1)
3746 self.assertEqual(isinstance(d, D), True)
3747 self.assertEqual(d.foo, 1)
3748 d = D(1)
3749 self.assertEqual(isinstance(d, D), True)
3750 self.assertEqual(d.foo, 1)
3751
3752 def test_imul_bug(self):
3753 # Testing for __imul__ problems...
3754 # SF bug 544647
3755 class C(object):
3756 def __imul__(self, other):
3757 return (self, other)
3758 x = C()
3759 y = x
3760 y *= 1.0
3761 self.assertEqual(y, (x, 1.0))
3762 y = x
3763 y *= 2
3764 self.assertEqual(y, (x, 2))
3765 y = x
3766 y *= 3L
3767 self.assertEqual(y, (x, 3L))
3768 y = x
3769 y *= 1L<<100
3770 self.assertEqual(y, (x, 1L<<100))
3771 y = x
3772 y *= None
3773 self.assertEqual(y, (x, None))
3774 y = x
3775 y *= "foo"
3776 self.assertEqual(y, (x, "foo"))
3777
3778 def test_copy_setstate(self):
3779 # Testing that copy.*copy() correctly uses __setstate__...
3780 import copy
3781 class C(object):
3782 def __init__(self, foo=None):
3783 self.foo = foo
3784 self.__foo = foo
3785 def setfoo(self, foo=None):
3786 self.foo = foo
3787 def getfoo(self):
3788 return self.__foo
3789 def __getstate__(self):
3790 return [self.foo]
3791 def __setstate__(self_, lst):
3792 self.assertEqual(len(lst), 1)
3793 self_.__foo = self_.foo = lst[0]
3794 a = C(42)
3795 a.setfoo(24)
3796 self.assertEqual(a.foo, 24)
3797 self.assertEqual(a.getfoo(), 42)
3798 b = copy.copy(a)
3799 self.assertEqual(b.foo, 24)
3800 self.assertEqual(b.getfoo(), 24)
3801 b = copy.deepcopy(a)
3802 self.assertEqual(b.foo, 24)
3803 self.assertEqual(b.getfoo(), 24)
3804
3805 def test_slices(self):
3806 # Testing cases with slices and overridden __getitem__ ...
3807
3808 # Strings
3809 self.assertEqual("hello"[:4], "hell")
3810 self.assertEqual("hello"[slice(4)], "hell")
3811 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3812 class S(str):
3813 def __getitem__(self, x):
3814 return str.__getitem__(self, x)
3815 self.assertEqual(S("hello")[:4], "hell")
3816 self.assertEqual(S("hello")[slice(4)], "hell")
3817 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3818 # Tuples
3819 self.assertEqual((1,2,3)[:2], (1,2))
3820 self.assertEqual((1,2,3)[slice(2)], (1,2))
3821 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3822 class T(tuple):
3823 def __getitem__(self, x):
3824 return tuple.__getitem__(self, x)
3825 self.assertEqual(T((1,2,3))[:2], (1,2))
3826 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3827 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3828 # Lists
3829 self.assertEqual([1,2,3][:2], [1,2])
3830 self.assertEqual([1,2,3][slice(2)], [1,2])
3831 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3832 class L(list):
3833 def __getitem__(self, x):
3834 return list.__getitem__(self, x)
3835 self.assertEqual(L([1,2,3])[:2], [1,2])
3836 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3837 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3838 # Now do lists and __setitem__
3839 a = L([1,2,3])
3840 a[slice(1, 3)] = [3,2]
3841 self.assertEqual(a, [1,3,2])
3842 a[slice(0, 2, 1)] = [3,1]
3843 self.assertEqual(a, [3,1,2])
3844 a.__setitem__(slice(1, 3), [2,1])
3845 self.assertEqual(a, [3,2,1])
3846 a.__setitem__(slice(0, 2, 1), [2,3])
3847 self.assertEqual(a, [2,3,1])
3848
3849 def test_subtype_resurrection(self):
3850 # Testing resurrection of new-style instance...
3851
3852 class C(object):
3853 container = []
3854
3855 def __del__(self):
3856 # resurrect the instance
3857 C.container.append(self)
3858
3859 c = C()
3860 c.attr = 42
3861
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003862 # The most interesting thing here is whether this blows up, due to
3863 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3864 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003865 del c
3866
3867 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003868 # the last container slot works: that will attempt to delete c again,
3869 # which will cause c to get appended back to the container again
3870 # "during" the del. (On non-CPython implementations, however, __del__
3871 # is typically not called again.)
3872 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003873 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003874 del C.container[-1]
3875 if test_support.check_impl_detail():
3876 test_support.gc_collect()
3877 self.assertEqual(len(C.container), 1)
3878 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003879
3880 # Make c mortal again, so that the test framework with -l doesn't report
3881 # it as a leak.
3882 del C.__del__
3883
3884 def test_slots_trash(self):
3885 # Testing slot trash...
3886 # Deallocating deeply nested slotted trash caused stack overflows
3887 class trash(object):
3888 __slots__ = ['x']
3889 def __init__(self, x):
3890 self.x = x
3891 o = None
3892 for i in xrange(50000):
3893 o = trash(o)
3894 del o
3895
3896 def test_slots_multiple_inheritance(self):
3897 # SF bug 575229, multiple inheritance w/ slots dumps core
3898 class A(object):
3899 __slots__=()
3900 class B(object):
3901 pass
3902 class C(A,B) :
3903 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003904 if test_support.check_impl_detail():
3905 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003906 self.assertHasAttr(C, '__dict__')
3907 self.assertHasAttr(C, '__weakref__')
Georg Brandl48545522008-02-02 10:12:36 +00003908 C().x = 2
3909
3910 def test_rmul(self):
3911 # Testing correct invocation of __rmul__...
3912 # SF patch 592646
3913 class C(object):
3914 def __mul__(self, other):
3915 return "mul"
3916 def __rmul__(self, other):
3917 return "rmul"
3918 a = C()
3919 self.assertEqual(a*2, "mul")
3920 self.assertEqual(a*2.2, "mul")
3921 self.assertEqual(2*a, "rmul")
3922 self.assertEqual(2.2*a, "rmul")
3923
3924 def test_ipow(self):
3925 # Testing correct invocation of __ipow__...
3926 # [SF bug 620179]
3927 class C(object):
3928 def __ipow__(self, other):
3929 pass
3930 a = C()
3931 a **= 2
3932
3933 def test_mutable_bases(self):
3934 # Testing mutable bases...
3935
3936 # stuff that should work:
3937 class C(object):
3938 pass
3939 class C2(object):
3940 def __getattribute__(self, attr):
3941 if attr == 'a':
3942 return 2
3943 else:
3944 return super(C2, self).__getattribute__(attr)
3945 def meth(self):
3946 return 1
3947 class D(C):
3948 pass
3949 class E(D):
3950 pass
3951 d = D()
3952 e = E()
3953 D.__bases__ = (C,)
3954 D.__bases__ = (C2,)
3955 self.assertEqual(d.meth(), 1)
3956 self.assertEqual(e.meth(), 1)
3957 self.assertEqual(d.a, 2)
3958 self.assertEqual(e.a, 2)
3959 self.assertEqual(C2.__subclasses__(), [D])
3960
Georg Brandl48545522008-02-02 10:12:36 +00003961 try:
3962 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003963 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003964 pass
3965 else:
3966 self.fail("shouldn't be able to delete .__bases__")
3967
3968 try:
3969 D.__bases__ = ()
3970 except TypeError, msg:
3971 if str(msg) == "a new-style class can't have only classic bases":
3972 self.fail("wrong error message for .__bases__ = ()")
3973 else:
3974 self.fail("shouldn't be able to set .__bases__ to ()")
3975
3976 try:
3977 D.__bases__ = (D,)
3978 except TypeError:
3979 pass
3980 else:
3981 # actually, we'll have crashed by here...
3982 self.fail("shouldn't be able to create inheritance cycles")
3983
3984 try:
3985 D.__bases__ = (C, C)
3986 except TypeError:
3987 pass
3988 else:
3989 self.fail("didn't detect repeated base classes")
3990
3991 try:
3992 D.__bases__ = (E,)
3993 except TypeError:
3994 pass
3995 else:
3996 self.fail("shouldn't be able to create inheritance cycles")
3997
3998 # let's throw a classic class into the mix:
3999 class Classic:
4000 def meth2(self):
4001 return 3
4002
4003 D.__bases__ = (C, Classic)
4004
4005 self.assertEqual(d.meth2(), 3)
4006 self.assertEqual(e.meth2(), 3)
4007 try:
4008 d.a
4009 except AttributeError:
4010 pass
4011 else:
4012 self.fail("attribute should have vanished")
4013
4014 try:
4015 D.__bases__ = (Classic,)
4016 except TypeError:
4017 pass
4018 else:
4019 self.fail("new-style class must have a new-style base")
4020
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004021 def test_builtin_bases(self):
4022 # Make sure all the builtin types can have their base queried without
4023 # segfaulting. See issue #5787.
4024 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
4025 if isinstance(tp, type)]
4026 for tp in builtin_types:
4027 object.__getattribute__(tp, "__bases__")
4028 if tp is not object:
4029 self.assertEqual(len(tp.__bases__), 1, tp)
4030
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00004031 class L(list):
4032 pass
4033
4034 class C(object):
4035 pass
4036
4037 class D(C):
4038 pass
4039
4040 try:
4041 L.__bases__ = (dict,)
4042 except TypeError:
4043 pass
4044 else:
4045 self.fail("shouldn't turn list subclass into dict subclass")
4046
4047 try:
4048 list.__bases__ = (dict,)
4049 except TypeError:
4050 pass
4051 else:
4052 self.fail("shouldn't be able to assign to list.__bases__")
4053
4054 try:
4055 D.__bases__ = (C, list)
4056 except TypeError:
4057 pass
4058 else:
4059 assert 0, "best_base calculation found wanting"
4060
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004061
Georg Brandl48545522008-02-02 10:12:36 +00004062 def test_mutable_bases_with_failing_mro(self):
4063 # Testing mutable bases with failing mro...
4064 class WorkOnce(type):
4065 def __new__(self, name, bases, ns):
4066 self.flag = 0
4067 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4068 def mro(self):
4069 if self.flag > 0:
4070 raise RuntimeError, "bozo"
4071 else:
4072 self.flag += 1
4073 return type.mro(self)
4074
4075 class WorkAlways(type):
4076 def mro(self):
4077 # this is here to make sure that .mro()s aren't called
4078 # with an exception set (which was possible at one point).
4079 # An error message will be printed in a debug build.
4080 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004081 return type.mro(self)
4082
Georg Brandl48545522008-02-02 10:12:36 +00004083 class C(object):
4084 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004085
Georg Brandl48545522008-02-02 10:12:36 +00004086 class C2(object):
4087 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004088
Georg Brandl48545522008-02-02 10:12:36 +00004089 class D(C):
4090 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004091
Georg Brandl48545522008-02-02 10:12:36 +00004092 class E(D):
4093 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004094
Georg Brandl48545522008-02-02 10:12:36 +00004095 class F(D):
4096 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004097
Georg Brandl48545522008-02-02 10:12:36 +00004098 class G(D):
4099 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004100
Georg Brandl48545522008-02-02 10:12:36 +00004101 # Immediate subclasses have their mro's adjusted in alphabetical
4102 # order, so E's will get adjusted before adjusting F's fails. We
4103 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004104
Georg Brandl48545522008-02-02 10:12:36 +00004105 E_mro_before = E.__mro__
4106 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004107
Armin Rigofd163f92005-12-29 15:59:19 +00004108 try:
Georg Brandl48545522008-02-02 10:12:36 +00004109 D.__bases__ = (C2,)
4110 except RuntimeError:
4111 self.assertEqual(E.__mro__, E_mro_before)
4112 self.assertEqual(D.__mro__, D_mro_before)
4113 else:
4114 self.fail("exception not propagated")
4115
4116 def test_mutable_bases_catch_mro_conflict(self):
4117 # Testing mutable bases catch mro conflict...
4118 class A(object):
4119 pass
4120
4121 class B(object):
4122 pass
4123
4124 class C(A, B):
4125 pass
4126
4127 class D(A, B):
4128 pass
4129
4130 class E(C, D):
4131 pass
4132
4133 try:
4134 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004135 except TypeError:
4136 pass
4137 else:
Georg Brandl48545522008-02-02 10:12:36 +00004138 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004139
Georg Brandl48545522008-02-02 10:12:36 +00004140 def test_mutable_names(self):
4141 # Testing mutable names...
4142 class C(object):
4143 pass
4144
4145 # C.__module__ could be 'test_descr' or '__main__'
4146 mod = C.__module__
4147
4148 C.__name__ = 'D'
4149 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4150
4151 C.__name__ = 'D.E'
4152 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4153
Mark Dickinsonf794b142013-04-13 15:19:05 +01004154 def test_evil_type_name(self):
4155 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4156 # execution while the type structure was not in a sane state, and a
4157 # possible segmentation fault as a result. See bug #16447.
4158 class Nasty(str):
4159 def __del__(self):
4160 C.__name__ = "other"
4161
4162 class C(object):
4163 pass
4164
4165 C.__name__ = Nasty("abc")
4166 C.__name__ = "normal"
4167
Georg Brandl48545522008-02-02 10:12:36 +00004168 def test_subclass_right_op(self):
4169 # Testing correct dispatch of subclass overloading __r<op>__...
4170
4171 # This code tests various cases where right-dispatch of a subclass
4172 # should be preferred over left-dispatch of a base class.
4173
4174 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4175
4176 class B(int):
4177 def __floordiv__(self, other):
4178 return "B.__floordiv__"
4179 def __rfloordiv__(self, other):
4180 return "B.__rfloordiv__"
4181
4182 self.assertEqual(B(1) // 1, "B.__floordiv__")
4183 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4184
4185 # Case 2: subclass of object; this is just the baseline for case 3
4186
4187 class C(object):
4188 def __floordiv__(self, other):
4189 return "C.__floordiv__"
4190 def __rfloordiv__(self, other):
4191 return "C.__rfloordiv__"
4192
4193 self.assertEqual(C() // 1, "C.__floordiv__")
4194 self.assertEqual(1 // C(), "C.__rfloordiv__")
4195
4196 # Case 3: subclass of new-style class; here it gets interesting
4197
4198 class D(C):
4199 def __floordiv__(self, other):
4200 return "D.__floordiv__"
4201 def __rfloordiv__(self, other):
4202 return "D.__rfloordiv__"
4203
4204 self.assertEqual(D() // C(), "D.__floordiv__")
4205 self.assertEqual(C() // D(), "D.__rfloordiv__")
4206
4207 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4208
4209 class E(C):
4210 pass
4211
4212 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4213
4214 self.assertEqual(E() // 1, "C.__floordiv__")
4215 self.assertEqual(1 // E(), "C.__rfloordiv__")
4216 self.assertEqual(E() // C(), "C.__floordiv__")
4217 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4218
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004219 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004220 def test_meth_class_get(self):
4221 # Testing __get__ method of METH_CLASS C methods...
4222 # Full coverage of descrobject.c::classmethod_get()
4223
4224 # Baseline
4225 arg = [1, 2, 3]
4226 res = {1: None, 2: None, 3: None}
4227 self.assertEqual(dict.fromkeys(arg), res)
4228 self.assertEqual({}.fromkeys(arg), res)
4229
4230 # Now get the descriptor
4231 descr = dict.__dict__["fromkeys"]
4232
4233 # More baseline using the descriptor directly
4234 self.assertEqual(descr.__get__(None, dict)(arg), res)
4235 self.assertEqual(descr.__get__({})(arg), res)
4236
4237 # Now check various error cases
4238 try:
4239 descr.__get__(None, None)
4240 except TypeError:
4241 pass
4242 else:
4243 self.fail("shouldn't have allowed descr.__get__(None, None)")
4244 try:
4245 descr.__get__(42)
4246 except TypeError:
4247 pass
4248 else:
4249 self.fail("shouldn't have allowed descr.__get__(42)")
4250 try:
4251 descr.__get__(None, 42)
4252 except TypeError:
4253 pass
4254 else:
4255 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4256 try:
4257 descr.__get__(None, int)
4258 except TypeError:
4259 pass
4260 else:
4261 self.fail("shouldn't have allowed descr.__get__(None, int)")
4262
4263 def test_isinst_isclass(self):
4264 # Testing proxy isinstance() and isclass()...
4265 class Proxy(object):
4266 def __init__(self, obj):
4267 self.__obj = obj
4268 def __getattribute__(self, name):
4269 if name.startswith("_Proxy__"):
4270 return object.__getattribute__(self, name)
4271 else:
4272 return getattr(self.__obj, name)
4273 # Test with a classic class
4274 class C:
4275 pass
4276 a = C()
4277 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004278 self.assertIsInstance(a, C) # Baseline
4279 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004280 # Test with a classic subclass
4281 class D(C):
4282 pass
4283 a = D()
4284 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004285 self.assertIsInstance(a, C) # Baseline
4286 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004287 # Test with a new-style class
4288 class C(object):
4289 pass
4290 a = C()
4291 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004292 self.assertIsInstance(a, C) # Baseline
4293 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004294 # Test with a new-style subclass
4295 class D(C):
4296 pass
4297 a = D()
4298 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004299 self.assertIsInstance(a, C) # Baseline
4300 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004301
4302 def test_proxy_super(self):
4303 # Testing super() for a proxy object...
4304 class Proxy(object):
4305 def __init__(self, obj):
4306 self.__obj = obj
4307 def __getattribute__(self, name):
4308 if name.startswith("_Proxy__"):
4309 return object.__getattribute__(self, name)
4310 else:
4311 return getattr(self.__obj, name)
4312
4313 class B(object):
4314 def f(self):
4315 return "B.f"
4316
4317 class C(B):
4318 def f(self):
4319 return super(C, self).f() + "->C.f"
4320
4321 obj = C()
4322 p = Proxy(obj)
4323 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4324
4325 def test_carloverre(self):
4326 # Testing prohibition of Carlo Verre's hack...
4327 try:
4328 object.__setattr__(str, "foo", 42)
4329 except TypeError:
4330 pass
4331 else:
Ezio Melottic2077b02011-03-16 12:34:31 +02004332 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl48545522008-02-02 10:12:36 +00004333 try:
4334 object.__delattr__(str, "lower")
4335 except TypeError:
4336 pass
4337 else:
4338 self.fail("Carlo Verre __delattr__ succeeded!")
4339
4340 def test_weakref_segfault(self):
4341 # Testing weakref segfault...
4342 # SF 742911
4343 import weakref
4344
4345 class Provoker:
4346 def __init__(self, referrent):
4347 self.ref = weakref.ref(referrent)
4348
4349 def __del__(self):
4350 x = self.ref()
4351
4352 class Oops(object):
4353 pass
4354
4355 o = Oops()
4356 o.whatever = Provoker(o)
4357 del o
4358
4359 def test_wrapper_segfault(self):
4360 # SF 927248: deeply nested wrappers could cause stack overflow
4361 f = lambda:None
4362 for i in xrange(1000000):
4363 f = f.__call__
4364 f = None
4365
4366 def test_file_fault(self):
4367 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004368 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004369 class StdoutGuard:
4370 def __getattr__(self, attr):
4371 sys.stdout = sys.__stdout__
4372 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4373 sys.stdout = StdoutGuard()
4374 try:
4375 print "Oops!"
4376 except RuntimeError:
4377 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004378 finally:
4379 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004380
4381 def test_vicious_descriptor_nonsense(self):
4382 # Testing vicious_descriptor_nonsense...
4383
4384 # A potential segfault spotted by Thomas Wouters in mail to
4385 # python-dev 2003-04-17, turned into an example & fixed by Michael
4386 # Hudson just less than four months later...
4387
4388 class Evil(object):
4389 def __hash__(self):
4390 return hash('attr')
4391 def __eq__(self, other):
4392 del C.attr
4393 return 0
4394
4395 class Descr(object):
4396 def __get__(self, ob, type=None):
4397 return 1
4398
4399 class C(object):
4400 attr = Descr()
4401
4402 c = C()
4403 c.__dict__[Evil()] = 0
4404
4405 self.assertEqual(c.attr, 1)
4406 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004407 test_support.gc_collect()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004408 self.assertNotHasAttr(c, 'attr')
Georg Brandl48545522008-02-02 10:12:36 +00004409
4410 def test_init(self):
4411 # SF 1155938
4412 class Foo(object):
4413 def __init__(self):
4414 return 10
4415 try:
4416 Foo()
4417 except TypeError:
4418 pass
4419 else:
4420 self.fail("did not test __init__() for None return")
4421
4422 def test_method_wrapper(self):
4423 # Testing method-wrapper objects...
4424 # <type 'method-wrapper'> did not support any reflection before 2.5
4425
4426 l = []
4427 self.assertEqual(l.__add__, l.__add__)
4428 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004429 self.assertNotEqual(l.__add__, [5].__add__)
4430 self.assertNotEqual(l.__add__, l.__mul__)
4431 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004432 if hasattr(l.__add__, '__self__'):
4433 # CPython
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004434 self.assertIs(l.__add__.__self__, l)
4435 self.assertIs(l.__add__.__objclass__, list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004436 else:
4437 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004438 self.assertIs(l.__add__.im_self, l)
4439 self.assertIs(l.__add__.im_class, list)
Georg Brandl48545522008-02-02 10:12:36 +00004440 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4441 try:
4442 hash(l.__add__)
4443 except TypeError:
4444 pass
4445 else:
4446 self.fail("no TypeError from hash([].__add__)")
4447
4448 t = ()
4449 t += (7,)
4450 self.assertEqual(t.__add__, (7,).__add__)
4451 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4452
4453 def test_not_implemented(self):
4454 # Testing NotImplemented...
4455 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004456 import operator
4457
4458 def specialmethod(self, other):
4459 return NotImplemented
4460
4461 def check(expr, x, y):
4462 try:
4463 exec expr in {'x': x, 'y': y, 'operator': operator}
4464 except TypeError:
4465 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004466 else:
Georg Brandl48545522008-02-02 10:12:36 +00004467 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004468
Georg Brandl48545522008-02-02 10:12:36 +00004469 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4470 # TypeErrors
4471 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4472 # ValueErrors instead of TypeErrors
4473 for metaclass in [type, types.ClassType]:
4474 for name, expr, iexpr in [
4475 ('__add__', 'x + y', 'x += y'),
4476 ('__sub__', 'x - y', 'x -= y'),
4477 ('__mul__', 'x * y', 'x *= y'),
4478 ('__truediv__', 'operator.truediv(x, y)', None),
4479 ('__floordiv__', 'operator.floordiv(x, y)', None),
4480 ('__div__', 'x / y', 'x /= y'),
4481 ('__mod__', 'x % y', 'x %= y'),
4482 ('__divmod__', 'divmod(x, y)', None),
4483 ('__pow__', 'x ** y', 'x **= y'),
4484 ('__lshift__', 'x << y', 'x <<= y'),
4485 ('__rshift__', 'x >> y', 'x >>= y'),
4486 ('__and__', 'x & y', 'x &= y'),
4487 ('__or__', 'x | y', 'x |= y'),
4488 ('__xor__', 'x ^ y', 'x ^= y'),
4489 ('__coerce__', 'coerce(x, y)', None)]:
4490 if name == '__coerce__':
4491 rname = name
4492 else:
4493 rname = '__r' + name[2:]
4494 A = metaclass('A', (), {name: specialmethod})
4495 B = metaclass('B', (), {rname: specialmethod})
4496 a = A()
4497 b = B()
4498 check(expr, a, a)
4499 check(expr, a, b)
4500 check(expr, b, a)
4501 check(expr, b, b)
4502 check(expr, a, N1)
4503 check(expr, a, N2)
4504 check(expr, N1, b)
4505 check(expr, N2, b)
4506 if iexpr:
4507 check(iexpr, a, a)
4508 check(iexpr, a, b)
4509 check(iexpr, b, a)
4510 check(iexpr, b, b)
4511 check(iexpr, a, N1)
4512 check(iexpr, a, N2)
4513 iname = '__i' + name[2:]
4514 C = metaclass('C', (), {iname: specialmethod})
4515 c = C()
4516 check(iexpr, c, a)
4517 check(iexpr, c, b)
4518 check(iexpr, c, N1)
4519 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004520
Georg Brandl48545522008-02-02 10:12:36 +00004521 def test_assign_slice(self):
4522 # ceval.c's assign_slice used to check for
4523 # tp->tp_as_sequence->sq_slice instead of
4524 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004525
Georg Brandl48545522008-02-02 10:12:36 +00004526 class C(object):
4527 def __setslice__(self, start, stop, value):
4528 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004529
Georg Brandl48545522008-02-02 10:12:36 +00004530 c = C()
4531 c[1:2] = 3
4532 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004533
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004534 def test_set_and_no_get(self):
4535 # See
4536 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4537 class Descr(object):
4538
4539 def __init__(self, name):
4540 self.name = name
4541
4542 def __set__(self, obj, value):
4543 obj.__dict__[self.name] = value
4544 descr = Descr("a")
4545
4546 class X(object):
4547 a = descr
4548
4549 x = X()
4550 self.assertIs(x.a, descr)
4551 x.a = 42
4552 self.assertEqual(x.a, 42)
4553
Benjamin Peterson42d59472010-02-06 20:14:10 +00004554 # Also check type_getattro for correctness.
4555 class Meta(type):
4556 pass
4557 class X(object):
4558 __metaclass__ = Meta
4559 X.a = 42
4560 Meta.a = Descr("a")
4561 self.assertEqual(X.a, 42)
4562
Benjamin Peterson273c2332008-11-17 22:39:09 +00004563 def test_getattr_hooks(self):
4564 # issue 4230
4565
4566 class Descriptor(object):
4567 counter = 0
4568 def __get__(self, obj, objtype=None):
4569 def getter(name):
4570 self.counter += 1
4571 raise AttributeError(name)
4572 return getter
4573
4574 descr = Descriptor()
4575 class A(object):
4576 __getattribute__ = descr
4577 class B(object):
4578 __getattr__ = descr
4579 class C(object):
4580 __getattribute__ = descr
4581 __getattr__ = descr
4582
4583 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004584 self.assertEqual(descr.counter, 1)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004585 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004586 self.assertEqual(descr.counter, 2)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004587 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004588 self.assertEqual(descr.counter, 4)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004589
Benjamin Peterson273c2332008-11-17 22:39:09 +00004590 class EvilGetattribute(object):
4591 # This used to segfault
4592 def __getattr__(self, name):
4593 raise AttributeError(name)
4594 def __getattribute__(self, name):
4595 del EvilGetattribute.__getattr__
4596 for i in range(5):
4597 gc.collect()
4598 raise AttributeError(name)
4599
4600 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4601
Benjamin Peterson6e7832b2012-03-16 09:32:59 -05004602 def test_type___getattribute__(self):
4603 self.assertRaises(TypeError, type.__getattribute__, list, type)
4604
Benjamin Peterson9b911ca2011-01-12 15:49:47 +00004605 def test_abstractmethods(self):
4606 # type pretends not to have __abstractmethods__.
4607 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4608 class meta(type):
4609 pass
4610 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4611 class X(object):
4612 pass
4613 with self.assertRaises(AttributeError):
4614 del X.__abstractmethods__
4615
Victor Stinnere363ec12011-05-01 23:43:37 +02004616 def test_proxy_call(self):
4617 class FakeStr(object):
4618 __class__ = str
4619
4620 fake_str = FakeStr()
4621 # isinstance() reads __class__ on new style classes
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004622 self.assertIsInstance(fake_str, str)
Victor Stinnere363ec12011-05-01 23:43:37 +02004623
4624 # call a method descriptor
4625 with self.assertRaises(TypeError):
4626 str.split(fake_str)
4627
4628 # call a slot wrapper descriptor
4629 with self.assertRaises(TypeError):
4630 str.__add__(fake_str, "abc")
4631
Antoine Pitrou304f0f92011-07-15 21:22:50 +02004632 def test_repr_as_str(self):
4633 # Issue #11603: crash or infinite loop when rebinding __str__ as
4634 # __repr__.
4635 class Foo(object):
4636 pass
4637 Foo.__repr__ = Foo.__str__
4638 foo = Foo()
Benjamin Petersond157a4c2012-04-24 11:06:25 -04004639 self.assertRaises(RuntimeError, str, foo)
4640 self.assertRaises(RuntimeError, repr, foo)
4641
4642 def test_mixing_slot_wrappers(self):
4643 class X(dict):
4644 __setattr__ = dict.__setitem__
4645 x = X()
4646 x.y = 42
4647 self.assertEqual(x["y"], 42)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004648
Benjamin Petersona8d45852012-03-07 18:41:11 -06004649 def test_cycle_through_dict(self):
4650 # See bug #1469629
4651 class X(dict):
4652 def __init__(self):
4653 dict.__init__(self)
4654 self.__dict__ = self
4655 x = X()
4656 x.attr = 42
4657 wr = weakref.ref(x)
4658 del x
4659 test_support.gc_collect()
4660 self.assertIsNone(wr())
4661 for o in gc.get_objects():
4662 self.assertIsNot(type(o), X)
4663
Georg Brandl48545522008-02-02 10:12:36 +00004664class DictProxyTests(unittest.TestCase):
4665 def setUp(self):
4666 class C(object):
4667 def meth(self):
4668 pass
4669 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004670
Raymond Hettingerbf7a2662011-06-30 00:44:36 +01004671 def test_repr(self):
4672 self.assertIn('dict_proxy({', repr(vars(self.C)))
4673 self.assertIn("'meth':", repr(vars(self.C)))
4674
Georg Brandl48545522008-02-02 10:12:36 +00004675 def test_iter_keys(self):
4676 # Testing dict-proxy iterkeys...
4677 keys = [ key for key in self.C.__dict__.iterkeys() ]
4678 keys.sort()
Ezio Melotti2623a372010-11-21 13:34:58 +00004679 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl48545522008-02-02 10:12:36 +00004680 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004681
Georg Brandl48545522008-02-02 10:12:36 +00004682 def test_iter_values(self):
4683 # Testing dict-proxy itervalues...
4684 values = [ values for values in self.C.__dict__.itervalues() ]
4685 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004686
Georg Brandl48545522008-02-02 10:12:36 +00004687 def test_iter_items(self):
4688 # Testing dict-proxy iteritems...
4689 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4690 keys.sort()
4691 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4692 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004693
Georg Brandl48545522008-02-02 10:12:36 +00004694 def test_dict_type_with_metaclass(self):
4695 # Testing type of __dict__ when __metaclass__ set...
4696 class B(object):
4697 pass
4698 class M(type):
4699 pass
4700 class C:
4701 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4702 __metaclass__ = M
4703 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004704
Guido van Rossum9acc3872008-01-23 23:23:43 +00004705
Georg Brandl48545522008-02-02 10:12:36 +00004706class PTypesLongInitTest(unittest.TestCase):
4707 # This is in its own TestCase so that it can be run before any other tests.
4708 def test_pytype_long_ready(self):
4709 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004710
Georg Brandl48545522008-02-02 10:12:36 +00004711 # This dumps core when SF bug 551412 isn't fixed --
4712 # but only when test_descr.py is run separately.
4713 # (That can't be helped -- as soon as PyType_Ready()
4714 # is called for PyLong_Type, the bug is gone.)
4715 class UserLong(object):
4716 def __pow__(self, *args):
4717 pass
4718 try:
4719 pow(0L, UserLong(), 0L)
4720 except:
4721 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004722
Georg Brandl48545522008-02-02 10:12:36 +00004723 # Another segfault only when run early
4724 # (before PyType_Ready(tuple) is called)
4725 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004726
4727
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004728def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004729 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4730 DeprecationWarning)]
4731 if sys.py3kwarning:
4732 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004733 ("classic (int|long) division", DeprecationWarning),
4734 ("coerce.. not supported", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004735 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4736 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004737 # Run all local test cases, with PTypesLongInitTest first.
4738 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4739 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004741if __name__ == "__main__":
4742 test_main()