blob: 15a304993004f403dd81ca9b2380d7325aa39a26 [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
Zachary Ware1f702212013-12-10 14:09:20 -06001062 def test_unicode_slots(self):
Georg Brandl48545522008-02-02 10:12:36 +00001063 # Test unicode slot names
1064 try:
1065 unicode
1066 except NameError:
Zachary Ware1f702212013-12-10 14:09:20 -06001067 self.skipTest('no unicode support')
Georg Brandl48545522008-02-02 10:12:36 +00001068 else:
1069 # Test a single unicode string is not expanded as a sequence.
1070 class C(object):
1071 __slots__ = unicode("abc")
1072 c = C()
1073 c.abc = 5
1074 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001075
Georg Brandl48545522008-02-02 10:12:36 +00001076 # _unicode_to_string used to modify slots in certain circumstances
1077 slots = (unicode("foo"), unicode("bar"))
1078 class C(object):
1079 __slots__ = slots
1080 x = C()
1081 x.foo = 5
1082 self.assertEqual(x.foo, 5)
1083 self.assertEqual(type(slots[0]), unicode)
1084 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001085 try:
Georg Brandl48545522008-02-02 10:12:36 +00001086 class C(object):
1087 __slots__ = [unichr(128)]
1088 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001089 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001090 else:
Georg Brandl48545522008-02-02 10:12:36 +00001091 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001092
Georg Brandl48545522008-02-02 10:12:36 +00001093 # Test leaks
1094 class Counted(object):
1095 counter = 0 # counts the number of instances alive
1096 def __init__(self):
1097 Counted.counter += 1
1098 def __del__(self):
1099 Counted.counter -= 1
1100 class C(object):
1101 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001102 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001103 x.a = Counted()
1104 x.b = Counted()
1105 x.c = Counted()
1106 self.assertEqual(Counted.counter, 3)
1107 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001108 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001109 self.assertEqual(Counted.counter, 0)
1110 class D(C):
1111 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001112 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001113 x.a = Counted()
1114 x.z = Counted()
1115 self.assertEqual(Counted.counter, 2)
1116 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001117 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001118 self.assertEqual(Counted.counter, 0)
1119 class E(D):
1120 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001121 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001122 x.a = Counted()
1123 x.z = Counted()
1124 x.e = Counted()
1125 self.assertEqual(Counted.counter, 3)
1126 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001127 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001128 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001129
Georg Brandl48545522008-02-02 10:12:36 +00001130 # Test cyclical leaks [SF bug 519621]
1131 class F(object):
1132 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001133 s = F()
1134 s.a = [Counted(), s]
1135 self.assertEqual(Counted.counter, 1)
1136 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001137 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001138 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001139
Georg Brandl48545522008-02-02 10:12:36 +00001140 # Test lookup leaks [SF bug 572567]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001141 if hasattr(gc, 'get_objects'):
1142 class G(object):
1143 def __cmp__(self, other):
1144 return 0
1145 __hash__ = None # Silence Py3k warning
1146 g = G()
1147 orig_objects = len(gc.get_objects())
1148 for i in xrange(10):
1149 g==g
1150 new_objects = len(gc.get_objects())
1151 self.assertEqual(orig_objects, new_objects)
1152
Georg Brandl48545522008-02-02 10:12:36 +00001153 class H(object):
1154 __slots__ = ['a', 'b']
1155 def __init__(self):
1156 self.a = 1
1157 self.b = 2
1158 def __del__(self_):
1159 self.assertEqual(self_.a, 1)
1160 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001161 with test_support.captured_output('stderr') as s:
1162 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001163 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001164 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001165
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001166 class X(object):
1167 __slots__ = "a"
1168 with self.assertRaises(AttributeError):
1169 del X().a
1170
Georg Brandl48545522008-02-02 10:12:36 +00001171 def test_slots_special(self):
1172 # Testing __dict__ and __weakref__ in __slots__...
1173 class D(object):
1174 __slots__ = ["__dict__"]
1175 a = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001176 self.assertHasAttr(a, "__dict__")
1177 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001178 a.foo = 42
1179 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001180
Georg Brandl48545522008-02-02 10:12:36 +00001181 class W(object):
1182 __slots__ = ["__weakref__"]
1183 a = W()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001184 self.assertHasAttr(a, "__weakref__")
1185 self.assertNotHasAttr(a, "__dict__")
Georg Brandl48545522008-02-02 10:12:36 +00001186 try:
1187 a.foo = 42
1188 except AttributeError:
1189 pass
1190 else:
1191 self.fail("shouldn't be allowed to set a.foo")
1192
1193 class C1(W, D):
1194 __slots__ = []
1195 a = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001196 self.assertHasAttr(a, "__dict__")
1197 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001198 a.foo = 42
1199 self.assertEqual(a.__dict__, {"foo": 42})
1200
1201 class C2(D, W):
1202 __slots__ = []
1203 a = C2()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001204 self.assertHasAttr(a, "__dict__")
1205 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001206 a.foo = 42
1207 self.assertEqual(a.__dict__, {"foo": 42})
1208
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001209 def test_slots_descriptor(self):
1210 # Issue2115: slot descriptors did not correctly check
1211 # the type of the given object
1212 import abc
1213 class MyABC:
1214 __metaclass__ = abc.ABCMeta
1215 __slots__ = "a"
1216
1217 class Unrelated(object):
1218 pass
1219 MyABC.register(Unrelated)
1220
1221 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001222 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001223
1224 # This used to crash
1225 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1226
Benjamin Peterson4895af42009-12-13 16:36:53 +00001227 def test_metaclass_cmp(self):
1228 # See bug 7491.
1229 class M(type):
1230 def __cmp__(self, other):
1231 return -1
1232 class X(object):
1233 __metaclass__ = M
1234 self.assertTrue(X < M)
1235
Georg Brandl48545522008-02-02 10:12:36 +00001236 def test_dynamics(self):
1237 # Testing class attribute propagation...
1238 class D(object):
1239 pass
1240 class E(D):
1241 pass
1242 class F(D):
1243 pass
1244 D.foo = 1
1245 self.assertEqual(D.foo, 1)
1246 # Test that dynamic attributes are inherited
1247 self.assertEqual(E.foo, 1)
1248 self.assertEqual(F.foo, 1)
1249 # Test dynamic instances
1250 class C(object):
1251 pass
1252 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001253 self.assertNotHasAttr(a, "foobar")
Georg Brandl48545522008-02-02 10:12:36 +00001254 C.foobar = 2
1255 self.assertEqual(a.foobar, 2)
1256 C.method = lambda self: 42
1257 self.assertEqual(a.method(), 42)
1258 C.__repr__ = lambda self: "C()"
1259 self.assertEqual(repr(a), "C()")
1260 C.__int__ = lambda self: 100
1261 self.assertEqual(int(a), 100)
1262 self.assertEqual(a.foobar, 2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001263 self.assertNotHasAttr(a, "spam")
Georg Brandl48545522008-02-02 10:12:36 +00001264 def mygetattr(self, name):
1265 if name == "spam":
1266 return "spam"
1267 raise AttributeError
1268 C.__getattr__ = mygetattr
1269 self.assertEqual(a.spam, "spam")
1270 a.new = 12
1271 self.assertEqual(a.new, 12)
1272 def mysetattr(self, name, value):
1273 if name == "spam":
1274 raise AttributeError
1275 return object.__setattr__(self, name, value)
1276 C.__setattr__ = mysetattr
1277 try:
1278 a.spam = "not spam"
1279 except AttributeError:
1280 pass
1281 else:
1282 self.fail("expected AttributeError")
1283 self.assertEqual(a.spam, "spam")
1284 class D(C):
1285 pass
1286 d = D()
1287 d.foo = 1
1288 self.assertEqual(d.foo, 1)
1289
1290 # Test handling of int*seq and seq*int
1291 class I(int):
1292 pass
1293 self.assertEqual("a"*I(2), "aa")
1294 self.assertEqual(I(2)*"a", "aa")
1295 self.assertEqual(2*I(3), 6)
1296 self.assertEqual(I(3)*2, 6)
1297 self.assertEqual(I(3)*I(2), 6)
1298
1299 # Test handling of long*seq and seq*long
1300 class L(long):
1301 pass
1302 self.assertEqual("a"*L(2L), "aa")
1303 self.assertEqual(L(2L)*"a", "aa")
1304 self.assertEqual(2*L(3), 6)
1305 self.assertEqual(L(3)*2, 6)
1306 self.assertEqual(L(3)*L(2), 6)
1307
1308 # Test comparison of classes with dynamic metaclasses
1309 class dynamicmetaclass(type):
1310 pass
1311 class someclass:
1312 __metaclass__ = dynamicmetaclass
1313 self.assertNotEqual(someclass, object)
1314
1315 def test_errors(self):
1316 # Testing errors...
1317 try:
1318 class C(list, dict):
1319 pass
1320 except TypeError:
1321 pass
1322 else:
1323 self.fail("inheritance from both list and dict should be illegal")
1324
1325 try:
1326 class C(object, None):
1327 pass
1328 except TypeError:
1329 pass
1330 else:
1331 self.fail("inheritance from non-type should be illegal")
1332 class Classic:
1333 pass
1334
1335 try:
1336 class C(type(len)):
1337 pass
1338 except TypeError:
1339 pass
1340 else:
1341 self.fail("inheritance from CFunction should be illegal")
1342
1343 try:
1344 class C(object):
1345 __slots__ = 1
1346 except TypeError:
1347 pass
1348 else:
1349 self.fail("__slots__ = 1 should be illegal")
1350
1351 try:
1352 class C(object):
1353 __slots__ = [1]
1354 except TypeError:
1355 pass
1356 else:
1357 self.fail("__slots__ = [1] should be illegal")
1358
1359 class M1(type):
1360 pass
1361 class M2(type):
1362 pass
1363 class A1(object):
1364 __metaclass__ = M1
1365 class A2(object):
1366 __metaclass__ = M2
1367 try:
1368 class B(A1, A2):
1369 pass
1370 except TypeError:
1371 pass
1372 else:
1373 self.fail("finding the most derived metaclass should have failed")
1374
1375 def test_classmethods(self):
1376 # Testing class methods...
1377 class C(object):
1378 def foo(*a): return a
1379 goo = classmethod(foo)
1380 c = C()
1381 self.assertEqual(C.goo(1), (C, 1))
1382 self.assertEqual(c.goo(1), (C, 1))
1383 self.assertEqual(c.foo(1), (c, 1))
1384 class D(C):
1385 pass
1386 d = D()
1387 self.assertEqual(D.goo(1), (D, 1))
1388 self.assertEqual(d.goo(1), (D, 1))
1389 self.assertEqual(d.foo(1), (d, 1))
1390 self.assertEqual(D.foo(d, 1), (d, 1))
1391 # Test for a specific crash (SF bug 528132)
1392 def f(cls, arg): return (cls, arg)
1393 ff = classmethod(f)
1394 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1395 self.assertEqual(ff.__get__(0)(42), (int, 42))
1396
1397 # Test super() with classmethods (SF bug 535444)
1398 self.assertEqual(C.goo.im_self, C)
1399 self.assertEqual(D.goo.im_self, D)
1400 self.assertEqual(super(D,D).goo.im_self, D)
1401 self.assertEqual(super(D,d).goo.im_self, D)
1402 self.assertEqual(super(D,D).goo(), (D,))
1403 self.assertEqual(super(D,d).goo(), (D,))
1404
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001405 # Verify that a non-callable will raise
1406 meth = classmethod(1).__get__(1)
1407 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001408
1409 # Verify that classmethod() doesn't allow keyword args
1410 try:
1411 classmethod(f, kw=1)
1412 except TypeError:
1413 pass
1414 else:
1415 self.fail("classmethod shouldn't accept keyword args")
1416
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001417 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001418 def test_classmethods_in_c(self):
1419 # Testing C-based class methods...
1420 import xxsubtype as spam
1421 a = (1, 2, 3)
1422 d = {'abc': 123}
1423 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1424 self.assertEqual(x, spam.spamlist)
1425 self.assertEqual(a, a1)
1426 self.assertEqual(d, d1)
1427 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1428 self.assertEqual(x, spam.spamlist)
1429 self.assertEqual(a, a1)
1430 self.assertEqual(d, d1)
Benjamin Peterson042c47b2012-05-01 09:51:09 -04001431 spam_cm = spam.spamlist.__dict__['classmeth']
1432 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1433 self.assertEqual(x2, spam.spamlist)
1434 self.assertEqual(a2, a1)
1435 self.assertEqual(d2, d1)
1436 class SubSpam(spam.spamlist): pass
1437 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1438 self.assertEqual(x2, SubSpam)
1439 self.assertEqual(a2, a1)
1440 self.assertEqual(d2, d1)
1441 with self.assertRaises(TypeError):
1442 spam_cm()
1443 with self.assertRaises(TypeError):
1444 spam_cm(spam.spamlist())
1445 with self.assertRaises(TypeError):
1446 spam_cm(list)
Georg Brandl48545522008-02-02 10:12:36 +00001447
1448 def test_staticmethods(self):
1449 # Testing static methods...
1450 class C(object):
1451 def foo(*a): return a
1452 goo = staticmethod(foo)
1453 c = C()
1454 self.assertEqual(C.goo(1), (1,))
1455 self.assertEqual(c.goo(1), (1,))
1456 self.assertEqual(c.foo(1), (c, 1,))
1457 class D(C):
1458 pass
1459 d = D()
1460 self.assertEqual(D.goo(1), (1,))
1461 self.assertEqual(d.goo(1), (1,))
1462 self.assertEqual(d.foo(1), (d, 1))
1463 self.assertEqual(D.foo(d, 1), (d, 1))
1464
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001465 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001466 def test_staticmethods_in_c(self):
1467 # Testing C-based static methods...
1468 import xxsubtype as spam
1469 a = (1, 2, 3)
1470 d = {"abc": 123}
1471 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1472 self.assertEqual(x, None)
1473 self.assertEqual(a, a1)
1474 self.assertEqual(d, d1)
1475 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1476 self.assertEqual(x, None)
1477 self.assertEqual(a, a1)
1478 self.assertEqual(d, d1)
1479
1480 def test_classic(self):
1481 # Testing classic classes...
1482 class C:
1483 def foo(*a): return a
1484 goo = classmethod(foo)
1485 c = C()
1486 self.assertEqual(C.goo(1), (C, 1))
1487 self.assertEqual(c.goo(1), (C, 1))
1488 self.assertEqual(c.foo(1), (c, 1))
1489 class D(C):
1490 pass
1491 d = D()
1492 self.assertEqual(D.goo(1), (D, 1))
1493 self.assertEqual(d.goo(1), (D, 1))
1494 self.assertEqual(d.foo(1), (d, 1))
1495 self.assertEqual(D.foo(d, 1), (d, 1))
1496 class E: # *not* subclassing from C
1497 foo = C.foo
1498 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001499 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001500
1501 def test_compattr(self):
1502 # Testing computed attributes...
1503 class C(object):
1504 class computed_attribute(object):
1505 def __init__(self, get, set=None, delete=None):
1506 self.__get = get
1507 self.__set = set
1508 self.__delete = delete
1509 def __get__(self, obj, type=None):
1510 return self.__get(obj)
1511 def __set__(self, obj, value):
1512 return self.__set(obj, value)
1513 def __delete__(self, obj):
1514 return self.__delete(obj)
1515 def __init__(self):
1516 self.__x = 0
1517 def __get_x(self):
1518 x = self.__x
1519 self.__x = x+1
1520 return x
1521 def __set_x(self, x):
1522 self.__x = x
1523 def __delete_x(self):
1524 del self.__x
1525 x = computed_attribute(__get_x, __set_x, __delete_x)
1526 a = C()
1527 self.assertEqual(a.x, 0)
1528 self.assertEqual(a.x, 1)
1529 a.x = 10
1530 self.assertEqual(a.x, 10)
1531 self.assertEqual(a.x, 11)
1532 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001533 self.assertNotHasAttr(a, 'x')
Georg Brandl48545522008-02-02 10:12:36 +00001534
1535 def test_newslots(self):
1536 # Testing __new__ slot override...
1537 class C(list):
1538 def __new__(cls):
1539 self = list.__new__(cls)
1540 self.foo = 1
1541 return self
1542 def __init__(self):
1543 self.foo = self.foo + 2
1544 a = C()
1545 self.assertEqual(a.foo, 3)
1546 self.assertEqual(a.__class__, C)
1547 class D(C):
1548 pass
1549 b = D()
1550 self.assertEqual(b.foo, 3)
1551 self.assertEqual(b.__class__, D)
1552
1553 def test_altmro(self):
1554 # Testing mro() and overriding it...
1555 class A(object):
1556 def f(self): return "A"
1557 class B(A):
1558 pass
1559 class C(A):
1560 def f(self): return "C"
1561 class D(B, C):
1562 pass
1563 self.assertEqual(D.mro(), [D, B, C, A, object])
1564 self.assertEqual(D.__mro__, (D, B, C, A, object))
1565 self.assertEqual(D().f(), "C")
1566
1567 class PerverseMetaType(type):
1568 def mro(cls):
1569 L = type.mro(cls)
1570 L.reverse()
1571 return L
1572 class X(D,B,C,A):
1573 __metaclass__ = PerverseMetaType
1574 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1575 self.assertEqual(X().f(), "A")
1576
1577 try:
1578 class X(object):
1579 class __metaclass__(type):
1580 def mro(self):
1581 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001582 # In CPython, the class creation above already raises
1583 # TypeError, as a protection against the fact that
1584 # instances of X would segfault it. In other Python
1585 # implementations it would be ok to let the class X
1586 # be created, but instead get a clean TypeError on the
1587 # __setitem__ below.
1588 x = object.__new__(X)
1589 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001590 except TypeError:
1591 pass
1592 else:
1593 self.fail("devious mro() return not caught")
1594
1595 try:
1596 class X(object):
1597 class __metaclass__(type):
1598 def mro(self):
1599 return [1]
1600 except TypeError:
1601 pass
1602 else:
1603 self.fail("non-class mro() return not caught")
1604
1605 try:
1606 class X(object):
1607 class __metaclass__(type):
1608 def mro(self):
1609 return 1
1610 except TypeError:
1611 pass
1612 else:
1613 self.fail("non-sequence mro() return not caught")
1614
1615 def test_overloading(self):
1616 # Testing operator overloading...
1617
1618 class B(object):
1619 "Intermediate class because object doesn't have a __setattr__"
1620
1621 class C(B):
1622 def __getattr__(self, name):
1623 if name == "foo":
1624 return ("getattr", name)
1625 else:
1626 raise AttributeError
1627 def __setattr__(self, name, value):
1628 if name == "foo":
1629 self.setattr = (name, value)
1630 else:
1631 return B.__setattr__(self, name, value)
1632 def __delattr__(self, name):
1633 if name == "foo":
1634 self.delattr = name
1635 else:
1636 return B.__delattr__(self, name)
1637
1638 def __getitem__(self, key):
1639 return ("getitem", key)
1640 def __setitem__(self, key, value):
1641 self.setitem = (key, value)
1642 def __delitem__(self, key):
1643 self.delitem = key
1644
1645 def __getslice__(self, i, j):
1646 return ("getslice", i, j)
1647 def __setslice__(self, i, j, value):
1648 self.setslice = (i, j, value)
1649 def __delslice__(self, i, j):
1650 self.delslice = (i, j)
1651
1652 a = C()
1653 self.assertEqual(a.foo, ("getattr", "foo"))
1654 a.foo = 12
1655 self.assertEqual(a.setattr, ("foo", 12))
1656 del a.foo
1657 self.assertEqual(a.delattr, "foo")
1658
1659 self.assertEqual(a[12], ("getitem", 12))
1660 a[12] = 21
1661 self.assertEqual(a.setitem, (12, 21))
1662 del a[12]
1663 self.assertEqual(a.delitem, 12)
1664
1665 self.assertEqual(a[0:10], ("getslice", 0, 10))
1666 a[0:10] = "foo"
1667 self.assertEqual(a.setslice, (0, 10, "foo"))
1668 del a[0:10]
1669 self.assertEqual(a.delslice, (0, 10))
1670
1671 def test_methods(self):
1672 # Testing methods...
1673 class C(object):
1674 def __init__(self, x):
1675 self.x = x
1676 def foo(self):
1677 return self.x
1678 c1 = C(1)
1679 self.assertEqual(c1.foo(), 1)
1680 class D(C):
1681 boo = C.foo
1682 goo = c1.foo
1683 d2 = D(2)
1684 self.assertEqual(d2.foo(), 2)
1685 self.assertEqual(d2.boo(), 2)
1686 self.assertEqual(d2.goo(), 1)
1687 class E(object):
1688 foo = C.foo
1689 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001690 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001691
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001692 def test_special_method_lookup(self):
1693 # The lookup of special methods bypasses __getattr__ and
1694 # __getattribute__, but they still can be descriptors.
1695
1696 def run_context(manager):
1697 with manager:
1698 pass
1699 def iden(self):
1700 return self
1701 def hello(self):
1702 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001703 def empty_seq(self):
1704 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001705 def zero(self):
1706 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001707 def complex_num(self):
1708 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001709 def stop(self):
1710 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001711 def return_true(self, thing=None):
1712 return True
1713 def do_isinstance(obj):
1714 return isinstance(int, obj)
1715 def do_issubclass(obj):
1716 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001717 def swallow(*args):
1718 pass
1719 def do_dict_missing(checker):
1720 class DictSub(checker.__class__, dict):
1721 pass
1722 self.assertEqual(DictSub()["hi"], 4)
1723 def some_number(self_, key):
1724 self.assertEqual(key, "hi")
1725 return 4
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001726 def format_impl(self, spec):
1727 return "hello"
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001728
1729 # It would be nice to have every special method tested here, but I'm
1730 # only listing the ones I can remember outside of typeobject.c, since it
1731 # does it right.
1732 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001733 ("__unicode__", unicode, hello, set(), {}),
1734 ("__reversed__", reversed, empty_seq, set(), {}),
1735 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001736 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001737 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1738 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001739 ("__missing__", do_dict_missing, some_number,
1740 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001741 ("__subclasscheck__", do_issubclass, return_true,
1742 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001743 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1744 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001745 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001746 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001747 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001748 ]
1749
1750 class Checker(object):
1751 def __getattr__(self, attr, test=self):
1752 test.fail("__getattr__ called with {0}".format(attr))
1753 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001754 if attr not in ok:
1755 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001756 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001757 class SpecialDescr(object):
1758 def __init__(self, impl):
1759 self.impl = impl
1760 def __get__(self, obj, owner):
1761 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001762 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001763 class MyException(Exception):
1764 pass
1765 class ErrDescr(object):
1766 def __get__(self, obj, owner):
1767 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001768
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001769 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001770 class X(Checker):
1771 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001772 for attr, obj in env.iteritems():
1773 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001774 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001775 runner(X())
1776
1777 record = []
1778 class X(Checker):
1779 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001780 for attr, obj in env.iteritems():
1781 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001782 setattr(X, name, SpecialDescr(meth_impl))
1783 runner(X())
1784 self.assertEqual(record, [1], name)
1785
Benjamin Peterson87e50062009-05-25 02:40:21 +00001786 class X(Checker):
1787 pass
1788 for attr, obj in env.iteritems():
1789 setattr(X, attr, obj)
1790 setattr(X, name, ErrDescr())
1791 try:
1792 runner(X())
1793 except MyException:
1794 pass
1795 else:
1796 self.fail("{0!r} didn't raise".format(name))
1797
Georg Brandl48545522008-02-02 10:12:36 +00001798 def test_specials(self):
1799 # Testing special operators...
1800 # Test operators like __hash__ for which a built-in default exists
1801
1802 # Test the default behavior for static classes
1803 class C(object):
1804 def __getitem__(self, i):
1805 if 0 <= i < 10: return i
1806 raise IndexError
1807 c1 = C()
1808 c2 = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001809 self.assertFalse(not c1)
Georg Brandl48545522008-02-02 10:12:36 +00001810 self.assertNotEqual(id(c1), id(c2))
1811 hash(c1)
1812 hash(c2)
1813 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1814 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001815 self.assertTrue(c1 != c2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001816 self.assertFalse(c1 != c1)
1817 self.assertFalse(c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001818 # Note that the module name appears in str/repr, and that varies
1819 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001820 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001821 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001822 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001823 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001824 self.assertIn(i, c1)
1825 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001826 # Test the default behavior for dynamic classes
1827 class D(object):
1828 def __getitem__(self, i):
1829 if 0 <= i < 10: return i
1830 raise IndexError
1831 d1 = D()
1832 d2 = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001833 self.assertFalse(not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001834 self.assertNotEqual(id(d1), id(d2))
1835 hash(d1)
1836 hash(d2)
1837 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1838 self.assertEqual(d1, d1)
1839 self.assertNotEqual(d1, d2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001840 self.assertFalse(d1 != d1)
1841 self.assertFalse(d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001842 # Note that the module name appears in str/repr, and that varies
1843 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001844 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001845 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001846 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001847 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001848 self.assertIn(i, d1)
1849 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001850 # Test overridden behavior for static classes
1851 class Proxy(object):
1852 def __init__(self, x):
1853 self.x = x
1854 def __nonzero__(self):
1855 return not not self.x
1856 def __hash__(self):
1857 return hash(self.x)
1858 def __eq__(self, other):
1859 return self.x == other
1860 def __ne__(self, other):
1861 return self.x != other
1862 def __cmp__(self, other):
1863 return cmp(self.x, other.x)
1864 def __str__(self):
1865 return "Proxy:%s" % self.x
1866 def __repr__(self):
1867 return "Proxy(%r)" % self.x
1868 def __contains__(self, value):
1869 return value in self.x
1870 p0 = Proxy(0)
1871 p1 = Proxy(1)
1872 p_1 = Proxy(-1)
1873 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001874 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001875 self.assertEqual(hash(p0), hash(0))
1876 self.assertEqual(p0, p0)
1877 self.assertNotEqual(p0, p1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001878 self.assertFalse(p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001879 self.assertEqual(not p0, p1)
1880 self.assertEqual(cmp(p0, p1), -1)
1881 self.assertEqual(cmp(p0, p0), 0)
1882 self.assertEqual(cmp(p0, p_1), 1)
1883 self.assertEqual(str(p0), "Proxy:0")
1884 self.assertEqual(repr(p0), "Proxy(0)")
1885 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001886 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001887 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001888 self.assertIn(i, p10)
1889 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001890 # Test overridden behavior for dynamic classes
1891 class DProxy(object):
1892 def __init__(self, x):
1893 self.x = x
1894 def __nonzero__(self):
1895 return not not self.x
1896 def __hash__(self):
1897 return hash(self.x)
1898 def __eq__(self, other):
1899 return self.x == other
1900 def __ne__(self, other):
1901 return self.x != other
1902 def __cmp__(self, other):
1903 return cmp(self.x, other.x)
1904 def __str__(self):
1905 return "DProxy:%s" % self.x
1906 def __repr__(self):
1907 return "DProxy(%r)" % self.x
1908 def __contains__(self, value):
1909 return value in self.x
1910 p0 = DProxy(0)
1911 p1 = DProxy(1)
1912 p_1 = DProxy(-1)
1913 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001914 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001915 self.assertEqual(hash(p0), hash(0))
1916 self.assertEqual(p0, p0)
1917 self.assertNotEqual(p0, p1)
1918 self.assertNotEqual(not p0, p0)
1919 self.assertEqual(not p0, p1)
1920 self.assertEqual(cmp(p0, p1), -1)
1921 self.assertEqual(cmp(p0, p0), 0)
1922 self.assertEqual(cmp(p0, p_1), 1)
1923 self.assertEqual(str(p0), "DProxy:0")
1924 self.assertEqual(repr(p0), "DProxy(0)")
1925 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001926 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001927 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001928 self.assertIn(i, p10)
1929 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001930
1931 # Safety test for __cmp__
1932 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001933 if not hasattr(a, '__cmp__'):
1934 return # some types don't have a __cmp__ any more (so the
1935 # test doesn't make sense any more), or maybe they
1936 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001937 try:
1938 a.__class__.__cmp__(a, b)
1939 except TypeError:
1940 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001941 else:
Georg Brandl48545522008-02-02 10:12:36 +00001942 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1943 a.__class__, a, b))
1944
1945 unsafecmp(u"123", "123")
1946 unsafecmp("123", u"123")
1947 unsafecmp(1, 1.0)
1948 unsafecmp(1.0, 1)
1949 unsafecmp(1, 1L)
1950 unsafecmp(1L, 1)
1951
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001952 @test_support.impl_detail("custom logic for printing to real file objects")
1953 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001954 # Testing recursion checks ...
1955 class Letter(str):
1956 def __new__(cls, letter):
1957 if letter == 'EPS':
1958 return str.__new__(cls)
1959 return str.__new__(cls, letter)
1960 def __str__(self):
1961 if not self:
1962 return 'EPS'
1963 return self
1964 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00001965 test_stdout = sys.stdout
1966 sys.stdout = test_support.get_original_stdout()
1967 try:
1968 # nothing should actually be printed, this should raise an exception
1969 print Letter('w')
1970 except RuntimeError:
1971 pass
1972 else:
1973 self.fail("expected a RuntimeError for print recursion")
1974 finally:
1975 sys.stdout = test_stdout
1976
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001977 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001978 # Bug #1202533.
1979 class A(object):
1980 pass
1981 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1982 try:
1983 A()*2
1984 except RuntimeError:
1985 pass
1986 else:
1987 self.fail("expected a RuntimeError")
1988
1989 def test_weakrefs(self):
1990 # Testing weak references...
1991 import weakref
1992 class C(object):
1993 pass
1994 c = C()
1995 r = weakref.ref(c)
1996 self.assertEqual(r(), c)
1997 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001998 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001999 self.assertEqual(r(), None)
2000 del r
2001 class NoWeak(object):
2002 __slots__ = ['foo']
2003 no = NoWeak()
2004 try:
2005 weakref.ref(no)
2006 except TypeError, msg:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002007 self.assertIn("weak reference", str(msg))
Georg Brandl48545522008-02-02 10:12:36 +00002008 else:
2009 self.fail("weakref.ref(no) should be illegal")
2010 class Weak(object):
2011 __slots__ = ['foo', '__weakref__']
2012 yes = Weak()
2013 r = weakref.ref(yes)
2014 self.assertEqual(r(), yes)
2015 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002016 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00002017 self.assertEqual(r(), None)
2018 del r
2019
2020 def test_properties(self):
2021 # Testing property...
2022 class C(object):
2023 def getx(self):
2024 return self.__x
2025 def setx(self, value):
2026 self.__x = value
2027 def delx(self):
2028 del self.__x
2029 x = property(getx, setx, delx, doc="I'm the x property.")
2030 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002031 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002032 a.x = 42
2033 self.assertEqual(a._C__x, 42)
2034 self.assertEqual(a.x, 42)
2035 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002036 self.assertNotHasAttr(a, "x")
2037 self.assertNotHasAttr(a, "_C__x")
Georg Brandl48545522008-02-02 10:12:36 +00002038 C.x.__set__(a, 100)
2039 self.assertEqual(C.x.__get__(a), 100)
2040 C.x.__delete__(a)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002041 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002042
2043 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002044 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002045
2046 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002047 self.assertIn("__doc__", attrs)
2048 self.assertIn("fget", attrs)
2049 self.assertIn("fset", attrs)
2050 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002051
2052 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002053 self.assertIs(raw.fget, C.__dict__['getx'])
2054 self.assertIs(raw.fset, C.__dict__['setx'])
2055 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002056
2057 for attr in "__doc__", "fget", "fset", "fdel":
2058 try:
2059 setattr(raw, attr, 42)
2060 except TypeError, msg:
2061 if str(msg).find('readonly') < 0:
2062 self.fail("when setting readonly attr %r on a property, "
2063 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002064 else:
Georg Brandl48545522008-02-02 10:12:36 +00002065 self.fail("expected TypeError from trying to set readonly %r "
2066 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002067
Georg Brandl48545522008-02-02 10:12:36 +00002068 class D(object):
2069 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002070
Georg Brandl48545522008-02-02 10:12:36 +00002071 d = D()
2072 try:
2073 for i in d:
2074 str(i)
2075 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002076 pass
Georg Brandl48545522008-02-02 10:12:36 +00002077 else:
2078 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002079
R. David Murrayf28fd242010-02-23 00:24:49 +00002080 @unittest.skipIf(sys.flags.optimize >= 2,
2081 "Docstrings are omitted with -O2 and above")
2082 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002083 class E(object):
2084 def getter(self):
2085 "getter method"
2086 return 0
2087 def setter(self_, value):
2088 "setter method"
2089 pass
2090 prop = property(getter)
2091 self.assertEqual(prop.__doc__, "getter method")
2092 prop2 = property(fset=setter)
2093 self.assertEqual(prop2.__doc__, None)
2094
R. David Murrayf28fd242010-02-23 00:24:49 +00002095 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002096 # this segfaulted in 2.5b2
2097 try:
2098 import _testcapi
2099 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002100 pass
Georg Brandl48545522008-02-02 10:12:36 +00002101 else:
2102 class X(object):
2103 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002104
Georg Brandl48545522008-02-02 10:12:36 +00002105 def test_properties_plus(self):
2106 class C(object):
2107 foo = property(doc="hello")
2108 @foo.getter
2109 def foo(self):
2110 return self._foo
2111 @foo.setter
2112 def foo(self, value):
2113 self._foo = abs(value)
2114 @foo.deleter
2115 def foo(self):
2116 del self._foo
2117 c = C()
2118 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002119 self.assertNotHasAttr(c, "foo")
Georg Brandl48545522008-02-02 10:12:36 +00002120 c.foo = -42
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002121 self.assertHasAttr(c, '_foo')
Georg Brandl48545522008-02-02 10:12:36 +00002122 self.assertEqual(c._foo, 42)
2123 self.assertEqual(c.foo, 42)
2124 del c.foo
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002125 self.assertNotHasAttr(c, '_foo')
2126 self.assertNotHasAttr(c, "foo")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002127
Georg Brandl48545522008-02-02 10:12:36 +00002128 class D(C):
2129 @C.foo.deleter
2130 def foo(self):
2131 try:
2132 del self._foo
2133 except AttributeError:
2134 pass
2135 d = D()
2136 d.foo = 24
2137 self.assertEqual(d.foo, 24)
2138 del d.foo
2139 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002140
Georg Brandl48545522008-02-02 10:12:36 +00002141 class E(object):
2142 @property
2143 def foo(self):
2144 return self._foo
2145 @foo.setter
2146 def foo(self, value):
2147 raise RuntimeError
2148 @foo.setter
2149 def foo(self, value):
2150 self._foo = abs(value)
2151 @foo.deleter
2152 def foo(self, value=None):
2153 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002154
Georg Brandl48545522008-02-02 10:12:36 +00002155 e = E()
2156 e.foo = -42
2157 self.assertEqual(e.foo, 42)
2158 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002159
Georg Brandl48545522008-02-02 10:12:36 +00002160 class F(E):
2161 @E.foo.deleter
2162 def foo(self):
2163 del self._foo
2164 @foo.setter
2165 def foo(self, value):
2166 self._foo = max(0, value)
2167 f = F()
2168 f.foo = -10
2169 self.assertEqual(f.foo, 0)
2170 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002171
Georg Brandl48545522008-02-02 10:12:36 +00002172 def test_dict_constructors(self):
2173 # Testing dict constructor ...
2174 d = dict()
2175 self.assertEqual(d, {})
2176 d = dict({})
2177 self.assertEqual(d, {})
2178 d = dict({1: 2, 'a': 'b'})
2179 self.assertEqual(d, {1: 2, 'a': 'b'})
2180 self.assertEqual(d, dict(d.items()))
2181 self.assertEqual(d, dict(d.iteritems()))
2182 d = dict({'one':1, 'two':2})
2183 self.assertEqual(d, dict(one=1, two=2))
2184 self.assertEqual(d, dict(**d))
2185 self.assertEqual(d, dict({"one": 1}, two=2))
2186 self.assertEqual(d, dict([("two", 2)], one=1))
2187 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2188 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002189
Georg Brandl48545522008-02-02 10:12:36 +00002190 for badarg in 0, 0L, 0j, "0", [0], (0,):
2191 try:
2192 dict(badarg)
2193 except TypeError:
2194 pass
2195 except ValueError:
2196 if badarg == "0":
2197 # It's a sequence, and its elements are also sequences (gotta
2198 # love strings <wink>), but they aren't of length 2, so this
2199 # one seemed better as a ValueError than a TypeError.
2200 pass
2201 else:
2202 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002203 else:
Georg Brandl48545522008-02-02 10:12:36 +00002204 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002205
Georg Brandl48545522008-02-02 10:12:36 +00002206 try:
2207 dict({}, {})
2208 except TypeError:
2209 pass
2210 else:
2211 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002212
Georg Brandl48545522008-02-02 10:12:36 +00002213 class Mapping:
2214 # Lacks a .keys() method; will be added later.
2215 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002216
Georg Brandl48545522008-02-02 10:12:36 +00002217 try:
2218 dict(Mapping())
2219 except TypeError:
2220 pass
2221 else:
2222 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002223
Georg Brandl48545522008-02-02 10:12:36 +00002224 Mapping.keys = lambda self: self.dict.keys()
2225 Mapping.__getitem__ = lambda self, i: self.dict[i]
2226 d = dict(Mapping())
2227 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002228
Georg Brandl48545522008-02-02 10:12:36 +00002229 # Init from sequence of iterable objects, each producing a 2-sequence.
2230 class AddressBookEntry:
2231 def __init__(self, first, last):
2232 self.first = first
2233 self.last = last
2234 def __iter__(self):
2235 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002236
Georg Brandl48545522008-02-02 10:12:36 +00002237 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2238 AddressBookEntry('Barry', 'Peters'),
2239 AddressBookEntry('Tim', 'Peters'),
2240 AddressBookEntry('Barry', 'Warsaw')])
2241 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002242
Georg Brandl48545522008-02-02 10:12:36 +00002243 d = dict(zip(range(4), range(1, 5)))
2244 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002245
Georg Brandl48545522008-02-02 10:12:36 +00002246 # Bad sequence lengths.
2247 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2248 try:
2249 dict(bad)
2250 except ValueError:
2251 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002252 else:
Georg Brandl48545522008-02-02 10:12:36 +00002253 self.fail("no ValueError from dict(%r)" % bad)
2254
2255 def test_dir(self):
2256 # Testing dir() ...
2257 junk = 12
2258 self.assertEqual(dir(), ['junk', 'self'])
2259 del junk
2260
2261 # Just make sure these don't blow up!
2262 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2263 dir(arg)
2264
2265 # Try classic classes.
2266 class C:
2267 Cdata = 1
2268 def Cmethod(self): pass
2269
2270 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2271 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002272 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002273
2274 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2275 self.assertEqual(dir(c), cstuff)
2276
2277 c.cdata = 2
2278 c.cmethod = lambda self: 0
2279 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002280 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002281
2282 class A(C):
2283 Adata = 1
2284 def Amethod(self): pass
2285
2286 astuff = ['Adata', 'Amethod'] + cstuff
2287 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002288 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002289 a = A()
2290 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002291 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002292 a.adata = 42
2293 a.amethod = lambda self: 3
2294 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2295
2296 # The same, but with new-style classes. Since these have object as a
2297 # base class, a lot more gets sucked in.
2298 def interesting(strings):
2299 return [s for s in strings if not s.startswith('_')]
2300
2301 class C(object):
2302 Cdata = 1
2303 def Cmethod(self): pass
2304
2305 cstuff = ['Cdata', 'Cmethod']
2306 self.assertEqual(interesting(dir(C)), cstuff)
2307
2308 c = C()
2309 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002310 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002311
2312 c.cdata = 2
2313 c.cmethod = lambda self: 0
2314 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002315 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002316
2317 class A(C):
2318 Adata = 1
2319 def Amethod(self): pass
2320
2321 astuff = ['Adata', 'Amethod'] + cstuff
2322 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002323 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002324 a = A()
2325 self.assertEqual(interesting(dir(a)), astuff)
2326 a.adata = 42
2327 a.amethod = lambda self: 3
2328 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002329 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002330
2331 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002332 class M(type(sys)):
2333 pass
2334 minstance = M("m")
2335 minstance.b = 2
2336 minstance.a = 1
2337 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2338 self.assertEqual(names, ['a', 'b'])
2339
2340 class M2(M):
2341 def getdict(self):
2342 return "Not a dict!"
2343 __dict__ = property(getdict)
2344
2345 m2instance = M2("m2")
2346 m2instance.b = 2
2347 m2instance.a = 1
2348 self.assertEqual(m2instance.__dict__, "Not a dict!")
2349 try:
2350 dir(m2instance)
2351 except TypeError:
2352 pass
2353
2354 # Two essentially featureless objects, just inheriting stuff from
2355 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002356 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2357 if test_support.check_impl_detail():
2358 # None differs in PyPy: it has a __nonzero__
2359 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002360
2361 # Nasty test case for proxied objects
2362 class Wrapper(object):
2363 def __init__(self, obj):
2364 self.__obj = obj
2365 def __repr__(self):
2366 return "Wrapper(%s)" % repr(self.__obj)
2367 def __getitem__(self, key):
2368 return Wrapper(self.__obj[key])
2369 def __len__(self):
2370 return len(self.__obj)
2371 def __getattr__(self, name):
2372 return Wrapper(getattr(self.__obj, name))
2373
2374 class C(object):
2375 def __getclass(self):
2376 return Wrapper(type(self))
2377 __class__ = property(__getclass)
2378
2379 dir(C()) # This used to segfault
2380
2381 def test_supers(self):
2382 # Testing super...
2383
2384 class A(object):
2385 def meth(self, a):
2386 return "A(%r)" % a
2387
2388 self.assertEqual(A().meth(1), "A(1)")
2389
2390 class B(A):
2391 def __init__(self):
2392 self.__super = super(B, self)
2393 def meth(self, a):
2394 return "B(%r)" % a + self.__super.meth(a)
2395
2396 self.assertEqual(B().meth(2), "B(2)A(2)")
2397
2398 class C(A):
2399 def meth(self, a):
2400 return "C(%r)" % a + self.__super.meth(a)
2401 C._C__super = super(C)
2402
2403 self.assertEqual(C().meth(3), "C(3)A(3)")
2404
2405 class D(C, B):
2406 def meth(self, a):
2407 return "D(%r)" % a + super(D, self).meth(a)
2408
2409 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2410
2411 # Test for subclassing super
2412
2413 class mysuper(super):
2414 def __init__(self, *args):
2415 return super(mysuper, self).__init__(*args)
2416
2417 class E(D):
2418 def meth(self, a):
2419 return "E(%r)" % a + mysuper(E, self).meth(a)
2420
2421 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2422
2423 class F(E):
2424 def meth(self, a):
2425 s = self.__super # == mysuper(F, self)
2426 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2427 F._F__super = mysuper(F)
2428
2429 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2430
2431 # Make sure certain errors are raised
2432
2433 try:
2434 super(D, 42)
2435 except TypeError:
2436 pass
2437 else:
2438 self.fail("shouldn't allow super(D, 42)")
2439
2440 try:
2441 super(D, C())
2442 except TypeError:
2443 pass
2444 else:
2445 self.fail("shouldn't allow super(D, C())")
2446
2447 try:
2448 super(D).__get__(12)
2449 except TypeError:
2450 pass
2451 else:
2452 self.fail("shouldn't allow super(D).__get__(12)")
2453
2454 try:
2455 super(D).__get__(C())
2456 except TypeError:
2457 pass
2458 else:
2459 self.fail("shouldn't allow super(D).__get__(C())")
2460
2461 # Make sure data descriptors can be overridden and accessed via super
2462 # (new feature in Python 2.3)
2463
2464 class DDbase(object):
2465 def getx(self): return 42
2466 x = property(getx)
2467
2468 class DDsub(DDbase):
2469 def getx(self): return "hello"
2470 x = property(getx)
2471
2472 dd = DDsub()
2473 self.assertEqual(dd.x, "hello")
2474 self.assertEqual(super(DDsub, dd).x, 42)
2475
2476 # Ensure that super() lookup of descriptor from classmethod
2477 # works (SF ID# 743627)
2478
2479 class Base(object):
2480 aProp = property(lambda self: "foo")
2481
2482 class Sub(Base):
2483 @classmethod
2484 def test(klass):
2485 return super(Sub,klass).aProp
2486
2487 self.assertEqual(Sub.test(), Base.aProp)
2488
2489 # Verify that super() doesn't allow keyword args
2490 try:
2491 super(Base, kw=1)
2492 except TypeError:
2493 pass
2494 else:
2495 self.assertEqual("super shouldn't accept keyword args")
2496
2497 def test_basic_inheritance(self):
2498 # Testing inheritance from basic types...
2499
2500 class hexint(int):
2501 def __repr__(self):
2502 return hex(self)
2503 def __add__(self, other):
2504 return hexint(int.__add__(self, other))
2505 # (Note that overriding __radd__ doesn't work,
2506 # because the int type gets first dibs.)
2507 self.assertEqual(repr(hexint(7) + 9), "0x10")
2508 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2509 a = hexint(12345)
2510 self.assertEqual(a, 12345)
2511 self.assertEqual(int(a), 12345)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002512 self.assertIs(int(a).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002513 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002514 self.assertIs((+a).__class__, int)
2515 self.assertIs((a >> 0).__class__, int)
2516 self.assertIs((a << 0).__class__, int)
2517 self.assertIs((hexint(0) << 12).__class__, int)
2518 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002519
2520 class octlong(long):
2521 __slots__ = []
2522 def __str__(self):
2523 s = oct(self)
2524 if s[-1] == 'L':
2525 s = s[:-1]
2526 return s
2527 def __add__(self, other):
2528 return self.__class__(super(octlong, self).__add__(other))
2529 __radd__ = __add__
2530 self.assertEqual(str(octlong(3) + 5), "010")
2531 # (Note that overriding __radd__ here only seems to work
2532 # because the example uses a short int left argument.)
2533 self.assertEqual(str(5 + octlong(3000)), "05675")
2534 a = octlong(12345)
2535 self.assertEqual(a, 12345L)
2536 self.assertEqual(long(a), 12345L)
2537 self.assertEqual(hash(a), hash(12345L))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002538 self.assertIs(long(a).__class__, long)
2539 self.assertIs((+a).__class__, long)
2540 self.assertIs((-a).__class__, long)
2541 self.assertIs((-octlong(0)).__class__, long)
2542 self.assertIs((a >> 0).__class__, long)
2543 self.assertIs((a << 0).__class__, long)
2544 self.assertIs((a - 0).__class__, long)
2545 self.assertIs((a * 1).__class__, long)
2546 self.assertIs((a ** 1).__class__, long)
2547 self.assertIs((a // 1).__class__, long)
2548 self.assertIs((1 * a).__class__, long)
2549 self.assertIs((a | 0).__class__, long)
2550 self.assertIs((a ^ 0).__class__, long)
2551 self.assertIs((a & -1L).__class__, long)
2552 self.assertIs((octlong(0) << 12).__class__, long)
2553 self.assertIs((octlong(0) >> 12).__class__, long)
2554 self.assertIs(abs(octlong(0)).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002555
2556 # Because octlong overrides __add__, we can't check the absence of +0
2557 # optimizations using octlong.
2558 class longclone(long):
2559 pass
2560 a = longclone(1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002561 self.assertIs((a + 0).__class__, long)
2562 self.assertIs((0 + a).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002563
2564 # Check that negative clones don't segfault
2565 a = longclone(-1)
2566 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002567 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002568
2569 class precfloat(float):
2570 __slots__ = ['prec']
2571 def __init__(self, value=0.0, prec=12):
2572 self.prec = int(prec)
2573 def __repr__(self):
2574 return "%.*g" % (self.prec, self)
2575 self.assertEqual(repr(precfloat(1.1)), "1.1")
2576 a = precfloat(12345)
2577 self.assertEqual(a, 12345.0)
2578 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002579 self.assertIs(float(a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002580 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002581 self.assertIs((+a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002582
2583 class madcomplex(complex):
2584 def __repr__(self):
2585 return "%.17gj%+.17g" % (self.imag, self.real)
2586 a = madcomplex(-3, 4)
2587 self.assertEqual(repr(a), "4j-3")
2588 base = complex(-3, 4)
2589 self.assertEqual(base.__class__, complex)
2590 self.assertEqual(a, base)
2591 self.assertEqual(complex(a), base)
2592 self.assertEqual(complex(a).__class__, complex)
2593 a = madcomplex(a) # just trying another form of the constructor
2594 self.assertEqual(repr(a), "4j-3")
2595 self.assertEqual(a, base)
2596 self.assertEqual(complex(a), base)
2597 self.assertEqual(complex(a).__class__, complex)
2598 self.assertEqual(hash(a), hash(base))
2599 self.assertEqual((+a).__class__, complex)
2600 self.assertEqual((a + 0).__class__, complex)
2601 self.assertEqual(a + 0, base)
2602 self.assertEqual((a - 0).__class__, complex)
2603 self.assertEqual(a - 0, base)
2604 self.assertEqual((a * 1).__class__, complex)
2605 self.assertEqual(a * 1, base)
2606 self.assertEqual((a / 1).__class__, complex)
2607 self.assertEqual(a / 1, base)
2608
2609 class madtuple(tuple):
2610 _rev = None
2611 def rev(self):
2612 if self._rev is not None:
2613 return self._rev
2614 L = list(self)
2615 L.reverse()
2616 self._rev = self.__class__(L)
2617 return self._rev
2618 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2619 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2620 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2621 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2622 for i in range(512):
2623 t = madtuple(range(i))
2624 u = t.rev()
2625 v = u.rev()
2626 self.assertEqual(v, t)
2627 a = madtuple((1,2,3,4,5))
2628 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002629 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002630 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002631 self.assertIs(a[:].__class__, tuple)
2632 self.assertIs((a * 1).__class__, tuple)
2633 self.assertIs((a * 0).__class__, tuple)
2634 self.assertIs((a + ()).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002635 a = madtuple(())
2636 self.assertEqual(tuple(a), ())
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002637 self.assertIs(tuple(a).__class__, tuple)
2638 self.assertIs((a + a).__class__, tuple)
2639 self.assertIs((a * 0).__class__, tuple)
2640 self.assertIs((a * 1).__class__, tuple)
2641 self.assertIs((a * 2).__class__, tuple)
2642 self.assertIs(a[:].__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002643
2644 class madstring(str):
2645 _rev = None
2646 def rev(self):
2647 if self._rev is not None:
2648 return self._rev
2649 L = list(self)
2650 L.reverse()
2651 self._rev = self.__class__("".join(L))
2652 return self._rev
2653 s = madstring("abcdefghijklmnopqrstuvwxyz")
2654 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2655 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2656 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2657 for i in range(256):
2658 s = madstring("".join(map(chr, range(i))))
2659 t = s.rev()
2660 u = t.rev()
2661 self.assertEqual(u, s)
2662 s = madstring("12345")
2663 self.assertEqual(str(s), "12345")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002664 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002665
2666 base = "\x00" * 5
2667 s = madstring(base)
2668 self.assertEqual(s, base)
2669 self.assertEqual(str(s), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002670 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002671 self.assertEqual(hash(s), hash(base))
2672 self.assertEqual({s: 1}[base], 1)
2673 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002674 self.assertIs((s + "").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002675 self.assertEqual(s + "", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002676 self.assertIs(("" + s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002677 self.assertEqual("" + s, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002678 self.assertIs((s * 0).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002679 self.assertEqual(s * 0, "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002680 self.assertIs((s * 1).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002681 self.assertEqual(s * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002682 self.assertIs((s * 2).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002683 self.assertEqual(s * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002684 self.assertIs(s[:].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002685 self.assertEqual(s[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002686 self.assertIs(s[0:0].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002687 self.assertEqual(s[0:0], "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002688 self.assertIs(s.strip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002689 self.assertEqual(s.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002690 self.assertIs(s.lstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002691 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002692 self.assertIs(s.rstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002693 self.assertEqual(s.rstrip(), base)
2694 identitytab = ''.join([chr(i) for i in range(256)])
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002695 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002696 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002697 self.assertIs(s.translate(identitytab, "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002698 self.assertEqual(s.translate(identitytab, "x"), base)
2699 self.assertEqual(s.translate(identitytab, "\x00"), "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002700 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002701 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002702 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002703 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002704 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002705 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002706 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002707 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002708 self.assertIs(s.lower().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002709 self.assertEqual(s.lower(), base)
2710
2711 class madunicode(unicode):
2712 _rev = None
2713 def rev(self):
2714 if self._rev is not None:
2715 return self._rev
2716 L = list(self)
2717 L.reverse()
2718 self._rev = self.__class__(u"".join(L))
2719 return self._rev
2720 u = madunicode("ABCDEF")
2721 self.assertEqual(u, u"ABCDEF")
2722 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2723 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2724 base = u"12345"
2725 u = madunicode(base)
2726 self.assertEqual(unicode(u), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002727 self.assertIs(unicode(u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002728 self.assertEqual(hash(u), hash(base))
2729 self.assertEqual({u: 1}[base], 1)
2730 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002731 self.assertIs(u.strip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002732 self.assertEqual(u.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002733 self.assertIs(u.lstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002734 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002735 self.assertIs(u.rstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002736 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002737 self.assertIs(u.replace(u"x", u"x").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002738 self.assertEqual(u.replace(u"x", u"x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002739 self.assertIs(u.replace(u"xy", u"xy").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002740 self.assertEqual(u.replace(u"xy", u"xy"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002741 self.assertIs(u.center(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002742 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002743 self.assertIs(u.ljust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002744 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002745 self.assertIs(u.rjust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002746 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002747 self.assertIs(u.lower().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002748 self.assertEqual(u.lower(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002749 self.assertIs(u.upper().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002750 self.assertEqual(u.upper(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002751 self.assertIs(u.capitalize().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002752 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002753 self.assertIs(u.title().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002754 self.assertEqual(u.title(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002755 self.assertIs((u + u"").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002756 self.assertEqual(u + u"", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002757 self.assertIs((u"" + u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002758 self.assertEqual(u"" + u, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002759 self.assertIs((u * 0).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002760 self.assertEqual(u * 0, u"")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002761 self.assertIs((u * 1).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002762 self.assertEqual(u * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002763 self.assertIs((u * 2).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002764 self.assertEqual(u * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002765 self.assertIs(u[:].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002766 self.assertEqual(u[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002767 self.assertIs(u[0:0].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002768 self.assertEqual(u[0:0], u"")
2769
2770 class sublist(list):
2771 pass
2772 a = sublist(range(5))
2773 self.assertEqual(a, range(5))
2774 a.append("hello")
2775 self.assertEqual(a, range(5) + ["hello"])
2776 a[5] = 5
2777 self.assertEqual(a, range(6))
2778 a.extend(range(6, 20))
2779 self.assertEqual(a, range(20))
2780 a[-5:] = []
2781 self.assertEqual(a, range(15))
2782 del a[10:15]
2783 self.assertEqual(len(a), 10)
2784 self.assertEqual(a, range(10))
2785 self.assertEqual(list(a), range(10))
2786 self.assertEqual(a[0], 0)
2787 self.assertEqual(a[9], 9)
2788 self.assertEqual(a[-10], 0)
2789 self.assertEqual(a[-1], 9)
2790 self.assertEqual(a[:5], range(5))
2791
2792 class CountedInput(file):
2793 """Counts lines read by self.readline().
2794
2795 self.lineno is the 0-based ordinal of the last line read, up to
2796 a maximum of one greater than the number of lines in the file.
2797
2798 self.ateof is true if and only if the final "" line has been read,
2799 at which point self.lineno stops incrementing, and further calls
2800 to readline() continue to return "".
2801 """
2802
2803 lineno = 0
2804 ateof = 0
2805 def readline(self):
2806 if self.ateof:
2807 return ""
2808 s = file.readline(self)
2809 # Next line works too.
2810 # s = super(CountedInput, self).readline()
2811 self.lineno += 1
2812 if s == "":
2813 self.ateof = 1
2814 return s
2815
2816 f = file(name=test_support.TESTFN, mode='w')
2817 lines = ['a\n', 'b\n', 'c\n']
2818 try:
2819 f.writelines(lines)
2820 f.close()
2821 f = CountedInput(test_support.TESTFN)
2822 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2823 got = f.readline()
2824 self.assertEqual(expected, got)
2825 self.assertEqual(f.lineno, i)
2826 self.assertEqual(f.ateof, (i > len(lines)))
2827 f.close()
2828 finally:
2829 try:
2830 f.close()
2831 except:
2832 pass
2833 test_support.unlink(test_support.TESTFN)
2834
2835 def test_keywords(self):
2836 # Testing keyword args to basic type constructors ...
2837 self.assertEqual(int(x=1), 1)
2838 self.assertEqual(float(x=2), 2.0)
2839 self.assertEqual(long(x=3), 3L)
2840 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2841 self.assertEqual(str(object=500), '500')
2842 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2843 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2844 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2845 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2846
2847 for constructor in (int, float, long, complex, str, unicode,
2848 tuple, list, file):
2849 try:
2850 constructor(bogus_keyword_arg=1)
2851 except TypeError:
2852 pass
2853 else:
2854 self.fail("expected TypeError from bogus keyword argument to %r"
2855 % constructor)
2856
2857 def test_str_subclass_as_dict_key(self):
2858 # Testing a str subclass used as dict key ..
2859
2860 class cistr(str):
2861 """Sublcass of str that computes __eq__ case-insensitively.
2862
2863 Also computes a hash code of the string in canonical form.
2864 """
2865
2866 def __init__(self, value):
2867 self.canonical = value.lower()
2868 self.hashcode = hash(self.canonical)
2869
2870 def __eq__(self, other):
2871 if not isinstance(other, cistr):
2872 other = cistr(other)
2873 return self.canonical == other.canonical
2874
2875 def __hash__(self):
2876 return self.hashcode
2877
2878 self.assertEqual(cistr('ABC'), 'abc')
2879 self.assertEqual('aBc', cistr('ABC'))
2880 self.assertEqual(str(cistr('ABC')), 'ABC')
2881
2882 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2883 self.assertEqual(d[cistr('one')], 1)
2884 self.assertEqual(d[cistr('tWo')], 2)
2885 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002886 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002887 self.assertEqual(d.get(cistr('thrEE')), 3)
2888
2889 def test_classic_comparisons(self):
2890 # Testing classic comparisons...
2891 class classic:
2892 pass
2893
2894 for base in (classic, int, object):
2895 class C(base):
2896 def __init__(self, value):
2897 self.value = int(value)
2898 def __cmp__(self, other):
2899 if isinstance(other, C):
2900 return cmp(self.value, other.value)
2901 if isinstance(other, int) or isinstance(other, long):
2902 return cmp(self.value, other)
2903 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002904 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002905
2906 c1 = C(1)
2907 c2 = C(2)
2908 c3 = C(3)
2909 self.assertEqual(c1, 1)
2910 c = {1: c1, 2: c2, 3: c3}
2911 for x in 1, 2, 3:
2912 for y in 1, 2, 3:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002913 self.assertEqual(cmp(c[x], c[y]), cmp(x, y),
2914 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002915 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002916 self.assertEqual(eval("c[x] %s c[y]" % op),
2917 eval("x %s y" % op),
2918 "x=%d, y=%d" % (x, y))
2919 self.assertEqual(cmp(c[x], y), cmp(x, y),
2920 "x=%d, y=%d" % (x, y))
2921 self.assertEqual(cmp(x, c[y]), cmp(x, y),
2922 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002923
2924 def test_rich_comparisons(self):
2925 # Testing rich comparisons...
2926 class Z(complex):
2927 pass
2928 z = Z(1)
2929 self.assertEqual(z, 1+0j)
2930 self.assertEqual(1+0j, z)
2931 class ZZ(complex):
2932 def __eq__(self, other):
2933 try:
2934 return abs(self - other) <= 1e-6
2935 except:
2936 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002937 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002938 zz = ZZ(1.0000003)
2939 self.assertEqual(zz, 1+0j)
2940 self.assertEqual(1+0j, zz)
2941
2942 class classic:
2943 pass
2944 for base in (classic, int, object, list):
2945 class C(base):
2946 def __init__(self, value):
2947 self.value = int(value)
2948 def __cmp__(self_, other):
2949 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002950 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002951 def __eq__(self, other):
2952 if isinstance(other, C):
2953 return self.value == other.value
2954 if isinstance(other, int) or isinstance(other, long):
2955 return self.value == other
2956 return NotImplemented
2957 def __ne__(self, other):
2958 if isinstance(other, C):
2959 return self.value != other.value
2960 if isinstance(other, int) or isinstance(other, long):
2961 return self.value != other
2962 return NotImplemented
2963 def __lt__(self, other):
2964 if isinstance(other, C):
2965 return self.value < other.value
2966 if isinstance(other, int) or isinstance(other, long):
2967 return self.value < other
2968 return NotImplemented
2969 def __le__(self, other):
2970 if isinstance(other, C):
2971 return self.value <= other.value
2972 if isinstance(other, int) or isinstance(other, long):
2973 return self.value <= other
2974 return NotImplemented
2975 def __gt__(self, other):
2976 if isinstance(other, C):
2977 return self.value > other.value
2978 if isinstance(other, int) or isinstance(other, long):
2979 return self.value > other
2980 return NotImplemented
2981 def __ge__(self, other):
2982 if isinstance(other, C):
2983 return self.value >= other.value
2984 if isinstance(other, int) or isinstance(other, long):
2985 return self.value >= other
2986 return NotImplemented
2987 c1 = C(1)
2988 c2 = C(2)
2989 c3 = C(3)
2990 self.assertEqual(c1, 1)
2991 c = {1: c1, 2: c2, 3: c3}
2992 for x in 1, 2, 3:
2993 for y in 1, 2, 3:
2994 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002995 self.assertEqual(eval("c[x] %s c[y]" % op),
2996 eval("x %s y" % op),
2997 "x=%d, y=%d" % (x, y))
2998 self.assertEqual(eval("c[x] %s y" % op),
2999 eval("x %s y" % op),
3000 "x=%d, y=%d" % (x, y))
3001 self.assertEqual(eval("x %s c[y]" % op),
3002 eval("x %s y" % op),
3003 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003004
3005 def test_coercions(self):
3006 # Testing coercions...
3007 class I(int): pass
3008 coerce(I(0), 0)
3009 coerce(0, I(0))
3010 class L(long): pass
3011 coerce(L(0), 0)
3012 coerce(L(0), 0L)
3013 coerce(0, L(0))
3014 coerce(0L, L(0))
3015 class F(float): pass
3016 coerce(F(0), 0)
3017 coerce(F(0), 0L)
3018 coerce(F(0), 0.)
3019 coerce(0, F(0))
3020 coerce(0L, F(0))
3021 coerce(0., F(0))
3022 class C(complex): pass
3023 coerce(C(0), 0)
3024 coerce(C(0), 0L)
3025 coerce(C(0), 0.)
3026 coerce(C(0), 0j)
3027 coerce(0, C(0))
3028 coerce(0L, C(0))
3029 coerce(0., C(0))
3030 coerce(0j, C(0))
3031
3032 def test_descrdoc(self):
3033 # Testing descriptor doc strings...
3034 def check(descr, what):
3035 self.assertEqual(descr.__doc__, what)
3036 check(file.closed, "True if the file is closed") # getset descriptor
3037 check(file.name, "file name") # member descriptor
3038
3039 def test_doc_descriptor(self):
3040 # Testing __doc__ descriptor...
3041 # SF bug 542984
3042 class DocDescr(object):
3043 def __get__(self, object, otype):
3044 if object:
3045 object = object.__class__.__name__ + ' instance'
3046 if otype:
3047 otype = otype.__name__
3048 return 'object=%s; type=%s' % (object, otype)
3049 class OldClass:
3050 __doc__ = DocDescr()
3051 class NewClass(object):
3052 __doc__ = DocDescr()
3053 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3054 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3055 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3056 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3057
3058 def test_set_class(self):
3059 # Testing __class__ assignment...
3060 class C(object): pass
3061 class D(object): pass
3062 class E(object): pass
3063 class F(D, E): pass
3064 for cls in C, D, E, F:
3065 for cls2 in C, D, E, F:
3066 x = cls()
3067 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003068 self.assertIs(x.__class__, cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003069 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003070 self.assertIs(x.__class__, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003071 def cant(x, C):
3072 try:
3073 x.__class__ = C
3074 except TypeError:
3075 pass
3076 else:
3077 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3078 try:
3079 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003080 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003081 pass
3082 else:
3083 self.fail("shouldn't allow del %r.__class__" % x)
3084 cant(C(), list)
3085 cant(list(), C)
3086 cant(C(), 1)
3087 cant(C(), object)
3088 cant(object(), list)
3089 cant(list(), object)
3090 class Int(int): __slots__ = []
3091 cant(2, Int)
3092 cant(Int(), int)
3093 cant(True, int)
3094 cant(2, bool)
3095 o = object()
3096 cant(o, type(1))
3097 cant(o, type(None))
3098 del o
3099 class G(object):
3100 __slots__ = ["a", "b"]
3101 class H(object):
3102 __slots__ = ["b", "a"]
3103 try:
3104 unicode
3105 except NameError:
3106 class I(object):
3107 __slots__ = ["a", "b"]
3108 else:
3109 class I(object):
3110 __slots__ = [unicode("a"), unicode("b")]
3111 class J(object):
3112 __slots__ = ["c", "b"]
3113 class K(object):
3114 __slots__ = ["a", "b", "d"]
3115 class L(H):
3116 __slots__ = ["e"]
3117 class M(I):
3118 __slots__ = ["e"]
3119 class N(J):
3120 __slots__ = ["__weakref__"]
3121 class P(J):
3122 __slots__ = ["__dict__"]
3123 class Q(J):
3124 pass
3125 class R(J):
3126 __slots__ = ["__dict__", "__weakref__"]
3127
3128 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3129 x = cls()
3130 x.a = 1
3131 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003132 self.assertIs(x.__class__, cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003133 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3134 self.assertEqual(x.a, 1)
3135 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003136 self.assertIs(x.__class__, cls,
Georg Brandl48545522008-02-02 10:12:36 +00003137 "assigning %r as __class__ for %r silently failed" % (cls, x))
3138 self.assertEqual(x.a, 1)
3139 for cls in G, J, K, L, M, N, P, R, list, Int:
3140 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3141 if cls is cls2:
3142 continue
3143 cant(cls(), cls2)
3144
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003145 # Issue5283: when __class__ changes in __del__, the wrong
3146 # type gets DECREF'd.
3147 class O(object):
3148 pass
3149 class A(object):
3150 def __del__(self):
3151 self.__class__ = O
3152 l = [A() for x in range(100)]
3153 del l
3154
Georg Brandl48545522008-02-02 10:12:36 +00003155 def test_set_dict(self):
3156 # Testing __dict__ assignment...
3157 class C(object): pass
3158 a = C()
3159 a.__dict__ = {'b': 1}
3160 self.assertEqual(a.b, 1)
3161 def cant(x, dict):
3162 try:
3163 x.__dict__ = dict
3164 except (AttributeError, TypeError):
3165 pass
3166 else:
3167 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3168 cant(a, None)
3169 cant(a, [])
3170 cant(a, 1)
3171 del a.__dict__ # Deleting __dict__ is allowed
3172
3173 class Base(object):
3174 pass
3175 def verify_dict_readonly(x):
3176 """
3177 x has to be an instance of a class inheriting from Base.
3178 """
3179 cant(x, {})
3180 try:
3181 del x.__dict__
3182 except (AttributeError, TypeError):
3183 pass
3184 else:
3185 self.fail("shouldn't allow del %r.__dict__" % x)
3186 dict_descr = Base.__dict__["__dict__"]
3187 try:
3188 dict_descr.__set__(x, {})
3189 except (AttributeError, TypeError):
3190 pass
3191 else:
3192 self.fail("dict_descr allowed access to %r's dict" % x)
3193
3194 # Classes don't allow __dict__ assignment and have readonly dicts
3195 class Meta1(type, Base):
3196 pass
3197 class Meta2(Base, type):
3198 pass
3199 class D(object):
3200 __metaclass__ = Meta1
3201 class E(object):
3202 __metaclass__ = Meta2
3203 for cls in C, D, E:
3204 verify_dict_readonly(cls)
3205 class_dict = cls.__dict__
3206 try:
3207 class_dict["spam"] = "eggs"
3208 except TypeError:
3209 pass
3210 else:
3211 self.fail("%r's __dict__ can be modified" % cls)
3212
3213 # Modules also disallow __dict__ assignment
3214 class Module1(types.ModuleType, Base):
3215 pass
3216 class Module2(Base, types.ModuleType):
3217 pass
3218 for ModuleType in Module1, Module2:
3219 mod = ModuleType("spam")
3220 verify_dict_readonly(mod)
3221 mod.__dict__["spam"] = "eggs"
3222
3223 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003224 # (at least not any more than regular exception's __dict__ can
3225 # be deleted; on CPython it is not the case, whereas on PyPy they
3226 # can, just like any other new-style instance's __dict__.)
3227 def can_delete_dict(e):
3228 try:
3229 del e.__dict__
3230 except (TypeError, AttributeError):
3231 return False
3232 else:
3233 return True
Georg Brandl48545522008-02-02 10:12:36 +00003234 class Exception1(Exception, Base):
3235 pass
3236 class Exception2(Base, Exception):
3237 pass
3238 for ExceptionType in Exception, Exception1, Exception2:
3239 e = ExceptionType()
3240 e.__dict__ = {"a": 1}
3241 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003242 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003243
3244 def test_pickles(self):
3245 # Testing pickling and copying new-style classes and objects...
3246 import pickle, cPickle
3247
3248 def sorteditems(d):
3249 L = d.items()
3250 L.sort()
3251 return L
3252
3253 global C
3254 class C(object):
3255 def __init__(self, a, b):
3256 super(C, self).__init__()
3257 self.a = a
3258 self.b = b
3259 def __repr__(self):
3260 return "C(%r, %r)" % (self.a, self.b)
3261
3262 global C1
3263 class C1(list):
3264 def __new__(cls, a, b):
3265 return super(C1, cls).__new__(cls)
3266 def __getnewargs__(self):
3267 return (self.a, self.b)
3268 def __init__(self, a, b):
3269 self.a = a
3270 self.b = b
3271 def __repr__(self):
3272 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3273
3274 global C2
3275 class C2(int):
3276 def __new__(cls, a, b, val=0):
3277 return super(C2, cls).__new__(cls, val)
3278 def __getnewargs__(self):
3279 return (self.a, self.b, int(self))
3280 def __init__(self, a, b, val=0):
3281 self.a = a
3282 self.b = b
3283 def __repr__(self):
3284 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3285
3286 global C3
3287 class C3(object):
3288 def __init__(self, foo):
3289 self.foo = foo
3290 def __getstate__(self):
3291 return self.foo
3292 def __setstate__(self, foo):
3293 self.foo = foo
3294
3295 global C4classic, C4
3296 class C4classic: # classic
3297 pass
3298 class C4(C4classic, object): # mixed inheritance
3299 pass
3300
3301 for p in pickle, cPickle:
3302 for bin in 0, 1:
3303 for cls in C, C1, C2:
3304 s = p.dumps(cls, bin)
3305 cls2 = p.loads(s)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003306 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003307
3308 a = C1(1, 2); a.append(42); a.append(24)
3309 b = C2("hello", "world", 42)
3310 s = p.dumps((a, b), bin)
3311 x, y = p.loads(s)
3312 self.assertEqual(x.__class__, a.__class__)
3313 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3314 self.assertEqual(y.__class__, b.__class__)
3315 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3316 self.assertEqual(repr(x), repr(a))
3317 self.assertEqual(repr(y), repr(b))
3318 # Test for __getstate__ and __setstate__ on new style class
3319 u = C3(42)
3320 s = p.dumps(u, bin)
3321 v = p.loads(s)
3322 self.assertEqual(u.__class__, v.__class__)
3323 self.assertEqual(u.foo, v.foo)
3324 # Test for picklability of hybrid class
3325 u = C4()
3326 u.foo = 42
3327 s = p.dumps(u, bin)
3328 v = p.loads(s)
3329 self.assertEqual(u.__class__, v.__class__)
3330 self.assertEqual(u.foo, v.foo)
3331
3332 # Testing copy.deepcopy()
3333 import copy
3334 for cls in C, C1, C2:
3335 cls2 = copy.deepcopy(cls)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003336 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003337
3338 a = C1(1, 2); a.append(42); a.append(24)
3339 b = C2("hello", "world", 42)
3340 x, y = copy.deepcopy((a, b))
3341 self.assertEqual(x.__class__, a.__class__)
3342 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3343 self.assertEqual(y.__class__, b.__class__)
3344 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3345 self.assertEqual(repr(x), repr(a))
3346 self.assertEqual(repr(y), repr(b))
3347
3348 def test_pickle_slots(self):
3349 # Testing pickling of classes with __slots__ ...
3350 import pickle, cPickle
3351 # Pickling of classes with __slots__ but without __getstate__ should fail
3352 global B, C, D, E
3353 class B(object):
3354 pass
3355 for base in [object, B]:
3356 class C(base):
3357 __slots__ = ['a']
3358 class D(C):
3359 pass
3360 try:
3361 pickle.dumps(C())
3362 except TypeError:
3363 pass
3364 else:
3365 self.fail("should fail: pickle C instance - %s" % base)
3366 try:
3367 cPickle.dumps(C())
3368 except TypeError:
3369 pass
3370 else:
3371 self.fail("should fail: cPickle C instance - %s" % base)
3372 try:
3373 pickle.dumps(C())
3374 except TypeError:
3375 pass
3376 else:
3377 self.fail("should fail: pickle D instance - %s" % base)
3378 try:
3379 cPickle.dumps(D())
3380 except TypeError:
3381 pass
3382 else:
3383 self.fail("should fail: cPickle D instance - %s" % base)
3384 # Give C a nice generic __getstate__ and __setstate__
3385 class C(base):
3386 __slots__ = ['a']
3387 def __getstate__(self):
3388 try:
3389 d = self.__dict__.copy()
3390 except AttributeError:
3391 d = {}
3392 for cls in self.__class__.__mro__:
3393 for sn in cls.__dict__.get('__slots__', ()):
3394 try:
3395 d[sn] = getattr(self, sn)
3396 except AttributeError:
3397 pass
3398 return d
3399 def __setstate__(self, d):
3400 for k, v in d.items():
3401 setattr(self, k, v)
3402 class D(C):
3403 pass
3404 # Now it should work
3405 x = C()
3406 y = pickle.loads(pickle.dumps(x))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003407 self.assertNotHasAttr(y, 'a')
Georg Brandl48545522008-02-02 10:12:36 +00003408 y = cPickle.loads(cPickle.dumps(x))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003409 self.assertNotHasAttr(y, 'a')
Georg Brandl48545522008-02-02 10:12:36 +00003410 x.a = 42
3411 y = pickle.loads(pickle.dumps(x))
3412 self.assertEqual(y.a, 42)
3413 y = cPickle.loads(cPickle.dumps(x))
3414 self.assertEqual(y.a, 42)
3415 x = D()
3416 x.a = 42
3417 x.b = 100
3418 y = pickle.loads(pickle.dumps(x))
3419 self.assertEqual(y.a + y.b, 142)
3420 y = cPickle.loads(cPickle.dumps(x))
3421 self.assertEqual(y.a + y.b, 142)
3422 # A subclass that adds a slot should also work
3423 class E(C):
3424 __slots__ = ['b']
3425 x = E()
3426 x.a = 42
3427 x.b = "foo"
3428 y = pickle.loads(pickle.dumps(x))
3429 self.assertEqual(y.a, x.a)
3430 self.assertEqual(y.b, x.b)
3431 y = cPickle.loads(cPickle.dumps(x))
3432 self.assertEqual(y.a, x.a)
3433 self.assertEqual(y.b, x.b)
3434
3435 def test_binary_operator_override(self):
3436 # Testing overrides of binary operations...
3437 class I(int):
3438 def __repr__(self):
3439 return "I(%r)" % int(self)
3440 def __add__(self, other):
3441 return I(int(self) + int(other))
3442 __radd__ = __add__
3443 def __pow__(self, other, mod=None):
3444 if mod is None:
3445 return I(pow(int(self), int(other)))
3446 else:
3447 return I(pow(int(self), int(other), int(mod)))
3448 def __rpow__(self, other, mod=None):
3449 if mod is None:
3450 return I(pow(int(other), int(self), mod))
3451 else:
3452 return I(pow(int(other), int(self), int(mod)))
3453
3454 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3455 self.assertEqual(repr(I(1) + 2), "I(3)")
3456 self.assertEqual(repr(1 + I(2)), "I(3)")
3457 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3458 self.assertEqual(repr(2 ** I(3)), "I(8)")
3459 self.assertEqual(repr(I(2) ** 3), "I(8)")
3460 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3461 class S(str):
3462 def __eq__(self, other):
3463 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003464 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003465
3466 def test_subclass_propagation(self):
3467 # Testing propagation of slot functions to subclasses...
3468 class A(object):
3469 pass
3470 class B(A):
3471 pass
3472 class C(A):
3473 pass
3474 class D(B, C):
3475 pass
3476 d = D()
3477 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3478 A.__hash__ = lambda self: 42
3479 self.assertEqual(hash(d), 42)
3480 C.__hash__ = lambda self: 314
3481 self.assertEqual(hash(d), 314)
3482 B.__hash__ = lambda self: 144
3483 self.assertEqual(hash(d), 144)
3484 D.__hash__ = lambda self: 100
3485 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003486 D.__hash__ = None
3487 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003488 del D.__hash__
3489 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003490 B.__hash__ = None
3491 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003492 del B.__hash__
3493 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003494 C.__hash__ = None
3495 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003496 del C.__hash__
3497 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003498 A.__hash__ = None
3499 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003500 del A.__hash__
3501 self.assertEqual(hash(d), orig_hash)
3502 d.foo = 42
3503 d.bar = 42
3504 self.assertEqual(d.foo, 42)
3505 self.assertEqual(d.bar, 42)
3506 def __getattribute__(self, name):
3507 if name == "foo":
3508 return 24
3509 return object.__getattribute__(self, name)
3510 A.__getattribute__ = __getattribute__
3511 self.assertEqual(d.foo, 24)
3512 self.assertEqual(d.bar, 42)
3513 def __getattr__(self, name):
3514 if name in ("spam", "foo", "bar"):
3515 return "hello"
3516 raise AttributeError, name
3517 B.__getattr__ = __getattr__
3518 self.assertEqual(d.spam, "hello")
3519 self.assertEqual(d.foo, 24)
3520 self.assertEqual(d.bar, 42)
3521 del A.__getattribute__
3522 self.assertEqual(d.foo, 42)
3523 del d.foo
3524 self.assertEqual(d.foo, "hello")
3525 self.assertEqual(d.bar, 42)
3526 del B.__getattr__
3527 try:
3528 d.foo
3529 except AttributeError:
3530 pass
3531 else:
3532 self.fail("d.foo should be undefined now")
3533
3534 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003535 class A(object):
3536 pass
3537 class B(A):
3538 pass
3539 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003540 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003541 A.__setitem__ = lambda *a: None # crash
3542
3543 def test_buffer_inheritance(self):
3544 # Testing that buffer interface is inherited ...
3545
3546 import binascii
3547 # SF bug [#470040] ParseTuple t# vs subclasses.
3548
3549 class MyStr(str):
3550 pass
3551 base = 'abc'
3552 m = MyStr(base)
3553 # b2a_hex uses the buffer interface to get its argument's value, via
3554 # PyArg_ParseTuple 't#' code.
3555 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3556
3557 # It's not clear that unicode will continue to support the character
3558 # buffer interface, and this test will fail if that's taken away.
3559 class MyUni(unicode):
3560 pass
3561 base = u'abc'
3562 m = MyUni(base)
3563 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3564
3565 class MyInt(int):
3566 pass
3567 m = MyInt(42)
3568 try:
3569 binascii.b2a_hex(m)
3570 self.fail('subclass of int should not have a buffer interface')
3571 except TypeError:
3572 pass
3573
3574 def test_str_of_str_subclass(self):
3575 # Testing __str__ defined in subclass of str ...
3576 import binascii
3577 import cStringIO
3578
3579 class octetstring(str):
3580 def __str__(self):
3581 return binascii.b2a_hex(self)
3582 def __repr__(self):
3583 return self + " repr"
3584
3585 o = octetstring('A')
3586 self.assertEqual(type(o), octetstring)
3587 self.assertEqual(type(str(o)), str)
3588 self.assertEqual(type(repr(o)), str)
3589 self.assertEqual(ord(o), 0x41)
3590 self.assertEqual(str(o), '41')
3591 self.assertEqual(repr(o), 'A repr')
3592 self.assertEqual(o.__str__(), '41')
3593 self.assertEqual(o.__repr__(), 'A repr')
3594
3595 capture = cStringIO.StringIO()
3596 # Calling str() or not exercises different internal paths.
3597 print >> capture, o
3598 print >> capture, str(o)
3599 self.assertEqual(capture.getvalue(), '41\n41\n')
3600 capture.close()
3601
3602 def test_keyword_arguments(self):
3603 # Testing keyword arguments to __init__, __call__...
3604 def f(a): return a
3605 self.assertEqual(f.__call__(a=42), 42)
3606 a = []
3607 list.__init__(a, sequence=[0, 1, 2])
3608 self.assertEqual(a, [0, 1, 2])
3609
3610 def test_recursive_call(self):
3611 # Testing recursive __call__() by setting to instance of class...
3612 class A(object):
3613 pass
3614
3615 A.__call__ = A()
3616 try:
3617 A()()
3618 except RuntimeError:
3619 pass
3620 else:
3621 self.fail("Recursion limit should have been reached for __call__()")
3622
3623 def test_delete_hook(self):
3624 # Testing __del__ hook...
3625 log = []
3626 class C(object):
3627 def __del__(self):
3628 log.append(1)
3629 c = C()
3630 self.assertEqual(log, [])
3631 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003632 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003633 self.assertEqual(log, [1])
3634
3635 class D(object): pass
3636 d = D()
3637 try: del d[0]
3638 except TypeError: pass
3639 else: self.fail("invalid del() didn't raise TypeError")
3640
3641 def test_hash_inheritance(self):
3642 # Testing hash of mutable subclasses...
3643
3644 class mydict(dict):
3645 pass
3646 d = mydict()
3647 try:
3648 hash(d)
3649 except TypeError:
3650 pass
3651 else:
3652 self.fail("hash() of dict subclass should fail")
3653
3654 class mylist(list):
3655 pass
3656 d = mylist()
3657 try:
3658 hash(d)
3659 except TypeError:
3660 pass
3661 else:
3662 self.fail("hash() of list subclass should fail")
3663
3664 def test_str_operations(self):
3665 try: 'a' + 5
3666 except TypeError: pass
3667 else: self.fail("'' + 5 doesn't raise TypeError")
3668
3669 try: ''.split('')
3670 except ValueError: pass
3671 else: self.fail("''.split('') doesn't raise ValueError")
3672
3673 try: ''.join([0])
3674 except TypeError: pass
3675 else: self.fail("''.join([0]) doesn't raise TypeError")
3676
3677 try: ''.rindex('5')
3678 except ValueError: pass
3679 else: self.fail("''.rindex('5') doesn't raise ValueError")
3680
3681 try: '%(n)s' % None
3682 except TypeError: pass
3683 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3684
3685 try: '%(n' % {}
3686 except ValueError: pass
3687 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3688
3689 try: '%*s' % ('abc')
3690 except TypeError: pass
3691 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3692
3693 try: '%*.*s' % ('abc', 5)
3694 except TypeError: pass
3695 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3696
3697 try: '%s' % (1, 2)
3698 except TypeError: pass
3699 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3700
3701 try: '%' % None
3702 except ValueError: pass
3703 else: self.fail("'%' % None doesn't raise ValueError")
3704
3705 self.assertEqual('534253'.isdigit(), 1)
3706 self.assertEqual('534253x'.isdigit(), 0)
3707 self.assertEqual('%c' % 5, '\x05')
3708 self.assertEqual('%c' % '5', '5')
3709
3710 def test_deepcopy_recursive(self):
3711 # Testing deepcopy of recursive objects...
3712 class Node:
3713 pass
3714 a = Node()
3715 b = Node()
3716 a.b = b
3717 b.a = a
3718 z = deepcopy(a) # This blew up before
3719
3720 def test_unintialized_modules(self):
3721 # Testing uninitialized module objects...
3722 from types import ModuleType as M
3723 m = M.__new__(M)
3724 str(m)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003725 self.assertNotHasAttr(m, "__name__")
3726 self.assertNotHasAttr(m, "__file__")
3727 self.assertNotHasAttr(m, "foo")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003728 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003729 m.foo = 1
3730 self.assertEqual(m.__dict__, {"foo": 1})
3731
3732 def test_funny_new(self):
3733 # Testing __new__ returning something unexpected...
3734 class C(object):
3735 def __new__(cls, arg):
3736 if isinstance(arg, str): return [1, 2, 3]
3737 elif isinstance(arg, int): return object.__new__(D)
3738 else: return object.__new__(cls)
3739 class D(C):
3740 def __init__(self, arg):
3741 self.foo = arg
3742 self.assertEqual(C("1"), [1, 2, 3])
3743 self.assertEqual(D("1"), [1, 2, 3])
3744 d = D(None)
3745 self.assertEqual(d.foo, None)
3746 d = C(1)
3747 self.assertEqual(isinstance(d, D), True)
3748 self.assertEqual(d.foo, 1)
3749 d = D(1)
3750 self.assertEqual(isinstance(d, D), True)
3751 self.assertEqual(d.foo, 1)
3752
3753 def test_imul_bug(self):
3754 # Testing for __imul__ problems...
3755 # SF bug 544647
3756 class C(object):
3757 def __imul__(self, other):
3758 return (self, other)
3759 x = C()
3760 y = x
3761 y *= 1.0
3762 self.assertEqual(y, (x, 1.0))
3763 y = x
3764 y *= 2
3765 self.assertEqual(y, (x, 2))
3766 y = x
3767 y *= 3L
3768 self.assertEqual(y, (x, 3L))
3769 y = x
3770 y *= 1L<<100
3771 self.assertEqual(y, (x, 1L<<100))
3772 y = x
3773 y *= None
3774 self.assertEqual(y, (x, None))
3775 y = x
3776 y *= "foo"
3777 self.assertEqual(y, (x, "foo"))
3778
3779 def test_copy_setstate(self):
3780 # Testing that copy.*copy() correctly uses __setstate__...
3781 import copy
3782 class C(object):
3783 def __init__(self, foo=None):
3784 self.foo = foo
3785 self.__foo = foo
3786 def setfoo(self, foo=None):
3787 self.foo = foo
3788 def getfoo(self):
3789 return self.__foo
3790 def __getstate__(self):
3791 return [self.foo]
3792 def __setstate__(self_, lst):
3793 self.assertEqual(len(lst), 1)
3794 self_.__foo = self_.foo = lst[0]
3795 a = C(42)
3796 a.setfoo(24)
3797 self.assertEqual(a.foo, 24)
3798 self.assertEqual(a.getfoo(), 42)
3799 b = copy.copy(a)
3800 self.assertEqual(b.foo, 24)
3801 self.assertEqual(b.getfoo(), 24)
3802 b = copy.deepcopy(a)
3803 self.assertEqual(b.foo, 24)
3804 self.assertEqual(b.getfoo(), 24)
3805
3806 def test_slices(self):
3807 # Testing cases with slices and overridden __getitem__ ...
3808
3809 # Strings
3810 self.assertEqual("hello"[:4], "hell")
3811 self.assertEqual("hello"[slice(4)], "hell")
3812 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3813 class S(str):
3814 def __getitem__(self, x):
3815 return str.__getitem__(self, x)
3816 self.assertEqual(S("hello")[:4], "hell")
3817 self.assertEqual(S("hello")[slice(4)], "hell")
3818 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3819 # Tuples
3820 self.assertEqual((1,2,3)[:2], (1,2))
3821 self.assertEqual((1,2,3)[slice(2)], (1,2))
3822 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3823 class T(tuple):
3824 def __getitem__(self, x):
3825 return tuple.__getitem__(self, x)
3826 self.assertEqual(T((1,2,3))[:2], (1,2))
3827 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3828 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3829 # Lists
3830 self.assertEqual([1,2,3][:2], [1,2])
3831 self.assertEqual([1,2,3][slice(2)], [1,2])
3832 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3833 class L(list):
3834 def __getitem__(self, x):
3835 return list.__getitem__(self, x)
3836 self.assertEqual(L([1,2,3])[:2], [1,2])
3837 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3838 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3839 # Now do lists and __setitem__
3840 a = L([1,2,3])
3841 a[slice(1, 3)] = [3,2]
3842 self.assertEqual(a, [1,3,2])
3843 a[slice(0, 2, 1)] = [3,1]
3844 self.assertEqual(a, [3,1,2])
3845 a.__setitem__(slice(1, 3), [2,1])
3846 self.assertEqual(a, [3,2,1])
3847 a.__setitem__(slice(0, 2, 1), [2,3])
3848 self.assertEqual(a, [2,3,1])
3849
3850 def test_subtype_resurrection(self):
3851 # Testing resurrection of new-style instance...
3852
3853 class C(object):
3854 container = []
3855
3856 def __del__(self):
3857 # resurrect the instance
3858 C.container.append(self)
3859
3860 c = C()
3861 c.attr = 42
3862
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003863 # The most interesting thing here is whether this blows up, due to
3864 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3865 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003866 del c
3867
3868 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003869 # the last container slot works: that will attempt to delete c again,
3870 # which will cause c to get appended back to the container again
3871 # "during" the del. (On non-CPython implementations, however, __del__
3872 # is typically not called again.)
3873 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003874 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003875 del C.container[-1]
3876 if test_support.check_impl_detail():
3877 test_support.gc_collect()
3878 self.assertEqual(len(C.container), 1)
3879 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003880
3881 # Make c mortal again, so that the test framework with -l doesn't report
3882 # it as a leak.
3883 del C.__del__
3884
3885 def test_slots_trash(self):
3886 # Testing slot trash...
3887 # Deallocating deeply nested slotted trash caused stack overflows
3888 class trash(object):
3889 __slots__ = ['x']
3890 def __init__(self, x):
3891 self.x = x
3892 o = None
3893 for i in xrange(50000):
3894 o = trash(o)
3895 del o
3896
3897 def test_slots_multiple_inheritance(self):
3898 # SF bug 575229, multiple inheritance w/ slots dumps core
3899 class A(object):
3900 __slots__=()
3901 class B(object):
3902 pass
3903 class C(A,B) :
3904 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003905 if test_support.check_impl_detail():
3906 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003907 self.assertHasAttr(C, '__dict__')
3908 self.assertHasAttr(C, '__weakref__')
Georg Brandl48545522008-02-02 10:12:36 +00003909 C().x = 2
3910
3911 def test_rmul(self):
3912 # Testing correct invocation of __rmul__...
3913 # SF patch 592646
3914 class C(object):
3915 def __mul__(self, other):
3916 return "mul"
3917 def __rmul__(self, other):
3918 return "rmul"
3919 a = C()
3920 self.assertEqual(a*2, "mul")
3921 self.assertEqual(a*2.2, "mul")
3922 self.assertEqual(2*a, "rmul")
3923 self.assertEqual(2.2*a, "rmul")
3924
3925 def test_ipow(self):
3926 # Testing correct invocation of __ipow__...
3927 # [SF bug 620179]
3928 class C(object):
3929 def __ipow__(self, other):
3930 pass
3931 a = C()
3932 a **= 2
3933
3934 def test_mutable_bases(self):
3935 # Testing mutable bases...
3936
3937 # stuff that should work:
3938 class C(object):
3939 pass
3940 class C2(object):
3941 def __getattribute__(self, attr):
3942 if attr == 'a':
3943 return 2
3944 else:
3945 return super(C2, self).__getattribute__(attr)
3946 def meth(self):
3947 return 1
3948 class D(C):
3949 pass
3950 class E(D):
3951 pass
3952 d = D()
3953 e = E()
3954 D.__bases__ = (C,)
3955 D.__bases__ = (C2,)
3956 self.assertEqual(d.meth(), 1)
3957 self.assertEqual(e.meth(), 1)
3958 self.assertEqual(d.a, 2)
3959 self.assertEqual(e.a, 2)
3960 self.assertEqual(C2.__subclasses__(), [D])
3961
Georg Brandl48545522008-02-02 10:12:36 +00003962 try:
3963 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003964 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003965 pass
3966 else:
3967 self.fail("shouldn't be able to delete .__bases__")
3968
3969 try:
3970 D.__bases__ = ()
3971 except TypeError, msg:
3972 if str(msg) == "a new-style class can't have only classic bases":
3973 self.fail("wrong error message for .__bases__ = ()")
3974 else:
3975 self.fail("shouldn't be able to set .__bases__ to ()")
3976
3977 try:
3978 D.__bases__ = (D,)
3979 except TypeError:
3980 pass
3981 else:
3982 # actually, we'll have crashed by here...
3983 self.fail("shouldn't be able to create inheritance cycles")
3984
3985 try:
3986 D.__bases__ = (C, C)
3987 except TypeError:
3988 pass
3989 else:
3990 self.fail("didn't detect repeated base classes")
3991
3992 try:
3993 D.__bases__ = (E,)
3994 except TypeError:
3995 pass
3996 else:
3997 self.fail("shouldn't be able to create inheritance cycles")
3998
3999 # let's throw a classic class into the mix:
4000 class Classic:
4001 def meth2(self):
4002 return 3
4003
4004 D.__bases__ = (C, Classic)
4005
4006 self.assertEqual(d.meth2(), 3)
4007 self.assertEqual(e.meth2(), 3)
4008 try:
4009 d.a
4010 except AttributeError:
4011 pass
4012 else:
4013 self.fail("attribute should have vanished")
4014
4015 try:
4016 D.__bases__ = (Classic,)
4017 except TypeError:
4018 pass
4019 else:
4020 self.fail("new-style class must have a new-style base")
4021
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004022 def test_builtin_bases(self):
4023 # Make sure all the builtin types can have their base queried without
4024 # segfaulting. See issue #5787.
4025 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
4026 if isinstance(tp, type)]
4027 for tp in builtin_types:
4028 object.__getattribute__(tp, "__bases__")
4029 if tp is not object:
4030 self.assertEqual(len(tp.__bases__), 1, tp)
4031
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00004032 class L(list):
4033 pass
4034
4035 class C(object):
4036 pass
4037
4038 class D(C):
4039 pass
4040
4041 try:
4042 L.__bases__ = (dict,)
4043 except TypeError:
4044 pass
4045 else:
4046 self.fail("shouldn't turn list subclass into dict subclass")
4047
4048 try:
4049 list.__bases__ = (dict,)
4050 except TypeError:
4051 pass
4052 else:
4053 self.fail("shouldn't be able to assign to list.__bases__")
4054
4055 try:
4056 D.__bases__ = (C, list)
4057 except TypeError:
4058 pass
4059 else:
4060 assert 0, "best_base calculation found wanting"
4061
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004062
Georg Brandl48545522008-02-02 10:12:36 +00004063 def test_mutable_bases_with_failing_mro(self):
4064 # Testing mutable bases with failing mro...
4065 class WorkOnce(type):
4066 def __new__(self, name, bases, ns):
4067 self.flag = 0
4068 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4069 def mro(self):
4070 if self.flag > 0:
4071 raise RuntimeError, "bozo"
4072 else:
4073 self.flag += 1
4074 return type.mro(self)
4075
4076 class WorkAlways(type):
4077 def mro(self):
4078 # this is here to make sure that .mro()s aren't called
4079 # with an exception set (which was possible at one point).
4080 # An error message will be printed in a debug build.
4081 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004082 return type.mro(self)
4083
Georg Brandl48545522008-02-02 10:12:36 +00004084 class C(object):
4085 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004086
Georg Brandl48545522008-02-02 10:12:36 +00004087 class C2(object):
4088 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004089
Georg Brandl48545522008-02-02 10:12:36 +00004090 class D(C):
4091 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004092
Georg Brandl48545522008-02-02 10:12:36 +00004093 class E(D):
4094 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004095
Georg Brandl48545522008-02-02 10:12:36 +00004096 class F(D):
4097 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004098
Georg Brandl48545522008-02-02 10:12:36 +00004099 class G(D):
4100 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004101
Georg Brandl48545522008-02-02 10:12:36 +00004102 # Immediate subclasses have their mro's adjusted in alphabetical
4103 # order, so E's will get adjusted before adjusting F's fails. We
4104 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004105
Georg Brandl48545522008-02-02 10:12:36 +00004106 E_mro_before = E.__mro__
4107 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004108
Armin Rigofd163f92005-12-29 15:59:19 +00004109 try:
Georg Brandl48545522008-02-02 10:12:36 +00004110 D.__bases__ = (C2,)
4111 except RuntimeError:
4112 self.assertEqual(E.__mro__, E_mro_before)
4113 self.assertEqual(D.__mro__, D_mro_before)
4114 else:
4115 self.fail("exception not propagated")
4116
4117 def test_mutable_bases_catch_mro_conflict(self):
4118 # Testing mutable bases catch mro conflict...
4119 class A(object):
4120 pass
4121
4122 class B(object):
4123 pass
4124
4125 class C(A, B):
4126 pass
4127
4128 class D(A, B):
4129 pass
4130
4131 class E(C, D):
4132 pass
4133
4134 try:
4135 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004136 except TypeError:
4137 pass
4138 else:
Georg Brandl48545522008-02-02 10:12:36 +00004139 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004140
Georg Brandl48545522008-02-02 10:12:36 +00004141 def test_mutable_names(self):
4142 # Testing mutable names...
4143 class C(object):
4144 pass
4145
4146 # C.__module__ could be 'test_descr' or '__main__'
4147 mod = C.__module__
4148
4149 C.__name__ = 'D'
4150 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4151
4152 C.__name__ = 'D.E'
4153 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4154
Mark Dickinsonf794b142013-04-13 15:19:05 +01004155 def test_evil_type_name(self):
4156 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4157 # execution while the type structure was not in a sane state, and a
4158 # possible segmentation fault as a result. See bug #16447.
4159 class Nasty(str):
4160 def __del__(self):
4161 C.__name__ = "other"
4162
4163 class C(object):
4164 pass
4165
4166 C.__name__ = Nasty("abc")
4167 C.__name__ = "normal"
4168
Georg Brandl48545522008-02-02 10:12:36 +00004169 def test_subclass_right_op(self):
4170 # Testing correct dispatch of subclass overloading __r<op>__...
4171
4172 # This code tests various cases where right-dispatch of a subclass
4173 # should be preferred over left-dispatch of a base class.
4174
4175 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4176
4177 class B(int):
4178 def __floordiv__(self, other):
4179 return "B.__floordiv__"
4180 def __rfloordiv__(self, other):
4181 return "B.__rfloordiv__"
4182
4183 self.assertEqual(B(1) // 1, "B.__floordiv__")
4184 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4185
4186 # Case 2: subclass of object; this is just the baseline for case 3
4187
4188 class C(object):
4189 def __floordiv__(self, other):
4190 return "C.__floordiv__"
4191 def __rfloordiv__(self, other):
4192 return "C.__rfloordiv__"
4193
4194 self.assertEqual(C() // 1, "C.__floordiv__")
4195 self.assertEqual(1 // C(), "C.__rfloordiv__")
4196
4197 # Case 3: subclass of new-style class; here it gets interesting
4198
4199 class D(C):
4200 def __floordiv__(self, other):
4201 return "D.__floordiv__"
4202 def __rfloordiv__(self, other):
4203 return "D.__rfloordiv__"
4204
4205 self.assertEqual(D() // C(), "D.__floordiv__")
4206 self.assertEqual(C() // D(), "D.__rfloordiv__")
4207
4208 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4209
4210 class E(C):
4211 pass
4212
4213 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4214
4215 self.assertEqual(E() // 1, "C.__floordiv__")
4216 self.assertEqual(1 // E(), "C.__rfloordiv__")
4217 self.assertEqual(E() // C(), "C.__floordiv__")
4218 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4219
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004220 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004221 def test_meth_class_get(self):
4222 # Testing __get__ method of METH_CLASS C methods...
4223 # Full coverage of descrobject.c::classmethod_get()
4224
4225 # Baseline
4226 arg = [1, 2, 3]
4227 res = {1: None, 2: None, 3: None}
4228 self.assertEqual(dict.fromkeys(arg), res)
4229 self.assertEqual({}.fromkeys(arg), res)
4230
4231 # Now get the descriptor
4232 descr = dict.__dict__["fromkeys"]
4233
4234 # More baseline using the descriptor directly
4235 self.assertEqual(descr.__get__(None, dict)(arg), res)
4236 self.assertEqual(descr.__get__({})(arg), res)
4237
4238 # Now check various error cases
4239 try:
4240 descr.__get__(None, None)
4241 except TypeError:
4242 pass
4243 else:
4244 self.fail("shouldn't have allowed descr.__get__(None, None)")
4245 try:
4246 descr.__get__(42)
4247 except TypeError:
4248 pass
4249 else:
4250 self.fail("shouldn't have allowed descr.__get__(42)")
4251 try:
4252 descr.__get__(None, 42)
4253 except TypeError:
4254 pass
4255 else:
4256 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4257 try:
4258 descr.__get__(None, int)
4259 except TypeError:
4260 pass
4261 else:
4262 self.fail("shouldn't have allowed descr.__get__(None, int)")
4263
4264 def test_isinst_isclass(self):
4265 # Testing proxy isinstance() and isclass()...
4266 class Proxy(object):
4267 def __init__(self, obj):
4268 self.__obj = obj
4269 def __getattribute__(self, name):
4270 if name.startswith("_Proxy__"):
4271 return object.__getattribute__(self, name)
4272 else:
4273 return getattr(self.__obj, name)
4274 # Test with a classic class
4275 class C:
4276 pass
4277 a = C()
4278 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004279 self.assertIsInstance(a, C) # Baseline
4280 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004281 # Test with a classic subclass
4282 class D(C):
4283 pass
4284 a = D()
4285 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004286 self.assertIsInstance(a, C) # Baseline
4287 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004288 # Test with a new-style class
4289 class C(object):
4290 pass
4291 a = C()
4292 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004293 self.assertIsInstance(a, C) # Baseline
4294 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004295 # Test with a new-style subclass
4296 class D(C):
4297 pass
4298 a = D()
4299 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004300 self.assertIsInstance(a, C) # Baseline
4301 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004302
4303 def test_proxy_super(self):
4304 # Testing super() for a proxy object...
4305 class Proxy(object):
4306 def __init__(self, obj):
4307 self.__obj = obj
4308 def __getattribute__(self, name):
4309 if name.startswith("_Proxy__"):
4310 return object.__getattribute__(self, name)
4311 else:
4312 return getattr(self.__obj, name)
4313
4314 class B(object):
4315 def f(self):
4316 return "B.f"
4317
4318 class C(B):
4319 def f(self):
4320 return super(C, self).f() + "->C.f"
4321
4322 obj = C()
4323 p = Proxy(obj)
4324 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4325
4326 def test_carloverre(self):
4327 # Testing prohibition of Carlo Verre's hack...
4328 try:
4329 object.__setattr__(str, "foo", 42)
4330 except TypeError:
4331 pass
4332 else:
Ezio Melottic2077b02011-03-16 12:34:31 +02004333 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl48545522008-02-02 10:12:36 +00004334 try:
4335 object.__delattr__(str, "lower")
4336 except TypeError:
4337 pass
4338 else:
4339 self.fail("Carlo Verre __delattr__ succeeded!")
4340
4341 def test_weakref_segfault(self):
4342 # Testing weakref segfault...
4343 # SF 742911
4344 import weakref
4345
4346 class Provoker:
4347 def __init__(self, referrent):
4348 self.ref = weakref.ref(referrent)
4349
4350 def __del__(self):
4351 x = self.ref()
4352
4353 class Oops(object):
4354 pass
4355
4356 o = Oops()
4357 o.whatever = Provoker(o)
4358 del o
4359
4360 def test_wrapper_segfault(self):
4361 # SF 927248: deeply nested wrappers could cause stack overflow
4362 f = lambda:None
4363 for i in xrange(1000000):
4364 f = f.__call__
4365 f = None
4366
4367 def test_file_fault(self):
4368 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004369 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004370 class StdoutGuard:
4371 def __getattr__(self, attr):
4372 sys.stdout = sys.__stdout__
4373 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4374 sys.stdout = StdoutGuard()
4375 try:
4376 print "Oops!"
4377 except RuntimeError:
4378 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004379 finally:
4380 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004381
4382 def test_vicious_descriptor_nonsense(self):
4383 # Testing vicious_descriptor_nonsense...
4384
4385 # A potential segfault spotted by Thomas Wouters in mail to
4386 # python-dev 2003-04-17, turned into an example & fixed by Michael
4387 # Hudson just less than four months later...
4388
4389 class Evil(object):
4390 def __hash__(self):
4391 return hash('attr')
4392 def __eq__(self, other):
4393 del C.attr
4394 return 0
4395
4396 class Descr(object):
4397 def __get__(self, ob, type=None):
4398 return 1
4399
4400 class C(object):
4401 attr = Descr()
4402
4403 c = C()
4404 c.__dict__[Evil()] = 0
4405
4406 self.assertEqual(c.attr, 1)
4407 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004408 test_support.gc_collect()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004409 self.assertNotHasAttr(c, 'attr')
Georg Brandl48545522008-02-02 10:12:36 +00004410
4411 def test_init(self):
4412 # SF 1155938
4413 class Foo(object):
4414 def __init__(self):
4415 return 10
4416 try:
4417 Foo()
4418 except TypeError:
4419 pass
4420 else:
4421 self.fail("did not test __init__() for None return")
4422
4423 def test_method_wrapper(self):
4424 # Testing method-wrapper objects...
4425 # <type 'method-wrapper'> did not support any reflection before 2.5
4426
4427 l = []
4428 self.assertEqual(l.__add__, l.__add__)
4429 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004430 self.assertNotEqual(l.__add__, [5].__add__)
4431 self.assertNotEqual(l.__add__, l.__mul__)
4432 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004433 if hasattr(l.__add__, '__self__'):
4434 # CPython
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004435 self.assertIs(l.__add__.__self__, l)
4436 self.assertIs(l.__add__.__objclass__, list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004437 else:
4438 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004439 self.assertIs(l.__add__.im_self, l)
4440 self.assertIs(l.__add__.im_class, list)
Georg Brandl48545522008-02-02 10:12:36 +00004441 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4442 try:
4443 hash(l.__add__)
4444 except TypeError:
4445 pass
4446 else:
4447 self.fail("no TypeError from hash([].__add__)")
4448
4449 t = ()
4450 t += (7,)
4451 self.assertEqual(t.__add__, (7,).__add__)
4452 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4453
4454 def test_not_implemented(self):
4455 # Testing NotImplemented...
4456 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004457 import operator
4458
4459 def specialmethod(self, other):
4460 return NotImplemented
4461
4462 def check(expr, x, y):
4463 try:
4464 exec expr in {'x': x, 'y': y, 'operator': operator}
4465 except TypeError:
4466 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004467 else:
Georg Brandl48545522008-02-02 10:12:36 +00004468 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004469
Georg Brandl48545522008-02-02 10:12:36 +00004470 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4471 # TypeErrors
4472 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4473 # ValueErrors instead of TypeErrors
4474 for metaclass in [type, types.ClassType]:
4475 for name, expr, iexpr in [
4476 ('__add__', 'x + y', 'x += y'),
4477 ('__sub__', 'x - y', 'x -= y'),
4478 ('__mul__', 'x * y', 'x *= y'),
4479 ('__truediv__', 'operator.truediv(x, y)', None),
4480 ('__floordiv__', 'operator.floordiv(x, y)', None),
4481 ('__div__', 'x / y', 'x /= y'),
4482 ('__mod__', 'x % y', 'x %= y'),
4483 ('__divmod__', 'divmod(x, y)', None),
4484 ('__pow__', 'x ** y', 'x **= y'),
4485 ('__lshift__', 'x << y', 'x <<= y'),
4486 ('__rshift__', 'x >> y', 'x >>= y'),
4487 ('__and__', 'x & y', 'x &= y'),
4488 ('__or__', 'x | y', 'x |= y'),
4489 ('__xor__', 'x ^ y', 'x ^= y'),
4490 ('__coerce__', 'coerce(x, y)', None)]:
4491 if name == '__coerce__':
4492 rname = name
4493 else:
4494 rname = '__r' + name[2:]
4495 A = metaclass('A', (), {name: specialmethod})
4496 B = metaclass('B', (), {rname: specialmethod})
4497 a = A()
4498 b = B()
4499 check(expr, a, a)
4500 check(expr, a, b)
4501 check(expr, b, a)
4502 check(expr, b, b)
4503 check(expr, a, N1)
4504 check(expr, a, N2)
4505 check(expr, N1, b)
4506 check(expr, N2, b)
4507 if iexpr:
4508 check(iexpr, a, a)
4509 check(iexpr, a, b)
4510 check(iexpr, b, a)
4511 check(iexpr, b, b)
4512 check(iexpr, a, N1)
4513 check(iexpr, a, N2)
4514 iname = '__i' + name[2:]
4515 C = metaclass('C', (), {iname: specialmethod})
4516 c = C()
4517 check(iexpr, c, a)
4518 check(iexpr, c, b)
4519 check(iexpr, c, N1)
4520 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004521
Georg Brandl48545522008-02-02 10:12:36 +00004522 def test_assign_slice(self):
4523 # ceval.c's assign_slice used to check for
4524 # tp->tp_as_sequence->sq_slice instead of
4525 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004526
Georg Brandl48545522008-02-02 10:12:36 +00004527 class C(object):
4528 def __setslice__(self, start, stop, value):
4529 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004530
Georg Brandl48545522008-02-02 10:12:36 +00004531 c = C()
4532 c[1:2] = 3
4533 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004534
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004535 def test_set_and_no_get(self):
4536 # See
4537 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4538 class Descr(object):
4539
4540 def __init__(self, name):
4541 self.name = name
4542
4543 def __set__(self, obj, value):
4544 obj.__dict__[self.name] = value
4545 descr = Descr("a")
4546
4547 class X(object):
4548 a = descr
4549
4550 x = X()
4551 self.assertIs(x.a, descr)
4552 x.a = 42
4553 self.assertEqual(x.a, 42)
4554
Benjamin Peterson42d59472010-02-06 20:14:10 +00004555 # Also check type_getattro for correctness.
4556 class Meta(type):
4557 pass
4558 class X(object):
4559 __metaclass__ = Meta
4560 X.a = 42
4561 Meta.a = Descr("a")
4562 self.assertEqual(X.a, 42)
4563
Benjamin Peterson273c2332008-11-17 22:39:09 +00004564 def test_getattr_hooks(self):
4565 # issue 4230
4566
4567 class Descriptor(object):
4568 counter = 0
4569 def __get__(self, obj, objtype=None):
4570 def getter(name):
4571 self.counter += 1
4572 raise AttributeError(name)
4573 return getter
4574
4575 descr = Descriptor()
4576 class A(object):
4577 __getattribute__ = descr
4578 class B(object):
4579 __getattr__ = descr
4580 class C(object):
4581 __getattribute__ = descr
4582 __getattr__ = descr
4583
4584 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004585 self.assertEqual(descr.counter, 1)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004586 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004587 self.assertEqual(descr.counter, 2)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004588 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004589 self.assertEqual(descr.counter, 4)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004590
Benjamin Peterson273c2332008-11-17 22:39:09 +00004591 class EvilGetattribute(object):
4592 # This used to segfault
4593 def __getattr__(self, name):
4594 raise AttributeError(name)
4595 def __getattribute__(self, name):
4596 del EvilGetattribute.__getattr__
4597 for i in range(5):
4598 gc.collect()
4599 raise AttributeError(name)
4600
4601 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4602
Benjamin Peterson6e7832b2012-03-16 09:32:59 -05004603 def test_type___getattribute__(self):
4604 self.assertRaises(TypeError, type.__getattribute__, list, type)
4605
Benjamin Peterson9b911ca2011-01-12 15:49:47 +00004606 def test_abstractmethods(self):
4607 # type pretends not to have __abstractmethods__.
4608 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4609 class meta(type):
4610 pass
4611 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4612 class X(object):
4613 pass
4614 with self.assertRaises(AttributeError):
4615 del X.__abstractmethods__
4616
Victor Stinnere363ec12011-05-01 23:43:37 +02004617 def test_proxy_call(self):
4618 class FakeStr(object):
4619 __class__ = str
4620
4621 fake_str = FakeStr()
4622 # isinstance() reads __class__ on new style classes
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004623 self.assertIsInstance(fake_str, str)
Victor Stinnere363ec12011-05-01 23:43:37 +02004624
4625 # call a method descriptor
4626 with self.assertRaises(TypeError):
4627 str.split(fake_str)
4628
4629 # call a slot wrapper descriptor
4630 with self.assertRaises(TypeError):
4631 str.__add__(fake_str, "abc")
4632
Antoine Pitrou304f0f92011-07-15 21:22:50 +02004633 def test_repr_as_str(self):
4634 # Issue #11603: crash or infinite loop when rebinding __str__ as
4635 # __repr__.
4636 class Foo(object):
4637 pass
4638 Foo.__repr__ = Foo.__str__
4639 foo = Foo()
Benjamin Petersond157a4c2012-04-24 11:06:25 -04004640 self.assertRaises(RuntimeError, str, foo)
4641 self.assertRaises(RuntimeError, repr, foo)
4642
4643 def test_mixing_slot_wrappers(self):
4644 class X(dict):
4645 __setattr__ = dict.__setitem__
4646 x = X()
4647 x.y = 42
4648 self.assertEqual(x["y"], 42)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004649
Benjamin Petersona8d45852012-03-07 18:41:11 -06004650 def test_cycle_through_dict(self):
4651 # See bug #1469629
4652 class X(dict):
4653 def __init__(self):
4654 dict.__init__(self)
4655 self.__dict__ = self
4656 x = X()
4657 x.attr = 42
4658 wr = weakref.ref(x)
4659 del x
4660 test_support.gc_collect()
4661 self.assertIsNone(wr())
4662 for o in gc.get_objects():
4663 self.assertIsNot(type(o), X)
4664
Georg Brandl48545522008-02-02 10:12:36 +00004665class DictProxyTests(unittest.TestCase):
4666 def setUp(self):
4667 class C(object):
4668 def meth(self):
4669 pass
4670 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004671
Raymond Hettingerbf7a2662011-06-30 00:44:36 +01004672 def test_repr(self):
4673 self.assertIn('dict_proxy({', repr(vars(self.C)))
4674 self.assertIn("'meth':", repr(vars(self.C)))
4675
Georg Brandl48545522008-02-02 10:12:36 +00004676 def test_iter_keys(self):
4677 # Testing dict-proxy iterkeys...
4678 keys = [ key for key in self.C.__dict__.iterkeys() ]
4679 keys.sort()
Ezio Melotti2623a372010-11-21 13:34:58 +00004680 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl48545522008-02-02 10:12:36 +00004681 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004682
Georg Brandl48545522008-02-02 10:12:36 +00004683 def test_iter_values(self):
4684 # Testing dict-proxy itervalues...
4685 values = [ values for values in self.C.__dict__.itervalues() ]
4686 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004687
Georg Brandl48545522008-02-02 10:12:36 +00004688 def test_iter_items(self):
4689 # Testing dict-proxy iteritems...
4690 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4691 keys.sort()
4692 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4693 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004694
Georg Brandl48545522008-02-02 10:12:36 +00004695 def test_dict_type_with_metaclass(self):
4696 # Testing type of __dict__ when __metaclass__ set...
4697 class B(object):
4698 pass
4699 class M(type):
4700 pass
4701 class C:
4702 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4703 __metaclass__ = M
4704 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004705
Guido van Rossum9acc3872008-01-23 23:23:43 +00004706
Georg Brandl48545522008-02-02 10:12:36 +00004707class PTypesLongInitTest(unittest.TestCase):
4708 # This is in its own TestCase so that it can be run before any other tests.
4709 def test_pytype_long_ready(self):
4710 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004711
Georg Brandl48545522008-02-02 10:12:36 +00004712 # This dumps core when SF bug 551412 isn't fixed --
4713 # but only when test_descr.py is run separately.
4714 # (That can't be helped -- as soon as PyType_Ready()
4715 # is called for PyLong_Type, the bug is gone.)
4716 class UserLong(object):
4717 def __pow__(self, *args):
4718 pass
4719 try:
4720 pow(0L, UserLong(), 0L)
4721 except:
4722 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004723
Georg Brandl48545522008-02-02 10:12:36 +00004724 # Another segfault only when run early
4725 # (before PyType_Ready(tuple) is called)
4726 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004727
4728
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004729def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004730 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4731 DeprecationWarning)]
4732 if sys.py3kwarning:
4733 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004734 ("classic (int|long) division", DeprecationWarning),
4735 ("coerce.. not supported", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004736 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4737 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004738 # Run all local test cases, with PTypesLongInitTest first.
4739 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4740 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004742if __name__ == "__main__":
4743 test_main()