blob: 1e63761f6d0d223b634d78429c8f7a0ec3c5a0c0 [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
Serhiy Storchaka7117d352016-12-14 19:48:38 +02006import warnings
Benjamin Petersona8d45852012-03-07 18:41:11 -06007import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +00008
Georg Brandl48545522008-02-02 10:12:36 +00009from copy import deepcopy
10from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Guido van Rossum875eeaa2001-10-11 18:33:53 +000012
Georg Brandl48545522008-02-02 10:12:36 +000013class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000014
Georg Brandl48545522008-02-02 10:12:36 +000015 def __init__(self, *args, **kwargs):
16 unittest.TestCase.__init__(self, *args, **kwargs)
17 self.binops = {
18 'add': '+',
19 'sub': '-',
20 'mul': '*',
21 'div': '/',
22 'divmod': 'divmod',
23 'pow': '**',
24 'lshift': '<<',
25 'rshift': '>>',
26 'and': '&',
27 'xor': '^',
28 'or': '|',
29 'cmp': 'cmp',
30 'lt': '<',
31 'le': '<=',
32 'eq': '==',
33 'ne': '!=',
34 'gt': '>',
35 'ge': '>=',
36 }
Tim Peters3caca232001-12-06 06:23:26 +000037
Georg Brandl48545522008-02-02 10:12:36 +000038 for name, expr in self.binops.items():
39 if expr.islower():
40 expr = expr + "(a, b)"
41 else:
42 expr = 'a %s b' % expr
43 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000044
Georg Brandl48545522008-02-02 10:12:36 +000045 self.unops = {
46 'pos': '+',
47 'neg': '-',
48 'abs': 'abs',
49 'invert': '~',
50 'int': 'int',
51 'long': 'long',
52 'float': 'float',
53 'oct': 'oct',
54 'hex': 'hex',
55 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000056
Georg Brandl48545522008-02-02 10:12:36 +000057 for name, expr in self.unops.items():
58 if expr.islower():
59 expr = expr + "(a)"
60 else:
61 expr = '%s a' % expr
62 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000063
Georg Brandl48545522008-02-02 10:12:36 +000064 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
65 d = {'a': a}
66 self.assertEqual(eval(expr, d), res)
67 t = type(a)
68 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000069
Georg Brandl48545522008-02-02 10:12:36 +000070 # Find method in parent class
71 while meth not in t.__dict__:
72 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000073 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
74 # method object; the getattr() below obtains its underlying function.
75 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000076 self.assertEqual(m(a), res)
77 bm = getattr(a, meth)
78 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000079
Georg Brandl48545522008-02-02 10:12:36 +000080 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
81 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000082
Georg Brandl48545522008-02-02 10:12:36 +000083 # XXX Hack so this passes before 2.3 when -Qnew is specified.
84 if meth == "__div__" and 1/2 == 0.5:
85 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000086
Georg Brandl48545522008-02-02 10:12:36 +000087 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000088
Georg Brandl48545522008-02-02 10:12:36 +000089 self.assertEqual(eval(expr, d), res)
90 t = type(a)
91 m = getattr(t, meth)
92 while meth not in t.__dict__:
93 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000094 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
95 # method object; the getattr() below obtains its underlying function.
96 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000097 self.assertEqual(m(a, b), res)
98 bm = getattr(a, meth)
99 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000100
Georg Brandl48545522008-02-02 10:12:36 +0000101 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
102 d = {'a': a, 'b': b, 'c': c}
103 self.assertEqual(eval(expr, d), res)
104 t = type(a)
105 m = getattr(t, meth)
106 while meth not in t.__dict__:
107 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000108 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
109 # method object; the getattr() below obtains its underlying function.
110 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000111 self.assertEqual(m(a, b, c), res)
112 bm = getattr(a, meth)
113 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114
Georg Brandl48545522008-02-02 10:12:36 +0000115 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
116 d = {'a': deepcopy(a), 'b': b}
117 exec stmt in d
118 self.assertEqual(d['a'], res)
119 t = type(a)
120 m = getattr(t, meth)
121 while meth not in t.__dict__:
122 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000123 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
124 # method object; the getattr() below obtains its underlying function.
125 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000126 d['a'] = deepcopy(a)
127 m(d['a'], b)
128 self.assertEqual(d['a'], res)
129 d['a'] = deepcopy(a)
130 bm = getattr(d['a'], meth)
131 bm(b)
132 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000133
Georg Brandl48545522008-02-02 10:12:36 +0000134 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
135 d = {'a': deepcopy(a), 'b': b, 'c': c}
136 exec stmt in d
137 self.assertEqual(d['a'], res)
138 t = type(a)
139 m = getattr(t, meth)
140 while meth not in t.__dict__:
141 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000142 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
143 # method object; the getattr() below obtains its underlying function.
144 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000145 d['a'] = deepcopy(a)
146 m(d['a'], b, c)
147 self.assertEqual(d['a'], res)
148 d['a'] = deepcopy(a)
149 bm = getattr(d['a'], meth)
150 bm(b, c)
151 self.assertEqual(d['a'], res)
152
153 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
154 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
155 exec stmt in dictionary
156 self.assertEqual(dictionary['a'], res)
157 t = type(a)
158 while meth not in t.__dict__:
159 t = t.__bases__[0]
160 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000161 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
162 # method object; the getattr() below obtains its underlying function.
163 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000164 dictionary['a'] = deepcopy(a)
165 m(dictionary['a'], b, c, d)
166 self.assertEqual(dictionary['a'], res)
167 dictionary['a'] = deepcopy(a)
168 bm = getattr(dictionary['a'], meth)
169 bm(b, c, d)
170 self.assertEqual(dictionary['a'], res)
171
172 def test_lists(self):
173 # Testing list operations...
174 # Asserts are within individual test methods
175 self.binop_test([1], [2], [1,2], "a+b", "__add__")
176 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
177 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
178 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
179 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
180 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
181 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
182 self.unop_test([1,2,3], 3, "len(a)", "__len__")
183 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
184 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
185 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
186 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
187 "__setslice__")
188
189 def test_dicts(self):
190 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000191 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
192 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
193 else:
194 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000195 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
196 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
197 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
198
199 d = {1:2, 3:4}
200 l1 = []
201 for i in d.keys():
202 l1.append(i)
203 l = []
204 for i in iter(d):
205 l.append(i)
206 self.assertEqual(l, l1)
207 l = []
208 for i in d.__iter__():
209 l.append(i)
210 self.assertEqual(l, l1)
211 l = []
212 for i in dict.__iter__(d):
213 l.append(i)
214 self.assertEqual(l, l1)
215 d = {1:2, 3:4}
216 self.unop_test(d, 2, "len(a)", "__len__")
217 self.assertEqual(eval(repr(d), {}), d)
218 self.assertEqual(eval(d.__repr__(), {}), d)
219 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
220 "__setitem__")
221
222 # Tests for unary and binary operators
223 def number_operators(self, a, b, skip=[]):
224 dict = {'a': a, 'b': b}
225
226 for name, expr in self.binops.items():
227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.binop_test(a, b, res, expr, name)
232
233 for name, expr in self.unops.items():
234 if name not in skip:
235 name = "__%s__" % name
236 if hasattr(a, name):
237 res = eval(expr, dict)
238 self.unop_test(a, res, expr, name)
239
240 def test_ints(self):
241 # Testing int operations...
242 self.number_operators(100, 3)
243 # The following crashes in Python 2.2
244 self.assertEqual((1).__nonzero__(), 1)
245 self.assertEqual((0).__nonzero__(), 0)
246 # This returns 'NotImplemented' in Python 2.2
247 class C(int):
248 def __add__(self, other):
249 return NotImplemented
250 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000251 try:
Georg Brandl48545522008-02-02 10:12:36 +0000252 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000253 except TypeError:
254 pass
255 else:
Georg Brandl48545522008-02-02 10:12:36 +0000256 self.fail("NotImplemented should have caused TypeError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000257 try:
Georg Brandl48545522008-02-02 10:12:36 +0000258 C(sys.maxint+1)
259 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000260 pass
261 else:
Georg Brandl48545522008-02-02 10:12:36 +0000262 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000263
Georg Brandl48545522008-02-02 10:12:36 +0000264 def test_longs(self):
265 # Testing long operations...
266 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000267
Georg Brandl48545522008-02-02 10:12:36 +0000268 def test_floats(self):
269 # Testing float operations...
270 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000271
Georg Brandl48545522008-02-02 10:12:36 +0000272 def test_complexes(self):
273 # Testing complex operations...
274 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
275 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000276
Georg Brandl48545522008-02-02 10:12:36 +0000277 class Number(complex):
278 __slots__ = ['prec']
279 def __new__(cls, *args, **kwds):
280 result = complex.__new__(cls, *args)
281 result.prec = kwds.get('prec', 12)
282 return result
283 def __repr__(self):
284 prec = self.prec
285 if self.imag == 0.0:
286 return "%.*g" % (prec, self.real)
287 if self.real == 0.0:
288 return "%.*gj" % (prec, self.imag)
289 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
290 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000291
Georg Brandl48545522008-02-02 10:12:36 +0000292 a = Number(3.14, prec=6)
293 self.assertEqual(repr(a), "3.14")
294 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000295
Georg Brandl48545522008-02-02 10:12:36 +0000296 a = Number(a, prec=2)
297 self.assertEqual(repr(a), "3.1")
298 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000299
Georg Brandl48545522008-02-02 10:12:36 +0000300 a = Number(234.5)
301 self.assertEqual(repr(a), "234.5")
302 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000303
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000304 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000305 def test_spam_lists(self):
306 # Testing spamlist operations...
307 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000308
Georg Brandl48545522008-02-02 10:12:36 +0000309 def spamlist(l, memo=None):
310 import xxsubtype as spam
311 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000312
Georg Brandl48545522008-02-02 10:12:36 +0000313 # This is an ugly hack:
314 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000315
Georg Brandl48545522008-02-02 10:12:36 +0000316 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
317 "__add__")
318 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
319 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
320 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
321 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
322 "__getslice__")
323 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
324 "__iadd__")
325 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
326 "__imul__")
327 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
328 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
329 "__mul__")
330 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
331 "__rmul__")
332 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
333 "__setitem__")
334 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
335 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
336 # Test subclassing
337 class C(spam.spamlist):
338 def foo(self): return 1
339 a = C()
340 self.assertEqual(a, [])
341 self.assertEqual(a.foo(), 1)
342 a.append(100)
343 self.assertEqual(a, [100])
344 self.assertEqual(a.getstate(), 0)
345 a.setstate(42)
346 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000347
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000348 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000349 def test_spam_dicts(self):
350 # Testing spamdict operations...
351 import copy, xxsubtype as spam
352 def spamdict(d, memo=None):
353 import xxsubtype as spam
354 sd = spam.spamdict()
355 for k, v in d.items():
356 sd[k] = v
357 return sd
358 # This is an ugly hack:
359 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000360
Georg Brandl48545522008-02-02 10:12:36 +0000361 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
362 "__cmp__")
363 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
364 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
365 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
366 d = spamdict({1:2,3:4})
367 l1 = []
368 for i in d.keys():
369 l1.append(i)
370 l = []
371 for i in iter(d):
372 l.append(i)
373 self.assertEqual(l, l1)
374 l = []
375 for i in d.__iter__():
376 l.append(i)
377 self.assertEqual(l, l1)
378 l = []
379 for i in type(spamdict({})).__iter__(d):
380 l.append(i)
381 self.assertEqual(l, l1)
382 straightd = {1:2, 3:4}
383 spamd = spamdict(straightd)
384 self.unop_test(spamd, 2, "len(a)", "__len__")
385 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
386 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
387 "a[b]=c", "__setitem__")
388 # Test subclassing
389 class C(spam.spamdict):
390 def foo(self): return 1
391 a = C()
392 self.assertEqual(a.items(), [])
393 self.assertEqual(a.foo(), 1)
394 a['foo'] = 'bar'
395 self.assertEqual(a.items(), [('foo', 'bar')])
396 self.assertEqual(a.getstate(), 0)
397 a.setstate(100)
398 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000399
Georg Brandl48545522008-02-02 10:12:36 +0000400class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000401
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200402 def assertHasAttr(self, obj, name):
403 self.assertTrue(hasattr(obj, name),
404 '%r has no attribute %r' % (obj, name))
405
406 def assertNotHasAttr(self, obj, name):
407 self.assertFalse(hasattr(obj, name),
408 '%r has unexpected attribute %r' % (obj, name))
409
Georg Brandl48545522008-02-02 10:12:36 +0000410 def test_python_dicts(self):
411 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000412 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000413 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000414 d = dict()
415 self.assertEqual(d, {})
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200416 self.assertIs(d.__class__, dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000417 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000418 class C(dict):
419 state = -1
420 def __init__(self_local, *a, **kw):
421 if a:
422 self.assertEqual(len(a), 1)
423 self_local.state = a[0]
424 if kw:
425 for k, v in kw.items():
426 self_local[v] = k
427 def __getitem__(self, key):
428 return self.get(key, 0)
429 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000430 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000431 dict.__setitem__(self_local, key, value)
432 def setstate(self, state):
433 self.state = state
434 def getstate(self):
435 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000436 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000437 a1 = C(12)
438 self.assertEqual(a1.state, 12)
439 a2 = C(foo=1, bar=2)
440 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
441 a = C()
442 self.assertEqual(a.state, -1)
443 self.assertEqual(a.getstate(), -1)
444 a.setstate(0)
445 self.assertEqual(a.state, 0)
446 self.assertEqual(a.getstate(), 0)
447 a.setstate(10)
448 self.assertEqual(a.state, 10)
449 self.assertEqual(a.getstate(), 10)
450 self.assertEqual(a[42], 0)
451 a[42] = 24
452 self.assertEqual(a[42], 24)
453 N = 50
454 for i in range(N):
455 a[i] = C()
456 for j in range(N):
457 a[i][j] = i*j
458 for i in range(N):
459 for j in range(N):
460 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000461
Georg Brandl48545522008-02-02 10:12:36 +0000462 def test_python_lists(self):
463 # Testing Python subclass of list...
464 class C(list):
465 def __getitem__(self, i):
466 return list.__getitem__(self, i) + 100
467 def __getslice__(self, i, j):
468 return (i, j)
469 a = C()
470 a.extend([0,1,2])
471 self.assertEqual(a[0], 100)
472 self.assertEqual(a[1], 101)
473 self.assertEqual(a[2], 102)
474 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000475
Georg Brandl48545522008-02-02 10:12:36 +0000476 def test_metaclass(self):
477 # Testing __metaclass__...
478 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000479 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000480 def __init__(self):
481 self.__state = 0
482 def getstate(self):
483 return self.__state
484 def setstate(self, state):
485 self.__state = state
486 a = C()
487 self.assertEqual(a.getstate(), 0)
488 a.setstate(10)
489 self.assertEqual(a.getstate(), 10)
490 class D:
491 class __metaclass__(type):
492 def myself(cls): return cls
493 self.assertEqual(D.myself(), D)
494 d = D()
495 self.assertEqual(d.__class__, D)
496 class M1(type):
497 def __new__(cls, name, bases, dict):
498 dict['__spam__'] = 1
499 return type.__new__(cls, name, bases, dict)
500 class C:
501 __metaclass__ = M1
502 self.assertEqual(C.__spam__, 1)
503 c = C()
504 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000505
Georg Brandl48545522008-02-02 10:12:36 +0000506 class _instance(object):
507 pass
508 class M2(object):
509 @staticmethod
510 def __new__(cls, name, bases, dict):
511 self = object.__new__(cls)
512 self.name = name
513 self.bases = bases
514 self.dict = dict
515 return self
516 def __call__(self):
517 it = _instance()
518 # Early binding of methods
519 for key in self.dict:
520 if key.startswith("__"):
521 continue
522 setattr(it, key, self.dict[key].__get__(it, self))
523 return it
524 class C:
525 __metaclass__ = M2
526 def spam(self):
527 return 42
528 self.assertEqual(C.name, 'C')
529 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000530 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000531 c = C()
532 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000533
Georg Brandl48545522008-02-02 10:12:36 +0000534 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000535
Georg Brandl48545522008-02-02 10:12:36 +0000536 class autosuper(type):
537 # Automatically add __super to the class
538 # This trick only works for dynamic classes
539 def __new__(metaclass, name, bases, dict):
540 cls = super(autosuper, metaclass).__new__(metaclass,
541 name, bases, dict)
542 # Name mangling for __super removes leading underscores
543 while name[:1] == "_":
544 name = name[1:]
545 if name:
546 name = "_%s__super" % name
547 else:
548 name = "__super"
549 setattr(cls, name, super(cls))
550 return cls
551 class A:
552 __metaclass__ = autosuper
553 def meth(self):
554 return "A"
555 class B(A):
556 def meth(self):
557 return "B" + self.__super.meth()
558 class C(A):
559 def meth(self):
560 return "C" + self.__super.meth()
561 class D(C, B):
562 def meth(self):
563 return "D" + self.__super.meth()
564 self.assertEqual(D().meth(), "DCBA")
565 class E(B, C):
566 def meth(self):
567 return "E" + self.__super.meth()
568 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000569
Georg Brandl48545522008-02-02 10:12:36 +0000570 class autoproperty(type):
571 # Automatically create property attributes when methods
572 # named _get_x and/or _set_x are found
573 def __new__(metaclass, name, bases, dict):
574 hits = {}
575 for key, val in dict.iteritems():
576 if key.startswith("_get_"):
577 key = key[5:]
578 get, set = hits.get(key, (None, None))
579 get = val
580 hits[key] = get, set
581 elif key.startswith("_set_"):
582 key = key[5:]
583 get, set = hits.get(key, (None, None))
584 set = val
585 hits[key] = get, set
586 for key, (get, set) in hits.iteritems():
587 dict[key] = property(get, set)
588 return super(autoproperty, metaclass).__new__(metaclass,
589 name, bases, dict)
590 class A:
591 __metaclass__ = autoproperty
592 def _get_x(self):
593 return -self.__x
594 def _set_x(self, x):
595 self.__x = -x
596 a = A()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200597 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +0000598 a.x = 12
599 self.assertEqual(a.x, 12)
600 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000601
Georg Brandl48545522008-02-02 10:12:36 +0000602 class multimetaclass(autoproperty, autosuper):
603 # Merge of multiple cooperating metaclasses
604 pass
605 class A:
606 __metaclass__ = multimetaclass
607 def _get_x(self):
608 return "A"
609 class B(A):
610 def _get_x(self):
611 return "B" + self.__super._get_x()
612 class C(A):
613 def _get_x(self):
614 return "C" + self.__super._get_x()
615 class D(C, B):
616 def _get_x(self):
617 return "D" + self.__super._get_x()
618 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000619
Georg Brandl48545522008-02-02 10:12:36 +0000620 # Make sure type(x) doesn't call x.__class__.__init__
621 class T(type):
622 counter = 0
623 def __init__(self, *args):
624 T.counter += 1
625 class C:
626 __metaclass__ = T
627 self.assertEqual(T.counter, 1)
628 a = C()
629 self.assertEqual(type(a), C)
630 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000631
Georg Brandl48545522008-02-02 10:12:36 +0000632 class C(object): pass
633 c = C()
634 try: c()
635 except TypeError: pass
636 else: self.fail("calling object w/o call method should raise "
637 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000638
Georg Brandl48545522008-02-02 10:12:36 +0000639 # Testing code to find most derived baseclass
640 class A(type):
641 def __new__(*args, **kwargs):
642 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000643
Georg Brandl48545522008-02-02 10:12:36 +0000644 class B(object):
645 pass
646
647 class C(object):
648 __metaclass__ = A
649
650 # The most derived metaclass of D is A rather than type.
651 class D(B, C):
652 pass
653
654 def test_module_subclasses(self):
655 # Testing Python subclass of module...
656 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000657 MT = type(sys)
658 class MM(MT):
659 def __init__(self, name):
660 MT.__init__(self, name)
661 def __getattribute__(self, name):
662 log.append(("getattr", name))
663 return MT.__getattribute__(self, name)
664 def __setattr__(self, name, value):
665 log.append(("setattr", name, value))
666 MT.__setattr__(self, name, value)
667 def __delattr__(self, name):
668 log.append(("delattr", name))
669 MT.__delattr__(self, name)
670 a = MM("a")
671 a.foo = 12
672 x = a.foo
673 del a.foo
674 self.assertEqual(log, [("setattr", "foo", 12),
675 ("getattr", "foo"),
676 ("delattr", "foo")])
677
678 # http://python.org/sf/1174712
679 try:
680 class Module(types.ModuleType, str):
681 pass
682 except TypeError:
683 pass
684 else:
685 self.fail("inheriting from ModuleType and str at the same time "
686 "should fail")
687
Martin Panter65076572016-09-07 12:03:06 +0000688 def test_multiple_inheritance(self):
Georg Brandl48545522008-02-02 10:12:36 +0000689 # Testing multiple inheritance...
690 class C(object):
691 def __init__(self):
692 self.__state = 0
693 def getstate(self):
694 return self.__state
695 def setstate(self, state):
696 self.__state = state
697 a = C()
698 self.assertEqual(a.getstate(), 0)
699 a.setstate(10)
700 self.assertEqual(a.getstate(), 10)
701 class D(dict, C):
702 def __init__(self):
703 type({}).__init__(self)
704 C.__init__(self)
705 d = D()
706 self.assertEqual(d.keys(), [])
707 d["hello"] = "world"
708 self.assertEqual(d.items(), [("hello", "world")])
709 self.assertEqual(d["hello"], "world")
710 self.assertEqual(d.getstate(), 0)
711 d.setstate(10)
712 self.assertEqual(d.getstate(), 10)
713 self.assertEqual(D.__mro__, (D, dict, C, object))
714
715 # SF bug #442833
716 class Node(object):
717 def __int__(self):
718 return int(self.foo())
719 def foo(self):
720 return "23"
721 class Frag(Node, list):
722 def foo(self):
723 return "42"
724 self.assertEqual(Node().__int__(), 23)
725 self.assertEqual(int(Node()), 23)
726 self.assertEqual(Frag().__int__(), 42)
727 self.assertEqual(int(Frag()), 42)
728
729 # MI mixing classic and new-style classes.
730
731 class A:
732 x = 1
733
734 class B(A):
735 pass
736
737 class C(A):
738 x = 2
739
740 class D(B, C):
741 pass
742 self.assertEqual(D.x, 1)
743
744 # Classic MRO is preserved for a classic base class.
745 class E(D, object):
746 pass
747 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
748 self.assertEqual(E.x, 1)
749
750 # But with a mix of classic bases, their MROs are combined using
751 # new-style MRO.
752 class F(B, C, object):
753 pass
754 self.assertEqual(F.__mro__, (F, B, C, A, object))
755 self.assertEqual(F.x, 2)
756
757 # Try something else.
758 class C:
759 def cmethod(self):
760 return "C a"
761 def all_method(self):
762 return "C b"
763
764 class M1(C, object):
765 def m1method(self):
766 return "M1 a"
767 def all_method(self):
768 return "M1 b"
769
770 self.assertEqual(M1.__mro__, (M1, C, object))
771 m = M1()
772 self.assertEqual(m.cmethod(), "C a")
773 self.assertEqual(m.m1method(), "M1 a")
774 self.assertEqual(m.all_method(), "M1 b")
775
776 class D(C):
777 def dmethod(self):
778 return "D a"
779 def all_method(self):
780 return "D b"
781
782 class M2(D, object):
783 def m2method(self):
784 return "M2 a"
785 def all_method(self):
786 return "M2 b"
787
788 self.assertEqual(M2.__mro__, (M2, D, C, object))
789 m = M2()
790 self.assertEqual(m.cmethod(), "C a")
791 self.assertEqual(m.dmethod(), "D a")
792 self.assertEqual(m.m2method(), "M2 a")
793 self.assertEqual(m.all_method(), "M2 b")
794
795 class M3(M1, M2, object):
796 def m3method(self):
797 return "M3 a"
798 def all_method(self):
799 return "M3 b"
800 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
801 m = M3()
802 self.assertEqual(m.cmethod(), "C a")
803 self.assertEqual(m.dmethod(), "D a")
804 self.assertEqual(m.m1method(), "M1 a")
805 self.assertEqual(m.m2method(), "M2 a")
806 self.assertEqual(m.m3method(), "M3 a")
807 self.assertEqual(m.all_method(), "M3 b")
808
809 class Classic:
810 pass
811 try:
812 class New(Classic):
813 __metaclass__ = type
814 except TypeError:
815 pass
816 else:
817 self.fail("new class with only classic bases - shouldn't be")
818
Martin Panter65076572016-09-07 12:03:06 +0000819 def test_diamond_inheritance(self):
Georg Brandl48545522008-02-02 10:12:36 +0000820 # Testing multiple inheritance special cases...
821 class A(object):
822 def spam(self): return "A"
823 self.assertEqual(A().spam(), "A")
824 class B(A):
825 def boo(self): return "B"
826 def spam(self): return "B"
827 self.assertEqual(B().spam(), "B")
828 self.assertEqual(B().boo(), "B")
829 class C(A):
830 def boo(self): return "C"
831 self.assertEqual(C().spam(), "A")
832 self.assertEqual(C().boo(), "C")
833 class D(B, C): pass
834 self.assertEqual(D().spam(), "B")
835 self.assertEqual(D().boo(), "B")
836 self.assertEqual(D.__mro__, (D, B, C, A, object))
837 class E(C, B): pass
838 self.assertEqual(E().spam(), "B")
839 self.assertEqual(E().boo(), "C")
840 self.assertEqual(E.__mro__, (E, C, B, A, object))
841 # MRO order disagreement
842 try:
843 class F(D, E): pass
844 except TypeError:
845 pass
846 else:
847 self.fail("expected MRO order disagreement (F)")
848 try:
849 class G(E, D): pass
850 except TypeError:
851 pass
852 else:
853 self.fail("expected MRO order disagreement (G)")
854
855 # see thread python-dev/2002-October/029035.html
856 def test_ex5_from_c3_switch(self):
857 # Testing ex5 from C3 switch discussion...
858 class A(object): pass
859 class B(object): pass
860 class C(object): pass
861 class X(A): pass
862 class Y(A): pass
863 class Z(X,B,Y,C): pass
864 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
865
866 # see "A Monotonic Superclass Linearization for Dylan",
867 # by Kim Barrett et al. (OOPSLA 1996)
868 def test_monotonicity(self):
869 # Testing MRO monotonicity...
870 class Boat(object): pass
871 class DayBoat(Boat): pass
872 class WheelBoat(Boat): pass
873 class EngineLess(DayBoat): pass
874 class SmallMultihull(DayBoat): pass
875 class PedalWheelBoat(EngineLess,WheelBoat): pass
876 class SmallCatamaran(SmallMultihull): pass
877 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
878
879 self.assertEqual(PedalWheelBoat.__mro__,
880 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
881 self.assertEqual(SmallCatamaran.__mro__,
882 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
883 self.assertEqual(Pedalo.__mro__,
884 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
885 SmallMultihull, DayBoat, WheelBoat, Boat, object))
886
887 # see "A Monotonic Superclass Linearization for Dylan",
888 # by Kim Barrett et al. (OOPSLA 1996)
889 def test_consistency_with_epg(self):
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200890 # Testing consistency with EPG...
Georg Brandl48545522008-02-02 10:12:36 +0000891 class Pane(object): pass
892 class ScrollingMixin(object): pass
893 class EditingMixin(object): pass
894 class ScrollablePane(Pane,ScrollingMixin): pass
895 class EditablePane(Pane,EditingMixin): pass
896 class EditableScrollablePane(ScrollablePane,EditablePane): pass
897
898 self.assertEqual(EditableScrollablePane.__mro__,
899 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
900 ScrollingMixin, EditingMixin, object))
901
902 def test_mro_disagreement(self):
903 # Testing error messages for MRO disagreement...
904 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000905order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000906
Georg Brandl48545522008-02-02 10:12:36 +0000907 def raises(exc, expected, callable, *args):
908 try:
909 callable(*args)
910 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000911 # the exact msg is generally considered an impl detail
912 if test_support.check_impl_detail():
913 if not str(msg).startswith(expected):
914 self.fail("Message %r, expected %r" %
915 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000916 else:
917 self.fail("Expected %s" % exc)
918
919 class A(object): pass
920 class B(A): pass
921 class C(object): pass
922
923 # Test some very simple errors
924 raises(TypeError, "duplicate base class A",
925 type, "X", (A, A), {})
926 raises(TypeError, mro_err_msg,
927 type, "X", (A, B), {})
928 raises(TypeError, mro_err_msg,
929 type, "X", (A, C, B), {})
930 # Test a slightly more complex error
931 class GridLayout(object): pass
932 class HorizontalGrid(GridLayout): pass
933 class VerticalGrid(GridLayout): pass
934 class HVGrid(HorizontalGrid, VerticalGrid): pass
935 class VHGrid(VerticalGrid, HorizontalGrid): pass
936 raises(TypeError, mro_err_msg,
937 type, "ConfusedGrid", (HVGrid, VHGrid), {})
938
939 def test_object_class(self):
940 # Testing object class...
941 a = object()
942 self.assertEqual(a.__class__, object)
943 self.assertEqual(type(a), object)
944 b = object()
945 self.assertNotEqual(a, b)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200946 self.assertNotHasAttr(a, "foo")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000947 try:
Georg Brandl48545522008-02-02 10:12:36 +0000948 a.foo = 12
949 except (AttributeError, TypeError):
950 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000951 else:
Georg Brandl48545522008-02-02 10:12:36 +0000952 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200953 self.assertNotHasAttr(object(), "__dict__")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000954
Georg Brandl48545522008-02-02 10:12:36 +0000955 class Cdict(object):
956 pass
957 x = Cdict()
958 self.assertEqual(x.__dict__, {})
959 x.foo = 1
960 self.assertEqual(x.foo, 1)
961 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000962
Georg Brandl48545522008-02-02 10:12:36 +0000963 def test_slots(self):
964 # Testing __slots__...
965 class C0(object):
966 __slots__ = []
967 x = C0()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200968 self.assertNotHasAttr(x, "__dict__")
969 self.assertNotHasAttr(x, "foo")
Guido van Rossum37202612001-08-09 19:45:21 +0000970
Georg Brandl48545522008-02-02 10:12:36 +0000971 class C1(object):
972 __slots__ = ['a']
973 x = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200974 self.assertNotHasAttr(x, "__dict__")
975 self.assertNotHasAttr(x, "a")
Georg Brandl48545522008-02-02 10:12:36 +0000976 x.a = 1
977 self.assertEqual(x.a, 1)
978 x.a = None
979 self.assertEqual(x.a, None)
980 del x.a
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200981 self.assertNotHasAttr(x, "a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000982
Georg Brandl48545522008-02-02 10:12:36 +0000983 class C3(object):
984 __slots__ = ['a', 'b', 'c']
985 x = C3()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200986 self.assertNotHasAttr(x, "__dict__")
987 self.assertNotHasAttr(x, 'a')
988 self.assertNotHasAttr(x, 'b')
989 self.assertNotHasAttr(x, 'c')
Georg Brandl48545522008-02-02 10:12:36 +0000990 x.a = 1
991 x.b = 2
992 x.c = 3
993 self.assertEqual(x.a, 1)
994 self.assertEqual(x.b, 2)
995 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000996
Georg Brandl48545522008-02-02 10:12:36 +0000997 class C4(object):
998 """Validate name mangling"""
999 __slots__ = ['__a']
1000 def __init__(self, value):
1001 self.__a = value
1002 def get(self):
1003 return self.__a
1004 x = C4(5)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001005 self.assertNotHasAttr(x, '__dict__')
1006 self.assertNotHasAttr(x, '__a')
Georg Brandl48545522008-02-02 10:12:36 +00001007 self.assertEqual(x.get(), 5)
1008 try:
1009 x.__a = 6
1010 except AttributeError:
1011 pass
1012 else:
1013 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014
Georg Brandl48545522008-02-02 10:12:36 +00001015 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001016 try:
1017 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001018 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001019 except TypeError:
1020 pass
1021 else:
Georg Brandl48545522008-02-02 10:12:36 +00001022 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001023 try:
Georg Brandl48545522008-02-02 10:12:36 +00001024 class C(object):
1025 __slots__ = ["foo bar"]
1026 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001027 pass
Georg Brandl48545522008-02-02 10:12:36 +00001028 else:
1029 self.fail("['foo bar'] slots not caught")
1030 try:
1031 class C(object):
1032 __slots__ = ["foo\0bar"]
1033 except TypeError:
1034 pass
1035 else:
1036 self.fail("['foo\\0bar'] slots not caught")
1037 try:
1038 class C(object):
1039 __slots__ = ["1"]
1040 except TypeError:
1041 pass
1042 else:
1043 self.fail("['1'] slots not caught")
1044 try:
1045 class C(object):
1046 __slots__ = [""]
1047 except TypeError:
1048 pass
1049 else:
1050 self.fail("[''] slots not caught")
1051 class C(object):
1052 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1053 # XXX(nnorwitz): was there supposed to be something tested
1054 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001055
Georg Brandl48545522008-02-02 10:12:36 +00001056 # Test a single string is not expanded as a sequence.
1057 class C(object):
1058 __slots__ = "abc"
1059 c = C()
1060 c.abc = 5
1061 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001062
Zachary Ware1f702212013-12-10 14:09:20 -06001063 def test_unicode_slots(self):
Georg Brandl48545522008-02-02 10:12:36 +00001064 # Test unicode slot names
1065 try:
1066 unicode
1067 except NameError:
Zachary Ware1f702212013-12-10 14:09:20 -06001068 self.skipTest('no unicode support')
Georg Brandl48545522008-02-02 10:12:36 +00001069 else:
1070 # Test a single unicode string is not expanded as a sequence.
1071 class C(object):
1072 __slots__ = unicode("abc")
1073 c = C()
1074 c.abc = 5
1075 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001076
Georg Brandl48545522008-02-02 10:12:36 +00001077 # _unicode_to_string used to modify slots in certain circumstances
1078 slots = (unicode("foo"), unicode("bar"))
1079 class C(object):
1080 __slots__ = slots
1081 x = C()
1082 x.foo = 5
1083 self.assertEqual(x.foo, 5)
1084 self.assertEqual(type(slots[0]), unicode)
1085 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001086 try:
Georg Brandl48545522008-02-02 10:12:36 +00001087 class C(object):
1088 __slots__ = [unichr(128)]
1089 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001090 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001091 else:
Georg Brandl48545522008-02-02 10:12:36 +00001092 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001093
Georg Brandl48545522008-02-02 10:12:36 +00001094 # Test leaks
1095 class Counted(object):
1096 counter = 0 # counts the number of instances alive
1097 def __init__(self):
1098 Counted.counter += 1
1099 def __del__(self):
1100 Counted.counter -= 1
1101 class C(object):
1102 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001103 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001104 x.a = Counted()
1105 x.b = Counted()
1106 x.c = Counted()
1107 self.assertEqual(Counted.counter, 3)
1108 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001109 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001110 self.assertEqual(Counted.counter, 0)
1111 class D(C):
1112 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001113 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001114 x.a = Counted()
1115 x.z = Counted()
1116 self.assertEqual(Counted.counter, 2)
1117 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001118 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001119 self.assertEqual(Counted.counter, 0)
1120 class E(D):
1121 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001122 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001123 x.a = Counted()
1124 x.z = Counted()
1125 x.e = Counted()
1126 self.assertEqual(Counted.counter, 3)
1127 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001128 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001129 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001130
Georg Brandl48545522008-02-02 10:12:36 +00001131 # Test cyclical leaks [SF bug 519621]
1132 class F(object):
1133 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001134 s = F()
1135 s.a = [Counted(), s]
1136 self.assertEqual(Counted.counter, 1)
1137 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001138 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001139 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001140
Georg Brandl48545522008-02-02 10:12:36 +00001141 # Test lookup leaks [SF bug 572567]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001142 if hasattr(gc, 'get_objects'):
1143 class G(object):
1144 def __cmp__(self, other):
1145 return 0
1146 __hash__ = None # Silence Py3k warning
1147 g = G()
1148 orig_objects = len(gc.get_objects())
1149 for i in xrange(10):
1150 g==g
1151 new_objects = len(gc.get_objects())
1152 self.assertEqual(orig_objects, new_objects)
1153
Georg Brandl48545522008-02-02 10:12:36 +00001154 class H(object):
1155 __slots__ = ['a', 'b']
1156 def __init__(self):
1157 self.a = 1
1158 self.b = 2
1159 def __del__(self_):
1160 self.assertEqual(self_.a, 1)
1161 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001162 with test_support.captured_output('stderr') as s:
1163 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001164 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001165 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001166
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001167 class X(object):
1168 __slots__ = "a"
1169 with self.assertRaises(AttributeError):
1170 del X().a
1171
Georg Brandl48545522008-02-02 10:12:36 +00001172 def test_slots_special(self):
1173 # Testing __dict__ and __weakref__ in __slots__...
1174 class D(object):
1175 __slots__ = ["__dict__"]
1176 a = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001177 self.assertHasAttr(a, "__dict__")
1178 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001179 a.foo = 42
1180 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001181
Georg Brandl48545522008-02-02 10:12:36 +00001182 class W(object):
1183 __slots__ = ["__weakref__"]
1184 a = W()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001185 self.assertHasAttr(a, "__weakref__")
1186 self.assertNotHasAttr(a, "__dict__")
Georg Brandl48545522008-02-02 10:12:36 +00001187 try:
1188 a.foo = 42
1189 except AttributeError:
1190 pass
1191 else:
1192 self.fail("shouldn't be allowed to set a.foo")
1193
1194 class C1(W, D):
1195 __slots__ = []
1196 a = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001197 self.assertHasAttr(a, "__dict__")
1198 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001199 a.foo = 42
1200 self.assertEqual(a.__dict__, {"foo": 42})
1201
1202 class C2(D, W):
1203 __slots__ = []
1204 a = C2()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001205 self.assertHasAttr(a, "__dict__")
1206 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001207 a.foo = 42
1208 self.assertEqual(a.__dict__, {"foo": 42})
1209
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001210 def test_slots_descriptor(self):
1211 # Issue2115: slot descriptors did not correctly check
1212 # the type of the given object
1213 import abc
1214 class MyABC:
1215 __metaclass__ = abc.ABCMeta
1216 __slots__ = "a"
1217
1218 class Unrelated(object):
1219 pass
1220 MyABC.register(Unrelated)
1221
1222 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001223 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001224
1225 # This used to crash
1226 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1227
Benjamin Peterson4895af42009-12-13 16:36:53 +00001228 def test_metaclass_cmp(self):
1229 # See bug 7491.
1230 class M(type):
1231 def __cmp__(self, other):
1232 return -1
1233 class X(object):
1234 __metaclass__ = M
1235 self.assertTrue(X < M)
1236
Georg Brandl48545522008-02-02 10:12:36 +00001237 def test_dynamics(self):
1238 # Testing class attribute propagation...
1239 class D(object):
1240 pass
1241 class E(D):
1242 pass
1243 class F(D):
1244 pass
1245 D.foo = 1
1246 self.assertEqual(D.foo, 1)
1247 # Test that dynamic attributes are inherited
1248 self.assertEqual(E.foo, 1)
1249 self.assertEqual(F.foo, 1)
1250 # Test dynamic instances
1251 class C(object):
1252 pass
1253 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001254 self.assertNotHasAttr(a, "foobar")
Georg Brandl48545522008-02-02 10:12:36 +00001255 C.foobar = 2
1256 self.assertEqual(a.foobar, 2)
1257 C.method = lambda self: 42
1258 self.assertEqual(a.method(), 42)
1259 C.__repr__ = lambda self: "C()"
1260 self.assertEqual(repr(a), "C()")
1261 C.__int__ = lambda self: 100
1262 self.assertEqual(int(a), 100)
1263 self.assertEqual(a.foobar, 2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001264 self.assertNotHasAttr(a, "spam")
Georg Brandl48545522008-02-02 10:12:36 +00001265 def mygetattr(self, name):
1266 if name == "spam":
1267 return "spam"
1268 raise AttributeError
1269 C.__getattr__ = mygetattr
1270 self.assertEqual(a.spam, "spam")
1271 a.new = 12
1272 self.assertEqual(a.new, 12)
1273 def mysetattr(self, name, value):
1274 if name == "spam":
1275 raise AttributeError
1276 return object.__setattr__(self, name, value)
1277 C.__setattr__ = mysetattr
1278 try:
1279 a.spam = "not spam"
1280 except AttributeError:
1281 pass
1282 else:
1283 self.fail("expected AttributeError")
1284 self.assertEqual(a.spam, "spam")
1285 class D(C):
1286 pass
1287 d = D()
1288 d.foo = 1
1289 self.assertEqual(d.foo, 1)
1290
1291 # Test handling of int*seq and seq*int
1292 class I(int):
1293 pass
1294 self.assertEqual("a"*I(2), "aa")
1295 self.assertEqual(I(2)*"a", "aa")
1296 self.assertEqual(2*I(3), 6)
1297 self.assertEqual(I(3)*2, 6)
1298 self.assertEqual(I(3)*I(2), 6)
1299
1300 # Test handling of long*seq and seq*long
1301 class L(long):
1302 pass
1303 self.assertEqual("a"*L(2L), "aa")
1304 self.assertEqual(L(2L)*"a", "aa")
1305 self.assertEqual(2*L(3), 6)
1306 self.assertEqual(L(3)*2, 6)
1307 self.assertEqual(L(3)*L(2), 6)
1308
1309 # Test comparison of classes with dynamic metaclasses
1310 class dynamicmetaclass(type):
1311 pass
1312 class someclass:
1313 __metaclass__ = dynamicmetaclass
1314 self.assertNotEqual(someclass, object)
1315
1316 def test_errors(self):
1317 # Testing errors...
1318 try:
1319 class C(list, dict):
1320 pass
1321 except TypeError:
1322 pass
1323 else:
1324 self.fail("inheritance from both list and dict should be illegal")
1325
1326 try:
1327 class C(object, None):
1328 pass
1329 except TypeError:
1330 pass
1331 else:
1332 self.fail("inheritance from non-type should be illegal")
1333 class Classic:
1334 pass
1335
1336 try:
1337 class C(type(len)):
1338 pass
1339 except TypeError:
1340 pass
1341 else:
1342 self.fail("inheritance from CFunction should be illegal")
1343
1344 try:
1345 class C(object):
1346 __slots__ = 1
1347 except TypeError:
1348 pass
1349 else:
1350 self.fail("__slots__ = 1 should be illegal")
1351
1352 try:
1353 class C(object):
1354 __slots__ = [1]
1355 except TypeError:
1356 pass
1357 else:
1358 self.fail("__slots__ = [1] should be illegal")
1359
1360 class M1(type):
1361 pass
1362 class M2(type):
1363 pass
1364 class A1(object):
1365 __metaclass__ = M1
1366 class A2(object):
1367 __metaclass__ = M2
1368 try:
1369 class B(A1, A2):
1370 pass
1371 except TypeError:
1372 pass
1373 else:
1374 self.fail("finding the most derived metaclass should have failed")
1375
1376 def test_classmethods(self):
1377 # Testing class methods...
1378 class C(object):
1379 def foo(*a): return a
1380 goo = classmethod(foo)
1381 c = C()
1382 self.assertEqual(C.goo(1), (C, 1))
1383 self.assertEqual(c.goo(1), (C, 1))
1384 self.assertEqual(c.foo(1), (c, 1))
1385 class D(C):
1386 pass
1387 d = D()
1388 self.assertEqual(D.goo(1), (D, 1))
1389 self.assertEqual(d.goo(1), (D, 1))
1390 self.assertEqual(d.foo(1), (d, 1))
1391 self.assertEqual(D.foo(d, 1), (d, 1))
1392 # Test for a specific crash (SF bug 528132)
1393 def f(cls, arg): return (cls, arg)
1394 ff = classmethod(f)
1395 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1396 self.assertEqual(ff.__get__(0)(42), (int, 42))
1397
1398 # Test super() with classmethods (SF bug 535444)
1399 self.assertEqual(C.goo.im_self, C)
1400 self.assertEqual(D.goo.im_self, D)
1401 self.assertEqual(super(D,D).goo.im_self, D)
1402 self.assertEqual(super(D,d).goo.im_self, D)
1403 self.assertEqual(super(D,D).goo(), (D,))
1404 self.assertEqual(super(D,d).goo(), (D,))
1405
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001406 # Verify that a non-callable will raise
1407 meth = classmethod(1).__get__(1)
1408 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001409
1410 # Verify that classmethod() doesn't allow keyword args
1411 try:
1412 classmethod(f, kw=1)
1413 except TypeError:
1414 pass
1415 else:
1416 self.fail("classmethod shouldn't accept keyword args")
1417
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001418 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001419 def test_classmethods_in_c(self):
1420 # Testing C-based class methods...
1421 import xxsubtype as spam
1422 a = (1, 2, 3)
1423 d = {'abc': 123}
1424 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1425 self.assertEqual(x, spam.spamlist)
1426 self.assertEqual(a, a1)
1427 self.assertEqual(d, d1)
1428 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1429 self.assertEqual(x, spam.spamlist)
1430 self.assertEqual(a, a1)
1431 self.assertEqual(d, d1)
Benjamin Peterson042c47b2012-05-01 09:51:09 -04001432 spam_cm = spam.spamlist.__dict__['classmeth']
1433 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1434 self.assertEqual(x2, spam.spamlist)
1435 self.assertEqual(a2, a1)
1436 self.assertEqual(d2, d1)
1437 class SubSpam(spam.spamlist): pass
1438 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1439 self.assertEqual(x2, SubSpam)
1440 self.assertEqual(a2, a1)
1441 self.assertEqual(d2, d1)
1442 with self.assertRaises(TypeError):
1443 spam_cm()
1444 with self.assertRaises(TypeError):
1445 spam_cm(spam.spamlist())
1446 with self.assertRaises(TypeError):
1447 spam_cm(list)
Georg Brandl48545522008-02-02 10:12:36 +00001448
1449 def test_staticmethods(self):
1450 # Testing static methods...
1451 class C(object):
1452 def foo(*a): return a
1453 goo = staticmethod(foo)
1454 c = C()
1455 self.assertEqual(C.goo(1), (1,))
1456 self.assertEqual(c.goo(1), (1,))
1457 self.assertEqual(c.foo(1), (c, 1,))
1458 class D(C):
1459 pass
1460 d = D()
1461 self.assertEqual(D.goo(1), (1,))
1462 self.assertEqual(d.goo(1), (1,))
1463 self.assertEqual(d.foo(1), (d, 1))
1464 self.assertEqual(D.foo(d, 1), (d, 1))
1465
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001466 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001467 def test_staticmethods_in_c(self):
1468 # Testing C-based static methods...
1469 import xxsubtype as spam
1470 a = (1, 2, 3)
1471 d = {"abc": 123}
1472 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1473 self.assertEqual(x, None)
1474 self.assertEqual(a, a1)
1475 self.assertEqual(d, d1)
1476 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1477 self.assertEqual(x, None)
1478 self.assertEqual(a, a1)
1479 self.assertEqual(d, d1)
1480
1481 def test_classic(self):
1482 # Testing classic classes...
1483 class C:
1484 def foo(*a): return a
1485 goo = classmethod(foo)
1486 c = C()
1487 self.assertEqual(C.goo(1), (C, 1))
1488 self.assertEqual(c.goo(1), (C, 1))
1489 self.assertEqual(c.foo(1), (c, 1))
1490 class D(C):
1491 pass
1492 d = D()
1493 self.assertEqual(D.goo(1), (D, 1))
1494 self.assertEqual(d.goo(1), (D, 1))
1495 self.assertEqual(d.foo(1), (d, 1))
1496 self.assertEqual(D.foo(d, 1), (d, 1))
1497 class E: # *not* subclassing from C
1498 foo = C.foo
1499 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001500 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001501
1502 def test_compattr(self):
1503 # Testing computed attributes...
1504 class C(object):
1505 class computed_attribute(object):
1506 def __init__(self, get, set=None, delete=None):
1507 self.__get = get
1508 self.__set = set
1509 self.__delete = delete
1510 def __get__(self, obj, type=None):
1511 return self.__get(obj)
1512 def __set__(self, obj, value):
1513 return self.__set(obj, value)
1514 def __delete__(self, obj):
1515 return self.__delete(obj)
1516 def __init__(self):
1517 self.__x = 0
1518 def __get_x(self):
1519 x = self.__x
1520 self.__x = x+1
1521 return x
1522 def __set_x(self, x):
1523 self.__x = x
1524 def __delete_x(self):
1525 del self.__x
1526 x = computed_attribute(__get_x, __set_x, __delete_x)
1527 a = C()
1528 self.assertEqual(a.x, 0)
1529 self.assertEqual(a.x, 1)
1530 a.x = 10
1531 self.assertEqual(a.x, 10)
1532 self.assertEqual(a.x, 11)
1533 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001534 self.assertNotHasAttr(a, 'x')
Georg Brandl48545522008-02-02 10:12:36 +00001535
1536 def test_newslots(self):
1537 # Testing __new__ slot override...
1538 class C(list):
1539 def __new__(cls):
1540 self = list.__new__(cls)
1541 self.foo = 1
1542 return self
1543 def __init__(self):
1544 self.foo = self.foo + 2
1545 a = C()
1546 self.assertEqual(a.foo, 3)
1547 self.assertEqual(a.__class__, C)
1548 class D(C):
1549 pass
1550 b = D()
1551 self.assertEqual(b.foo, 3)
1552 self.assertEqual(b.__class__, D)
1553
Serhiy Storchaka7117d352016-12-14 19:48:38 +02001554 @unittest.expectedFailure
1555 def test_bad_new(self):
1556 self.assertRaises(TypeError, object.__new__)
1557 self.assertRaises(TypeError, object.__new__, '')
1558 self.assertRaises(TypeError, list.__new__, object)
1559 self.assertRaises(TypeError, object.__new__, list)
1560 class C(object):
1561 __new__ = list.__new__
1562 self.assertRaises(TypeError, C)
1563 class C(list):
1564 __new__ = object.__new__
1565 self.assertRaises(TypeError, C)
1566
1567 def test_object_new(self):
1568 class A(object):
1569 pass
1570 object.__new__(A)
1571 self.assertRaises(TypeError, object.__new__, A, 5)
1572 object.__init__(A())
1573 self.assertRaises(TypeError, object.__init__, A(), 5)
1574
1575 class A(object):
1576 def __init__(self, foo):
1577 self.foo = foo
1578 object.__new__(A)
1579 object.__new__(A, 5)
1580 object.__init__(A(3))
1581 self.assertRaises(TypeError, object.__init__, A(3), 5)
1582
1583 class A(object):
1584 def __new__(cls, foo):
1585 return object.__new__(cls)
1586 object.__new__(A)
1587 self.assertRaises(TypeError, object.__new__, A, 5)
1588 object.__init__(A(3))
1589 object.__init__(A(3), 5)
1590
1591 class A(object):
1592 def __new__(cls, foo):
1593 return object.__new__(cls)
1594 def __init__(self, foo):
1595 self.foo = foo
1596 object.__new__(A)
1597 with warnings.catch_warnings(record=True) as w:
1598 warnings.simplefilter('always', DeprecationWarning)
1599 a = object.__new__(A, 5)
1600 self.assertEqual(type(a), A)
1601 self.assertEqual(len(w), 1)
1602 object.__init__(A(3))
1603 a = A(3)
1604 with warnings.catch_warnings(record=True) as w:
1605 warnings.simplefilter('always', DeprecationWarning)
1606 object.__init__(a, 5)
1607 self.assertEqual(a.foo, 3)
1608 self.assertEqual(len(w), 1)
1609
1610 @unittest.expectedFailure
1611 def test_restored_object_new(self):
1612 class A(object):
1613 def __new__(cls, *args, **kwargs):
1614 raise AssertionError
1615 self.assertRaises(AssertionError, A)
1616 class B(A):
1617 __new__ = object.__new__
1618 def __init__(self, foo):
1619 self.foo = foo
1620 with warnings.catch_warnings():
1621 warnings.simplefilter('error', DeprecationWarning)
1622 b = B(3)
1623 self.assertEqual(b.foo, 3)
1624 self.assertEqual(b.__class__, B)
1625 del B.__new__
1626 self.assertRaises(AssertionError, B)
1627 del A.__new__
1628 with warnings.catch_warnings():
1629 warnings.simplefilter('error', DeprecationWarning)
1630 b = B(3)
1631 self.assertEqual(b.foo, 3)
1632 self.assertEqual(b.__class__, B)
1633
Georg Brandl48545522008-02-02 10:12:36 +00001634 def test_altmro(self):
1635 # Testing mro() and overriding it...
1636 class A(object):
1637 def f(self): return "A"
1638 class B(A):
1639 pass
1640 class C(A):
1641 def f(self): return "C"
1642 class D(B, C):
1643 pass
1644 self.assertEqual(D.mro(), [D, B, C, A, object])
1645 self.assertEqual(D.__mro__, (D, B, C, A, object))
1646 self.assertEqual(D().f(), "C")
1647
1648 class PerverseMetaType(type):
1649 def mro(cls):
1650 L = type.mro(cls)
1651 L.reverse()
1652 return L
1653 class X(D,B,C,A):
1654 __metaclass__ = PerverseMetaType
1655 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1656 self.assertEqual(X().f(), "A")
1657
1658 try:
1659 class X(object):
1660 class __metaclass__(type):
1661 def mro(self):
1662 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001663 # In CPython, the class creation above already raises
1664 # TypeError, as a protection against the fact that
1665 # instances of X would segfault it. In other Python
1666 # implementations it would be ok to let the class X
1667 # be created, but instead get a clean TypeError on the
1668 # __setitem__ below.
1669 x = object.__new__(X)
1670 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001671 except TypeError:
1672 pass
1673 else:
1674 self.fail("devious mro() return not caught")
1675
1676 try:
1677 class X(object):
1678 class __metaclass__(type):
1679 def mro(self):
1680 return [1]
1681 except TypeError:
1682 pass
1683 else:
1684 self.fail("non-class mro() return not caught")
1685
1686 try:
1687 class X(object):
1688 class __metaclass__(type):
1689 def mro(self):
1690 return 1
1691 except TypeError:
1692 pass
1693 else:
1694 self.fail("non-sequence mro() return not caught")
1695
1696 def test_overloading(self):
1697 # Testing operator overloading...
1698
1699 class B(object):
1700 "Intermediate class because object doesn't have a __setattr__"
1701
1702 class C(B):
1703 def __getattr__(self, name):
1704 if name == "foo":
1705 return ("getattr", name)
1706 else:
1707 raise AttributeError
1708 def __setattr__(self, name, value):
1709 if name == "foo":
1710 self.setattr = (name, value)
1711 else:
1712 return B.__setattr__(self, name, value)
1713 def __delattr__(self, name):
1714 if name == "foo":
1715 self.delattr = name
1716 else:
1717 return B.__delattr__(self, name)
1718
1719 def __getitem__(self, key):
1720 return ("getitem", key)
1721 def __setitem__(self, key, value):
1722 self.setitem = (key, value)
1723 def __delitem__(self, key):
1724 self.delitem = key
1725
1726 def __getslice__(self, i, j):
1727 return ("getslice", i, j)
1728 def __setslice__(self, i, j, value):
1729 self.setslice = (i, j, value)
1730 def __delslice__(self, i, j):
1731 self.delslice = (i, j)
1732
1733 a = C()
1734 self.assertEqual(a.foo, ("getattr", "foo"))
1735 a.foo = 12
1736 self.assertEqual(a.setattr, ("foo", 12))
1737 del a.foo
1738 self.assertEqual(a.delattr, "foo")
1739
1740 self.assertEqual(a[12], ("getitem", 12))
1741 a[12] = 21
1742 self.assertEqual(a.setitem, (12, 21))
1743 del a[12]
1744 self.assertEqual(a.delitem, 12)
1745
1746 self.assertEqual(a[0:10], ("getslice", 0, 10))
1747 a[0:10] = "foo"
1748 self.assertEqual(a.setslice, (0, 10, "foo"))
1749 del a[0:10]
1750 self.assertEqual(a.delslice, (0, 10))
1751
1752 def test_methods(self):
1753 # Testing methods...
1754 class C(object):
1755 def __init__(self, x):
1756 self.x = x
1757 def foo(self):
1758 return self.x
1759 c1 = C(1)
1760 self.assertEqual(c1.foo(), 1)
1761 class D(C):
1762 boo = C.foo
1763 goo = c1.foo
1764 d2 = D(2)
1765 self.assertEqual(d2.foo(), 2)
1766 self.assertEqual(d2.boo(), 2)
1767 self.assertEqual(d2.goo(), 1)
1768 class E(object):
1769 foo = C.foo
1770 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001771 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001772
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001773 def test_special_method_lookup(self):
1774 # The lookup of special methods bypasses __getattr__ and
1775 # __getattribute__, but they still can be descriptors.
1776
1777 def run_context(manager):
1778 with manager:
1779 pass
1780 def iden(self):
1781 return self
1782 def hello(self):
1783 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001784 def empty_seq(self):
1785 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001786 def zero(self):
1787 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001788 def complex_num(self):
1789 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001790 def stop(self):
1791 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001792 def return_true(self, thing=None):
1793 return True
1794 def do_isinstance(obj):
1795 return isinstance(int, obj)
1796 def do_issubclass(obj):
1797 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001798 def swallow(*args):
1799 pass
1800 def do_dict_missing(checker):
1801 class DictSub(checker.__class__, dict):
1802 pass
1803 self.assertEqual(DictSub()["hi"], 4)
1804 def some_number(self_, key):
1805 self.assertEqual(key, "hi")
1806 return 4
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001807 def format_impl(self, spec):
1808 return "hello"
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001809
1810 # It would be nice to have every special method tested here, but I'm
1811 # only listing the ones I can remember outside of typeobject.c, since it
1812 # does it right.
1813 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001814 ("__unicode__", unicode, hello, set(), {}),
1815 ("__reversed__", reversed, empty_seq, set(), {}),
1816 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001817 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001818 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1819 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001820 ("__missing__", do_dict_missing, some_number,
1821 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001822 ("__subclasscheck__", do_issubclass, return_true,
1823 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001824 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1825 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001826 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001827 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001828 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001829 ]
1830
1831 class Checker(object):
1832 def __getattr__(self, attr, test=self):
1833 test.fail("__getattr__ called with {0}".format(attr))
1834 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001835 if attr not in ok:
1836 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001837 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001838 class SpecialDescr(object):
1839 def __init__(self, impl):
1840 self.impl = impl
1841 def __get__(self, obj, owner):
1842 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001843 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001844 class MyException(Exception):
1845 pass
1846 class ErrDescr(object):
1847 def __get__(self, obj, owner):
1848 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001849
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001850 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001851 class X(Checker):
1852 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001853 for attr, obj in env.iteritems():
1854 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001855 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001856 runner(X())
1857
1858 record = []
1859 class X(Checker):
1860 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001861 for attr, obj in env.iteritems():
1862 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001863 setattr(X, name, SpecialDescr(meth_impl))
1864 runner(X())
1865 self.assertEqual(record, [1], name)
1866
Benjamin Peterson87e50062009-05-25 02:40:21 +00001867 class X(Checker):
1868 pass
1869 for attr, obj in env.iteritems():
1870 setattr(X, attr, obj)
1871 setattr(X, name, ErrDescr())
1872 try:
1873 runner(X())
1874 except MyException:
1875 pass
1876 else:
1877 self.fail("{0!r} didn't raise".format(name))
1878
Georg Brandl48545522008-02-02 10:12:36 +00001879 def test_specials(self):
1880 # Testing special operators...
1881 # Test operators like __hash__ for which a built-in default exists
1882
1883 # Test the default behavior for static classes
1884 class C(object):
1885 def __getitem__(self, i):
1886 if 0 <= i < 10: return i
1887 raise IndexError
1888 c1 = C()
1889 c2 = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001890 self.assertFalse(not c1)
Georg Brandl48545522008-02-02 10:12:36 +00001891 self.assertNotEqual(id(c1), id(c2))
1892 hash(c1)
1893 hash(c2)
1894 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1895 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001896 self.assertTrue(c1 != c2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001897 self.assertFalse(c1 != c1)
1898 self.assertFalse(c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001899 # Note that the module name appears in str/repr, and that varies
1900 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001901 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001902 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001903 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001904 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001905 self.assertIn(i, c1)
1906 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001907 # Test the default behavior for dynamic classes
1908 class D(object):
1909 def __getitem__(self, i):
1910 if 0 <= i < 10: return i
1911 raise IndexError
1912 d1 = D()
1913 d2 = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001914 self.assertFalse(not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001915 self.assertNotEqual(id(d1), id(d2))
1916 hash(d1)
1917 hash(d2)
1918 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1919 self.assertEqual(d1, d1)
1920 self.assertNotEqual(d1, d2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001921 self.assertFalse(d1 != d1)
1922 self.assertFalse(d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001923 # Note that the module name appears in str/repr, and that varies
1924 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001925 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001926 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001927 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001928 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001929 self.assertIn(i, d1)
1930 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001931 # Test overridden behavior for static classes
1932 class Proxy(object):
1933 def __init__(self, x):
1934 self.x = x
1935 def __nonzero__(self):
1936 return not not self.x
1937 def __hash__(self):
1938 return hash(self.x)
1939 def __eq__(self, other):
1940 return self.x == other
1941 def __ne__(self, other):
1942 return self.x != other
1943 def __cmp__(self, other):
1944 return cmp(self.x, other.x)
1945 def __str__(self):
1946 return "Proxy:%s" % self.x
1947 def __repr__(self):
1948 return "Proxy(%r)" % self.x
1949 def __contains__(self, value):
1950 return value in self.x
1951 p0 = Proxy(0)
1952 p1 = Proxy(1)
1953 p_1 = Proxy(-1)
1954 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001955 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001956 self.assertEqual(hash(p0), hash(0))
1957 self.assertEqual(p0, p0)
1958 self.assertNotEqual(p0, p1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001959 self.assertFalse(p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001960 self.assertEqual(not p0, p1)
1961 self.assertEqual(cmp(p0, p1), -1)
1962 self.assertEqual(cmp(p0, p0), 0)
1963 self.assertEqual(cmp(p0, p_1), 1)
1964 self.assertEqual(str(p0), "Proxy:0")
1965 self.assertEqual(repr(p0), "Proxy(0)")
1966 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001967 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001968 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001969 self.assertIn(i, p10)
1970 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001971 # Test overridden behavior for dynamic classes
1972 class DProxy(object):
1973 def __init__(self, x):
1974 self.x = x
1975 def __nonzero__(self):
1976 return not not self.x
1977 def __hash__(self):
1978 return hash(self.x)
1979 def __eq__(self, other):
1980 return self.x == other
1981 def __ne__(self, other):
1982 return self.x != other
1983 def __cmp__(self, other):
1984 return cmp(self.x, other.x)
1985 def __str__(self):
1986 return "DProxy:%s" % self.x
1987 def __repr__(self):
1988 return "DProxy(%r)" % self.x
1989 def __contains__(self, value):
1990 return value in self.x
1991 p0 = DProxy(0)
1992 p1 = DProxy(1)
1993 p_1 = DProxy(-1)
1994 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001995 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001996 self.assertEqual(hash(p0), hash(0))
1997 self.assertEqual(p0, p0)
1998 self.assertNotEqual(p0, p1)
1999 self.assertNotEqual(not p0, p0)
2000 self.assertEqual(not p0, p1)
2001 self.assertEqual(cmp(p0, p1), -1)
2002 self.assertEqual(cmp(p0, p0), 0)
2003 self.assertEqual(cmp(p0, p_1), 1)
2004 self.assertEqual(str(p0), "DProxy:0")
2005 self.assertEqual(repr(p0), "DProxy(0)")
2006 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00002007 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00002008 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00002009 self.assertIn(i, p10)
2010 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00002011
2012 # Safety test for __cmp__
2013 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002014 if not hasattr(a, '__cmp__'):
2015 return # some types don't have a __cmp__ any more (so the
2016 # test doesn't make sense any more), or maybe they
2017 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00002018 try:
2019 a.__class__.__cmp__(a, b)
2020 except TypeError:
2021 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002022 else:
Georg Brandl48545522008-02-02 10:12:36 +00002023 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
2024 a.__class__, a, b))
2025
2026 unsafecmp(u"123", "123")
2027 unsafecmp("123", u"123")
2028 unsafecmp(1, 1.0)
2029 unsafecmp(1.0, 1)
2030 unsafecmp(1, 1L)
2031 unsafecmp(1L, 1)
2032
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002033 @test_support.impl_detail("custom logic for printing to real file objects")
2034 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00002035 # Testing recursion checks ...
2036 class Letter(str):
2037 def __new__(cls, letter):
2038 if letter == 'EPS':
2039 return str.__new__(cls)
2040 return str.__new__(cls, letter)
2041 def __str__(self):
2042 if not self:
2043 return 'EPS'
2044 return self
2045 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00002046 test_stdout = sys.stdout
2047 sys.stdout = test_support.get_original_stdout()
2048 try:
2049 # nothing should actually be printed, this should raise an exception
2050 print Letter('w')
2051 except RuntimeError:
2052 pass
2053 else:
2054 self.fail("expected a RuntimeError for print recursion")
2055 finally:
2056 sys.stdout = test_stdout
2057
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002058 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00002059 # Bug #1202533.
2060 class A(object):
2061 pass
2062 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
2063 try:
2064 A()*2
2065 except RuntimeError:
2066 pass
2067 else:
2068 self.fail("expected a RuntimeError")
2069
2070 def test_weakrefs(self):
2071 # Testing weak references...
2072 import weakref
2073 class C(object):
2074 pass
2075 c = C()
2076 r = weakref.ref(c)
2077 self.assertEqual(r(), c)
2078 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002079 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00002080 self.assertEqual(r(), None)
2081 del r
2082 class NoWeak(object):
2083 __slots__ = ['foo']
2084 no = NoWeak()
2085 try:
2086 weakref.ref(no)
2087 except TypeError, msg:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002088 self.assertIn("weak reference", str(msg))
Georg Brandl48545522008-02-02 10:12:36 +00002089 else:
2090 self.fail("weakref.ref(no) should be illegal")
2091 class Weak(object):
2092 __slots__ = ['foo', '__weakref__']
2093 yes = Weak()
2094 r = weakref.ref(yes)
2095 self.assertEqual(r(), yes)
2096 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002097 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00002098 self.assertEqual(r(), None)
2099 del r
2100
2101 def test_properties(self):
2102 # Testing property...
2103 class C(object):
2104 def getx(self):
2105 return self.__x
2106 def setx(self, value):
2107 self.__x = value
2108 def delx(self):
2109 del self.__x
2110 x = property(getx, setx, delx, doc="I'm the x property.")
2111 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002112 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002113 a.x = 42
2114 self.assertEqual(a._C__x, 42)
2115 self.assertEqual(a.x, 42)
2116 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002117 self.assertNotHasAttr(a, "x")
2118 self.assertNotHasAttr(a, "_C__x")
Georg Brandl48545522008-02-02 10:12:36 +00002119 C.x.__set__(a, 100)
2120 self.assertEqual(C.x.__get__(a), 100)
2121 C.x.__delete__(a)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002122 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002123
2124 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002125 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002126
2127 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002128 self.assertIn("__doc__", attrs)
2129 self.assertIn("fget", attrs)
2130 self.assertIn("fset", attrs)
2131 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002132
2133 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002134 self.assertIs(raw.fget, C.__dict__['getx'])
2135 self.assertIs(raw.fset, C.__dict__['setx'])
2136 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002137
2138 for attr in "__doc__", "fget", "fset", "fdel":
2139 try:
2140 setattr(raw, attr, 42)
2141 except TypeError, msg:
2142 if str(msg).find('readonly') < 0:
2143 self.fail("when setting readonly attr %r on a property, "
2144 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002145 else:
Georg Brandl48545522008-02-02 10:12:36 +00002146 self.fail("expected TypeError from trying to set readonly %r "
2147 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002148
Georg Brandl48545522008-02-02 10:12:36 +00002149 class D(object):
Serhiy Storchaka5312a7f2015-01-31 11:27:06 +02002150 __getitem__ = property(lambda s: 1.0/0.0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002151
Georg Brandl48545522008-02-02 10:12:36 +00002152 d = D()
2153 try:
2154 for i in d:
2155 str(i)
2156 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002157 pass
Georg Brandl48545522008-02-02 10:12:36 +00002158 else:
2159 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002160
R. David Murrayf28fd242010-02-23 00:24:49 +00002161 @unittest.skipIf(sys.flags.optimize >= 2,
2162 "Docstrings are omitted with -O2 and above")
2163 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002164 class E(object):
2165 def getter(self):
2166 "getter method"
2167 return 0
2168 def setter(self_, value):
2169 "setter method"
2170 pass
2171 prop = property(getter)
2172 self.assertEqual(prop.__doc__, "getter method")
2173 prop2 = property(fset=setter)
2174 self.assertEqual(prop2.__doc__, None)
2175
Serhiy Storchaka76249ea2014-02-07 10:06:05 +02002176 @test_support.cpython_only
R. David Murrayf28fd242010-02-23 00:24:49 +00002177 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002178 # this segfaulted in 2.5b2
2179 try:
2180 import _testcapi
2181 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002182 pass
Georg Brandl48545522008-02-02 10:12:36 +00002183 else:
2184 class X(object):
2185 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002186
Georg Brandl48545522008-02-02 10:12:36 +00002187 def test_properties_plus(self):
2188 class C(object):
2189 foo = property(doc="hello")
2190 @foo.getter
2191 def foo(self):
2192 return self._foo
2193 @foo.setter
2194 def foo(self, value):
2195 self._foo = abs(value)
2196 @foo.deleter
2197 def foo(self):
2198 del self._foo
2199 c = C()
2200 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002201 self.assertNotHasAttr(c, "foo")
Georg Brandl48545522008-02-02 10:12:36 +00002202 c.foo = -42
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002203 self.assertHasAttr(c, '_foo')
Georg Brandl48545522008-02-02 10:12:36 +00002204 self.assertEqual(c._foo, 42)
2205 self.assertEqual(c.foo, 42)
2206 del c.foo
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002207 self.assertNotHasAttr(c, '_foo')
2208 self.assertNotHasAttr(c, "foo")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002209
Georg Brandl48545522008-02-02 10:12:36 +00002210 class D(C):
2211 @C.foo.deleter
2212 def foo(self):
2213 try:
2214 del self._foo
2215 except AttributeError:
2216 pass
2217 d = D()
2218 d.foo = 24
2219 self.assertEqual(d.foo, 24)
2220 del d.foo
2221 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002222
Georg Brandl48545522008-02-02 10:12:36 +00002223 class E(object):
2224 @property
2225 def foo(self):
2226 return self._foo
2227 @foo.setter
2228 def foo(self, value):
2229 raise RuntimeError
2230 @foo.setter
2231 def foo(self, value):
2232 self._foo = abs(value)
2233 @foo.deleter
2234 def foo(self, value=None):
2235 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002236
Georg Brandl48545522008-02-02 10:12:36 +00002237 e = E()
2238 e.foo = -42
2239 self.assertEqual(e.foo, 42)
2240 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002241
Georg Brandl48545522008-02-02 10:12:36 +00002242 class F(E):
2243 @E.foo.deleter
2244 def foo(self):
2245 del self._foo
2246 @foo.setter
2247 def foo(self, value):
2248 self._foo = max(0, value)
2249 f = F()
2250 f.foo = -10
2251 self.assertEqual(f.foo, 0)
2252 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002253
Georg Brandl48545522008-02-02 10:12:36 +00002254 def test_dict_constructors(self):
2255 # Testing dict constructor ...
2256 d = dict()
2257 self.assertEqual(d, {})
2258 d = dict({})
2259 self.assertEqual(d, {})
2260 d = dict({1: 2, 'a': 'b'})
2261 self.assertEqual(d, {1: 2, 'a': 'b'})
2262 self.assertEqual(d, dict(d.items()))
2263 self.assertEqual(d, dict(d.iteritems()))
2264 d = dict({'one':1, 'two':2})
2265 self.assertEqual(d, dict(one=1, two=2))
2266 self.assertEqual(d, dict(**d))
2267 self.assertEqual(d, dict({"one": 1}, two=2))
2268 self.assertEqual(d, dict([("two", 2)], one=1))
2269 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2270 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002271
Georg Brandl48545522008-02-02 10:12:36 +00002272 for badarg in 0, 0L, 0j, "0", [0], (0,):
2273 try:
2274 dict(badarg)
2275 except TypeError:
2276 pass
2277 except ValueError:
2278 if badarg == "0":
2279 # It's a sequence, and its elements are also sequences (gotta
2280 # love strings <wink>), but they aren't of length 2, so this
2281 # one seemed better as a ValueError than a TypeError.
2282 pass
2283 else:
2284 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002285 else:
Georg Brandl48545522008-02-02 10:12:36 +00002286 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002287
Georg Brandl48545522008-02-02 10:12:36 +00002288 try:
2289 dict({}, {})
2290 except TypeError:
2291 pass
2292 else:
2293 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002294
Georg Brandl48545522008-02-02 10:12:36 +00002295 class Mapping:
2296 # Lacks a .keys() method; will be added later.
2297 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002298
Georg Brandl48545522008-02-02 10:12:36 +00002299 try:
2300 dict(Mapping())
2301 except TypeError:
2302 pass
2303 else:
2304 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002305
Georg Brandl48545522008-02-02 10:12:36 +00002306 Mapping.keys = lambda self: self.dict.keys()
2307 Mapping.__getitem__ = lambda self, i: self.dict[i]
2308 d = dict(Mapping())
2309 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002310
Georg Brandl48545522008-02-02 10:12:36 +00002311 # Init from sequence of iterable objects, each producing a 2-sequence.
2312 class AddressBookEntry:
2313 def __init__(self, first, last):
2314 self.first = first
2315 self.last = last
2316 def __iter__(self):
2317 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002318
Georg Brandl48545522008-02-02 10:12:36 +00002319 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2320 AddressBookEntry('Barry', 'Peters'),
2321 AddressBookEntry('Tim', 'Peters'),
2322 AddressBookEntry('Barry', 'Warsaw')])
2323 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002324
Georg Brandl48545522008-02-02 10:12:36 +00002325 d = dict(zip(range(4), range(1, 5)))
2326 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002327
Georg Brandl48545522008-02-02 10:12:36 +00002328 # Bad sequence lengths.
2329 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2330 try:
2331 dict(bad)
2332 except ValueError:
2333 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002334 else:
Georg Brandl48545522008-02-02 10:12:36 +00002335 self.fail("no ValueError from dict(%r)" % bad)
2336
2337 def test_dir(self):
2338 # Testing dir() ...
2339 junk = 12
2340 self.assertEqual(dir(), ['junk', 'self'])
2341 del junk
2342
2343 # Just make sure these don't blow up!
2344 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2345 dir(arg)
2346
2347 # Try classic classes.
2348 class C:
2349 Cdata = 1
2350 def Cmethod(self): pass
2351
2352 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2353 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002354 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002355
2356 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2357 self.assertEqual(dir(c), cstuff)
2358
2359 c.cdata = 2
2360 c.cmethod = lambda self: 0
2361 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002362 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002363
2364 class A(C):
2365 Adata = 1
2366 def Amethod(self): pass
2367
2368 astuff = ['Adata', 'Amethod'] + cstuff
2369 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002370 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002371 a = A()
2372 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002373 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002374 a.adata = 42
2375 a.amethod = lambda self: 3
2376 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2377
2378 # The same, but with new-style classes. Since these have object as a
2379 # base class, a lot more gets sucked in.
2380 def interesting(strings):
2381 return [s for s in strings if not s.startswith('_')]
2382
2383 class C(object):
2384 Cdata = 1
2385 def Cmethod(self): pass
2386
2387 cstuff = ['Cdata', 'Cmethod']
2388 self.assertEqual(interesting(dir(C)), cstuff)
2389
2390 c = C()
2391 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002392 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002393
2394 c.cdata = 2
2395 c.cmethod = lambda self: 0
2396 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002397 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002398
2399 class A(C):
2400 Adata = 1
2401 def Amethod(self): pass
2402
2403 astuff = ['Adata', 'Amethod'] + cstuff
2404 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002405 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002406 a = A()
2407 self.assertEqual(interesting(dir(a)), astuff)
2408 a.adata = 42
2409 a.amethod = lambda self: 3
2410 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002411 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002412
2413 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002414 class M(type(sys)):
2415 pass
2416 minstance = M("m")
2417 minstance.b = 2
2418 minstance.a = 1
2419 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2420 self.assertEqual(names, ['a', 'b'])
2421
2422 class M2(M):
2423 def getdict(self):
2424 return "Not a dict!"
2425 __dict__ = property(getdict)
2426
2427 m2instance = M2("m2")
2428 m2instance.b = 2
2429 m2instance.a = 1
2430 self.assertEqual(m2instance.__dict__, "Not a dict!")
2431 try:
2432 dir(m2instance)
2433 except TypeError:
2434 pass
2435
2436 # Two essentially featureless objects, just inheriting stuff from
2437 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002438 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2439 if test_support.check_impl_detail():
2440 # None differs in PyPy: it has a __nonzero__
2441 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002442
2443 # Nasty test case for proxied objects
2444 class Wrapper(object):
2445 def __init__(self, obj):
2446 self.__obj = obj
2447 def __repr__(self):
2448 return "Wrapper(%s)" % repr(self.__obj)
2449 def __getitem__(self, key):
2450 return Wrapper(self.__obj[key])
2451 def __len__(self):
2452 return len(self.__obj)
2453 def __getattr__(self, name):
2454 return Wrapper(getattr(self.__obj, name))
2455
2456 class C(object):
2457 def __getclass(self):
2458 return Wrapper(type(self))
2459 __class__ = property(__getclass)
2460
2461 dir(C()) # This used to segfault
2462
2463 def test_supers(self):
2464 # Testing super...
2465
2466 class A(object):
2467 def meth(self, a):
2468 return "A(%r)" % a
2469
2470 self.assertEqual(A().meth(1), "A(1)")
2471
2472 class B(A):
2473 def __init__(self):
2474 self.__super = super(B, self)
2475 def meth(self, a):
2476 return "B(%r)" % a + self.__super.meth(a)
2477
2478 self.assertEqual(B().meth(2), "B(2)A(2)")
2479
2480 class C(A):
2481 def meth(self, a):
2482 return "C(%r)" % a + self.__super.meth(a)
2483 C._C__super = super(C)
2484
2485 self.assertEqual(C().meth(3), "C(3)A(3)")
2486
2487 class D(C, B):
2488 def meth(self, a):
2489 return "D(%r)" % a + super(D, self).meth(a)
2490
2491 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2492
2493 # Test for subclassing super
2494
2495 class mysuper(super):
2496 def __init__(self, *args):
2497 return super(mysuper, self).__init__(*args)
2498
2499 class E(D):
2500 def meth(self, a):
2501 return "E(%r)" % a + mysuper(E, self).meth(a)
2502
2503 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2504
2505 class F(E):
2506 def meth(self, a):
2507 s = self.__super # == mysuper(F, self)
2508 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2509 F._F__super = mysuper(F)
2510
2511 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2512
2513 # Make sure certain errors are raised
2514
2515 try:
2516 super(D, 42)
2517 except TypeError:
2518 pass
2519 else:
2520 self.fail("shouldn't allow super(D, 42)")
2521
2522 try:
2523 super(D, C())
2524 except TypeError:
2525 pass
2526 else:
2527 self.fail("shouldn't allow super(D, C())")
2528
2529 try:
2530 super(D).__get__(12)
2531 except TypeError:
2532 pass
2533 else:
2534 self.fail("shouldn't allow super(D).__get__(12)")
2535
2536 try:
2537 super(D).__get__(C())
2538 except TypeError:
2539 pass
2540 else:
2541 self.fail("shouldn't allow super(D).__get__(C())")
2542
2543 # Make sure data descriptors can be overridden and accessed via super
2544 # (new feature in Python 2.3)
2545
2546 class DDbase(object):
2547 def getx(self): return 42
2548 x = property(getx)
2549
2550 class DDsub(DDbase):
2551 def getx(self): return "hello"
2552 x = property(getx)
2553
2554 dd = DDsub()
2555 self.assertEqual(dd.x, "hello")
2556 self.assertEqual(super(DDsub, dd).x, 42)
2557
2558 # Ensure that super() lookup of descriptor from classmethod
2559 # works (SF ID# 743627)
2560
2561 class Base(object):
2562 aProp = property(lambda self: "foo")
2563
2564 class Sub(Base):
2565 @classmethod
2566 def test(klass):
2567 return super(Sub,klass).aProp
2568
2569 self.assertEqual(Sub.test(), Base.aProp)
2570
2571 # Verify that super() doesn't allow keyword args
2572 try:
2573 super(Base, kw=1)
2574 except TypeError:
2575 pass
2576 else:
2577 self.assertEqual("super shouldn't accept keyword args")
2578
2579 def test_basic_inheritance(self):
2580 # Testing inheritance from basic types...
2581
2582 class hexint(int):
2583 def __repr__(self):
2584 return hex(self)
2585 def __add__(self, other):
2586 return hexint(int.__add__(self, other))
2587 # (Note that overriding __radd__ doesn't work,
2588 # because the int type gets first dibs.)
2589 self.assertEqual(repr(hexint(7) + 9), "0x10")
2590 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2591 a = hexint(12345)
2592 self.assertEqual(a, 12345)
2593 self.assertEqual(int(a), 12345)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002594 self.assertIs(int(a).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002595 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002596 self.assertIs((+a).__class__, int)
2597 self.assertIs((a >> 0).__class__, int)
2598 self.assertIs((a << 0).__class__, int)
2599 self.assertIs((hexint(0) << 12).__class__, int)
2600 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002601
2602 class octlong(long):
2603 __slots__ = []
2604 def __str__(self):
2605 s = oct(self)
2606 if s[-1] == 'L':
2607 s = s[:-1]
2608 return s
2609 def __add__(self, other):
2610 return self.__class__(super(octlong, self).__add__(other))
2611 __radd__ = __add__
2612 self.assertEqual(str(octlong(3) + 5), "010")
2613 # (Note that overriding __radd__ here only seems to work
2614 # because the example uses a short int left argument.)
2615 self.assertEqual(str(5 + octlong(3000)), "05675")
2616 a = octlong(12345)
2617 self.assertEqual(a, 12345L)
2618 self.assertEqual(long(a), 12345L)
2619 self.assertEqual(hash(a), hash(12345L))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002620 self.assertIs(long(a).__class__, long)
2621 self.assertIs((+a).__class__, long)
2622 self.assertIs((-a).__class__, long)
2623 self.assertIs((-octlong(0)).__class__, long)
2624 self.assertIs((a >> 0).__class__, long)
2625 self.assertIs((a << 0).__class__, long)
2626 self.assertIs((a - 0).__class__, long)
2627 self.assertIs((a * 1).__class__, long)
2628 self.assertIs((a ** 1).__class__, long)
2629 self.assertIs((a // 1).__class__, long)
2630 self.assertIs((1 * a).__class__, long)
2631 self.assertIs((a | 0).__class__, long)
2632 self.assertIs((a ^ 0).__class__, long)
2633 self.assertIs((a & -1L).__class__, long)
2634 self.assertIs((octlong(0) << 12).__class__, long)
2635 self.assertIs((octlong(0) >> 12).__class__, long)
2636 self.assertIs(abs(octlong(0)).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002637
2638 # Because octlong overrides __add__, we can't check the absence of +0
2639 # optimizations using octlong.
2640 class longclone(long):
2641 pass
2642 a = longclone(1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002643 self.assertIs((a + 0).__class__, long)
2644 self.assertIs((0 + a).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002645
2646 # Check that negative clones don't segfault
2647 a = longclone(-1)
2648 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002649 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002650
2651 class precfloat(float):
2652 __slots__ = ['prec']
2653 def __init__(self, value=0.0, prec=12):
2654 self.prec = int(prec)
2655 def __repr__(self):
2656 return "%.*g" % (self.prec, self)
2657 self.assertEqual(repr(precfloat(1.1)), "1.1")
2658 a = precfloat(12345)
2659 self.assertEqual(a, 12345.0)
2660 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002661 self.assertIs(float(a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002662 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002663 self.assertIs((+a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002664
2665 class madcomplex(complex):
2666 def __repr__(self):
2667 return "%.17gj%+.17g" % (self.imag, self.real)
2668 a = madcomplex(-3, 4)
2669 self.assertEqual(repr(a), "4j-3")
2670 base = complex(-3, 4)
2671 self.assertEqual(base.__class__, complex)
2672 self.assertEqual(a, base)
2673 self.assertEqual(complex(a), base)
2674 self.assertEqual(complex(a).__class__, complex)
2675 a = madcomplex(a) # just trying another form of the constructor
2676 self.assertEqual(repr(a), "4j-3")
2677 self.assertEqual(a, base)
2678 self.assertEqual(complex(a), base)
2679 self.assertEqual(complex(a).__class__, complex)
2680 self.assertEqual(hash(a), hash(base))
2681 self.assertEqual((+a).__class__, complex)
2682 self.assertEqual((a + 0).__class__, complex)
2683 self.assertEqual(a + 0, base)
2684 self.assertEqual((a - 0).__class__, complex)
2685 self.assertEqual(a - 0, base)
2686 self.assertEqual((a * 1).__class__, complex)
2687 self.assertEqual(a * 1, base)
2688 self.assertEqual((a / 1).__class__, complex)
2689 self.assertEqual(a / 1, base)
2690
2691 class madtuple(tuple):
2692 _rev = None
2693 def rev(self):
2694 if self._rev is not None:
2695 return self._rev
2696 L = list(self)
2697 L.reverse()
2698 self._rev = self.__class__(L)
2699 return self._rev
2700 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2701 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2702 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2703 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2704 for i in range(512):
2705 t = madtuple(range(i))
2706 u = t.rev()
2707 v = u.rev()
2708 self.assertEqual(v, t)
2709 a = madtuple((1,2,3,4,5))
2710 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002711 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002712 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002713 self.assertIs(a[:].__class__, tuple)
2714 self.assertIs((a * 1).__class__, tuple)
2715 self.assertIs((a * 0).__class__, tuple)
2716 self.assertIs((a + ()).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002717 a = madtuple(())
2718 self.assertEqual(tuple(a), ())
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002719 self.assertIs(tuple(a).__class__, tuple)
2720 self.assertIs((a + a).__class__, tuple)
2721 self.assertIs((a * 0).__class__, tuple)
2722 self.assertIs((a * 1).__class__, tuple)
2723 self.assertIs((a * 2).__class__, tuple)
2724 self.assertIs(a[:].__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002725
2726 class madstring(str):
2727 _rev = None
2728 def rev(self):
2729 if self._rev is not None:
2730 return self._rev
2731 L = list(self)
2732 L.reverse()
2733 self._rev = self.__class__("".join(L))
2734 return self._rev
2735 s = madstring("abcdefghijklmnopqrstuvwxyz")
2736 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2737 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2738 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2739 for i in range(256):
2740 s = madstring("".join(map(chr, range(i))))
2741 t = s.rev()
2742 u = t.rev()
2743 self.assertEqual(u, s)
2744 s = madstring("12345")
2745 self.assertEqual(str(s), "12345")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002746 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002747
2748 base = "\x00" * 5
2749 s = madstring(base)
2750 self.assertEqual(s, base)
2751 self.assertEqual(str(s), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002752 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002753 self.assertEqual(hash(s), hash(base))
2754 self.assertEqual({s: 1}[base], 1)
2755 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002756 self.assertIs((s + "").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002757 self.assertEqual(s + "", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002758 self.assertIs(("" + s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002759 self.assertEqual("" + s, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002760 self.assertIs((s * 0).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002761 self.assertEqual(s * 0, "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002762 self.assertIs((s * 1).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002763 self.assertEqual(s * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002764 self.assertIs((s * 2).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002765 self.assertEqual(s * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002766 self.assertIs(s[:].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002767 self.assertEqual(s[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002768 self.assertIs(s[0:0].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002769 self.assertEqual(s[0:0], "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002770 self.assertIs(s.strip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002771 self.assertEqual(s.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002772 self.assertIs(s.lstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002773 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002774 self.assertIs(s.rstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002775 self.assertEqual(s.rstrip(), base)
2776 identitytab = ''.join([chr(i) for i in range(256)])
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002777 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002778 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002779 self.assertIs(s.translate(identitytab, "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002780 self.assertEqual(s.translate(identitytab, "x"), base)
2781 self.assertEqual(s.translate(identitytab, "\x00"), "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002782 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002783 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002784 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002785 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002786 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002787 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002788 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002789 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002790 self.assertIs(s.lower().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002791 self.assertEqual(s.lower(), base)
2792
2793 class madunicode(unicode):
2794 _rev = None
2795 def rev(self):
2796 if self._rev is not None:
2797 return self._rev
2798 L = list(self)
2799 L.reverse()
2800 self._rev = self.__class__(u"".join(L))
2801 return self._rev
2802 u = madunicode("ABCDEF")
2803 self.assertEqual(u, u"ABCDEF")
2804 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2805 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2806 base = u"12345"
2807 u = madunicode(base)
2808 self.assertEqual(unicode(u), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002809 self.assertIs(unicode(u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002810 self.assertEqual(hash(u), hash(base))
2811 self.assertEqual({u: 1}[base], 1)
2812 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002813 self.assertIs(u.strip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002814 self.assertEqual(u.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002815 self.assertIs(u.lstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002816 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002817 self.assertIs(u.rstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002818 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002819 self.assertIs(u.replace(u"x", u"x").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002820 self.assertEqual(u.replace(u"x", u"x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002821 self.assertIs(u.replace(u"xy", u"xy").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002822 self.assertEqual(u.replace(u"xy", u"xy"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002823 self.assertIs(u.center(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002824 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002825 self.assertIs(u.ljust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002826 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002827 self.assertIs(u.rjust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002828 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002829 self.assertIs(u.lower().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002830 self.assertEqual(u.lower(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002831 self.assertIs(u.upper().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002832 self.assertEqual(u.upper(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002833 self.assertIs(u.capitalize().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002834 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002835 self.assertIs(u.title().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002836 self.assertEqual(u.title(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002837 self.assertIs((u + u"").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002838 self.assertEqual(u + u"", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002839 self.assertIs((u"" + u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002840 self.assertEqual(u"" + u, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002841 self.assertIs((u * 0).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002842 self.assertEqual(u * 0, u"")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002843 self.assertIs((u * 1).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002844 self.assertEqual(u * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002845 self.assertIs((u * 2).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002846 self.assertEqual(u * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002847 self.assertIs(u[:].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002848 self.assertEqual(u[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002849 self.assertIs(u[0:0].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002850 self.assertEqual(u[0:0], u"")
2851
2852 class sublist(list):
2853 pass
2854 a = sublist(range(5))
2855 self.assertEqual(a, range(5))
2856 a.append("hello")
2857 self.assertEqual(a, range(5) + ["hello"])
2858 a[5] = 5
2859 self.assertEqual(a, range(6))
2860 a.extend(range(6, 20))
2861 self.assertEqual(a, range(20))
2862 a[-5:] = []
2863 self.assertEqual(a, range(15))
2864 del a[10:15]
2865 self.assertEqual(len(a), 10)
2866 self.assertEqual(a, range(10))
2867 self.assertEqual(list(a), range(10))
2868 self.assertEqual(a[0], 0)
2869 self.assertEqual(a[9], 9)
2870 self.assertEqual(a[-10], 0)
2871 self.assertEqual(a[-1], 9)
2872 self.assertEqual(a[:5], range(5))
2873
2874 class CountedInput(file):
2875 """Counts lines read by self.readline().
2876
2877 self.lineno is the 0-based ordinal of the last line read, up to
2878 a maximum of one greater than the number of lines in the file.
2879
2880 self.ateof is true if and only if the final "" line has been read,
2881 at which point self.lineno stops incrementing, and further calls
2882 to readline() continue to return "".
2883 """
2884
2885 lineno = 0
2886 ateof = 0
2887 def readline(self):
2888 if self.ateof:
2889 return ""
2890 s = file.readline(self)
2891 # Next line works too.
2892 # s = super(CountedInput, self).readline()
2893 self.lineno += 1
2894 if s == "":
2895 self.ateof = 1
2896 return s
2897
2898 f = file(name=test_support.TESTFN, mode='w')
2899 lines = ['a\n', 'b\n', 'c\n']
2900 try:
2901 f.writelines(lines)
2902 f.close()
2903 f = CountedInput(test_support.TESTFN)
2904 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2905 got = f.readline()
2906 self.assertEqual(expected, got)
2907 self.assertEqual(f.lineno, i)
2908 self.assertEqual(f.ateof, (i > len(lines)))
2909 f.close()
2910 finally:
2911 try:
2912 f.close()
2913 except:
2914 pass
2915 test_support.unlink(test_support.TESTFN)
2916
2917 def test_keywords(self):
2918 # Testing keyword args to basic type constructors ...
2919 self.assertEqual(int(x=1), 1)
2920 self.assertEqual(float(x=2), 2.0)
2921 self.assertEqual(long(x=3), 3L)
2922 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2923 self.assertEqual(str(object=500), '500')
2924 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2925 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2926 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2927 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2928
2929 for constructor in (int, float, long, complex, str, unicode,
2930 tuple, list, file):
2931 try:
2932 constructor(bogus_keyword_arg=1)
2933 except TypeError:
2934 pass
2935 else:
2936 self.fail("expected TypeError from bogus keyword argument to %r"
2937 % constructor)
2938
2939 def test_str_subclass_as_dict_key(self):
2940 # Testing a str subclass used as dict key ..
2941
2942 class cistr(str):
2943 """Sublcass of str that computes __eq__ case-insensitively.
2944
2945 Also computes a hash code of the string in canonical form.
2946 """
2947
2948 def __init__(self, value):
2949 self.canonical = value.lower()
2950 self.hashcode = hash(self.canonical)
2951
2952 def __eq__(self, other):
2953 if not isinstance(other, cistr):
2954 other = cistr(other)
2955 return self.canonical == other.canonical
2956
2957 def __hash__(self):
2958 return self.hashcode
2959
2960 self.assertEqual(cistr('ABC'), 'abc')
2961 self.assertEqual('aBc', cistr('ABC'))
2962 self.assertEqual(str(cistr('ABC')), 'ABC')
2963
2964 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2965 self.assertEqual(d[cistr('one')], 1)
2966 self.assertEqual(d[cistr('tWo')], 2)
2967 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002968 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002969 self.assertEqual(d.get(cistr('thrEE')), 3)
2970
2971 def test_classic_comparisons(self):
2972 # Testing classic comparisons...
2973 class classic:
2974 pass
2975
2976 for base in (classic, int, object):
2977 class C(base):
2978 def __init__(self, value):
2979 self.value = int(value)
2980 def __cmp__(self, other):
2981 if isinstance(other, C):
2982 return cmp(self.value, other.value)
2983 if isinstance(other, int) or isinstance(other, long):
2984 return cmp(self.value, other)
2985 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002986 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002987
2988 c1 = C(1)
2989 c2 = C(2)
2990 c3 = C(3)
2991 self.assertEqual(c1, 1)
2992 c = {1: c1, 2: c2, 3: c3}
2993 for x in 1, 2, 3:
2994 for y in 1, 2, 3:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002995 self.assertEqual(cmp(c[x], c[y]), cmp(x, y),
2996 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002997 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002998 self.assertEqual(eval("c[x] %s c[y]" % op),
2999 eval("x %s y" % op),
3000 "x=%d, y=%d" % (x, y))
3001 self.assertEqual(cmp(c[x], y), cmp(x, y),
3002 "x=%d, y=%d" % (x, y))
3003 self.assertEqual(cmp(x, c[y]), cmp(x, y),
3004 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003005
3006 def test_rich_comparisons(self):
3007 # Testing rich comparisons...
3008 class Z(complex):
3009 pass
3010 z = Z(1)
3011 self.assertEqual(z, 1+0j)
3012 self.assertEqual(1+0j, z)
3013 class ZZ(complex):
3014 def __eq__(self, other):
3015 try:
3016 return abs(self - other) <= 1e-6
3017 except:
3018 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00003019 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003020 zz = ZZ(1.0000003)
3021 self.assertEqual(zz, 1+0j)
3022 self.assertEqual(1+0j, zz)
3023
3024 class classic:
3025 pass
3026 for base in (classic, int, object, list):
3027 class C(base):
3028 def __init__(self, value):
3029 self.value = int(value)
3030 def __cmp__(self_, other):
3031 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00003032 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003033 def __eq__(self, other):
3034 if isinstance(other, C):
3035 return self.value == other.value
3036 if isinstance(other, int) or isinstance(other, long):
3037 return self.value == other
3038 return NotImplemented
3039 def __ne__(self, other):
3040 if isinstance(other, C):
3041 return self.value != other.value
3042 if isinstance(other, int) or isinstance(other, long):
3043 return self.value != other
3044 return NotImplemented
3045 def __lt__(self, other):
3046 if isinstance(other, C):
3047 return self.value < other.value
3048 if isinstance(other, int) or isinstance(other, long):
3049 return self.value < other
3050 return NotImplemented
3051 def __le__(self, other):
3052 if isinstance(other, C):
3053 return self.value <= other.value
3054 if isinstance(other, int) or isinstance(other, long):
3055 return self.value <= other
3056 return NotImplemented
3057 def __gt__(self, other):
3058 if isinstance(other, C):
3059 return self.value > other.value
3060 if isinstance(other, int) or isinstance(other, long):
3061 return self.value > other
3062 return NotImplemented
3063 def __ge__(self, other):
3064 if isinstance(other, C):
3065 return self.value >= other.value
3066 if isinstance(other, int) or isinstance(other, long):
3067 return self.value >= other
3068 return NotImplemented
3069 c1 = C(1)
3070 c2 = C(2)
3071 c3 = C(3)
3072 self.assertEqual(c1, 1)
3073 c = {1: c1, 2: c2, 3: c3}
3074 for x in 1, 2, 3:
3075 for y in 1, 2, 3:
3076 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003077 self.assertEqual(eval("c[x] %s c[y]" % op),
3078 eval("x %s y" % op),
3079 "x=%d, y=%d" % (x, y))
3080 self.assertEqual(eval("c[x] %s y" % op),
3081 eval("x %s y" % op),
3082 "x=%d, y=%d" % (x, y))
3083 self.assertEqual(eval("x %s c[y]" % op),
3084 eval("x %s y" % op),
3085 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003086
3087 def test_coercions(self):
3088 # Testing coercions...
3089 class I(int): pass
3090 coerce(I(0), 0)
3091 coerce(0, I(0))
3092 class L(long): pass
3093 coerce(L(0), 0)
3094 coerce(L(0), 0L)
3095 coerce(0, L(0))
3096 coerce(0L, L(0))
3097 class F(float): pass
3098 coerce(F(0), 0)
3099 coerce(F(0), 0L)
3100 coerce(F(0), 0.)
3101 coerce(0, F(0))
3102 coerce(0L, F(0))
3103 coerce(0., F(0))
3104 class C(complex): pass
3105 coerce(C(0), 0)
3106 coerce(C(0), 0L)
3107 coerce(C(0), 0.)
3108 coerce(C(0), 0j)
3109 coerce(0, C(0))
3110 coerce(0L, C(0))
3111 coerce(0., C(0))
3112 coerce(0j, C(0))
3113
3114 def test_descrdoc(self):
3115 # Testing descriptor doc strings...
3116 def check(descr, what):
3117 self.assertEqual(descr.__doc__, what)
3118 check(file.closed, "True if the file is closed") # getset descriptor
3119 check(file.name, "file name") # member descriptor
3120
3121 def test_doc_descriptor(self):
3122 # Testing __doc__ descriptor...
3123 # SF bug 542984
3124 class DocDescr(object):
3125 def __get__(self, object, otype):
3126 if object:
3127 object = object.__class__.__name__ + ' instance'
3128 if otype:
3129 otype = otype.__name__
3130 return 'object=%s; type=%s' % (object, otype)
3131 class OldClass:
3132 __doc__ = DocDescr()
3133 class NewClass(object):
3134 __doc__ = DocDescr()
3135 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3136 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3137 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3138 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3139
3140 def test_set_class(self):
3141 # Testing __class__ assignment...
3142 class C(object): pass
3143 class D(object): pass
3144 class E(object): pass
3145 class F(D, E): pass
3146 for cls in C, D, E, F:
3147 for cls2 in C, D, E, F:
3148 x = cls()
3149 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003150 self.assertIs(x.__class__, cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003151 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003152 self.assertIs(x.__class__, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003153 def cant(x, C):
3154 try:
3155 x.__class__ = C
3156 except TypeError:
3157 pass
3158 else:
3159 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3160 try:
3161 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003162 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003163 pass
3164 else:
3165 self.fail("shouldn't allow del %r.__class__" % x)
3166 cant(C(), list)
3167 cant(list(), C)
3168 cant(C(), 1)
3169 cant(C(), object)
3170 cant(object(), list)
3171 cant(list(), object)
3172 class Int(int): __slots__ = []
3173 cant(2, Int)
3174 cant(Int(), int)
3175 cant(True, int)
3176 cant(2, bool)
3177 o = object()
3178 cant(o, type(1))
3179 cant(o, type(None))
3180 del o
3181 class G(object):
3182 __slots__ = ["a", "b"]
3183 class H(object):
3184 __slots__ = ["b", "a"]
3185 try:
3186 unicode
3187 except NameError:
3188 class I(object):
3189 __slots__ = ["a", "b"]
3190 else:
3191 class I(object):
3192 __slots__ = [unicode("a"), unicode("b")]
3193 class J(object):
3194 __slots__ = ["c", "b"]
3195 class K(object):
3196 __slots__ = ["a", "b", "d"]
3197 class L(H):
3198 __slots__ = ["e"]
3199 class M(I):
3200 __slots__ = ["e"]
3201 class N(J):
3202 __slots__ = ["__weakref__"]
3203 class P(J):
3204 __slots__ = ["__dict__"]
3205 class Q(J):
3206 pass
3207 class R(J):
3208 __slots__ = ["__dict__", "__weakref__"]
3209
3210 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3211 x = cls()
3212 x.a = 1
3213 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003214 self.assertIs(x.__class__, cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003215 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3216 self.assertEqual(x.a, 1)
3217 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003218 self.assertIs(x.__class__, cls,
Georg Brandl48545522008-02-02 10:12:36 +00003219 "assigning %r as __class__ for %r silently failed" % (cls, x))
3220 self.assertEqual(x.a, 1)
3221 for cls in G, J, K, L, M, N, P, R, list, Int:
3222 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3223 if cls is cls2:
3224 continue
3225 cant(cls(), cls2)
3226
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003227 # Issue5283: when __class__ changes in __del__, the wrong
3228 # type gets DECREF'd.
3229 class O(object):
3230 pass
3231 class A(object):
3232 def __del__(self):
3233 self.__class__ = O
3234 l = [A() for x in range(100)]
3235 del l
3236
Georg Brandl48545522008-02-02 10:12:36 +00003237 def test_set_dict(self):
3238 # Testing __dict__ assignment...
3239 class C(object): pass
3240 a = C()
3241 a.__dict__ = {'b': 1}
3242 self.assertEqual(a.b, 1)
3243 def cant(x, dict):
3244 try:
3245 x.__dict__ = dict
3246 except (AttributeError, TypeError):
3247 pass
3248 else:
3249 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3250 cant(a, None)
3251 cant(a, [])
3252 cant(a, 1)
3253 del a.__dict__ # Deleting __dict__ is allowed
3254
3255 class Base(object):
3256 pass
3257 def verify_dict_readonly(x):
3258 """
3259 x has to be an instance of a class inheriting from Base.
3260 """
3261 cant(x, {})
3262 try:
3263 del x.__dict__
3264 except (AttributeError, TypeError):
3265 pass
3266 else:
3267 self.fail("shouldn't allow del %r.__dict__" % x)
3268 dict_descr = Base.__dict__["__dict__"]
3269 try:
3270 dict_descr.__set__(x, {})
3271 except (AttributeError, TypeError):
3272 pass
3273 else:
3274 self.fail("dict_descr allowed access to %r's dict" % x)
3275
3276 # Classes don't allow __dict__ assignment and have readonly dicts
3277 class Meta1(type, Base):
3278 pass
3279 class Meta2(Base, type):
3280 pass
3281 class D(object):
3282 __metaclass__ = Meta1
3283 class E(object):
3284 __metaclass__ = Meta2
3285 for cls in C, D, E:
3286 verify_dict_readonly(cls)
3287 class_dict = cls.__dict__
3288 try:
3289 class_dict["spam"] = "eggs"
3290 except TypeError:
3291 pass
3292 else:
3293 self.fail("%r's __dict__ can be modified" % cls)
3294
3295 # Modules also disallow __dict__ assignment
3296 class Module1(types.ModuleType, Base):
3297 pass
3298 class Module2(Base, types.ModuleType):
3299 pass
3300 for ModuleType in Module1, Module2:
3301 mod = ModuleType("spam")
3302 verify_dict_readonly(mod)
3303 mod.__dict__["spam"] = "eggs"
3304
3305 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003306 # (at least not any more than regular exception's __dict__ can
3307 # be deleted; on CPython it is not the case, whereas on PyPy they
3308 # can, just like any other new-style instance's __dict__.)
3309 def can_delete_dict(e):
3310 try:
3311 del e.__dict__
3312 except (TypeError, AttributeError):
3313 return False
3314 else:
3315 return True
Georg Brandl48545522008-02-02 10:12:36 +00003316 class Exception1(Exception, Base):
3317 pass
3318 class Exception2(Base, Exception):
3319 pass
3320 for ExceptionType in Exception, Exception1, Exception2:
3321 e = ExceptionType()
3322 e.__dict__ = {"a": 1}
3323 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003324 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003325
3326 def test_pickles(self):
3327 # Testing pickling and copying new-style classes and objects...
3328 import pickle, cPickle
3329
3330 def sorteditems(d):
3331 L = d.items()
3332 L.sort()
3333 return L
3334
3335 global C
3336 class C(object):
3337 def __init__(self, a, b):
3338 super(C, self).__init__()
3339 self.a = a
3340 self.b = b
3341 def __repr__(self):
3342 return "C(%r, %r)" % (self.a, self.b)
3343
3344 global C1
3345 class C1(list):
3346 def __new__(cls, a, b):
3347 return super(C1, cls).__new__(cls)
3348 def __getnewargs__(self):
3349 return (self.a, self.b)
3350 def __init__(self, a, b):
3351 self.a = a
3352 self.b = b
3353 def __repr__(self):
3354 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3355
3356 global C2
3357 class C2(int):
3358 def __new__(cls, a, b, val=0):
3359 return super(C2, cls).__new__(cls, val)
3360 def __getnewargs__(self):
3361 return (self.a, self.b, int(self))
3362 def __init__(self, a, b, val=0):
3363 self.a = a
3364 self.b = b
3365 def __repr__(self):
3366 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3367
3368 global C3
3369 class C3(object):
3370 def __init__(self, foo):
3371 self.foo = foo
3372 def __getstate__(self):
3373 return self.foo
3374 def __setstate__(self, foo):
3375 self.foo = foo
3376
3377 global C4classic, C4
3378 class C4classic: # classic
3379 pass
3380 class C4(C4classic, object): # mixed inheritance
3381 pass
3382
3383 for p in pickle, cPickle:
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003384 for bin in range(p.HIGHEST_PROTOCOL + 1):
Georg Brandl48545522008-02-02 10:12:36 +00003385 for cls in C, C1, C2:
3386 s = p.dumps(cls, bin)
3387 cls2 = p.loads(s)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003388 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003389
3390 a = C1(1, 2); a.append(42); a.append(24)
3391 b = C2("hello", "world", 42)
3392 s = p.dumps((a, b), bin)
3393 x, y = p.loads(s)
3394 self.assertEqual(x.__class__, a.__class__)
3395 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3396 self.assertEqual(y.__class__, b.__class__)
3397 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3398 self.assertEqual(repr(x), repr(a))
3399 self.assertEqual(repr(y), repr(b))
3400 # Test for __getstate__ and __setstate__ on new style class
3401 u = C3(42)
3402 s = p.dumps(u, bin)
3403 v = p.loads(s)
3404 self.assertEqual(u.__class__, v.__class__)
3405 self.assertEqual(u.foo, v.foo)
3406 # Test for picklability of hybrid class
3407 u = C4()
3408 u.foo = 42
3409 s = p.dumps(u, bin)
3410 v = p.loads(s)
3411 self.assertEqual(u.__class__, v.__class__)
3412 self.assertEqual(u.foo, v.foo)
3413
3414 # Testing copy.deepcopy()
3415 import copy
3416 for cls in C, C1, C2:
3417 cls2 = copy.deepcopy(cls)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003418 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003419
3420 a = C1(1, 2); a.append(42); a.append(24)
3421 b = C2("hello", "world", 42)
3422 x, y = copy.deepcopy((a, b))
3423 self.assertEqual(x.__class__, a.__class__)
3424 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3425 self.assertEqual(y.__class__, b.__class__)
3426 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3427 self.assertEqual(repr(x), repr(a))
3428 self.assertEqual(repr(y), repr(b))
3429
3430 def test_pickle_slots(self):
3431 # Testing pickling of classes with __slots__ ...
3432 import pickle, cPickle
3433 # Pickling of classes with __slots__ but without __getstate__ should fail
3434 global B, C, D, E
3435 class B(object):
3436 pass
3437 for base in [object, B]:
3438 class C(base):
3439 __slots__ = ['a']
3440 class D(C):
3441 pass
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003442 for proto in range(2):
3443 try:
3444 pickle.dumps(C(), proto)
3445 except TypeError:
3446 pass
3447 else:
3448 self.fail("should fail: pickle C instance - %s" % base)
3449 try:
3450 cPickle.dumps(C(), proto)
3451 except TypeError:
3452 pass
3453 else:
3454 self.fail("should fail: cPickle C instance - %s" % base)
3455 try:
3456 pickle.dumps(C(), proto)
3457 except TypeError:
3458 pass
3459 else:
3460 self.fail("should fail: pickle D instance - %s" % base)
3461 try:
3462 cPickle.dumps(D(), proto)
3463 except TypeError:
3464 pass
3465 else:
3466 self.fail("should fail: cPickle D instance - %s" % base)
Georg Brandl48545522008-02-02 10:12:36 +00003467 # Give C a nice generic __getstate__ and __setstate__
3468 class C(base):
3469 __slots__ = ['a']
3470 def __getstate__(self):
3471 try:
3472 d = self.__dict__.copy()
3473 except AttributeError:
3474 d = {}
3475 for cls in self.__class__.__mro__:
3476 for sn in cls.__dict__.get('__slots__', ()):
3477 try:
3478 d[sn] = getattr(self, sn)
3479 except AttributeError:
3480 pass
3481 return d
3482 def __setstate__(self, d):
3483 for k, v in d.items():
3484 setattr(self, k, v)
3485 class D(C):
3486 pass
3487 # Now it should work
3488 x = C()
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003489 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3490 y = pickle.loads(pickle.dumps(x, proto))
3491 self.assertNotHasAttr(y, 'a')
3492 y = cPickle.loads(cPickle.dumps(x, proto))
3493 self.assertNotHasAttr(y, 'a')
Georg Brandl48545522008-02-02 10:12:36 +00003494 x.a = 42
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003495 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3496 y = pickle.loads(pickle.dumps(x, proto))
3497 self.assertEqual(y.a, 42)
3498 y = cPickle.loads(cPickle.dumps(x, proto))
3499 self.assertEqual(y.a, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003500 x = D()
3501 x.a = 42
3502 x.b = 100
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003503 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3504 y = pickle.loads(pickle.dumps(x, proto))
3505 self.assertEqual(y.a + y.b, 142)
3506 y = cPickle.loads(cPickle.dumps(x, proto))
3507 self.assertEqual(y.a + y.b, 142)
Georg Brandl48545522008-02-02 10:12:36 +00003508 # A subclass that adds a slot should also work
3509 class E(C):
3510 __slots__ = ['b']
3511 x = E()
3512 x.a = 42
3513 x.b = "foo"
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003514 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3515 y = pickle.loads(pickle.dumps(x, proto))
3516 self.assertEqual(y.a, x.a)
3517 self.assertEqual(y.b, x.b)
3518 y = cPickle.loads(cPickle.dumps(x, proto))
3519 self.assertEqual(y.a, x.a)
3520 self.assertEqual(y.b, x.b)
Georg Brandl48545522008-02-02 10:12:36 +00003521
3522 def test_binary_operator_override(self):
3523 # Testing overrides of binary operations...
3524 class I(int):
3525 def __repr__(self):
3526 return "I(%r)" % int(self)
3527 def __add__(self, other):
3528 return I(int(self) + int(other))
3529 __radd__ = __add__
3530 def __pow__(self, other, mod=None):
3531 if mod is None:
3532 return I(pow(int(self), int(other)))
3533 else:
3534 return I(pow(int(self), int(other), int(mod)))
3535 def __rpow__(self, other, mod=None):
3536 if mod is None:
3537 return I(pow(int(other), int(self), mod))
3538 else:
3539 return I(pow(int(other), int(self), int(mod)))
3540
3541 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3542 self.assertEqual(repr(I(1) + 2), "I(3)")
3543 self.assertEqual(repr(1 + I(2)), "I(3)")
3544 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3545 self.assertEqual(repr(2 ** I(3)), "I(8)")
3546 self.assertEqual(repr(I(2) ** 3), "I(8)")
3547 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3548 class S(str):
3549 def __eq__(self, other):
3550 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003551 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003552
3553 def test_subclass_propagation(self):
3554 # Testing propagation of slot functions to subclasses...
3555 class A(object):
3556 pass
3557 class B(A):
3558 pass
3559 class C(A):
3560 pass
3561 class D(B, C):
3562 pass
3563 d = D()
3564 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3565 A.__hash__ = lambda self: 42
3566 self.assertEqual(hash(d), 42)
3567 C.__hash__ = lambda self: 314
3568 self.assertEqual(hash(d), 314)
3569 B.__hash__ = lambda self: 144
3570 self.assertEqual(hash(d), 144)
3571 D.__hash__ = lambda self: 100
3572 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003573 D.__hash__ = None
3574 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003575 del D.__hash__
3576 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003577 B.__hash__ = None
3578 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003579 del B.__hash__
3580 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003581 C.__hash__ = None
3582 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003583 del C.__hash__
3584 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003585 A.__hash__ = None
3586 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003587 del A.__hash__
3588 self.assertEqual(hash(d), orig_hash)
3589 d.foo = 42
3590 d.bar = 42
3591 self.assertEqual(d.foo, 42)
3592 self.assertEqual(d.bar, 42)
3593 def __getattribute__(self, name):
3594 if name == "foo":
3595 return 24
3596 return object.__getattribute__(self, name)
3597 A.__getattribute__ = __getattribute__
3598 self.assertEqual(d.foo, 24)
3599 self.assertEqual(d.bar, 42)
3600 def __getattr__(self, name):
3601 if name in ("spam", "foo", "bar"):
3602 return "hello"
3603 raise AttributeError, name
3604 B.__getattr__ = __getattr__
3605 self.assertEqual(d.spam, "hello")
3606 self.assertEqual(d.foo, 24)
3607 self.assertEqual(d.bar, 42)
3608 del A.__getattribute__
3609 self.assertEqual(d.foo, 42)
3610 del d.foo
3611 self.assertEqual(d.foo, "hello")
3612 self.assertEqual(d.bar, 42)
3613 del B.__getattr__
3614 try:
3615 d.foo
3616 except AttributeError:
3617 pass
3618 else:
3619 self.fail("d.foo should be undefined now")
3620
3621 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003622 class A(object):
3623 pass
3624 class B(A):
3625 pass
3626 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003627 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003628 A.__setitem__ = lambda *a: None # crash
3629
3630 def test_buffer_inheritance(self):
3631 # Testing that buffer interface is inherited ...
3632
3633 import binascii
3634 # SF bug [#470040] ParseTuple t# vs subclasses.
3635
3636 class MyStr(str):
3637 pass
3638 base = 'abc'
3639 m = MyStr(base)
3640 # b2a_hex uses the buffer interface to get its argument's value, via
3641 # PyArg_ParseTuple 't#' code.
3642 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3643
3644 # It's not clear that unicode will continue to support the character
3645 # buffer interface, and this test will fail if that's taken away.
3646 class MyUni(unicode):
3647 pass
3648 base = u'abc'
3649 m = MyUni(base)
3650 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3651
3652 class MyInt(int):
3653 pass
3654 m = MyInt(42)
3655 try:
3656 binascii.b2a_hex(m)
3657 self.fail('subclass of int should not have a buffer interface')
3658 except TypeError:
3659 pass
3660
3661 def test_str_of_str_subclass(self):
3662 # Testing __str__ defined in subclass of str ...
3663 import binascii
3664 import cStringIO
3665
3666 class octetstring(str):
3667 def __str__(self):
3668 return binascii.b2a_hex(self)
3669 def __repr__(self):
3670 return self + " repr"
3671
3672 o = octetstring('A')
3673 self.assertEqual(type(o), octetstring)
3674 self.assertEqual(type(str(o)), str)
3675 self.assertEqual(type(repr(o)), str)
3676 self.assertEqual(ord(o), 0x41)
3677 self.assertEqual(str(o), '41')
3678 self.assertEqual(repr(o), 'A repr')
3679 self.assertEqual(o.__str__(), '41')
3680 self.assertEqual(o.__repr__(), 'A repr')
3681
3682 capture = cStringIO.StringIO()
3683 # Calling str() or not exercises different internal paths.
3684 print >> capture, o
3685 print >> capture, str(o)
3686 self.assertEqual(capture.getvalue(), '41\n41\n')
3687 capture.close()
3688
3689 def test_keyword_arguments(self):
3690 # Testing keyword arguments to __init__, __call__...
3691 def f(a): return a
3692 self.assertEqual(f.__call__(a=42), 42)
3693 a = []
3694 list.__init__(a, sequence=[0, 1, 2])
3695 self.assertEqual(a, [0, 1, 2])
3696
3697 def test_recursive_call(self):
3698 # Testing recursive __call__() by setting to instance of class...
3699 class A(object):
3700 pass
3701
3702 A.__call__ = A()
3703 try:
3704 A()()
3705 except RuntimeError:
3706 pass
3707 else:
3708 self.fail("Recursion limit should have been reached for __call__()")
3709
3710 def test_delete_hook(self):
3711 # Testing __del__ hook...
3712 log = []
3713 class C(object):
3714 def __del__(self):
3715 log.append(1)
3716 c = C()
3717 self.assertEqual(log, [])
3718 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003719 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003720 self.assertEqual(log, [1])
3721
3722 class D(object): pass
3723 d = D()
3724 try: del d[0]
3725 except TypeError: pass
3726 else: self.fail("invalid del() didn't raise TypeError")
3727
3728 def test_hash_inheritance(self):
3729 # Testing hash of mutable subclasses...
3730
3731 class mydict(dict):
3732 pass
3733 d = mydict()
3734 try:
3735 hash(d)
3736 except TypeError:
3737 pass
3738 else:
3739 self.fail("hash() of dict subclass should fail")
3740
3741 class mylist(list):
3742 pass
3743 d = mylist()
3744 try:
3745 hash(d)
3746 except TypeError:
3747 pass
3748 else:
3749 self.fail("hash() of list subclass should fail")
3750
3751 def test_str_operations(self):
3752 try: 'a' + 5
3753 except TypeError: pass
3754 else: self.fail("'' + 5 doesn't raise TypeError")
3755
3756 try: ''.split('')
3757 except ValueError: pass
3758 else: self.fail("''.split('') doesn't raise ValueError")
3759
3760 try: ''.join([0])
3761 except TypeError: pass
3762 else: self.fail("''.join([0]) doesn't raise TypeError")
3763
3764 try: ''.rindex('5')
3765 except ValueError: pass
3766 else: self.fail("''.rindex('5') doesn't raise ValueError")
3767
3768 try: '%(n)s' % None
3769 except TypeError: pass
3770 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3771
3772 try: '%(n' % {}
3773 except ValueError: pass
3774 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3775
3776 try: '%*s' % ('abc')
3777 except TypeError: pass
3778 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3779
3780 try: '%*.*s' % ('abc', 5)
3781 except TypeError: pass
3782 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3783
3784 try: '%s' % (1, 2)
3785 except TypeError: pass
3786 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3787
3788 try: '%' % None
3789 except ValueError: pass
3790 else: self.fail("'%' % None doesn't raise ValueError")
3791
3792 self.assertEqual('534253'.isdigit(), 1)
3793 self.assertEqual('534253x'.isdigit(), 0)
3794 self.assertEqual('%c' % 5, '\x05')
3795 self.assertEqual('%c' % '5', '5')
3796
3797 def test_deepcopy_recursive(self):
3798 # Testing deepcopy of recursive objects...
3799 class Node:
3800 pass
3801 a = Node()
3802 b = Node()
3803 a.b = b
3804 b.a = a
3805 z = deepcopy(a) # This blew up before
3806
Martin Panterf2f1c572016-05-08 13:18:25 +00003807 def test_uninitialized_modules(self):
Georg Brandl48545522008-02-02 10:12:36 +00003808 # Testing uninitialized module objects...
3809 from types import ModuleType as M
3810 m = M.__new__(M)
3811 str(m)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003812 self.assertNotHasAttr(m, "__name__")
3813 self.assertNotHasAttr(m, "__file__")
3814 self.assertNotHasAttr(m, "foo")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003815 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003816 m.foo = 1
3817 self.assertEqual(m.__dict__, {"foo": 1})
3818
3819 def test_funny_new(self):
3820 # Testing __new__ returning something unexpected...
3821 class C(object):
3822 def __new__(cls, arg):
3823 if isinstance(arg, str): return [1, 2, 3]
3824 elif isinstance(arg, int): return object.__new__(D)
3825 else: return object.__new__(cls)
3826 class D(C):
3827 def __init__(self, arg):
3828 self.foo = arg
3829 self.assertEqual(C("1"), [1, 2, 3])
3830 self.assertEqual(D("1"), [1, 2, 3])
3831 d = D(None)
3832 self.assertEqual(d.foo, None)
3833 d = C(1)
3834 self.assertEqual(isinstance(d, D), True)
3835 self.assertEqual(d.foo, 1)
3836 d = D(1)
3837 self.assertEqual(isinstance(d, D), True)
3838 self.assertEqual(d.foo, 1)
3839
Serhiy Storchaka7117d352016-12-14 19:48:38 +02003840 class C(object):
3841 @staticmethod
3842 def __new__(*args):
3843 return args
3844 self.assertEqual(C(1, 2), (C, 1, 2))
3845 class D(C):
3846 pass
3847 self.assertEqual(D(1, 2), (D, 1, 2))
3848
3849 class C(object):
3850 @classmethod
3851 def __new__(*args):
3852 return args
3853 self.assertEqual(C(1, 2), (C, C, 1, 2))
3854 class D(C):
3855 pass
3856 self.assertEqual(D(1, 2), (D, D, 1, 2))
3857
Georg Brandl48545522008-02-02 10:12:36 +00003858 def test_imul_bug(self):
3859 # Testing for __imul__ problems...
3860 # SF bug 544647
3861 class C(object):
3862 def __imul__(self, other):
3863 return (self, other)
3864 x = C()
3865 y = x
3866 y *= 1.0
3867 self.assertEqual(y, (x, 1.0))
3868 y = x
3869 y *= 2
3870 self.assertEqual(y, (x, 2))
3871 y = x
3872 y *= 3L
3873 self.assertEqual(y, (x, 3L))
3874 y = x
3875 y *= 1L<<100
3876 self.assertEqual(y, (x, 1L<<100))
3877 y = x
3878 y *= None
3879 self.assertEqual(y, (x, None))
3880 y = x
3881 y *= "foo"
3882 self.assertEqual(y, (x, "foo"))
3883
3884 def test_copy_setstate(self):
3885 # Testing that copy.*copy() correctly uses __setstate__...
3886 import copy
3887 class C(object):
3888 def __init__(self, foo=None):
3889 self.foo = foo
3890 self.__foo = foo
3891 def setfoo(self, foo=None):
3892 self.foo = foo
3893 def getfoo(self):
3894 return self.__foo
3895 def __getstate__(self):
3896 return [self.foo]
3897 def __setstate__(self_, lst):
3898 self.assertEqual(len(lst), 1)
3899 self_.__foo = self_.foo = lst[0]
3900 a = C(42)
3901 a.setfoo(24)
3902 self.assertEqual(a.foo, 24)
3903 self.assertEqual(a.getfoo(), 42)
3904 b = copy.copy(a)
3905 self.assertEqual(b.foo, 24)
3906 self.assertEqual(b.getfoo(), 24)
3907 b = copy.deepcopy(a)
3908 self.assertEqual(b.foo, 24)
3909 self.assertEqual(b.getfoo(), 24)
3910
3911 def test_slices(self):
3912 # Testing cases with slices and overridden __getitem__ ...
3913
3914 # Strings
3915 self.assertEqual("hello"[:4], "hell")
3916 self.assertEqual("hello"[slice(4)], "hell")
3917 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3918 class S(str):
3919 def __getitem__(self, x):
3920 return str.__getitem__(self, x)
3921 self.assertEqual(S("hello")[:4], "hell")
3922 self.assertEqual(S("hello")[slice(4)], "hell")
3923 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3924 # Tuples
3925 self.assertEqual((1,2,3)[:2], (1,2))
3926 self.assertEqual((1,2,3)[slice(2)], (1,2))
3927 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3928 class T(tuple):
3929 def __getitem__(self, x):
3930 return tuple.__getitem__(self, x)
3931 self.assertEqual(T((1,2,3))[:2], (1,2))
3932 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3933 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3934 # Lists
3935 self.assertEqual([1,2,3][:2], [1,2])
3936 self.assertEqual([1,2,3][slice(2)], [1,2])
3937 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3938 class L(list):
3939 def __getitem__(self, x):
3940 return list.__getitem__(self, x)
3941 self.assertEqual(L([1,2,3])[:2], [1,2])
3942 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3943 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3944 # Now do lists and __setitem__
3945 a = L([1,2,3])
3946 a[slice(1, 3)] = [3,2]
3947 self.assertEqual(a, [1,3,2])
3948 a[slice(0, 2, 1)] = [3,1]
3949 self.assertEqual(a, [3,1,2])
3950 a.__setitem__(slice(1, 3), [2,1])
3951 self.assertEqual(a, [3,2,1])
3952 a.__setitem__(slice(0, 2, 1), [2,3])
3953 self.assertEqual(a, [2,3,1])
3954
3955 def test_subtype_resurrection(self):
3956 # Testing resurrection of new-style instance...
3957
3958 class C(object):
3959 container = []
3960
3961 def __del__(self):
3962 # resurrect the instance
3963 C.container.append(self)
3964
3965 c = C()
3966 c.attr = 42
3967
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003968 # The most interesting thing here is whether this blows up, due to
3969 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3970 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003971 del c
3972
3973 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003974 # the last container slot works: that will attempt to delete c again,
3975 # which will cause c to get appended back to the container again
3976 # "during" the del. (On non-CPython implementations, however, __del__
3977 # is typically not called again.)
3978 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003979 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003980 del C.container[-1]
3981 if test_support.check_impl_detail():
3982 test_support.gc_collect()
3983 self.assertEqual(len(C.container), 1)
3984 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003985
3986 # Make c mortal again, so that the test framework with -l doesn't report
3987 # it as a leak.
3988 del C.__del__
3989
3990 def test_slots_trash(self):
3991 # Testing slot trash...
3992 # Deallocating deeply nested slotted trash caused stack overflows
3993 class trash(object):
3994 __slots__ = ['x']
3995 def __init__(self, x):
3996 self.x = x
3997 o = None
3998 for i in xrange(50000):
3999 o = trash(o)
4000 del o
4001
4002 def test_slots_multiple_inheritance(self):
4003 # SF bug 575229, multiple inheritance w/ slots dumps core
4004 class A(object):
4005 __slots__=()
4006 class B(object):
4007 pass
4008 class C(A,B) :
4009 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004010 if test_support.check_impl_detail():
4011 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004012 self.assertHasAttr(C, '__dict__')
4013 self.assertHasAttr(C, '__weakref__')
Georg Brandl48545522008-02-02 10:12:36 +00004014 C().x = 2
4015
4016 def test_rmul(self):
4017 # Testing correct invocation of __rmul__...
4018 # SF patch 592646
4019 class C(object):
4020 def __mul__(self, other):
4021 return "mul"
4022 def __rmul__(self, other):
4023 return "rmul"
4024 a = C()
4025 self.assertEqual(a*2, "mul")
4026 self.assertEqual(a*2.2, "mul")
4027 self.assertEqual(2*a, "rmul")
4028 self.assertEqual(2.2*a, "rmul")
4029
4030 def test_ipow(self):
4031 # Testing correct invocation of __ipow__...
4032 # [SF bug 620179]
4033 class C(object):
4034 def __ipow__(self, other):
4035 pass
4036 a = C()
4037 a **= 2
4038
4039 def test_mutable_bases(self):
4040 # Testing mutable bases...
4041
4042 # stuff that should work:
4043 class C(object):
4044 pass
4045 class C2(object):
4046 def __getattribute__(self, attr):
4047 if attr == 'a':
4048 return 2
4049 else:
4050 return super(C2, self).__getattribute__(attr)
4051 def meth(self):
4052 return 1
4053 class D(C):
4054 pass
4055 class E(D):
4056 pass
4057 d = D()
4058 e = E()
4059 D.__bases__ = (C,)
4060 D.__bases__ = (C2,)
4061 self.assertEqual(d.meth(), 1)
4062 self.assertEqual(e.meth(), 1)
4063 self.assertEqual(d.a, 2)
4064 self.assertEqual(e.a, 2)
4065 self.assertEqual(C2.__subclasses__(), [D])
4066
Georg Brandl48545522008-02-02 10:12:36 +00004067 try:
4068 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004069 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00004070 pass
4071 else:
4072 self.fail("shouldn't be able to delete .__bases__")
4073
4074 try:
4075 D.__bases__ = ()
4076 except TypeError, msg:
4077 if str(msg) == "a new-style class can't have only classic bases":
4078 self.fail("wrong error message for .__bases__ = ()")
4079 else:
4080 self.fail("shouldn't be able to set .__bases__ to ()")
4081
4082 try:
4083 D.__bases__ = (D,)
4084 except TypeError:
4085 pass
4086 else:
4087 # actually, we'll have crashed by here...
4088 self.fail("shouldn't be able to create inheritance cycles")
4089
4090 try:
4091 D.__bases__ = (C, C)
4092 except TypeError:
4093 pass
4094 else:
4095 self.fail("didn't detect repeated base classes")
4096
4097 try:
4098 D.__bases__ = (E,)
4099 except TypeError:
4100 pass
4101 else:
4102 self.fail("shouldn't be able to create inheritance cycles")
4103
4104 # let's throw a classic class into the mix:
4105 class Classic:
4106 def meth2(self):
4107 return 3
4108
4109 D.__bases__ = (C, Classic)
4110
4111 self.assertEqual(d.meth2(), 3)
4112 self.assertEqual(e.meth2(), 3)
4113 try:
4114 d.a
4115 except AttributeError:
4116 pass
4117 else:
4118 self.fail("attribute should have vanished")
4119
4120 try:
4121 D.__bases__ = (Classic,)
4122 except TypeError:
4123 pass
4124 else:
4125 self.fail("new-style class must have a new-style base")
4126
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004127 def test_builtin_bases(self):
4128 # Make sure all the builtin types can have their base queried without
4129 # segfaulting. See issue #5787.
4130 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
4131 if isinstance(tp, type)]
4132 for tp in builtin_types:
4133 object.__getattribute__(tp, "__bases__")
4134 if tp is not object:
4135 self.assertEqual(len(tp.__bases__), 1, tp)
4136
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00004137 class L(list):
4138 pass
4139
4140 class C(object):
4141 pass
4142
4143 class D(C):
4144 pass
4145
4146 try:
4147 L.__bases__ = (dict,)
4148 except TypeError:
4149 pass
4150 else:
4151 self.fail("shouldn't turn list subclass into dict subclass")
4152
4153 try:
4154 list.__bases__ = (dict,)
4155 except TypeError:
4156 pass
4157 else:
4158 self.fail("shouldn't be able to assign to list.__bases__")
4159
4160 try:
4161 D.__bases__ = (C, list)
4162 except TypeError:
4163 pass
4164 else:
4165 assert 0, "best_base calculation found wanting"
4166
Benjamin Peterson77d12ec2015-10-06 19:36:54 -07004167 def test_unsubclassable_types(self):
4168 with self.assertRaises(TypeError):
4169 class X(types.NoneType):
4170 pass
4171 with self.assertRaises(TypeError):
4172 class X(object, types.NoneType):
4173 pass
4174 with self.assertRaises(TypeError):
4175 class X(types.NoneType, object):
4176 pass
4177 class O(object):
4178 pass
4179 with self.assertRaises(TypeError):
4180 class X(O, types.NoneType):
4181 pass
4182 with self.assertRaises(TypeError):
4183 class X(types.NoneType, O):
4184 pass
4185
4186 class X(object):
4187 pass
4188 with self.assertRaises(TypeError):
4189 X.__bases__ = types.NoneType,
4190 with self.assertRaises(TypeError):
4191 X.__bases__ = object, types.NoneType
4192 with self.assertRaises(TypeError):
4193 X.__bases__ = types.NoneType, object
4194 with self.assertRaises(TypeError):
4195 X.__bases__ = O, types.NoneType
4196 with self.assertRaises(TypeError):
4197 X.__bases__ = types.NoneType, O
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004198
Georg Brandl48545522008-02-02 10:12:36 +00004199 def test_mutable_bases_with_failing_mro(self):
4200 # Testing mutable bases with failing mro...
4201 class WorkOnce(type):
4202 def __new__(self, name, bases, ns):
4203 self.flag = 0
4204 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4205 def mro(self):
4206 if self.flag > 0:
4207 raise RuntimeError, "bozo"
4208 else:
4209 self.flag += 1
4210 return type.mro(self)
4211
4212 class WorkAlways(type):
4213 def mro(self):
4214 # this is here to make sure that .mro()s aren't called
4215 # with an exception set (which was possible at one point).
4216 # An error message will be printed in a debug build.
4217 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004218 return type.mro(self)
4219
Georg Brandl48545522008-02-02 10:12:36 +00004220 class C(object):
4221 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004222
Georg Brandl48545522008-02-02 10:12:36 +00004223 class C2(object):
4224 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004225
Georg Brandl48545522008-02-02 10:12:36 +00004226 class D(C):
4227 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004228
Georg Brandl48545522008-02-02 10:12:36 +00004229 class E(D):
4230 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004231
Georg Brandl48545522008-02-02 10:12:36 +00004232 class F(D):
4233 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004234
Georg Brandl48545522008-02-02 10:12:36 +00004235 class G(D):
4236 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004237
Georg Brandl48545522008-02-02 10:12:36 +00004238 # Immediate subclasses have their mro's adjusted in alphabetical
4239 # order, so E's will get adjusted before adjusting F's fails. We
4240 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004241
Georg Brandl48545522008-02-02 10:12:36 +00004242 E_mro_before = E.__mro__
4243 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004244
Armin Rigofd163f92005-12-29 15:59:19 +00004245 try:
Georg Brandl48545522008-02-02 10:12:36 +00004246 D.__bases__ = (C2,)
4247 except RuntimeError:
4248 self.assertEqual(E.__mro__, E_mro_before)
4249 self.assertEqual(D.__mro__, D_mro_before)
4250 else:
4251 self.fail("exception not propagated")
4252
4253 def test_mutable_bases_catch_mro_conflict(self):
4254 # Testing mutable bases catch mro conflict...
4255 class A(object):
4256 pass
4257
4258 class B(object):
4259 pass
4260
4261 class C(A, B):
4262 pass
4263
4264 class D(A, B):
4265 pass
4266
4267 class E(C, D):
4268 pass
4269
4270 try:
4271 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004272 except TypeError:
4273 pass
4274 else:
Georg Brandl48545522008-02-02 10:12:36 +00004275 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004276
Georg Brandl48545522008-02-02 10:12:36 +00004277 def test_mutable_names(self):
4278 # Testing mutable names...
4279 class C(object):
4280 pass
4281
4282 # C.__module__ could be 'test_descr' or '__main__'
4283 mod = C.__module__
4284
4285 C.__name__ = 'D'
4286 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4287
4288 C.__name__ = 'D.E'
4289 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4290
Mark Dickinsonf794b142013-04-13 15:19:05 +01004291 def test_evil_type_name(self):
4292 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4293 # execution while the type structure was not in a sane state, and a
4294 # possible segmentation fault as a result. See bug #16447.
4295 class Nasty(str):
4296 def __del__(self):
4297 C.__name__ = "other"
4298
4299 class C(object):
4300 pass
4301
4302 C.__name__ = Nasty("abc")
4303 C.__name__ = "normal"
4304
Georg Brandl48545522008-02-02 10:12:36 +00004305 def test_subclass_right_op(self):
4306 # Testing correct dispatch of subclass overloading __r<op>__...
4307
4308 # This code tests various cases where right-dispatch of a subclass
4309 # should be preferred over left-dispatch of a base class.
4310
4311 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4312
4313 class B(int):
4314 def __floordiv__(self, other):
4315 return "B.__floordiv__"
4316 def __rfloordiv__(self, other):
4317 return "B.__rfloordiv__"
4318
4319 self.assertEqual(B(1) // 1, "B.__floordiv__")
4320 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4321
4322 # Case 2: subclass of object; this is just the baseline for case 3
4323
4324 class C(object):
4325 def __floordiv__(self, other):
4326 return "C.__floordiv__"
4327 def __rfloordiv__(self, other):
4328 return "C.__rfloordiv__"
4329
4330 self.assertEqual(C() // 1, "C.__floordiv__")
4331 self.assertEqual(1 // C(), "C.__rfloordiv__")
4332
4333 # Case 3: subclass of new-style class; here it gets interesting
4334
4335 class D(C):
4336 def __floordiv__(self, other):
4337 return "D.__floordiv__"
4338 def __rfloordiv__(self, other):
4339 return "D.__rfloordiv__"
4340
4341 self.assertEqual(D() // C(), "D.__floordiv__")
4342 self.assertEqual(C() // D(), "D.__rfloordiv__")
4343
4344 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4345
4346 class E(C):
4347 pass
4348
4349 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4350
4351 self.assertEqual(E() // 1, "C.__floordiv__")
4352 self.assertEqual(1 // E(), "C.__rfloordiv__")
4353 self.assertEqual(E() // C(), "C.__floordiv__")
4354 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4355
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004356 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004357 def test_meth_class_get(self):
4358 # Testing __get__ method of METH_CLASS C methods...
4359 # Full coverage of descrobject.c::classmethod_get()
4360
4361 # Baseline
4362 arg = [1, 2, 3]
4363 res = {1: None, 2: None, 3: None}
4364 self.assertEqual(dict.fromkeys(arg), res)
4365 self.assertEqual({}.fromkeys(arg), res)
4366
4367 # Now get the descriptor
4368 descr = dict.__dict__["fromkeys"]
4369
4370 # More baseline using the descriptor directly
4371 self.assertEqual(descr.__get__(None, dict)(arg), res)
4372 self.assertEqual(descr.__get__({})(arg), res)
4373
4374 # Now check various error cases
4375 try:
4376 descr.__get__(None, None)
4377 except TypeError:
4378 pass
4379 else:
4380 self.fail("shouldn't have allowed descr.__get__(None, None)")
4381 try:
4382 descr.__get__(42)
4383 except TypeError:
4384 pass
4385 else:
4386 self.fail("shouldn't have allowed descr.__get__(42)")
4387 try:
4388 descr.__get__(None, 42)
4389 except TypeError:
4390 pass
4391 else:
4392 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4393 try:
4394 descr.__get__(None, int)
4395 except TypeError:
4396 pass
4397 else:
4398 self.fail("shouldn't have allowed descr.__get__(None, int)")
4399
4400 def test_isinst_isclass(self):
4401 # Testing proxy isinstance() and isclass()...
4402 class Proxy(object):
4403 def __init__(self, obj):
4404 self.__obj = obj
4405 def __getattribute__(self, name):
4406 if name.startswith("_Proxy__"):
4407 return object.__getattribute__(self, name)
4408 else:
4409 return getattr(self.__obj, name)
4410 # Test with a classic class
4411 class C:
4412 pass
4413 a = C()
4414 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004415 self.assertIsInstance(a, C) # Baseline
4416 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004417 # Test with a classic subclass
4418 class D(C):
4419 pass
4420 a = D()
4421 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004422 self.assertIsInstance(a, C) # Baseline
4423 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004424 # Test with a new-style class
4425 class C(object):
4426 pass
4427 a = C()
4428 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004429 self.assertIsInstance(a, C) # Baseline
4430 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004431 # Test with a new-style subclass
4432 class D(C):
4433 pass
4434 a = D()
4435 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004436 self.assertIsInstance(a, C) # Baseline
4437 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004438
4439 def test_proxy_super(self):
4440 # Testing super() for a proxy object...
4441 class Proxy(object):
4442 def __init__(self, obj):
4443 self.__obj = obj
4444 def __getattribute__(self, name):
4445 if name.startswith("_Proxy__"):
4446 return object.__getattribute__(self, name)
4447 else:
4448 return getattr(self.__obj, name)
4449
4450 class B(object):
4451 def f(self):
4452 return "B.f"
4453
4454 class C(B):
4455 def f(self):
4456 return super(C, self).f() + "->C.f"
4457
4458 obj = C()
4459 p = Proxy(obj)
4460 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4461
4462 def test_carloverre(self):
4463 # Testing prohibition of Carlo Verre's hack...
4464 try:
4465 object.__setattr__(str, "foo", 42)
4466 except TypeError:
4467 pass
4468 else:
Ezio Melottic2077b02011-03-16 12:34:31 +02004469 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl48545522008-02-02 10:12:36 +00004470 try:
4471 object.__delattr__(str, "lower")
4472 except TypeError:
4473 pass
4474 else:
4475 self.fail("Carlo Verre __delattr__ succeeded!")
4476
4477 def test_weakref_segfault(self):
4478 # Testing weakref segfault...
4479 # SF 742911
4480 import weakref
4481
4482 class Provoker:
4483 def __init__(self, referrent):
4484 self.ref = weakref.ref(referrent)
4485
4486 def __del__(self):
4487 x = self.ref()
4488
4489 class Oops(object):
4490 pass
4491
4492 o = Oops()
4493 o.whatever = Provoker(o)
4494 del o
4495
4496 def test_wrapper_segfault(self):
4497 # SF 927248: deeply nested wrappers could cause stack overflow
4498 f = lambda:None
4499 for i in xrange(1000000):
4500 f = f.__call__
4501 f = None
4502
4503 def test_file_fault(self):
4504 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004505 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004506 class StdoutGuard:
4507 def __getattr__(self, attr):
4508 sys.stdout = sys.__stdout__
4509 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4510 sys.stdout = StdoutGuard()
4511 try:
4512 print "Oops!"
4513 except RuntimeError:
4514 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004515 finally:
4516 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004517
4518 def test_vicious_descriptor_nonsense(self):
4519 # Testing vicious_descriptor_nonsense...
4520
4521 # A potential segfault spotted by Thomas Wouters in mail to
4522 # python-dev 2003-04-17, turned into an example & fixed by Michael
4523 # Hudson just less than four months later...
4524
4525 class Evil(object):
4526 def __hash__(self):
4527 return hash('attr')
4528 def __eq__(self, other):
4529 del C.attr
4530 return 0
4531
4532 class Descr(object):
4533 def __get__(self, ob, type=None):
4534 return 1
4535
4536 class C(object):
4537 attr = Descr()
4538
4539 c = C()
4540 c.__dict__[Evil()] = 0
4541
4542 self.assertEqual(c.attr, 1)
4543 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004544 test_support.gc_collect()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004545 self.assertNotHasAttr(c, 'attr')
Georg Brandl48545522008-02-02 10:12:36 +00004546
4547 def test_init(self):
4548 # SF 1155938
4549 class Foo(object):
4550 def __init__(self):
4551 return 10
4552 try:
4553 Foo()
4554 except TypeError:
4555 pass
4556 else:
4557 self.fail("did not test __init__() for None return")
4558
4559 def test_method_wrapper(self):
4560 # Testing method-wrapper objects...
4561 # <type 'method-wrapper'> did not support any reflection before 2.5
4562
4563 l = []
4564 self.assertEqual(l.__add__, l.__add__)
4565 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004566 self.assertNotEqual(l.__add__, [5].__add__)
4567 self.assertNotEqual(l.__add__, l.__mul__)
4568 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004569 if hasattr(l.__add__, '__self__'):
4570 # CPython
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004571 self.assertIs(l.__add__.__self__, l)
4572 self.assertIs(l.__add__.__objclass__, list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004573 else:
4574 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004575 self.assertIs(l.__add__.im_self, l)
4576 self.assertIs(l.__add__.im_class, list)
Georg Brandl48545522008-02-02 10:12:36 +00004577 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4578 try:
4579 hash(l.__add__)
4580 except TypeError:
4581 pass
4582 else:
4583 self.fail("no TypeError from hash([].__add__)")
4584
4585 t = ()
4586 t += (7,)
4587 self.assertEqual(t.__add__, (7,).__add__)
4588 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4589
4590 def test_not_implemented(self):
4591 # Testing NotImplemented...
4592 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004593 import operator
4594
4595 def specialmethod(self, other):
4596 return NotImplemented
4597
4598 def check(expr, x, y):
4599 try:
4600 exec expr in {'x': x, 'y': y, 'operator': operator}
4601 except TypeError:
4602 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004603 else:
Georg Brandl48545522008-02-02 10:12:36 +00004604 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004605
Georg Brandl48545522008-02-02 10:12:36 +00004606 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4607 # TypeErrors
4608 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4609 # ValueErrors instead of TypeErrors
4610 for metaclass in [type, types.ClassType]:
4611 for name, expr, iexpr in [
4612 ('__add__', 'x + y', 'x += y'),
4613 ('__sub__', 'x - y', 'x -= y'),
4614 ('__mul__', 'x * y', 'x *= y'),
4615 ('__truediv__', 'operator.truediv(x, y)', None),
4616 ('__floordiv__', 'operator.floordiv(x, y)', None),
4617 ('__div__', 'x / y', 'x /= y'),
4618 ('__mod__', 'x % y', 'x %= y'),
4619 ('__divmod__', 'divmod(x, y)', None),
4620 ('__pow__', 'x ** y', 'x **= y'),
4621 ('__lshift__', 'x << y', 'x <<= y'),
4622 ('__rshift__', 'x >> y', 'x >>= y'),
4623 ('__and__', 'x & y', 'x &= y'),
4624 ('__or__', 'x | y', 'x |= y'),
4625 ('__xor__', 'x ^ y', 'x ^= y'),
4626 ('__coerce__', 'coerce(x, y)', None)]:
4627 if name == '__coerce__':
4628 rname = name
4629 else:
4630 rname = '__r' + name[2:]
4631 A = metaclass('A', (), {name: specialmethod})
4632 B = metaclass('B', (), {rname: specialmethod})
4633 a = A()
4634 b = B()
4635 check(expr, a, a)
4636 check(expr, a, b)
4637 check(expr, b, a)
4638 check(expr, b, b)
4639 check(expr, a, N1)
4640 check(expr, a, N2)
4641 check(expr, N1, b)
4642 check(expr, N2, b)
4643 if iexpr:
4644 check(iexpr, a, a)
4645 check(iexpr, a, b)
4646 check(iexpr, b, a)
4647 check(iexpr, b, b)
4648 check(iexpr, a, N1)
4649 check(iexpr, a, N2)
4650 iname = '__i' + name[2:]
4651 C = metaclass('C', (), {iname: specialmethod})
4652 c = C()
4653 check(iexpr, c, a)
4654 check(iexpr, c, b)
4655 check(iexpr, c, N1)
4656 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004657
Georg Brandl48545522008-02-02 10:12:36 +00004658 def test_assign_slice(self):
4659 # ceval.c's assign_slice used to check for
4660 # tp->tp_as_sequence->sq_slice instead of
4661 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004662
Georg Brandl48545522008-02-02 10:12:36 +00004663 class C(object):
4664 def __setslice__(self, start, stop, value):
4665 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004666
Georg Brandl48545522008-02-02 10:12:36 +00004667 c = C()
4668 c[1:2] = 3
4669 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004670
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004671 def test_set_and_no_get(self):
4672 # See
4673 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4674 class Descr(object):
4675
4676 def __init__(self, name):
4677 self.name = name
4678
4679 def __set__(self, obj, value):
4680 obj.__dict__[self.name] = value
4681 descr = Descr("a")
4682
4683 class X(object):
4684 a = descr
4685
4686 x = X()
4687 self.assertIs(x.a, descr)
4688 x.a = 42
4689 self.assertEqual(x.a, 42)
4690
Benjamin Peterson42d59472010-02-06 20:14:10 +00004691 # Also check type_getattro for correctness.
4692 class Meta(type):
4693 pass
4694 class X(object):
4695 __metaclass__ = Meta
4696 X.a = 42
4697 Meta.a = Descr("a")
4698 self.assertEqual(X.a, 42)
4699
Benjamin Peterson273c2332008-11-17 22:39:09 +00004700 def test_getattr_hooks(self):
4701 # issue 4230
4702
4703 class Descriptor(object):
4704 counter = 0
4705 def __get__(self, obj, objtype=None):
4706 def getter(name):
4707 self.counter += 1
4708 raise AttributeError(name)
4709 return getter
4710
4711 descr = Descriptor()
4712 class A(object):
4713 __getattribute__ = descr
4714 class B(object):
4715 __getattr__ = descr
4716 class C(object):
4717 __getattribute__ = descr
4718 __getattr__ = descr
4719
4720 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004721 self.assertEqual(descr.counter, 1)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004722 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004723 self.assertEqual(descr.counter, 2)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004724 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004725 self.assertEqual(descr.counter, 4)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004726
Benjamin Peterson273c2332008-11-17 22:39:09 +00004727 class EvilGetattribute(object):
4728 # This used to segfault
4729 def __getattr__(self, name):
4730 raise AttributeError(name)
4731 def __getattribute__(self, name):
4732 del EvilGetattribute.__getattr__
4733 for i in range(5):
4734 gc.collect()
4735 raise AttributeError(name)
4736
4737 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4738
Benjamin Peterson6e7832b2012-03-16 09:32:59 -05004739 def test_type___getattribute__(self):
4740 self.assertRaises(TypeError, type.__getattribute__, list, type)
4741
Benjamin Peterson9b911ca2011-01-12 15:49:47 +00004742 def test_abstractmethods(self):
4743 # type pretends not to have __abstractmethods__.
4744 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4745 class meta(type):
4746 pass
4747 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4748 class X(object):
4749 pass
4750 with self.assertRaises(AttributeError):
4751 del X.__abstractmethods__
4752
Victor Stinnere363ec12011-05-01 23:43:37 +02004753 def test_proxy_call(self):
4754 class FakeStr(object):
4755 __class__ = str
4756
4757 fake_str = FakeStr()
4758 # isinstance() reads __class__ on new style classes
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004759 self.assertIsInstance(fake_str, str)
Victor Stinnere363ec12011-05-01 23:43:37 +02004760
4761 # call a method descriptor
4762 with self.assertRaises(TypeError):
4763 str.split(fake_str)
4764
4765 # call a slot wrapper descriptor
4766 with self.assertRaises(TypeError):
4767 str.__add__(fake_str, "abc")
4768
Antoine Pitrou304f0f92011-07-15 21:22:50 +02004769 def test_repr_as_str(self):
4770 # Issue #11603: crash or infinite loop when rebinding __str__ as
4771 # __repr__.
4772 class Foo(object):
4773 pass
4774 Foo.__repr__ = Foo.__str__
4775 foo = Foo()
Benjamin Petersond157a4c2012-04-24 11:06:25 -04004776 self.assertRaises(RuntimeError, str, foo)
4777 self.assertRaises(RuntimeError, repr, foo)
4778
4779 def test_mixing_slot_wrappers(self):
4780 class X(dict):
4781 __setattr__ = dict.__setitem__
4782 x = X()
4783 x.y = 42
4784 self.assertEqual(x["y"], 42)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004785
Benjamin Petersona8d45852012-03-07 18:41:11 -06004786 def test_cycle_through_dict(self):
4787 # See bug #1469629
4788 class X(dict):
4789 def __init__(self):
4790 dict.__init__(self)
4791 self.__dict__ = self
4792 x = X()
4793 x.attr = 42
4794 wr = weakref.ref(x)
4795 del x
4796 test_support.gc_collect()
4797 self.assertIsNone(wr())
4798 for o in gc.get_objects():
4799 self.assertIsNot(type(o), X)
4800
Benjamin Petersondd171ea2016-01-18 21:18:49 -08004801
Georg Brandl48545522008-02-02 10:12:36 +00004802class DictProxyTests(unittest.TestCase):
4803 def setUp(self):
4804 class C(object):
4805 def meth(self):
4806 pass
4807 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004808
Raymond Hettingerbf7a2662011-06-30 00:44:36 +01004809 def test_repr(self):
4810 self.assertIn('dict_proxy({', repr(vars(self.C)))
4811 self.assertIn("'meth':", repr(vars(self.C)))
4812
Georg Brandl48545522008-02-02 10:12:36 +00004813 def test_iter_keys(self):
4814 # Testing dict-proxy iterkeys...
4815 keys = [ key for key in self.C.__dict__.iterkeys() ]
4816 keys.sort()
Ezio Melotti2623a372010-11-21 13:34:58 +00004817 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl48545522008-02-02 10:12:36 +00004818 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004819
Georg Brandl48545522008-02-02 10:12:36 +00004820 def test_iter_values(self):
4821 # Testing dict-proxy itervalues...
4822 values = [ values for values in self.C.__dict__.itervalues() ]
4823 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004824
Georg Brandl48545522008-02-02 10:12:36 +00004825 def test_iter_items(self):
4826 # Testing dict-proxy iteritems...
4827 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4828 keys.sort()
4829 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4830 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004831
Georg Brandl48545522008-02-02 10:12:36 +00004832 def test_dict_type_with_metaclass(self):
4833 # Testing type of __dict__ when __metaclass__ set...
4834 class B(object):
4835 pass
4836 class M(type):
4837 pass
4838 class C:
4839 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4840 __metaclass__ = M
4841 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004842
Guido van Rossum9acc3872008-01-23 23:23:43 +00004843
Georg Brandl48545522008-02-02 10:12:36 +00004844class PTypesLongInitTest(unittest.TestCase):
4845 # This is in its own TestCase so that it can be run before any other tests.
4846 def test_pytype_long_ready(self):
4847 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004848
Georg Brandl48545522008-02-02 10:12:36 +00004849 # This dumps core when SF bug 551412 isn't fixed --
4850 # but only when test_descr.py is run separately.
4851 # (That can't be helped -- as soon as PyType_Ready()
4852 # is called for PyLong_Type, the bug is gone.)
4853 class UserLong(object):
4854 def __pow__(self, *args):
4855 pass
4856 try:
4857 pow(0L, UserLong(), 0L)
4858 except:
4859 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004860
Georg Brandl48545522008-02-02 10:12:36 +00004861 # Another segfault only when run early
4862 # (before PyType_Ready(tuple) is called)
4863 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004864
4865
Serhiy Storchakaee1b24c2015-11-25 18:35:33 +02004866class PicklingTests(unittest.TestCase):
4867
4868 def test_issue24097(self):
4869 # Slot name is freed inside __getattr__ and is later used.
4870 class S(str): # Not interned
4871 pass
4872 class A(object):
4873 __slotnames__ = [S('spam')]
4874 def __getattr__(self, attr):
4875 if attr == 'spam':
4876 A.__slotnames__[:] = [S('spam')]
4877 return 42
4878 else:
4879 raise AttributeError
4880
4881 import copy_reg
4882 expected = (copy_reg.__newobj__, (A,), ({}, {'spam': 42}), None, None)
4883 self.assertEqual(A().__reduce__(2), expected)
4884
4885
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004886def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004887 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4888 DeprecationWarning)]
4889 if sys.py3kwarning:
4890 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004891 ("classic (int|long) division", DeprecationWarning),
4892 ("coerce.. not supported", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004893 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4894 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004895 # Run all local test cases, with PTypesLongInitTest first.
4896 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
Serhiy Storchakaee1b24c2015-11-25 18:35:33 +02004897 ClassPropertiesAndMethods, DictProxyTests,
4898 PicklingTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004899
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004900if __name__ == "__main__":
4901 test_main()