blob: bbc52aa67913145e06655f9fabf822abf7021005 [file] [log] [blame]
Benjamin Petersond4d400c2009-04-18 20:12:47 +00001import __builtin__
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +03002import copy
Benjamin Petersona8d45852012-03-07 18:41:11 -06003import gc
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +03004import pickle
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00005import sys
Armin Rigo9790a272007-05-02 19:23:31 +00006import types
Georg Brandl48545522008-02-02 10:12:36 +00007import unittest
Serhiy Storchaka7117d352016-12-14 19:48:38 +02008import warnings
Benjamin Petersona8d45852012-03-07 18:41:11 -06009import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +000010
Georg Brandl48545522008-02-02 10:12:36 +000011from copy import deepcopy
12from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +000013
Guido van Rossum875eeaa2001-10-11 18:33:53 +000014
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +030015def func(*args):
16 return args
17
18
Georg Brandl48545522008-02-02 10:12:36 +000019class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000020
Georg Brandl48545522008-02-02 10:12:36 +000021 def __init__(self, *args, **kwargs):
22 unittest.TestCase.__init__(self, *args, **kwargs)
23 self.binops = {
24 'add': '+',
25 'sub': '-',
26 'mul': '*',
27 'div': '/',
28 'divmod': 'divmod',
29 'pow': '**',
30 'lshift': '<<',
31 'rshift': '>>',
32 'and': '&',
33 'xor': '^',
34 'or': '|',
35 'cmp': 'cmp',
36 'lt': '<',
37 'le': '<=',
38 'eq': '==',
39 'ne': '!=',
40 'gt': '>',
41 'ge': '>=',
42 }
Tim Peters3caca232001-12-06 06:23:26 +000043
Georg Brandl48545522008-02-02 10:12:36 +000044 for name, expr in self.binops.items():
45 if expr.islower():
46 expr = expr + "(a, b)"
47 else:
48 expr = 'a %s b' % expr
49 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000050
Georg Brandl48545522008-02-02 10:12:36 +000051 self.unops = {
52 'pos': '+',
53 'neg': '-',
54 'abs': 'abs',
55 'invert': '~',
56 'int': 'int',
57 'long': 'long',
58 'float': 'float',
59 'oct': 'oct',
60 'hex': 'hex',
61 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000062
Georg Brandl48545522008-02-02 10:12:36 +000063 for name, expr in self.unops.items():
64 if expr.islower():
65 expr = expr + "(a)"
66 else:
67 expr = '%s a' % expr
68 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000069
Georg Brandl48545522008-02-02 10:12:36 +000070 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
71 d = {'a': a}
72 self.assertEqual(eval(expr, d), res)
73 t = type(a)
74 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000075
Georg Brandl48545522008-02-02 10:12:36 +000076 # Find method in parent class
77 while meth not in t.__dict__:
78 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000079 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
80 # method object; the getattr() below obtains its underlying function.
81 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000082 self.assertEqual(m(a), res)
83 bm = getattr(a, meth)
84 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl48545522008-02-02 10:12:36 +000086 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
87 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000088
Georg Brandl48545522008-02-02 10:12:36 +000089 # XXX Hack so this passes before 2.3 when -Qnew is specified.
90 if meth == "__div__" and 1/2 == 0.5:
91 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000092
Georg Brandl48545522008-02-02 10:12:36 +000093 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000094
Georg Brandl48545522008-02-02 10:12:36 +000095 self.assertEqual(eval(expr, d), res)
96 t = type(a)
97 m = getattr(t, meth)
98 while meth not in t.__dict__:
99 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000100 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
101 # method object; the getattr() below obtains its underlying function.
102 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000103 self.assertEqual(m(a, b), res)
104 bm = getattr(a, meth)
105 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000106
Georg Brandl48545522008-02-02 10:12:36 +0000107 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
108 d = {'a': a, 'b': b, 'c': c}
109 self.assertEqual(eval(expr, d), res)
110 t = type(a)
111 m = getattr(t, meth)
112 while meth not in t.__dict__:
113 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000114 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
115 # method object; the getattr() below obtains its underlying function.
116 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000117 self.assertEqual(m(a, b, c), res)
118 bm = getattr(a, meth)
119 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000120
Georg Brandl48545522008-02-02 10:12:36 +0000121 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
122 d = {'a': deepcopy(a), 'b': b}
123 exec stmt in d
124 self.assertEqual(d['a'], res)
125 t = type(a)
126 m = getattr(t, meth)
127 while meth not in t.__dict__:
128 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000129 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
130 # method object; the getattr() below obtains its underlying function.
131 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000132 d['a'] = deepcopy(a)
133 m(d['a'], b)
134 self.assertEqual(d['a'], res)
135 d['a'] = deepcopy(a)
136 bm = getattr(d['a'], meth)
137 bm(b)
138 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000139
Georg Brandl48545522008-02-02 10:12:36 +0000140 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
141 d = {'a': deepcopy(a), 'b': b, 'c': c}
142 exec stmt in d
143 self.assertEqual(d['a'], res)
144 t = type(a)
145 m = getattr(t, meth)
146 while meth not in t.__dict__:
147 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000148 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
149 # method object; the getattr() below obtains its underlying function.
150 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000151 d['a'] = deepcopy(a)
152 m(d['a'], b, c)
153 self.assertEqual(d['a'], res)
154 d['a'] = deepcopy(a)
155 bm = getattr(d['a'], meth)
156 bm(b, c)
157 self.assertEqual(d['a'], res)
158
159 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
160 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
161 exec stmt in dictionary
162 self.assertEqual(dictionary['a'], res)
163 t = type(a)
164 while meth not in t.__dict__:
165 t = t.__bases__[0]
166 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000167 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
168 # method object; the getattr() below obtains its underlying function.
169 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000170 dictionary['a'] = deepcopy(a)
171 m(dictionary['a'], b, c, d)
172 self.assertEqual(dictionary['a'], res)
173 dictionary['a'] = deepcopy(a)
174 bm = getattr(dictionary['a'], meth)
175 bm(b, c, d)
176 self.assertEqual(dictionary['a'], res)
177
178 def test_lists(self):
179 # Testing list operations...
180 # Asserts are within individual test methods
181 self.binop_test([1], [2], [1,2], "a+b", "__add__")
182 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
183 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
184 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
185 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
186 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
187 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
188 self.unop_test([1,2,3], 3, "len(a)", "__len__")
189 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
190 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
191 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
192 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
193 "__setslice__")
194
195 def test_dicts(self):
196 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000197 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
198 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
199 else:
200 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000201 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
202 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
203 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
204
205 d = {1:2, 3:4}
206 l1 = []
207 for i in d.keys():
208 l1.append(i)
209 l = []
210 for i in iter(d):
211 l.append(i)
212 self.assertEqual(l, l1)
213 l = []
214 for i in d.__iter__():
215 l.append(i)
216 self.assertEqual(l, l1)
217 l = []
218 for i in dict.__iter__(d):
219 l.append(i)
220 self.assertEqual(l, l1)
221 d = {1:2, 3:4}
222 self.unop_test(d, 2, "len(a)", "__len__")
223 self.assertEqual(eval(repr(d), {}), d)
224 self.assertEqual(eval(d.__repr__(), {}), d)
225 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
226 "__setitem__")
227
228 # Tests for unary and binary operators
229 def number_operators(self, a, b, skip=[]):
230 dict = {'a': a, 'b': b}
231
232 for name, expr in self.binops.items():
233 if name not in skip:
234 name = "__%s__" % name
235 if hasattr(a, name):
236 res = eval(expr, dict)
237 self.binop_test(a, b, res, expr, name)
238
239 for name, expr in self.unops.items():
240 if name not in skip:
241 name = "__%s__" % name
242 if hasattr(a, name):
243 res = eval(expr, dict)
244 self.unop_test(a, res, expr, name)
245
246 def test_ints(self):
247 # Testing int operations...
248 self.number_operators(100, 3)
249 # The following crashes in Python 2.2
250 self.assertEqual((1).__nonzero__(), 1)
251 self.assertEqual((0).__nonzero__(), 0)
252 # This returns 'NotImplemented' in Python 2.2
253 class C(int):
254 def __add__(self, other):
255 return NotImplemented
256 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000257 try:
Georg Brandl48545522008-02-02 10:12:36 +0000258 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000259 except TypeError:
260 pass
261 else:
Georg Brandl48545522008-02-02 10:12:36 +0000262 self.fail("NotImplemented should have caused TypeError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000263 try:
Georg Brandl48545522008-02-02 10:12:36 +0000264 C(sys.maxint+1)
265 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000266 pass
267 else:
Georg Brandl48545522008-02-02 10:12:36 +0000268 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000269
Georg Brandl48545522008-02-02 10:12:36 +0000270 def test_longs(self):
271 # Testing long operations...
272 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000273
Georg Brandl48545522008-02-02 10:12:36 +0000274 def test_floats(self):
275 # Testing float operations...
276 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000277
Georg Brandl48545522008-02-02 10:12:36 +0000278 def test_complexes(self):
279 # Testing complex operations...
280 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
281 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000282
Georg Brandl48545522008-02-02 10:12:36 +0000283 class Number(complex):
284 __slots__ = ['prec']
285 def __new__(cls, *args, **kwds):
286 result = complex.__new__(cls, *args)
287 result.prec = kwds.get('prec', 12)
288 return result
289 def __repr__(self):
290 prec = self.prec
291 if self.imag == 0.0:
292 return "%.*g" % (prec, self.real)
293 if self.real == 0.0:
294 return "%.*gj" % (prec, self.imag)
295 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
296 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000297
Georg Brandl48545522008-02-02 10:12:36 +0000298 a = Number(3.14, prec=6)
299 self.assertEqual(repr(a), "3.14")
300 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000301
Georg Brandl48545522008-02-02 10:12:36 +0000302 a = Number(a, prec=2)
303 self.assertEqual(repr(a), "3.1")
304 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000305
Georg Brandl48545522008-02-02 10:12:36 +0000306 a = Number(234.5)
307 self.assertEqual(repr(a), "234.5")
308 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000309
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000310 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000311 def test_spam_lists(self):
312 # Testing spamlist operations...
313 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000314
Georg Brandl48545522008-02-02 10:12:36 +0000315 def spamlist(l, memo=None):
316 import xxsubtype as spam
317 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000318
Georg Brandl48545522008-02-02 10:12:36 +0000319 # This is an ugly hack:
320 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000321
Georg Brandl48545522008-02-02 10:12:36 +0000322 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
323 "__add__")
324 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
325 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
326 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
327 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
328 "__getslice__")
329 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
330 "__iadd__")
331 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
332 "__imul__")
333 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
334 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
335 "__mul__")
336 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
337 "__rmul__")
338 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
339 "__setitem__")
340 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
341 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
342 # Test subclassing
343 class C(spam.spamlist):
344 def foo(self): return 1
345 a = C()
346 self.assertEqual(a, [])
347 self.assertEqual(a.foo(), 1)
348 a.append(100)
349 self.assertEqual(a, [100])
350 self.assertEqual(a.getstate(), 0)
351 a.setstate(42)
352 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000353
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000354 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000355 def test_spam_dicts(self):
356 # Testing spamdict operations...
357 import copy, xxsubtype as spam
358 def spamdict(d, memo=None):
359 import xxsubtype as spam
360 sd = spam.spamdict()
361 for k, v in d.items():
362 sd[k] = v
363 return sd
364 # This is an ugly hack:
365 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000366
Georg Brandl48545522008-02-02 10:12:36 +0000367 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
368 "__cmp__")
369 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
370 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
371 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
372 d = spamdict({1:2,3:4})
373 l1 = []
374 for i in d.keys():
375 l1.append(i)
376 l = []
377 for i in iter(d):
378 l.append(i)
379 self.assertEqual(l, l1)
380 l = []
381 for i in d.__iter__():
382 l.append(i)
383 self.assertEqual(l, l1)
384 l = []
385 for i in type(spamdict({})).__iter__(d):
386 l.append(i)
387 self.assertEqual(l, l1)
388 straightd = {1:2, 3:4}
389 spamd = spamdict(straightd)
390 self.unop_test(spamd, 2, "len(a)", "__len__")
391 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
392 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
393 "a[b]=c", "__setitem__")
394 # Test subclassing
395 class C(spam.spamdict):
396 def foo(self): return 1
397 a = C()
398 self.assertEqual(a.items(), [])
399 self.assertEqual(a.foo(), 1)
400 a['foo'] = 'bar'
401 self.assertEqual(a.items(), [('foo', 'bar')])
402 self.assertEqual(a.getstate(), 0)
403 a.setstate(100)
404 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000405
Georg Brandl48545522008-02-02 10:12:36 +0000406class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000407
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200408 def assertHasAttr(self, obj, name):
409 self.assertTrue(hasattr(obj, name),
410 '%r has no attribute %r' % (obj, name))
411
412 def assertNotHasAttr(self, obj, name):
413 self.assertFalse(hasattr(obj, name),
414 '%r has unexpected attribute %r' % (obj, name))
415
Georg Brandl48545522008-02-02 10:12:36 +0000416 def test_python_dicts(self):
417 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000418 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000419 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000420 d = dict()
421 self.assertEqual(d, {})
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200422 self.assertIs(d.__class__, dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000423 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000424 class C(dict):
425 state = -1
426 def __init__(self_local, *a, **kw):
427 if a:
428 self.assertEqual(len(a), 1)
429 self_local.state = a[0]
430 if kw:
431 for k, v in kw.items():
432 self_local[v] = k
433 def __getitem__(self, key):
434 return self.get(key, 0)
435 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000436 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000437 dict.__setitem__(self_local, key, value)
438 def setstate(self, state):
439 self.state = state
440 def getstate(self):
441 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000442 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000443 a1 = C(12)
444 self.assertEqual(a1.state, 12)
445 a2 = C(foo=1, bar=2)
446 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
447 a = C()
448 self.assertEqual(a.state, -1)
449 self.assertEqual(a.getstate(), -1)
450 a.setstate(0)
451 self.assertEqual(a.state, 0)
452 self.assertEqual(a.getstate(), 0)
453 a.setstate(10)
454 self.assertEqual(a.state, 10)
455 self.assertEqual(a.getstate(), 10)
456 self.assertEqual(a[42], 0)
457 a[42] = 24
458 self.assertEqual(a[42], 24)
459 N = 50
460 for i in range(N):
461 a[i] = C()
462 for j in range(N):
463 a[i][j] = i*j
464 for i in range(N):
465 for j in range(N):
466 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000467
Georg Brandl48545522008-02-02 10:12:36 +0000468 def test_python_lists(self):
469 # Testing Python subclass of list...
470 class C(list):
471 def __getitem__(self, i):
472 return list.__getitem__(self, i) + 100
473 def __getslice__(self, i, j):
474 return (i, j)
475 a = C()
476 a.extend([0,1,2])
477 self.assertEqual(a[0], 100)
478 self.assertEqual(a[1], 101)
479 self.assertEqual(a[2], 102)
480 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000481
Georg Brandl48545522008-02-02 10:12:36 +0000482 def test_metaclass(self):
483 # Testing __metaclass__...
484 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000485 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000486 def __init__(self):
487 self.__state = 0
488 def getstate(self):
489 return self.__state
490 def setstate(self, state):
491 self.__state = state
492 a = C()
493 self.assertEqual(a.getstate(), 0)
494 a.setstate(10)
495 self.assertEqual(a.getstate(), 10)
496 class D:
497 class __metaclass__(type):
498 def myself(cls): return cls
499 self.assertEqual(D.myself(), D)
500 d = D()
501 self.assertEqual(d.__class__, D)
502 class M1(type):
503 def __new__(cls, name, bases, dict):
504 dict['__spam__'] = 1
505 return type.__new__(cls, name, bases, dict)
506 class C:
507 __metaclass__ = M1
508 self.assertEqual(C.__spam__, 1)
509 c = C()
510 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000511
Georg Brandl48545522008-02-02 10:12:36 +0000512 class _instance(object):
513 pass
514 class M2(object):
515 @staticmethod
516 def __new__(cls, name, bases, dict):
517 self = object.__new__(cls)
518 self.name = name
519 self.bases = bases
520 self.dict = dict
521 return self
522 def __call__(self):
523 it = _instance()
524 # Early binding of methods
525 for key in self.dict:
526 if key.startswith("__"):
527 continue
528 setattr(it, key, self.dict[key].__get__(it, self))
529 return it
530 class C:
531 __metaclass__ = M2
532 def spam(self):
533 return 42
534 self.assertEqual(C.name, 'C')
535 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000536 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000537 c = C()
538 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000539
Georg Brandl48545522008-02-02 10:12:36 +0000540 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000541
Georg Brandl48545522008-02-02 10:12:36 +0000542 class autosuper(type):
543 # Automatically add __super to the class
544 # This trick only works for dynamic classes
545 def __new__(metaclass, name, bases, dict):
546 cls = super(autosuper, metaclass).__new__(metaclass,
547 name, bases, dict)
548 # Name mangling for __super removes leading underscores
549 while name[:1] == "_":
550 name = name[1:]
551 if name:
552 name = "_%s__super" % name
553 else:
554 name = "__super"
555 setattr(cls, name, super(cls))
556 return cls
557 class A:
558 __metaclass__ = autosuper
559 def meth(self):
560 return "A"
561 class B(A):
562 def meth(self):
563 return "B" + self.__super.meth()
564 class C(A):
565 def meth(self):
566 return "C" + self.__super.meth()
567 class D(C, B):
568 def meth(self):
569 return "D" + self.__super.meth()
570 self.assertEqual(D().meth(), "DCBA")
571 class E(B, C):
572 def meth(self):
573 return "E" + self.__super.meth()
574 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000575
Georg Brandl48545522008-02-02 10:12:36 +0000576 class autoproperty(type):
577 # Automatically create property attributes when methods
578 # named _get_x and/or _set_x are found
579 def __new__(metaclass, name, bases, dict):
580 hits = {}
581 for key, val in dict.iteritems():
582 if key.startswith("_get_"):
583 key = key[5:]
584 get, set = hits.get(key, (None, None))
585 get = val
586 hits[key] = get, set
587 elif key.startswith("_set_"):
588 key = key[5:]
589 get, set = hits.get(key, (None, None))
590 set = val
591 hits[key] = get, set
592 for key, (get, set) in hits.iteritems():
593 dict[key] = property(get, set)
594 return super(autoproperty, metaclass).__new__(metaclass,
595 name, bases, dict)
596 class A:
597 __metaclass__ = autoproperty
598 def _get_x(self):
599 return -self.__x
600 def _set_x(self, x):
601 self.__x = -x
602 a = A()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200603 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +0000604 a.x = 12
605 self.assertEqual(a.x, 12)
606 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000607
Georg Brandl48545522008-02-02 10:12:36 +0000608 class multimetaclass(autoproperty, autosuper):
609 # Merge of multiple cooperating metaclasses
610 pass
611 class A:
612 __metaclass__ = multimetaclass
613 def _get_x(self):
614 return "A"
615 class B(A):
616 def _get_x(self):
617 return "B" + self.__super._get_x()
618 class C(A):
619 def _get_x(self):
620 return "C" + self.__super._get_x()
621 class D(C, B):
622 def _get_x(self):
623 return "D" + self.__super._get_x()
624 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000625
Georg Brandl48545522008-02-02 10:12:36 +0000626 # Make sure type(x) doesn't call x.__class__.__init__
627 class T(type):
628 counter = 0
629 def __init__(self, *args):
630 T.counter += 1
631 class C:
632 __metaclass__ = T
633 self.assertEqual(T.counter, 1)
634 a = C()
635 self.assertEqual(type(a), C)
636 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000637
Georg Brandl48545522008-02-02 10:12:36 +0000638 class C(object): pass
639 c = C()
640 try: c()
641 except TypeError: pass
642 else: self.fail("calling object w/o call method should raise "
643 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000644
Georg Brandl48545522008-02-02 10:12:36 +0000645 # Testing code to find most derived baseclass
646 class A(type):
647 def __new__(*args, **kwargs):
648 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000649
Georg Brandl48545522008-02-02 10:12:36 +0000650 class B(object):
651 pass
652
653 class C(object):
654 __metaclass__ = A
655
656 # The most derived metaclass of D is A rather than type.
657 class D(B, C):
658 pass
659
660 def test_module_subclasses(self):
661 # Testing Python subclass of module...
662 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000663 MT = type(sys)
664 class MM(MT):
665 def __init__(self, name):
666 MT.__init__(self, name)
667 def __getattribute__(self, name):
668 log.append(("getattr", name))
669 return MT.__getattribute__(self, name)
670 def __setattr__(self, name, value):
671 log.append(("setattr", name, value))
672 MT.__setattr__(self, name, value)
673 def __delattr__(self, name):
674 log.append(("delattr", name))
675 MT.__delattr__(self, name)
676 a = MM("a")
677 a.foo = 12
678 x = a.foo
679 del a.foo
680 self.assertEqual(log, [("setattr", "foo", 12),
681 ("getattr", "foo"),
682 ("delattr", "foo")])
683
684 # http://python.org/sf/1174712
685 try:
686 class Module(types.ModuleType, str):
687 pass
688 except TypeError:
689 pass
690 else:
691 self.fail("inheriting from ModuleType and str at the same time "
692 "should fail")
693
Martin Panter65076572016-09-07 12:03:06 +0000694 def test_multiple_inheritance(self):
Georg Brandl48545522008-02-02 10:12:36 +0000695 # Testing multiple inheritance...
696 class C(object):
697 def __init__(self):
698 self.__state = 0
699 def getstate(self):
700 return self.__state
701 def setstate(self, state):
702 self.__state = state
703 a = C()
704 self.assertEqual(a.getstate(), 0)
705 a.setstate(10)
706 self.assertEqual(a.getstate(), 10)
707 class D(dict, C):
708 def __init__(self):
709 type({}).__init__(self)
710 C.__init__(self)
711 d = D()
712 self.assertEqual(d.keys(), [])
713 d["hello"] = "world"
714 self.assertEqual(d.items(), [("hello", "world")])
715 self.assertEqual(d["hello"], "world")
716 self.assertEqual(d.getstate(), 0)
717 d.setstate(10)
718 self.assertEqual(d.getstate(), 10)
719 self.assertEqual(D.__mro__, (D, dict, C, object))
720
721 # SF bug #442833
722 class Node(object):
723 def __int__(self):
724 return int(self.foo())
725 def foo(self):
726 return "23"
727 class Frag(Node, list):
728 def foo(self):
729 return "42"
730 self.assertEqual(Node().__int__(), 23)
731 self.assertEqual(int(Node()), 23)
732 self.assertEqual(Frag().__int__(), 42)
733 self.assertEqual(int(Frag()), 42)
734
735 # MI mixing classic and new-style classes.
736
737 class A:
738 x = 1
739
740 class B(A):
741 pass
742
743 class C(A):
744 x = 2
745
746 class D(B, C):
747 pass
748 self.assertEqual(D.x, 1)
749
750 # Classic MRO is preserved for a classic base class.
751 class E(D, object):
752 pass
753 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
754 self.assertEqual(E.x, 1)
755
756 # But with a mix of classic bases, their MROs are combined using
757 # new-style MRO.
758 class F(B, C, object):
759 pass
760 self.assertEqual(F.__mro__, (F, B, C, A, object))
761 self.assertEqual(F.x, 2)
762
763 # Try something else.
764 class C:
765 def cmethod(self):
766 return "C a"
767 def all_method(self):
768 return "C b"
769
770 class M1(C, object):
771 def m1method(self):
772 return "M1 a"
773 def all_method(self):
774 return "M1 b"
775
776 self.assertEqual(M1.__mro__, (M1, C, object))
777 m = M1()
778 self.assertEqual(m.cmethod(), "C a")
779 self.assertEqual(m.m1method(), "M1 a")
780 self.assertEqual(m.all_method(), "M1 b")
781
782 class D(C):
783 def dmethod(self):
784 return "D a"
785 def all_method(self):
786 return "D b"
787
788 class M2(D, object):
789 def m2method(self):
790 return "M2 a"
791 def all_method(self):
792 return "M2 b"
793
794 self.assertEqual(M2.__mro__, (M2, D, C, object))
795 m = M2()
796 self.assertEqual(m.cmethod(), "C a")
797 self.assertEqual(m.dmethod(), "D a")
798 self.assertEqual(m.m2method(), "M2 a")
799 self.assertEqual(m.all_method(), "M2 b")
800
801 class M3(M1, M2, object):
802 def m3method(self):
803 return "M3 a"
804 def all_method(self):
805 return "M3 b"
806 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
807 m = M3()
808 self.assertEqual(m.cmethod(), "C a")
809 self.assertEqual(m.dmethod(), "D a")
810 self.assertEqual(m.m1method(), "M1 a")
811 self.assertEqual(m.m2method(), "M2 a")
812 self.assertEqual(m.m3method(), "M3 a")
813 self.assertEqual(m.all_method(), "M3 b")
814
815 class Classic:
816 pass
817 try:
818 class New(Classic):
819 __metaclass__ = type
820 except TypeError:
821 pass
822 else:
823 self.fail("new class with only classic bases - shouldn't be")
824
Martin Panter65076572016-09-07 12:03:06 +0000825 def test_diamond_inheritance(self):
Georg Brandl48545522008-02-02 10:12:36 +0000826 # Testing multiple inheritance special cases...
827 class A(object):
828 def spam(self): return "A"
829 self.assertEqual(A().spam(), "A")
830 class B(A):
831 def boo(self): return "B"
832 def spam(self): return "B"
833 self.assertEqual(B().spam(), "B")
834 self.assertEqual(B().boo(), "B")
835 class C(A):
836 def boo(self): return "C"
837 self.assertEqual(C().spam(), "A")
838 self.assertEqual(C().boo(), "C")
839 class D(B, C): pass
840 self.assertEqual(D().spam(), "B")
841 self.assertEqual(D().boo(), "B")
842 self.assertEqual(D.__mro__, (D, B, C, A, object))
843 class E(C, B): pass
844 self.assertEqual(E().spam(), "B")
845 self.assertEqual(E().boo(), "C")
846 self.assertEqual(E.__mro__, (E, C, B, A, object))
847 # MRO order disagreement
848 try:
849 class F(D, E): pass
850 except TypeError:
851 pass
852 else:
853 self.fail("expected MRO order disagreement (F)")
854 try:
855 class G(E, D): pass
856 except TypeError:
857 pass
858 else:
859 self.fail("expected MRO order disagreement (G)")
860
861 # see thread python-dev/2002-October/029035.html
862 def test_ex5_from_c3_switch(self):
863 # Testing ex5 from C3 switch discussion...
864 class A(object): pass
865 class B(object): pass
866 class C(object): pass
867 class X(A): pass
868 class Y(A): pass
869 class Z(X,B,Y,C): pass
870 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
871
872 # see "A Monotonic Superclass Linearization for Dylan",
873 # by Kim Barrett et al. (OOPSLA 1996)
874 def test_monotonicity(self):
875 # Testing MRO monotonicity...
876 class Boat(object): pass
877 class DayBoat(Boat): pass
878 class WheelBoat(Boat): pass
879 class EngineLess(DayBoat): pass
880 class SmallMultihull(DayBoat): pass
881 class PedalWheelBoat(EngineLess,WheelBoat): pass
882 class SmallCatamaran(SmallMultihull): pass
883 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
884
885 self.assertEqual(PedalWheelBoat.__mro__,
886 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
887 self.assertEqual(SmallCatamaran.__mro__,
888 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
889 self.assertEqual(Pedalo.__mro__,
890 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
891 SmallMultihull, DayBoat, WheelBoat, Boat, object))
892
893 # see "A Monotonic Superclass Linearization for Dylan",
894 # by Kim Barrett et al. (OOPSLA 1996)
895 def test_consistency_with_epg(self):
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200896 # Testing consistency with EPG...
Georg Brandl48545522008-02-02 10:12:36 +0000897 class Pane(object): pass
898 class ScrollingMixin(object): pass
899 class EditingMixin(object): pass
900 class ScrollablePane(Pane,ScrollingMixin): pass
901 class EditablePane(Pane,EditingMixin): pass
902 class EditableScrollablePane(ScrollablePane,EditablePane): pass
903
904 self.assertEqual(EditableScrollablePane.__mro__,
905 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
906 ScrollingMixin, EditingMixin, object))
907
908 def test_mro_disagreement(self):
909 # Testing error messages for MRO disagreement...
910 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000911order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000912
Georg Brandl48545522008-02-02 10:12:36 +0000913 def raises(exc, expected, callable, *args):
914 try:
915 callable(*args)
916 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000917 # the exact msg is generally considered an impl detail
918 if test_support.check_impl_detail():
919 if not str(msg).startswith(expected):
920 self.fail("Message %r, expected %r" %
921 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000922 else:
923 self.fail("Expected %s" % exc)
924
925 class A(object): pass
926 class B(A): pass
927 class C(object): pass
928
929 # Test some very simple errors
930 raises(TypeError, "duplicate base class A",
931 type, "X", (A, A), {})
932 raises(TypeError, mro_err_msg,
933 type, "X", (A, B), {})
934 raises(TypeError, mro_err_msg,
935 type, "X", (A, C, B), {})
936 # Test a slightly more complex error
937 class GridLayout(object): pass
938 class HorizontalGrid(GridLayout): pass
939 class VerticalGrid(GridLayout): pass
940 class HVGrid(HorizontalGrid, VerticalGrid): pass
941 class VHGrid(VerticalGrid, HorizontalGrid): pass
942 raises(TypeError, mro_err_msg,
943 type, "ConfusedGrid", (HVGrid, VHGrid), {})
944
945 def test_object_class(self):
946 # Testing object class...
947 a = object()
948 self.assertEqual(a.__class__, object)
949 self.assertEqual(type(a), object)
950 b = object()
951 self.assertNotEqual(a, b)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200952 self.assertNotHasAttr(a, "foo")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000953 try:
Georg Brandl48545522008-02-02 10:12:36 +0000954 a.foo = 12
955 except (AttributeError, TypeError):
956 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000957 else:
Georg Brandl48545522008-02-02 10:12:36 +0000958 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200959 self.assertNotHasAttr(object(), "__dict__")
Guido van Rossumd32047f2002-11-25 21:38:52 +0000960
Georg Brandl48545522008-02-02 10:12:36 +0000961 class Cdict(object):
962 pass
963 x = Cdict()
964 self.assertEqual(x.__dict__, {})
965 x.foo = 1
966 self.assertEqual(x.foo, 1)
967 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000968
Georg Brandl48545522008-02-02 10:12:36 +0000969 def test_slots(self):
970 # Testing __slots__...
971 class C0(object):
972 __slots__ = []
973 x = C0()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200974 self.assertNotHasAttr(x, "__dict__")
975 self.assertNotHasAttr(x, "foo")
Guido van Rossum37202612001-08-09 19:45:21 +0000976
Georg Brandl48545522008-02-02 10:12:36 +0000977 class C1(object):
978 __slots__ = ['a']
979 x = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200980 self.assertNotHasAttr(x, "__dict__")
981 self.assertNotHasAttr(x, "a")
Georg Brandl48545522008-02-02 10:12:36 +0000982 x.a = 1
983 self.assertEqual(x.a, 1)
984 x.a = None
985 self.assertEqual(x.a, None)
986 del x.a
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200987 self.assertNotHasAttr(x, "a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000988
Georg Brandl48545522008-02-02 10:12:36 +0000989 class C3(object):
990 __slots__ = ['a', 'b', 'c']
991 x = C3()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +0200992 self.assertNotHasAttr(x, "__dict__")
993 self.assertNotHasAttr(x, 'a')
994 self.assertNotHasAttr(x, 'b')
995 self.assertNotHasAttr(x, 'c')
Georg Brandl48545522008-02-02 10:12:36 +0000996 x.a = 1
997 x.b = 2
998 x.c = 3
999 self.assertEqual(x.a, 1)
1000 self.assertEqual(x.b, 2)
1001 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002
Georg Brandl48545522008-02-02 10:12:36 +00001003 class C4(object):
1004 """Validate name mangling"""
1005 __slots__ = ['__a']
1006 def __init__(self, value):
1007 self.__a = value
1008 def get(self):
1009 return self.__a
1010 x = C4(5)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001011 self.assertNotHasAttr(x, '__dict__')
1012 self.assertNotHasAttr(x, '__a')
Georg Brandl48545522008-02-02 10:12:36 +00001013 self.assertEqual(x.get(), 5)
1014 try:
1015 x.__a = 6
1016 except AttributeError:
1017 pass
1018 else:
1019 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001020
Georg Brandl48545522008-02-02 10:12:36 +00001021 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001022 try:
1023 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001024 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001025 except TypeError:
1026 pass
1027 else:
Georg Brandl48545522008-02-02 10:12:36 +00001028 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001029 try:
Georg Brandl48545522008-02-02 10:12:36 +00001030 class C(object):
1031 __slots__ = ["foo bar"]
1032 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001033 pass
Georg Brandl48545522008-02-02 10:12:36 +00001034 else:
1035 self.fail("['foo bar'] slots not caught")
1036 try:
1037 class C(object):
1038 __slots__ = ["foo\0bar"]
1039 except TypeError:
1040 pass
1041 else:
1042 self.fail("['foo\\0bar'] slots not caught")
1043 try:
1044 class C(object):
1045 __slots__ = ["1"]
1046 except TypeError:
1047 pass
1048 else:
1049 self.fail("['1'] slots not caught")
1050 try:
1051 class C(object):
1052 __slots__ = [""]
1053 except TypeError:
1054 pass
1055 else:
1056 self.fail("[''] slots not caught")
1057 class C(object):
1058 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1059 # XXX(nnorwitz): was there supposed to be something tested
1060 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001061
Georg Brandl48545522008-02-02 10:12:36 +00001062 # Test a single string is not expanded as a sequence.
1063 class C(object):
1064 __slots__ = "abc"
1065 c = C()
1066 c.abc = 5
1067 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001068
Zachary Ware1f702212013-12-10 14:09:20 -06001069 def test_unicode_slots(self):
Georg Brandl48545522008-02-02 10:12:36 +00001070 # Test unicode slot names
1071 try:
1072 unicode
1073 except NameError:
Zachary Ware1f702212013-12-10 14:09:20 -06001074 self.skipTest('no unicode support')
Georg Brandl48545522008-02-02 10:12:36 +00001075 else:
1076 # Test a single unicode string is not expanded as a sequence.
1077 class C(object):
1078 __slots__ = unicode("abc")
1079 c = C()
1080 c.abc = 5
1081 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001082
Georg Brandl48545522008-02-02 10:12:36 +00001083 # _unicode_to_string used to modify slots in certain circumstances
1084 slots = (unicode("foo"), unicode("bar"))
1085 class C(object):
1086 __slots__ = slots
1087 x = C()
1088 x.foo = 5
1089 self.assertEqual(x.foo, 5)
1090 self.assertEqual(type(slots[0]), unicode)
1091 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001092 try:
Georg Brandl48545522008-02-02 10:12:36 +00001093 class C(object):
1094 __slots__ = [unichr(128)]
1095 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001096 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001097 else:
Georg Brandl48545522008-02-02 10:12:36 +00001098 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001099
Georg Brandl48545522008-02-02 10:12:36 +00001100 # Test leaks
1101 class Counted(object):
1102 counter = 0 # counts the number of instances alive
1103 def __init__(self):
1104 Counted.counter += 1
1105 def __del__(self):
1106 Counted.counter -= 1
1107 class C(object):
1108 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001109 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001110 x.a = Counted()
1111 x.b = Counted()
1112 x.c = Counted()
1113 self.assertEqual(Counted.counter, 3)
1114 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001115 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001116 self.assertEqual(Counted.counter, 0)
1117 class D(C):
1118 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001119 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001120 x.a = Counted()
1121 x.z = Counted()
1122 self.assertEqual(Counted.counter, 2)
1123 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001124 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001125 self.assertEqual(Counted.counter, 0)
1126 class E(D):
1127 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001128 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001129 x.a = Counted()
1130 x.z = Counted()
1131 x.e = Counted()
1132 self.assertEqual(Counted.counter, 3)
1133 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001134 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001135 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001136
Georg Brandl48545522008-02-02 10:12:36 +00001137 # Test cyclical leaks [SF bug 519621]
1138 class F(object):
1139 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001140 s = F()
1141 s.a = [Counted(), s]
1142 self.assertEqual(Counted.counter, 1)
1143 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001144 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001145 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001146
Georg Brandl48545522008-02-02 10:12:36 +00001147 # Test lookup leaks [SF bug 572567]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001148 if hasattr(gc, 'get_objects'):
1149 class G(object):
1150 def __cmp__(self, other):
1151 return 0
1152 __hash__ = None # Silence Py3k warning
1153 g = G()
1154 orig_objects = len(gc.get_objects())
1155 for i in xrange(10):
1156 g==g
1157 new_objects = len(gc.get_objects())
1158 self.assertEqual(orig_objects, new_objects)
1159
Georg Brandl48545522008-02-02 10:12:36 +00001160 class H(object):
1161 __slots__ = ['a', 'b']
1162 def __init__(self):
1163 self.a = 1
1164 self.b = 2
1165 def __del__(self_):
1166 self.assertEqual(self_.a, 1)
1167 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001168 with test_support.captured_output('stderr') as s:
1169 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001170 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001171 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001172
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001173 class X(object):
1174 __slots__ = "a"
1175 with self.assertRaises(AttributeError):
1176 del X().a
1177
Georg Brandl48545522008-02-02 10:12:36 +00001178 def test_slots_special(self):
1179 # Testing __dict__ and __weakref__ in __slots__...
1180 class D(object):
1181 __slots__ = ["__dict__"]
1182 a = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001183 self.assertHasAttr(a, "__dict__")
1184 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001185 a.foo = 42
1186 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001187
Georg Brandl48545522008-02-02 10:12:36 +00001188 class W(object):
1189 __slots__ = ["__weakref__"]
1190 a = W()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001191 self.assertHasAttr(a, "__weakref__")
1192 self.assertNotHasAttr(a, "__dict__")
Georg Brandl48545522008-02-02 10:12:36 +00001193 try:
1194 a.foo = 42
1195 except AttributeError:
1196 pass
1197 else:
1198 self.fail("shouldn't be allowed to set a.foo")
1199
1200 class C1(W, D):
1201 __slots__ = []
1202 a = C1()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001203 self.assertHasAttr(a, "__dict__")
1204 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001205 a.foo = 42
1206 self.assertEqual(a.__dict__, {"foo": 42})
1207
1208 class C2(D, W):
1209 __slots__ = []
1210 a = C2()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001211 self.assertHasAttr(a, "__dict__")
1212 self.assertHasAttr(a, "__weakref__")
Georg Brandl48545522008-02-02 10:12:36 +00001213 a.foo = 42
1214 self.assertEqual(a.__dict__, {"foo": 42})
1215
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001216 def test_slots_descriptor(self):
1217 # Issue2115: slot descriptors did not correctly check
1218 # the type of the given object
1219 import abc
1220 class MyABC:
1221 __metaclass__ = abc.ABCMeta
1222 __slots__ = "a"
1223
1224 class Unrelated(object):
1225 pass
1226 MyABC.register(Unrelated)
1227
1228 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001229 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001230
1231 # This used to crash
1232 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1233
Benjamin Peterson4895af42009-12-13 16:36:53 +00001234 def test_metaclass_cmp(self):
1235 # See bug 7491.
1236 class M(type):
1237 def __cmp__(self, other):
1238 return -1
1239 class X(object):
1240 __metaclass__ = M
1241 self.assertTrue(X < M)
1242
Georg Brandl48545522008-02-02 10:12:36 +00001243 def test_dynamics(self):
1244 # Testing class attribute propagation...
1245 class D(object):
1246 pass
1247 class E(D):
1248 pass
1249 class F(D):
1250 pass
1251 D.foo = 1
1252 self.assertEqual(D.foo, 1)
1253 # Test that dynamic attributes are inherited
1254 self.assertEqual(E.foo, 1)
1255 self.assertEqual(F.foo, 1)
1256 # Test dynamic instances
1257 class C(object):
1258 pass
1259 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001260 self.assertNotHasAttr(a, "foobar")
Georg Brandl48545522008-02-02 10:12:36 +00001261 C.foobar = 2
1262 self.assertEqual(a.foobar, 2)
1263 C.method = lambda self: 42
1264 self.assertEqual(a.method(), 42)
1265 C.__repr__ = lambda self: "C()"
1266 self.assertEqual(repr(a), "C()")
1267 C.__int__ = lambda self: 100
1268 self.assertEqual(int(a), 100)
1269 self.assertEqual(a.foobar, 2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001270 self.assertNotHasAttr(a, "spam")
Georg Brandl48545522008-02-02 10:12:36 +00001271 def mygetattr(self, name):
1272 if name == "spam":
1273 return "spam"
1274 raise AttributeError
1275 C.__getattr__ = mygetattr
1276 self.assertEqual(a.spam, "spam")
1277 a.new = 12
1278 self.assertEqual(a.new, 12)
1279 def mysetattr(self, name, value):
1280 if name == "spam":
1281 raise AttributeError
1282 return object.__setattr__(self, name, value)
1283 C.__setattr__ = mysetattr
1284 try:
1285 a.spam = "not spam"
1286 except AttributeError:
1287 pass
1288 else:
1289 self.fail("expected AttributeError")
1290 self.assertEqual(a.spam, "spam")
1291 class D(C):
1292 pass
1293 d = D()
1294 d.foo = 1
1295 self.assertEqual(d.foo, 1)
1296
1297 # Test handling of int*seq and seq*int
1298 class I(int):
1299 pass
1300 self.assertEqual("a"*I(2), "aa")
1301 self.assertEqual(I(2)*"a", "aa")
1302 self.assertEqual(2*I(3), 6)
1303 self.assertEqual(I(3)*2, 6)
1304 self.assertEqual(I(3)*I(2), 6)
1305
1306 # Test handling of long*seq and seq*long
1307 class L(long):
1308 pass
1309 self.assertEqual("a"*L(2L), "aa")
1310 self.assertEqual(L(2L)*"a", "aa")
1311 self.assertEqual(2*L(3), 6)
1312 self.assertEqual(L(3)*2, 6)
1313 self.assertEqual(L(3)*L(2), 6)
1314
1315 # Test comparison of classes with dynamic metaclasses
1316 class dynamicmetaclass(type):
1317 pass
1318 class someclass:
1319 __metaclass__ = dynamicmetaclass
1320 self.assertNotEqual(someclass, object)
1321
1322 def test_errors(self):
1323 # Testing errors...
1324 try:
1325 class C(list, dict):
1326 pass
1327 except TypeError:
1328 pass
1329 else:
1330 self.fail("inheritance from both list and dict should be illegal")
1331
1332 try:
1333 class C(object, None):
1334 pass
1335 except TypeError:
1336 pass
1337 else:
1338 self.fail("inheritance from non-type should be illegal")
1339 class Classic:
1340 pass
1341
1342 try:
1343 class C(type(len)):
1344 pass
1345 except TypeError:
1346 pass
1347 else:
1348 self.fail("inheritance from CFunction should be illegal")
1349
1350 try:
1351 class C(object):
1352 __slots__ = 1
1353 except TypeError:
1354 pass
1355 else:
1356 self.fail("__slots__ = 1 should be illegal")
1357
1358 try:
1359 class C(object):
1360 __slots__ = [1]
1361 except TypeError:
1362 pass
1363 else:
1364 self.fail("__slots__ = [1] should be illegal")
1365
1366 class M1(type):
1367 pass
1368 class M2(type):
1369 pass
1370 class A1(object):
1371 __metaclass__ = M1
1372 class A2(object):
1373 __metaclass__ = M2
1374 try:
1375 class B(A1, A2):
1376 pass
1377 except TypeError:
1378 pass
1379 else:
1380 self.fail("finding the most derived metaclass should have failed")
1381
1382 def test_classmethods(self):
1383 # Testing class methods...
1384 class C(object):
1385 def foo(*a): return a
1386 goo = classmethod(foo)
1387 c = C()
1388 self.assertEqual(C.goo(1), (C, 1))
1389 self.assertEqual(c.goo(1), (C, 1))
1390 self.assertEqual(c.foo(1), (c, 1))
1391 class D(C):
1392 pass
1393 d = D()
1394 self.assertEqual(D.goo(1), (D, 1))
1395 self.assertEqual(d.goo(1), (D, 1))
1396 self.assertEqual(d.foo(1), (d, 1))
1397 self.assertEqual(D.foo(d, 1), (d, 1))
1398 # Test for a specific crash (SF bug 528132)
1399 def f(cls, arg): return (cls, arg)
1400 ff = classmethod(f)
1401 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1402 self.assertEqual(ff.__get__(0)(42), (int, 42))
1403
1404 # Test super() with classmethods (SF bug 535444)
1405 self.assertEqual(C.goo.im_self, C)
1406 self.assertEqual(D.goo.im_self, D)
1407 self.assertEqual(super(D,D).goo.im_self, D)
1408 self.assertEqual(super(D,d).goo.im_self, D)
1409 self.assertEqual(super(D,D).goo(), (D,))
1410 self.assertEqual(super(D,d).goo(), (D,))
1411
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001412 # Verify that a non-callable will raise
1413 meth = classmethod(1).__get__(1)
1414 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001415
1416 # Verify that classmethod() doesn't allow keyword args
1417 try:
1418 classmethod(f, kw=1)
1419 except TypeError:
1420 pass
1421 else:
1422 self.fail("classmethod shouldn't accept keyword args")
1423
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +03001424 @test_support.cpython_only
1425 def test_classmethod_copy_pickle(self):
1426 cm = classmethod(func)
1427 with test_support.check_py3k_warnings(
1428 (".*classmethod", DeprecationWarning)):
1429 copy.copy(cm)
1430 with test_support.check_py3k_warnings(
1431 (".*classmethod", DeprecationWarning)):
1432 copy.deepcopy(cm)
1433 for proto in range(2):
1434 self.assertRaises(TypeError, pickle.dumps, cm, proto)
1435 with test_support.check_py3k_warnings(
1436 (".*classmethod", DeprecationWarning)):
1437 pickle.dumps(cm, 2)
1438
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001439 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001440 def test_classmethods_in_c(self):
1441 # Testing C-based class methods...
1442 import xxsubtype as spam
1443 a = (1, 2, 3)
1444 d = {'abc': 123}
1445 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1446 self.assertEqual(x, spam.spamlist)
1447 self.assertEqual(a, a1)
1448 self.assertEqual(d, d1)
1449 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1450 self.assertEqual(x, spam.spamlist)
1451 self.assertEqual(a, a1)
1452 self.assertEqual(d, d1)
Benjamin Peterson042c47b2012-05-01 09:51:09 -04001453 spam_cm = spam.spamlist.__dict__['classmeth']
1454 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1455 self.assertEqual(x2, spam.spamlist)
1456 self.assertEqual(a2, a1)
1457 self.assertEqual(d2, d1)
1458 class SubSpam(spam.spamlist): pass
1459 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1460 self.assertEqual(x2, SubSpam)
1461 self.assertEqual(a2, a1)
1462 self.assertEqual(d2, d1)
1463 with self.assertRaises(TypeError):
1464 spam_cm()
1465 with self.assertRaises(TypeError):
1466 spam_cm(spam.spamlist())
1467 with self.assertRaises(TypeError):
1468 spam_cm(list)
Georg Brandl48545522008-02-02 10:12:36 +00001469
1470 def test_staticmethods(self):
1471 # Testing static methods...
1472 class C(object):
1473 def foo(*a): return a
1474 goo = staticmethod(foo)
1475 c = C()
1476 self.assertEqual(C.goo(1), (1,))
1477 self.assertEqual(c.goo(1), (1,))
1478 self.assertEqual(c.foo(1), (c, 1,))
1479 class D(C):
1480 pass
1481 d = D()
1482 self.assertEqual(D.goo(1), (1,))
1483 self.assertEqual(d.goo(1), (1,))
1484 self.assertEqual(d.foo(1), (d, 1))
1485 self.assertEqual(D.foo(d, 1), (d, 1))
1486
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +03001487 @test_support.cpython_only
1488 def test_staticmethod_copy_pickle(self):
1489 sm = staticmethod(func)
1490 with test_support.check_py3k_warnings(
1491 (".*staticmethod", DeprecationWarning)):
1492 copy.copy(sm)
1493 with test_support.check_py3k_warnings(
1494 (".*staticmethod", DeprecationWarning)):
1495 copy.deepcopy(sm)
1496 for proto in range(2):
1497 self.assertRaises(TypeError, pickle.dumps, sm, proto)
1498 with test_support.check_py3k_warnings(
1499 (".*staticmethod", DeprecationWarning)):
1500 pickle.dumps(sm, 2)
1501
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001502 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001503 def test_staticmethods_in_c(self):
1504 # Testing C-based static methods...
1505 import xxsubtype as spam
1506 a = (1, 2, 3)
1507 d = {"abc": 123}
1508 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1509 self.assertEqual(x, None)
1510 self.assertEqual(a, a1)
1511 self.assertEqual(d, d1)
1512 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1513 self.assertEqual(x, None)
1514 self.assertEqual(a, a1)
1515 self.assertEqual(d, d1)
1516
1517 def test_classic(self):
1518 # Testing classic classes...
1519 class C:
1520 def foo(*a): return a
1521 goo = classmethod(foo)
1522 c = C()
1523 self.assertEqual(C.goo(1), (C, 1))
1524 self.assertEqual(c.goo(1), (C, 1))
1525 self.assertEqual(c.foo(1), (c, 1))
1526 class D(C):
1527 pass
1528 d = D()
1529 self.assertEqual(D.goo(1), (D, 1))
1530 self.assertEqual(d.goo(1), (D, 1))
1531 self.assertEqual(d.foo(1), (d, 1))
1532 self.assertEqual(D.foo(d, 1), (d, 1))
1533 class E: # *not* subclassing from C
1534 foo = C.foo
1535 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001536 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001537
1538 def test_compattr(self):
1539 # Testing computed attributes...
1540 class C(object):
1541 class computed_attribute(object):
1542 def __init__(self, get, set=None, delete=None):
1543 self.__get = get
1544 self.__set = set
1545 self.__delete = delete
1546 def __get__(self, obj, type=None):
1547 return self.__get(obj)
1548 def __set__(self, obj, value):
1549 return self.__set(obj, value)
1550 def __delete__(self, obj):
1551 return self.__delete(obj)
1552 def __init__(self):
1553 self.__x = 0
1554 def __get_x(self):
1555 x = self.__x
1556 self.__x = x+1
1557 return x
1558 def __set_x(self, x):
1559 self.__x = x
1560 def __delete_x(self):
1561 del self.__x
1562 x = computed_attribute(__get_x, __set_x, __delete_x)
1563 a = C()
1564 self.assertEqual(a.x, 0)
1565 self.assertEqual(a.x, 1)
1566 a.x = 10
1567 self.assertEqual(a.x, 10)
1568 self.assertEqual(a.x, 11)
1569 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001570 self.assertNotHasAttr(a, 'x')
Georg Brandl48545522008-02-02 10:12:36 +00001571
1572 def test_newslots(self):
1573 # Testing __new__ slot override...
1574 class C(list):
1575 def __new__(cls):
1576 self = list.__new__(cls)
1577 self.foo = 1
1578 return self
1579 def __init__(self):
1580 self.foo = self.foo + 2
1581 a = C()
1582 self.assertEqual(a.foo, 3)
1583 self.assertEqual(a.__class__, C)
1584 class D(C):
1585 pass
1586 b = D()
1587 self.assertEqual(b.foo, 3)
1588 self.assertEqual(b.__class__, D)
1589
Serhiy Storchaka7117d352016-12-14 19:48:38 +02001590 @unittest.expectedFailure
1591 def test_bad_new(self):
1592 self.assertRaises(TypeError, object.__new__)
1593 self.assertRaises(TypeError, object.__new__, '')
1594 self.assertRaises(TypeError, list.__new__, object)
1595 self.assertRaises(TypeError, object.__new__, list)
1596 class C(object):
1597 __new__ = list.__new__
1598 self.assertRaises(TypeError, C)
1599 class C(list):
1600 __new__ = object.__new__
1601 self.assertRaises(TypeError, C)
1602
1603 def test_object_new(self):
1604 class A(object):
1605 pass
1606 object.__new__(A)
1607 self.assertRaises(TypeError, object.__new__, A, 5)
1608 object.__init__(A())
1609 self.assertRaises(TypeError, object.__init__, A(), 5)
1610
1611 class A(object):
1612 def __init__(self, foo):
1613 self.foo = foo
1614 object.__new__(A)
1615 object.__new__(A, 5)
1616 object.__init__(A(3))
1617 self.assertRaises(TypeError, object.__init__, A(3), 5)
1618
1619 class A(object):
1620 def __new__(cls, foo):
1621 return object.__new__(cls)
1622 object.__new__(A)
1623 self.assertRaises(TypeError, object.__new__, A, 5)
1624 object.__init__(A(3))
1625 object.__init__(A(3), 5)
1626
1627 class A(object):
1628 def __new__(cls, foo):
1629 return object.__new__(cls)
1630 def __init__(self, foo):
1631 self.foo = foo
1632 object.__new__(A)
1633 with warnings.catch_warnings(record=True) as w:
1634 warnings.simplefilter('always', DeprecationWarning)
1635 a = object.__new__(A, 5)
1636 self.assertEqual(type(a), A)
1637 self.assertEqual(len(w), 1)
1638 object.__init__(A(3))
1639 a = A(3)
1640 with warnings.catch_warnings(record=True) as w:
1641 warnings.simplefilter('always', DeprecationWarning)
1642 object.__init__(a, 5)
1643 self.assertEqual(a.foo, 3)
1644 self.assertEqual(len(w), 1)
1645
1646 @unittest.expectedFailure
1647 def test_restored_object_new(self):
1648 class A(object):
1649 def __new__(cls, *args, **kwargs):
1650 raise AssertionError
1651 self.assertRaises(AssertionError, A)
1652 class B(A):
1653 __new__ = object.__new__
1654 def __init__(self, foo):
1655 self.foo = foo
1656 with warnings.catch_warnings():
1657 warnings.simplefilter('error', DeprecationWarning)
1658 b = B(3)
1659 self.assertEqual(b.foo, 3)
1660 self.assertEqual(b.__class__, B)
1661 del B.__new__
1662 self.assertRaises(AssertionError, B)
1663 del A.__new__
1664 with warnings.catch_warnings():
1665 warnings.simplefilter('error', DeprecationWarning)
1666 b = B(3)
1667 self.assertEqual(b.foo, 3)
1668 self.assertEqual(b.__class__, B)
1669
Georg Brandl48545522008-02-02 10:12:36 +00001670 def test_altmro(self):
1671 # Testing mro() and overriding it...
1672 class A(object):
1673 def f(self): return "A"
1674 class B(A):
1675 pass
1676 class C(A):
1677 def f(self): return "C"
1678 class D(B, C):
1679 pass
1680 self.assertEqual(D.mro(), [D, B, C, A, object])
1681 self.assertEqual(D.__mro__, (D, B, C, A, object))
1682 self.assertEqual(D().f(), "C")
1683
1684 class PerverseMetaType(type):
1685 def mro(cls):
1686 L = type.mro(cls)
1687 L.reverse()
1688 return L
1689 class X(D,B,C,A):
1690 __metaclass__ = PerverseMetaType
1691 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1692 self.assertEqual(X().f(), "A")
1693
1694 try:
1695 class X(object):
1696 class __metaclass__(type):
1697 def mro(self):
1698 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001699 # In CPython, the class creation above already raises
1700 # TypeError, as a protection against the fact that
1701 # instances of X would segfault it. In other Python
1702 # implementations it would be ok to let the class X
1703 # be created, but instead get a clean TypeError on the
1704 # __setitem__ below.
1705 x = object.__new__(X)
1706 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001707 except TypeError:
1708 pass
1709 else:
1710 self.fail("devious mro() return not caught")
1711
1712 try:
1713 class X(object):
1714 class __metaclass__(type):
1715 def mro(self):
1716 return [1]
1717 except TypeError:
1718 pass
1719 else:
1720 self.fail("non-class mro() return not caught")
1721
1722 try:
1723 class X(object):
1724 class __metaclass__(type):
1725 def mro(self):
1726 return 1
1727 except TypeError:
1728 pass
1729 else:
1730 self.fail("non-sequence mro() return not caught")
1731
1732 def test_overloading(self):
1733 # Testing operator overloading...
1734
1735 class B(object):
1736 "Intermediate class because object doesn't have a __setattr__"
1737
1738 class C(B):
1739 def __getattr__(self, name):
1740 if name == "foo":
1741 return ("getattr", name)
1742 else:
1743 raise AttributeError
1744 def __setattr__(self, name, value):
1745 if name == "foo":
1746 self.setattr = (name, value)
1747 else:
1748 return B.__setattr__(self, name, value)
1749 def __delattr__(self, name):
1750 if name == "foo":
1751 self.delattr = name
1752 else:
1753 return B.__delattr__(self, name)
1754
1755 def __getitem__(self, key):
1756 return ("getitem", key)
1757 def __setitem__(self, key, value):
1758 self.setitem = (key, value)
1759 def __delitem__(self, key):
1760 self.delitem = key
1761
1762 def __getslice__(self, i, j):
1763 return ("getslice", i, j)
1764 def __setslice__(self, i, j, value):
1765 self.setslice = (i, j, value)
1766 def __delslice__(self, i, j):
1767 self.delslice = (i, j)
1768
1769 a = C()
1770 self.assertEqual(a.foo, ("getattr", "foo"))
1771 a.foo = 12
1772 self.assertEqual(a.setattr, ("foo", 12))
1773 del a.foo
1774 self.assertEqual(a.delattr, "foo")
1775
1776 self.assertEqual(a[12], ("getitem", 12))
1777 a[12] = 21
1778 self.assertEqual(a.setitem, (12, 21))
1779 del a[12]
1780 self.assertEqual(a.delitem, 12)
1781
1782 self.assertEqual(a[0:10], ("getslice", 0, 10))
1783 a[0:10] = "foo"
1784 self.assertEqual(a.setslice, (0, 10, "foo"))
1785 del a[0:10]
1786 self.assertEqual(a.delslice, (0, 10))
1787
1788 def test_methods(self):
1789 # Testing methods...
1790 class C(object):
1791 def __init__(self, x):
1792 self.x = x
1793 def foo(self):
1794 return self.x
1795 c1 = C(1)
1796 self.assertEqual(c1.foo(), 1)
1797 class D(C):
1798 boo = C.foo
1799 goo = c1.foo
1800 d2 = D(2)
1801 self.assertEqual(d2.foo(), 2)
1802 self.assertEqual(d2.boo(), 2)
1803 self.assertEqual(d2.goo(), 1)
1804 class E(object):
1805 foo = C.foo
1806 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001807 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001808
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001809 def test_special_method_lookup(self):
1810 # The lookup of special methods bypasses __getattr__ and
1811 # __getattribute__, but they still can be descriptors.
1812
1813 def run_context(manager):
1814 with manager:
1815 pass
1816 def iden(self):
1817 return self
1818 def hello(self):
1819 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001820 def empty_seq(self):
1821 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001822 def zero(self):
1823 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001824 def complex_num(self):
1825 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001826 def stop(self):
1827 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001828 def return_true(self, thing=None):
1829 return True
1830 def do_isinstance(obj):
1831 return isinstance(int, obj)
1832 def do_issubclass(obj):
1833 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001834 def swallow(*args):
1835 pass
1836 def do_dict_missing(checker):
1837 class DictSub(checker.__class__, dict):
1838 pass
1839 self.assertEqual(DictSub()["hi"], 4)
1840 def some_number(self_, key):
1841 self.assertEqual(key, "hi")
1842 return 4
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001843 def format_impl(self, spec):
1844 return "hello"
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001845
1846 # It would be nice to have every special method tested here, but I'm
1847 # only listing the ones I can remember outside of typeobject.c, since it
1848 # does it right.
1849 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001850 ("__unicode__", unicode, hello, set(), {}),
1851 ("__reversed__", reversed, empty_seq, set(), {}),
1852 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001853 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001854 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1855 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001856 ("__missing__", do_dict_missing, some_number,
1857 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001858 ("__subclasscheck__", do_issubclass, return_true,
1859 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001860 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1861 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001862 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001863 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001864 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001865 ]
1866
1867 class Checker(object):
1868 def __getattr__(self, attr, test=self):
1869 test.fail("__getattr__ called with {0}".format(attr))
1870 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001871 if attr not in ok:
1872 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001873 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001874 class SpecialDescr(object):
1875 def __init__(self, impl):
1876 self.impl = impl
1877 def __get__(self, obj, owner):
1878 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001879 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001880 class MyException(Exception):
1881 pass
1882 class ErrDescr(object):
1883 def __get__(self, obj, owner):
1884 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001885
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001886 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001887 class X(Checker):
1888 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001889 for attr, obj in env.iteritems():
1890 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001891 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001892 runner(X())
1893
1894 record = []
1895 class X(Checker):
1896 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001897 for attr, obj in env.iteritems():
1898 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001899 setattr(X, name, SpecialDescr(meth_impl))
1900 runner(X())
1901 self.assertEqual(record, [1], name)
1902
Benjamin Peterson87e50062009-05-25 02:40:21 +00001903 class X(Checker):
1904 pass
1905 for attr, obj in env.iteritems():
1906 setattr(X, attr, obj)
1907 setattr(X, name, ErrDescr())
1908 try:
1909 runner(X())
1910 except MyException:
1911 pass
1912 else:
1913 self.fail("{0!r} didn't raise".format(name))
1914
Georg Brandl48545522008-02-02 10:12:36 +00001915 def test_specials(self):
1916 # Testing special operators...
1917 # Test operators like __hash__ for which a built-in default exists
1918
1919 # Test the default behavior for static classes
1920 class C(object):
1921 def __getitem__(self, i):
1922 if 0 <= i < 10: return i
1923 raise IndexError
1924 c1 = C()
1925 c2 = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001926 self.assertFalse(not c1)
Georg Brandl48545522008-02-02 10:12:36 +00001927 self.assertNotEqual(id(c1), id(c2))
1928 hash(c1)
1929 hash(c2)
1930 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1931 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001932 self.assertTrue(c1 != c2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001933 self.assertFalse(c1 != c1)
1934 self.assertFalse(c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001935 # Note that the module name appears in str/repr, and that varies
1936 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001937 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001938 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001939 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001940 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001941 self.assertIn(i, c1)
1942 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001943 # Test the default behavior for dynamic classes
1944 class D(object):
1945 def __getitem__(self, i):
1946 if 0 <= i < 10: return i
1947 raise IndexError
1948 d1 = D()
1949 d2 = D()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001950 self.assertFalse(not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001951 self.assertNotEqual(id(d1), id(d2))
1952 hash(d1)
1953 hash(d2)
1954 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1955 self.assertEqual(d1, d1)
1956 self.assertNotEqual(d1, d2)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001957 self.assertFalse(d1 != d1)
1958 self.assertFalse(d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001959 # Note that the module name appears in str/repr, and that varies
1960 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001961 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl48545522008-02-02 10:12:36 +00001962 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001963 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001964 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001965 self.assertIn(i, d1)
1966 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001967 # Test overridden behavior for static classes
1968 class Proxy(object):
1969 def __init__(self, x):
1970 self.x = x
1971 def __nonzero__(self):
1972 return not not self.x
1973 def __hash__(self):
1974 return hash(self.x)
1975 def __eq__(self, other):
1976 return self.x == other
1977 def __ne__(self, other):
1978 return self.x != other
1979 def __cmp__(self, other):
1980 return cmp(self.x, other.x)
1981 def __str__(self):
1982 return "Proxy:%s" % self.x
1983 def __repr__(self):
1984 return "Proxy(%r)" % self.x
1985 def __contains__(self, value):
1986 return value in self.x
1987 p0 = Proxy(0)
1988 p1 = Proxy(1)
1989 p_1 = Proxy(-1)
1990 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001991 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001992 self.assertEqual(hash(p0), hash(0))
1993 self.assertEqual(p0, p0)
1994 self.assertNotEqual(p0, p1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02001995 self.assertFalse(p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001996 self.assertEqual(not p0, p1)
1997 self.assertEqual(cmp(p0, p1), -1)
1998 self.assertEqual(cmp(p0, p0), 0)
1999 self.assertEqual(cmp(p0, p_1), 1)
2000 self.assertEqual(str(p0), "Proxy:0")
2001 self.assertEqual(repr(p0), "Proxy(0)")
2002 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00002003 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00002004 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00002005 self.assertIn(i, p10)
2006 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00002007 # Test overridden behavior for dynamic classes
2008 class DProxy(object):
2009 def __init__(self, x):
2010 self.x = x
2011 def __nonzero__(self):
2012 return not not self.x
2013 def __hash__(self):
2014 return hash(self.x)
2015 def __eq__(self, other):
2016 return self.x == other
2017 def __ne__(self, other):
2018 return self.x != other
2019 def __cmp__(self, other):
2020 return cmp(self.x, other.x)
2021 def __str__(self):
2022 return "DProxy:%s" % self.x
2023 def __repr__(self):
2024 return "DProxy(%r)" % self.x
2025 def __contains__(self, value):
2026 return value in self.x
2027 p0 = DProxy(0)
2028 p1 = DProxy(1)
2029 p_1 = DProxy(-1)
2030 self.assertFalse(p0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002031 self.assertFalse(not p1)
Georg Brandl48545522008-02-02 10:12:36 +00002032 self.assertEqual(hash(p0), hash(0))
2033 self.assertEqual(p0, p0)
2034 self.assertNotEqual(p0, p1)
2035 self.assertNotEqual(not p0, p0)
2036 self.assertEqual(not p0, p1)
2037 self.assertEqual(cmp(p0, p1), -1)
2038 self.assertEqual(cmp(p0, p0), 0)
2039 self.assertEqual(cmp(p0, p_1), 1)
2040 self.assertEqual(str(p0), "DProxy:0")
2041 self.assertEqual(repr(p0), "DProxy(0)")
2042 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00002043 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00002044 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00002045 self.assertIn(i, p10)
2046 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00002047
2048 # Safety test for __cmp__
2049 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002050 if not hasattr(a, '__cmp__'):
2051 return # some types don't have a __cmp__ any more (so the
2052 # test doesn't make sense any more), or maybe they
2053 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00002054 try:
2055 a.__class__.__cmp__(a, b)
2056 except TypeError:
2057 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002058 else:
Georg Brandl48545522008-02-02 10:12:36 +00002059 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
2060 a.__class__, a, b))
2061
2062 unsafecmp(u"123", "123")
2063 unsafecmp("123", u"123")
2064 unsafecmp(1, 1.0)
2065 unsafecmp(1.0, 1)
2066 unsafecmp(1, 1L)
2067 unsafecmp(1L, 1)
2068
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002069 @test_support.impl_detail("custom logic for printing to real file objects")
2070 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00002071 # Testing recursion checks ...
2072 class Letter(str):
2073 def __new__(cls, letter):
2074 if letter == 'EPS':
2075 return str.__new__(cls)
2076 return str.__new__(cls, letter)
2077 def __str__(self):
2078 if not self:
2079 return 'EPS'
2080 return self
2081 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00002082 test_stdout = sys.stdout
2083 sys.stdout = test_support.get_original_stdout()
2084 try:
2085 # nothing should actually be printed, this should raise an exception
2086 print Letter('w')
2087 except RuntimeError:
2088 pass
2089 else:
2090 self.fail("expected a RuntimeError for print recursion")
2091 finally:
2092 sys.stdout = test_stdout
2093
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002094 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00002095 # Bug #1202533.
2096 class A(object):
2097 pass
2098 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
2099 try:
2100 A()*2
2101 except RuntimeError:
2102 pass
2103 else:
2104 self.fail("expected a RuntimeError")
2105
2106 def test_weakrefs(self):
2107 # Testing weak references...
2108 import weakref
2109 class C(object):
2110 pass
2111 c = C()
2112 r = weakref.ref(c)
2113 self.assertEqual(r(), c)
2114 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002115 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00002116 self.assertEqual(r(), None)
2117 del r
2118 class NoWeak(object):
2119 __slots__ = ['foo']
2120 no = NoWeak()
2121 try:
2122 weakref.ref(no)
2123 except TypeError, msg:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002124 self.assertIn("weak reference", str(msg))
Georg Brandl48545522008-02-02 10:12:36 +00002125 else:
2126 self.fail("weakref.ref(no) should be illegal")
2127 class Weak(object):
2128 __slots__ = ['foo', '__weakref__']
2129 yes = Weak()
2130 r = weakref.ref(yes)
2131 self.assertEqual(r(), yes)
2132 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002133 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00002134 self.assertEqual(r(), None)
2135 del r
2136
2137 def test_properties(self):
2138 # Testing property...
2139 class C(object):
2140 def getx(self):
2141 return self.__x
2142 def setx(self, value):
2143 self.__x = value
2144 def delx(self):
2145 del self.__x
2146 x = property(getx, setx, delx, doc="I'm the x property.")
2147 a = C()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002148 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002149 a.x = 42
2150 self.assertEqual(a._C__x, 42)
2151 self.assertEqual(a.x, 42)
2152 del a.x
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002153 self.assertNotHasAttr(a, "x")
2154 self.assertNotHasAttr(a, "_C__x")
Georg Brandl48545522008-02-02 10:12:36 +00002155 C.x.__set__(a, 100)
2156 self.assertEqual(C.x.__get__(a), 100)
2157 C.x.__delete__(a)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002158 self.assertNotHasAttr(a, "x")
Georg Brandl48545522008-02-02 10:12:36 +00002159
2160 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002161 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002162
2163 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002164 self.assertIn("__doc__", attrs)
2165 self.assertIn("fget", attrs)
2166 self.assertIn("fset", attrs)
2167 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002168
2169 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002170 self.assertIs(raw.fget, C.__dict__['getx'])
2171 self.assertIs(raw.fset, C.__dict__['setx'])
2172 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002173
2174 for attr in "__doc__", "fget", "fset", "fdel":
2175 try:
2176 setattr(raw, attr, 42)
2177 except TypeError, msg:
2178 if str(msg).find('readonly') < 0:
2179 self.fail("when setting readonly attr %r on a property, "
2180 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002181 else:
Georg Brandl48545522008-02-02 10:12:36 +00002182 self.fail("expected TypeError from trying to set readonly %r "
2183 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002184
Georg Brandl48545522008-02-02 10:12:36 +00002185 class D(object):
Serhiy Storchaka5312a7f2015-01-31 11:27:06 +02002186 __getitem__ = property(lambda s: 1.0/0.0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002187
Georg Brandl48545522008-02-02 10:12:36 +00002188 d = D()
2189 try:
2190 for i in d:
2191 str(i)
2192 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002193 pass
Georg Brandl48545522008-02-02 10:12:36 +00002194 else:
2195 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002196
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +03002197 @test_support.cpython_only
2198 def test_property_copy_pickle(self):
2199 p = property(func)
2200 with test_support.check_py3k_warnings(
2201 (".*property", DeprecationWarning)):
2202 copy.copy(p)
2203 with test_support.check_py3k_warnings(
2204 (".*property", DeprecationWarning)):
2205 copy.deepcopy(p)
2206 for proto in range(2):
2207 self.assertRaises(TypeError, pickle.dumps, p, proto)
2208 with test_support.check_py3k_warnings(
2209 (".*property", DeprecationWarning)):
2210 pickle.dumps(p, 2)
2211
R. David Murrayf28fd242010-02-23 00:24:49 +00002212 @unittest.skipIf(sys.flags.optimize >= 2,
2213 "Docstrings are omitted with -O2 and above")
2214 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002215 class E(object):
2216 def getter(self):
2217 "getter method"
2218 return 0
2219 def setter(self_, value):
2220 "setter method"
2221 pass
2222 prop = property(getter)
2223 self.assertEqual(prop.__doc__, "getter method")
2224 prop2 = property(fset=setter)
2225 self.assertEqual(prop2.__doc__, None)
2226
Serhiy Storchaka76249ea2014-02-07 10:06:05 +02002227 @test_support.cpython_only
R. David Murrayf28fd242010-02-23 00:24:49 +00002228 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002229 # this segfaulted in 2.5b2
2230 try:
2231 import _testcapi
2232 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002233 pass
Georg Brandl48545522008-02-02 10:12:36 +00002234 else:
2235 class X(object):
2236 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002237
Georg Brandl48545522008-02-02 10:12:36 +00002238 def test_properties_plus(self):
2239 class C(object):
2240 foo = property(doc="hello")
2241 @foo.getter
2242 def foo(self):
2243 return self._foo
2244 @foo.setter
2245 def foo(self, value):
2246 self._foo = abs(value)
2247 @foo.deleter
2248 def foo(self):
2249 del self._foo
2250 c = C()
2251 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002252 self.assertNotHasAttr(c, "foo")
Georg Brandl48545522008-02-02 10:12:36 +00002253 c.foo = -42
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002254 self.assertHasAttr(c, '_foo')
Georg Brandl48545522008-02-02 10:12:36 +00002255 self.assertEqual(c._foo, 42)
2256 self.assertEqual(c.foo, 42)
2257 del c.foo
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002258 self.assertNotHasAttr(c, '_foo')
2259 self.assertNotHasAttr(c, "foo")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002260
Georg Brandl48545522008-02-02 10:12:36 +00002261 class D(C):
2262 @C.foo.deleter
2263 def foo(self):
2264 try:
2265 del self._foo
2266 except AttributeError:
2267 pass
2268 d = D()
2269 d.foo = 24
2270 self.assertEqual(d.foo, 24)
2271 del d.foo
2272 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002273
Georg Brandl48545522008-02-02 10:12:36 +00002274 class E(object):
2275 @property
2276 def foo(self):
2277 return self._foo
2278 @foo.setter
2279 def foo(self, value):
2280 raise RuntimeError
2281 @foo.setter
2282 def foo(self, value):
2283 self._foo = abs(value)
2284 @foo.deleter
2285 def foo(self, value=None):
2286 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002287
Georg Brandl48545522008-02-02 10:12:36 +00002288 e = E()
2289 e.foo = -42
2290 self.assertEqual(e.foo, 42)
2291 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002292
Georg Brandl48545522008-02-02 10:12:36 +00002293 class F(E):
2294 @E.foo.deleter
2295 def foo(self):
2296 del self._foo
2297 @foo.setter
2298 def foo(self, value):
2299 self._foo = max(0, value)
2300 f = F()
2301 f.foo = -10
2302 self.assertEqual(f.foo, 0)
2303 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002304
Georg Brandl48545522008-02-02 10:12:36 +00002305 def test_dict_constructors(self):
2306 # Testing dict constructor ...
2307 d = dict()
2308 self.assertEqual(d, {})
2309 d = dict({})
2310 self.assertEqual(d, {})
2311 d = dict({1: 2, 'a': 'b'})
2312 self.assertEqual(d, {1: 2, 'a': 'b'})
2313 self.assertEqual(d, dict(d.items()))
2314 self.assertEqual(d, dict(d.iteritems()))
2315 d = dict({'one':1, 'two':2})
2316 self.assertEqual(d, dict(one=1, two=2))
2317 self.assertEqual(d, dict(**d))
2318 self.assertEqual(d, dict({"one": 1}, two=2))
2319 self.assertEqual(d, dict([("two", 2)], one=1))
2320 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2321 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002322
Georg Brandl48545522008-02-02 10:12:36 +00002323 for badarg in 0, 0L, 0j, "0", [0], (0,):
2324 try:
2325 dict(badarg)
2326 except TypeError:
2327 pass
2328 except ValueError:
2329 if badarg == "0":
2330 # It's a sequence, and its elements are also sequences (gotta
2331 # love strings <wink>), but they aren't of length 2, so this
2332 # one seemed better as a ValueError than a TypeError.
2333 pass
2334 else:
2335 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002336 else:
Georg Brandl48545522008-02-02 10:12:36 +00002337 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002338
Georg Brandl48545522008-02-02 10:12:36 +00002339 try:
2340 dict({}, {})
2341 except TypeError:
2342 pass
2343 else:
2344 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002345
Georg Brandl48545522008-02-02 10:12:36 +00002346 class Mapping:
2347 # Lacks a .keys() method; will be added later.
2348 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002349
Georg Brandl48545522008-02-02 10:12:36 +00002350 try:
2351 dict(Mapping())
2352 except TypeError:
2353 pass
2354 else:
2355 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002356
Georg Brandl48545522008-02-02 10:12:36 +00002357 Mapping.keys = lambda self: self.dict.keys()
2358 Mapping.__getitem__ = lambda self, i: self.dict[i]
2359 d = dict(Mapping())
2360 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002361
Georg Brandl48545522008-02-02 10:12:36 +00002362 # Init from sequence of iterable objects, each producing a 2-sequence.
2363 class AddressBookEntry:
2364 def __init__(self, first, last):
2365 self.first = first
2366 self.last = last
2367 def __iter__(self):
2368 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002369
Georg Brandl48545522008-02-02 10:12:36 +00002370 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2371 AddressBookEntry('Barry', 'Peters'),
2372 AddressBookEntry('Tim', 'Peters'),
2373 AddressBookEntry('Barry', 'Warsaw')])
2374 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002375
Georg Brandl48545522008-02-02 10:12:36 +00002376 d = dict(zip(range(4), range(1, 5)))
2377 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002378
Georg Brandl48545522008-02-02 10:12:36 +00002379 # Bad sequence lengths.
2380 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2381 try:
2382 dict(bad)
2383 except ValueError:
2384 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002385 else:
Georg Brandl48545522008-02-02 10:12:36 +00002386 self.fail("no ValueError from dict(%r)" % bad)
2387
2388 def test_dir(self):
2389 # Testing dir() ...
2390 junk = 12
2391 self.assertEqual(dir(), ['junk', 'self'])
2392 del junk
2393
2394 # Just make sure these don't blow up!
2395 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2396 dir(arg)
2397
2398 # Try classic classes.
2399 class C:
2400 Cdata = 1
2401 def Cmethod(self): pass
2402
2403 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2404 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002405 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002406
2407 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2408 self.assertEqual(dir(c), cstuff)
2409
2410 c.cdata = 2
2411 c.cmethod = lambda self: 0
2412 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002413 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002414
2415 class A(C):
2416 Adata = 1
2417 def Amethod(self): pass
2418
2419 astuff = ['Adata', 'Amethod'] + cstuff
2420 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002421 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002422 a = A()
2423 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002424 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002425 a.adata = 42
2426 a.amethod = lambda self: 3
2427 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2428
2429 # The same, but with new-style classes. Since these have object as a
2430 # base class, a lot more gets sucked in.
2431 def interesting(strings):
2432 return [s for s in strings if not s.startswith('_')]
2433
2434 class C(object):
2435 Cdata = 1
2436 def Cmethod(self): pass
2437
2438 cstuff = ['Cdata', 'Cmethod']
2439 self.assertEqual(interesting(dir(C)), cstuff)
2440
2441 c = C()
2442 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002443 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002444
2445 c.cdata = 2
2446 c.cmethod = lambda self: 0
2447 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002448 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002449
2450 class A(C):
2451 Adata = 1
2452 def Amethod(self): pass
2453
2454 astuff = ['Adata', 'Amethod'] + cstuff
2455 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002456 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002457 a = A()
2458 self.assertEqual(interesting(dir(a)), astuff)
2459 a.adata = 42
2460 a.amethod = lambda self: 3
2461 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002462 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002463
2464 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002465 class M(type(sys)):
2466 pass
2467 minstance = M("m")
2468 minstance.b = 2
2469 minstance.a = 1
2470 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2471 self.assertEqual(names, ['a', 'b'])
2472
2473 class M2(M):
2474 def getdict(self):
2475 return "Not a dict!"
2476 __dict__ = property(getdict)
2477
2478 m2instance = M2("m2")
2479 m2instance.b = 2
2480 m2instance.a = 1
2481 self.assertEqual(m2instance.__dict__, "Not a dict!")
2482 try:
2483 dir(m2instance)
2484 except TypeError:
2485 pass
2486
2487 # Two essentially featureless objects, just inheriting stuff from
2488 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002489 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2490 if test_support.check_impl_detail():
2491 # None differs in PyPy: it has a __nonzero__
2492 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002493
2494 # Nasty test case for proxied objects
2495 class Wrapper(object):
2496 def __init__(self, obj):
2497 self.__obj = obj
2498 def __repr__(self):
2499 return "Wrapper(%s)" % repr(self.__obj)
2500 def __getitem__(self, key):
2501 return Wrapper(self.__obj[key])
2502 def __len__(self):
2503 return len(self.__obj)
2504 def __getattr__(self, name):
2505 return Wrapper(getattr(self.__obj, name))
2506
2507 class C(object):
2508 def __getclass(self):
2509 return Wrapper(type(self))
2510 __class__ = property(__getclass)
2511
2512 dir(C()) # This used to segfault
2513
2514 def test_supers(self):
2515 # Testing super...
2516
2517 class A(object):
2518 def meth(self, a):
2519 return "A(%r)" % a
2520
2521 self.assertEqual(A().meth(1), "A(1)")
2522
2523 class B(A):
2524 def __init__(self):
2525 self.__super = super(B, self)
2526 def meth(self, a):
2527 return "B(%r)" % a + self.__super.meth(a)
2528
2529 self.assertEqual(B().meth(2), "B(2)A(2)")
2530
2531 class C(A):
2532 def meth(self, a):
2533 return "C(%r)" % a + self.__super.meth(a)
2534 C._C__super = super(C)
2535
2536 self.assertEqual(C().meth(3), "C(3)A(3)")
2537
2538 class D(C, B):
2539 def meth(self, a):
2540 return "D(%r)" % a + super(D, self).meth(a)
2541
2542 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2543
2544 # Test for subclassing super
2545
2546 class mysuper(super):
2547 def __init__(self, *args):
2548 return super(mysuper, self).__init__(*args)
2549
2550 class E(D):
2551 def meth(self, a):
2552 return "E(%r)" % a + mysuper(E, self).meth(a)
2553
2554 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2555
2556 class F(E):
2557 def meth(self, a):
2558 s = self.__super # == mysuper(F, self)
2559 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2560 F._F__super = mysuper(F)
2561
2562 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2563
2564 # Make sure certain errors are raised
2565
2566 try:
2567 super(D, 42)
2568 except TypeError:
2569 pass
2570 else:
2571 self.fail("shouldn't allow super(D, 42)")
2572
2573 try:
2574 super(D, C())
2575 except TypeError:
2576 pass
2577 else:
2578 self.fail("shouldn't allow super(D, C())")
2579
2580 try:
2581 super(D).__get__(12)
2582 except TypeError:
2583 pass
2584 else:
2585 self.fail("shouldn't allow super(D).__get__(12)")
2586
2587 try:
2588 super(D).__get__(C())
2589 except TypeError:
2590 pass
2591 else:
2592 self.fail("shouldn't allow super(D).__get__(C())")
2593
2594 # Make sure data descriptors can be overridden and accessed via super
2595 # (new feature in Python 2.3)
2596
2597 class DDbase(object):
2598 def getx(self): return 42
2599 x = property(getx)
2600
2601 class DDsub(DDbase):
2602 def getx(self): return "hello"
2603 x = property(getx)
2604
2605 dd = DDsub()
2606 self.assertEqual(dd.x, "hello")
2607 self.assertEqual(super(DDsub, dd).x, 42)
2608
2609 # Ensure that super() lookup of descriptor from classmethod
2610 # works (SF ID# 743627)
2611
2612 class Base(object):
2613 aProp = property(lambda self: "foo")
2614
2615 class Sub(Base):
2616 @classmethod
2617 def test(klass):
2618 return super(Sub,klass).aProp
2619
2620 self.assertEqual(Sub.test(), Base.aProp)
2621
2622 # Verify that super() doesn't allow keyword args
2623 try:
2624 super(Base, kw=1)
2625 except TypeError:
2626 pass
2627 else:
2628 self.assertEqual("super shouldn't accept keyword args")
2629
2630 def test_basic_inheritance(self):
2631 # Testing inheritance from basic types...
2632
2633 class hexint(int):
2634 def __repr__(self):
2635 return hex(self)
2636 def __add__(self, other):
2637 return hexint(int.__add__(self, other))
2638 # (Note that overriding __radd__ doesn't work,
2639 # because the int type gets first dibs.)
2640 self.assertEqual(repr(hexint(7) + 9), "0x10")
2641 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2642 a = hexint(12345)
2643 self.assertEqual(a, 12345)
2644 self.assertEqual(int(a), 12345)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002645 self.assertIs(int(a).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002646 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002647 self.assertIs((+a).__class__, int)
2648 self.assertIs((a >> 0).__class__, int)
2649 self.assertIs((a << 0).__class__, int)
2650 self.assertIs((hexint(0) << 12).__class__, int)
2651 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl48545522008-02-02 10:12:36 +00002652
2653 class octlong(long):
2654 __slots__ = []
2655 def __str__(self):
2656 s = oct(self)
2657 if s[-1] == 'L':
2658 s = s[:-1]
2659 return s
2660 def __add__(self, other):
2661 return self.__class__(super(octlong, self).__add__(other))
2662 __radd__ = __add__
2663 self.assertEqual(str(octlong(3) + 5), "010")
2664 # (Note that overriding __radd__ here only seems to work
2665 # because the example uses a short int left argument.)
2666 self.assertEqual(str(5 + octlong(3000)), "05675")
2667 a = octlong(12345)
2668 self.assertEqual(a, 12345L)
2669 self.assertEqual(long(a), 12345L)
2670 self.assertEqual(hash(a), hash(12345L))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002671 self.assertIs(long(a).__class__, long)
2672 self.assertIs((+a).__class__, long)
2673 self.assertIs((-a).__class__, long)
2674 self.assertIs((-octlong(0)).__class__, long)
2675 self.assertIs((a >> 0).__class__, long)
2676 self.assertIs((a << 0).__class__, long)
2677 self.assertIs((a - 0).__class__, long)
2678 self.assertIs((a * 1).__class__, long)
2679 self.assertIs((a ** 1).__class__, long)
2680 self.assertIs((a // 1).__class__, long)
2681 self.assertIs((1 * a).__class__, long)
2682 self.assertIs((a | 0).__class__, long)
2683 self.assertIs((a ^ 0).__class__, long)
2684 self.assertIs((a & -1L).__class__, long)
2685 self.assertIs((octlong(0) << 12).__class__, long)
2686 self.assertIs((octlong(0) >> 12).__class__, long)
2687 self.assertIs(abs(octlong(0)).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002688
2689 # Because octlong overrides __add__, we can't check the absence of +0
2690 # optimizations using octlong.
2691 class longclone(long):
2692 pass
2693 a = longclone(1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002694 self.assertIs((a + 0).__class__, long)
2695 self.assertIs((0 + a).__class__, long)
Georg Brandl48545522008-02-02 10:12:36 +00002696
2697 # Check that negative clones don't segfault
2698 a = longclone(-1)
2699 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002700 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002701
2702 class precfloat(float):
2703 __slots__ = ['prec']
2704 def __init__(self, value=0.0, prec=12):
2705 self.prec = int(prec)
2706 def __repr__(self):
2707 return "%.*g" % (self.prec, self)
2708 self.assertEqual(repr(precfloat(1.1)), "1.1")
2709 a = precfloat(12345)
2710 self.assertEqual(a, 12345.0)
2711 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002712 self.assertIs(float(a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002713 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002714 self.assertIs((+a).__class__, float)
Georg Brandl48545522008-02-02 10:12:36 +00002715
2716 class madcomplex(complex):
2717 def __repr__(self):
2718 return "%.17gj%+.17g" % (self.imag, self.real)
2719 a = madcomplex(-3, 4)
2720 self.assertEqual(repr(a), "4j-3")
2721 base = complex(-3, 4)
2722 self.assertEqual(base.__class__, complex)
2723 self.assertEqual(a, base)
2724 self.assertEqual(complex(a), base)
2725 self.assertEqual(complex(a).__class__, complex)
2726 a = madcomplex(a) # just trying another form of the constructor
2727 self.assertEqual(repr(a), "4j-3")
2728 self.assertEqual(a, base)
2729 self.assertEqual(complex(a), base)
2730 self.assertEqual(complex(a).__class__, complex)
2731 self.assertEqual(hash(a), hash(base))
2732 self.assertEqual((+a).__class__, complex)
2733 self.assertEqual((a + 0).__class__, complex)
2734 self.assertEqual(a + 0, base)
2735 self.assertEqual((a - 0).__class__, complex)
2736 self.assertEqual(a - 0, base)
2737 self.assertEqual((a * 1).__class__, complex)
2738 self.assertEqual(a * 1, base)
2739 self.assertEqual((a / 1).__class__, complex)
2740 self.assertEqual(a / 1, base)
2741
2742 class madtuple(tuple):
2743 _rev = None
2744 def rev(self):
2745 if self._rev is not None:
2746 return self._rev
2747 L = list(self)
2748 L.reverse()
2749 self._rev = self.__class__(L)
2750 return self._rev
2751 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2752 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2753 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2754 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2755 for i in range(512):
2756 t = madtuple(range(i))
2757 u = t.rev()
2758 v = u.rev()
2759 self.assertEqual(v, t)
2760 a = madtuple((1,2,3,4,5))
2761 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002762 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002763 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002764 self.assertIs(a[:].__class__, tuple)
2765 self.assertIs((a * 1).__class__, tuple)
2766 self.assertIs((a * 0).__class__, tuple)
2767 self.assertIs((a + ()).__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002768 a = madtuple(())
2769 self.assertEqual(tuple(a), ())
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002770 self.assertIs(tuple(a).__class__, tuple)
2771 self.assertIs((a + a).__class__, tuple)
2772 self.assertIs((a * 0).__class__, tuple)
2773 self.assertIs((a * 1).__class__, tuple)
2774 self.assertIs((a * 2).__class__, tuple)
2775 self.assertIs(a[:].__class__, tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002776
2777 class madstring(str):
2778 _rev = None
2779 def rev(self):
2780 if self._rev is not None:
2781 return self._rev
2782 L = list(self)
2783 L.reverse()
2784 self._rev = self.__class__("".join(L))
2785 return self._rev
2786 s = madstring("abcdefghijklmnopqrstuvwxyz")
2787 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2788 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2789 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2790 for i in range(256):
2791 s = madstring("".join(map(chr, range(i))))
2792 t = s.rev()
2793 u = t.rev()
2794 self.assertEqual(u, s)
2795 s = madstring("12345")
2796 self.assertEqual(str(s), "12345")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002797 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002798
2799 base = "\x00" * 5
2800 s = madstring(base)
2801 self.assertEqual(s, base)
2802 self.assertEqual(str(s), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002803 self.assertIs(str(s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002804 self.assertEqual(hash(s), hash(base))
2805 self.assertEqual({s: 1}[base], 1)
2806 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002807 self.assertIs((s + "").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002808 self.assertEqual(s + "", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002809 self.assertIs(("" + s).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002810 self.assertEqual("" + s, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002811 self.assertIs((s * 0).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002812 self.assertEqual(s * 0, "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002813 self.assertIs((s * 1).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002814 self.assertEqual(s * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002815 self.assertIs((s * 2).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002816 self.assertEqual(s * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002817 self.assertIs(s[:].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002818 self.assertEqual(s[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002819 self.assertIs(s[0:0].__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002820 self.assertEqual(s[0:0], "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002821 self.assertIs(s.strip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002822 self.assertEqual(s.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002823 self.assertIs(s.lstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002824 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002825 self.assertIs(s.rstrip().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002826 self.assertEqual(s.rstrip(), base)
2827 identitytab = ''.join([chr(i) for i in range(256)])
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002828 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002829 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002830 self.assertIs(s.translate(identitytab, "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002831 self.assertEqual(s.translate(identitytab, "x"), base)
2832 self.assertEqual(s.translate(identitytab, "\x00"), "")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002833 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002834 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002835 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002836 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002837 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002838 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002839 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002840 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002841 self.assertIs(s.lower().__class__, str)
Georg Brandl48545522008-02-02 10:12:36 +00002842 self.assertEqual(s.lower(), base)
2843
2844 class madunicode(unicode):
2845 _rev = None
2846 def rev(self):
2847 if self._rev is not None:
2848 return self._rev
2849 L = list(self)
2850 L.reverse()
2851 self._rev = self.__class__(u"".join(L))
2852 return self._rev
2853 u = madunicode("ABCDEF")
2854 self.assertEqual(u, u"ABCDEF")
2855 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2856 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2857 base = u"12345"
2858 u = madunicode(base)
2859 self.assertEqual(unicode(u), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002860 self.assertIs(unicode(u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002861 self.assertEqual(hash(u), hash(base))
2862 self.assertEqual({u: 1}[base], 1)
2863 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002864 self.assertIs(u.strip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002865 self.assertEqual(u.strip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002866 self.assertIs(u.lstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002867 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002868 self.assertIs(u.rstrip().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002869 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002870 self.assertIs(u.replace(u"x", u"x").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002871 self.assertEqual(u.replace(u"x", u"x"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002872 self.assertIs(u.replace(u"xy", u"xy").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002873 self.assertEqual(u.replace(u"xy", u"xy"), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002874 self.assertIs(u.center(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002875 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002876 self.assertIs(u.ljust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002877 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002878 self.assertIs(u.rjust(len(u)).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002879 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002880 self.assertIs(u.lower().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002881 self.assertEqual(u.lower(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002882 self.assertIs(u.upper().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002883 self.assertEqual(u.upper(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002884 self.assertIs(u.capitalize().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002885 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002886 self.assertIs(u.title().__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002887 self.assertEqual(u.title(), base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002888 self.assertIs((u + u"").__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002889 self.assertEqual(u + u"", base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002890 self.assertIs((u"" + u).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002891 self.assertEqual(u"" + u, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002892 self.assertIs((u * 0).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002893 self.assertEqual(u * 0, u"")
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002894 self.assertIs((u * 1).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002895 self.assertEqual(u * 1, base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002896 self.assertIs((u * 2).__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002897 self.assertEqual(u * 2, base + base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002898 self.assertIs(u[:].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002899 self.assertEqual(u[:], base)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02002900 self.assertIs(u[0:0].__class__, unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002901 self.assertEqual(u[0:0], u"")
2902
2903 class sublist(list):
2904 pass
2905 a = sublist(range(5))
2906 self.assertEqual(a, range(5))
2907 a.append("hello")
2908 self.assertEqual(a, range(5) + ["hello"])
2909 a[5] = 5
2910 self.assertEqual(a, range(6))
2911 a.extend(range(6, 20))
2912 self.assertEqual(a, range(20))
2913 a[-5:] = []
2914 self.assertEqual(a, range(15))
2915 del a[10:15]
2916 self.assertEqual(len(a), 10)
2917 self.assertEqual(a, range(10))
2918 self.assertEqual(list(a), range(10))
2919 self.assertEqual(a[0], 0)
2920 self.assertEqual(a[9], 9)
2921 self.assertEqual(a[-10], 0)
2922 self.assertEqual(a[-1], 9)
2923 self.assertEqual(a[:5], range(5))
2924
2925 class CountedInput(file):
2926 """Counts lines read by self.readline().
2927
2928 self.lineno is the 0-based ordinal of the last line read, up to
2929 a maximum of one greater than the number of lines in the file.
2930
2931 self.ateof is true if and only if the final "" line has been read,
2932 at which point self.lineno stops incrementing, and further calls
2933 to readline() continue to return "".
2934 """
2935
2936 lineno = 0
2937 ateof = 0
2938 def readline(self):
2939 if self.ateof:
2940 return ""
2941 s = file.readline(self)
2942 # Next line works too.
2943 # s = super(CountedInput, self).readline()
2944 self.lineno += 1
2945 if s == "":
2946 self.ateof = 1
2947 return s
2948
2949 f = file(name=test_support.TESTFN, mode='w')
2950 lines = ['a\n', 'b\n', 'c\n']
2951 try:
2952 f.writelines(lines)
2953 f.close()
2954 f = CountedInput(test_support.TESTFN)
2955 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2956 got = f.readline()
2957 self.assertEqual(expected, got)
2958 self.assertEqual(f.lineno, i)
2959 self.assertEqual(f.ateof, (i > len(lines)))
2960 f.close()
2961 finally:
2962 try:
2963 f.close()
2964 except:
2965 pass
2966 test_support.unlink(test_support.TESTFN)
2967
2968 def test_keywords(self):
2969 # Testing keyword args to basic type constructors ...
2970 self.assertEqual(int(x=1), 1)
2971 self.assertEqual(float(x=2), 2.0)
2972 self.assertEqual(long(x=3), 3L)
2973 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2974 self.assertEqual(str(object=500), '500')
2975 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2976 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2977 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2978 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2979
2980 for constructor in (int, float, long, complex, str, unicode,
2981 tuple, list, file):
2982 try:
2983 constructor(bogus_keyword_arg=1)
2984 except TypeError:
2985 pass
2986 else:
2987 self.fail("expected TypeError from bogus keyword argument to %r"
2988 % constructor)
2989
2990 def test_str_subclass_as_dict_key(self):
2991 # Testing a str subclass used as dict key ..
2992
2993 class cistr(str):
2994 """Sublcass of str that computes __eq__ case-insensitively.
2995
2996 Also computes a hash code of the string in canonical form.
2997 """
2998
2999 def __init__(self, value):
3000 self.canonical = value.lower()
3001 self.hashcode = hash(self.canonical)
3002
3003 def __eq__(self, other):
3004 if not isinstance(other, cistr):
3005 other = cistr(other)
3006 return self.canonical == other.canonical
3007
3008 def __hash__(self):
3009 return self.hashcode
3010
3011 self.assertEqual(cistr('ABC'), 'abc')
3012 self.assertEqual('aBc', cistr('ABC'))
3013 self.assertEqual(str(cistr('ABC')), 'ABC')
3014
3015 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3016 self.assertEqual(d[cistr('one')], 1)
3017 self.assertEqual(d[cistr('tWo')], 2)
3018 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00003019 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00003020 self.assertEqual(d.get(cistr('thrEE')), 3)
3021
3022 def test_classic_comparisons(self):
3023 # Testing classic comparisons...
3024 class classic:
3025 pass
3026
3027 for base in (classic, int, object):
3028 class C(base):
3029 def __init__(self, value):
3030 self.value = int(value)
3031 def __cmp__(self, other):
3032 if isinstance(other, C):
3033 return cmp(self.value, other.value)
3034 if isinstance(other, int) or isinstance(other, long):
3035 return cmp(self.value, other)
3036 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00003037 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003038
3039 c1 = C(1)
3040 c2 = C(2)
3041 c3 = C(3)
3042 self.assertEqual(c1, 1)
3043 c = {1: c1, 2: c2, 3: c3}
3044 for x in 1, 2, 3:
3045 for y in 1, 2, 3:
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003046 self.assertEqual(cmp(c[x], c[y]), cmp(x, y),
3047 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003048 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003049 self.assertEqual(eval("c[x] %s c[y]" % op),
3050 eval("x %s y" % op),
3051 "x=%d, y=%d" % (x, y))
3052 self.assertEqual(cmp(c[x], y), cmp(x, y),
3053 "x=%d, y=%d" % (x, y))
3054 self.assertEqual(cmp(x, c[y]), cmp(x, y),
3055 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003056
3057 def test_rich_comparisons(self):
3058 # Testing rich comparisons...
3059 class Z(complex):
3060 pass
3061 z = Z(1)
3062 self.assertEqual(z, 1+0j)
3063 self.assertEqual(1+0j, z)
3064 class ZZ(complex):
3065 def __eq__(self, other):
3066 try:
3067 return abs(self - other) <= 1e-6
3068 except:
3069 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00003070 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003071 zz = ZZ(1.0000003)
3072 self.assertEqual(zz, 1+0j)
3073 self.assertEqual(1+0j, zz)
3074
3075 class classic:
3076 pass
3077 for base in (classic, int, object, list):
3078 class C(base):
3079 def __init__(self, value):
3080 self.value = int(value)
3081 def __cmp__(self_, other):
3082 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00003083 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003084 def __eq__(self, other):
3085 if isinstance(other, C):
3086 return self.value == other.value
3087 if isinstance(other, int) or isinstance(other, long):
3088 return self.value == other
3089 return NotImplemented
3090 def __ne__(self, other):
3091 if isinstance(other, C):
3092 return self.value != other.value
3093 if isinstance(other, int) or isinstance(other, long):
3094 return self.value != other
3095 return NotImplemented
3096 def __lt__(self, other):
3097 if isinstance(other, C):
3098 return self.value < other.value
3099 if isinstance(other, int) or isinstance(other, long):
3100 return self.value < other
3101 return NotImplemented
3102 def __le__(self, other):
3103 if isinstance(other, C):
3104 return self.value <= other.value
3105 if isinstance(other, int) or isinstance(other, long):
3106 return self.value <= other
3107 return NotImplemented
3108 def __gt__(self, other):
3109 if isinstance(other, C):
3110 return self.value > other.value
3111 if isinstance(other, int) or isinstance(other, long):
3112 return self.value > other
3113 return NotImplemented
3114 def __ge__(self, other):
3115 if isinstance(other, C):
3116 return self.value >= other.value
3117 if isinstance(other, int) or isinstance(other, long):
3118 return self.value >= other
3119 return NotImplemented
3120 c1 = C(1)
3121 c2 = C(2)
3122 c3 = C(3)
3123 self.assertEqual(c1, 1)
3124 c = {1: c1, 2: c2, 3: c3}
3125 for x in 1, 2, 3:
3126 for y in 1, 2, 3:
3127 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003128 self.assertEqual(eval("c[x] %s c[y]" % op),
3129 eval("x %s y" % op),
3130 "x=%d, y=%d" % (x, y))
3131 self.assertEqual(eval("c[x] %s y" % op),
3132 eval("x %s y" % op),
3133 "x=%d, y=%d" % (x, y))
3134 self.assertEqual(eval("x %s c[y]" % op),
3135 eval("x %s y" % op),
3136 "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00003137
3138 def test_coercions(self):
3139 # Testing coercions...
3140 class I(int): pass
3141 coerce(I(0), 0)
3142 coerce(0, I(0))
3143 class L(long): pass
3144 coerce(L(0), 0)
3145 coerce(L(0), 0L)
3146 coerce(0, L(0))
3147 coerce(0L, L(0))
3148 class F(float): pass
3149 coerce(F(0), 0)
3150 coerce(F(0), 0L)
3151 coerce(F(0), 0.)
3152 coerce(0, F(0))
3153 coerce(0L, F(0))
3154 coerce(0., F(0))
3155 class C(complex): pass
3156 coerce(C(0), 0)
3157 coerce(C(0), 0L)
3158 coerce(C(0), 0.)
3159 coerce(C(0), 0j)
3160 coerce(0, C(0))
3161 coerce(0L, C(0))
3162 coerce(0., C(0))
3163 coerce(0j, C(0))
3164
3165 def test_descrdoc(self):
3166 # Testing descriptor doc strings...
3167 def check(descr, what):
3168 self.assertEqual(descr.__doc__, what)
3169 check(file.closed, "True if the file is closed") # getset descriptor
3170 check(file.name, "file name") # member descriptor
3171
3172 def test_doc_descriptor(self):
3173 # Testing __doc__ descriptor...
3174 # SF bug 542984
3175 class DocDescr(object):
3176 def __get__(self, object, otype):
3177 if object:
3178 object = object.__class__.__name__ + ' instance'
3179 if otype:
3180 otype = otype.__name__
3181 return 'object=%s; type=%s' % (object, otype)
3182 class OldClass:
3183 __doc__ = DocDescr()
3184 class NewClass(object):
3185 __doc__ = DocDescr()
3186 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3187 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3188 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3189 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3190
3191 def test_set_class(self):
3192 # Testing __class__ assignment...
3193 class C(object): pass
3194 class D(object): pass
3195 class E(object): pass
3196 class F(D, E): pass
3197 for cls in C, D, E, F:
3198 for cls2 in C, D, E, F:
3199 x = cls()
3200 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003201 self.assertIs(x.__class__, cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003202 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003203 self.assertIs(x.__class__, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003204 def cant(x, C):
3205 try:
3206 x.__class__ = C
3207 except TypeError:
3208 pass
3209 else:
3210 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3211 try:
3212 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003213 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003214 pass
3215 else:
3216 self.fail("shouldn't allow del %r.__class__" % x)
3217 cant(C(), list)
3218 cant(list(), C)
3219 cant(C(), 1)
3220 cant(C(), object)
3221 cant(object(), list)
3222 cant(list(), object)
3223 class Int(int): __slots__ = []
3224 cant(2, Int)
3225 cant(Int(), int)
3226 cant(True, int)
3227 cant(2, bool)
3228 o = object()
3229 cant(o, type(1))
3230 cant(o, type(None))
3231 del o
3232 class G(object):
3233 __slots__ = ["a", "b"]
3234 class H(object):
3235 __slots__ = ["b", "a"]
3236 try:
3237 unicode
3238 except NameError:
3239 class I(object):
3240 __slots__ = ["a", "b"]
3241 else:
3242 class I(object):
3243 __slots__ = [unicode("a"), unicode("b")]
3244 class J(object):
3245 __slots__ = ["c", "b"]
3246 class K(object):
3247 __slots__ = ["a", "b", "d"]
3248 class L(H):
3249 __slots__ = ["e"]
3250 class M(I):
3251 __slots__ = ["e"]
3252 class N(J):
3253 __slots__ = ["__weakref__"]
3254 class P(J):
3255 __slots__ = ["__dict__"]
3256 class Q(J):
3257 pass
3258 class R(J):
3259 __slots__ = ["__dict__", "__weakref__"]
3260
3261 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3262 x = cls()
3263 x.a = 1
3264 x.__class__ = cls2
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003265 self.assertIs(x.__class__, cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003266 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3267 self.assertEqual(x.a, 1)
3268 x.__class__ = cls
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003269 self.assertIs(x.__class__, cls,
Georg Brandl48545522008-02-02 10:12:36 +00003270 "assigning %r as __class__ for %r silently failed" % (cls, x))
3271 self.assertEqual(x.a, 1)
3272 for cls in G, J, K, L, M, N, P, R, list, Int:
3273 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3274 if cls is cls2:
3275 continue
3276 cant(cls(), cls2)
3277
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003278 # Issue5283: when __class__ changes in __del__, the wrong
3279 # type gets DECREF'd.
3280 class O(object):
3281 pass
3282 class A(object):
3283 def __del__(self):
3284 self.__class__ = O
3285 l = [A() for x in range(100)]
3286 del l
3287
Georg Brandl48545522008-02-02 10:12:36 +00003288 def test_set_dict(self):
3289 # Testing __dict__ assignment...
3290 class C(object): pass
3291 a = C()
3292 a.__dict__ = {'b': 1}
3293 self.assertEqual(a.b, 1)
3294 def cant(x, dict):
3295 try:
3296 x.__dict__ = dict
3297 except (AttributeError, TypeError):
3298 pass
3299 else:
3300 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3301 cant(a, None)
3302 cant(a, [])
3303 cant(a, 1)
3304 del a.__dict__ # Deleting __dict__ is allowed
3305
3306 class Base(object):
3307 pass
3308 def verify_dict_readonly(x):
3309 """
3310 x has to be an instance of a class inheriting from Base.
3311 """
3312 cant(x, {})
3313 try:
3314 del x.__dict__
3315 except (AttributeError, TypeError):
3316 pass
3317 else:
3318 self.fail("shouldn't allow del %r.__dict__" % x)
3319 dict_descr = Base.__dict__["__dict__"]
3320 try:
3321 dict_descr.__set__(x, {})
3322 except (AttributeError, TypeError):
3323 pass
3324 else:
3325 self.fail("dict_descr allowed access to %r's dict" % x)
3326
3327 # Classes don't allow __dict__ assignment and have readonly dicts
3328 class Meta1(type, Base):
3329 pass
3330 class Meta2(Base, type):
3331 pass
3332 class D(object):
3333 __metaclass__ = Meta1
3334 class E(object):
3335 __metaclass__ = Meta2
3336 for cls in C, D, E:
3337 verify_dict_readonly(cls)
3338 class_dict = cls.__dict__
3339 try:
3340 class_dict["spam"] = "eggs"
3341 except TypeError:
3342 pass
3343 else:
3344 self.fail("%r's __dict__ can be modified" % cls)
3345
3346 # Modules also disallow __dict__ assignment
3347 class Module1(types.ModuleType, Base):
3348 pass
3349 class Module2(Base, types.ModuleType):
3350 pass
3351 for ModuleType in Module1, Module2:
3352 mod = ModuleType("spam")
3353 verify_dict_readonly(mod)
3354 mod.__dict__["spam"] = "eggs"
3355
3356 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003357 # (at least not any more than regular exception's __dict__ can
3358 # be deleted; on CPython it is not the case, whereas on PyPy they
3359 # can, just like any other new-style instance's __dict__.)
3360 def can_delete_dict(e):
3361 try:
3362 del e.__dict__
3363 except (TypeError, AttributeError):
3364 return False
3365 else:
3366 return True
Georg Brandl48545522008-02-02 10:12:36 +00003367 class Exception1(Exception, Base):
3368 pass
3369 class Exception2(Base, Exception):
3370 pass
3371 for ExceptionType in Exception, Exception1, Exception2:
3372 e = ExceptionType()
3373 e.__dict__ = {"a": 1}
3374 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003375 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003376
3377 def test_pickles(self):
3378 # Testing pickling and copying new-style classes and objects...
3379 import pickle, cPickle
3380
3381 def sorteditems(d):
3382 L = d.items()
3383 L.sort()
3384 return L
3385
3386 global C
3387 class C(object):
3388 def __init__(self, a, b):
3389 super(C, self).__init__()
3390 self.a = a
3391 self.b = b
3392 def __repr__(self):
3393 return "C(%r, %r)" % (self.a, self.b)
3394
3395 global C1
3396 class C1(list):
3397 def __new__(cls, a, b):
3398 return super(C1, cls).__new__(cls)
3399 def __getnewargs__(self):
3400 return (self.a, self.b)
3401 def __init__(self, a, b):
3402 self.a = a
3403 self.b = b
3404 def __repr__(self):
3405 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3406
3407 global C2
3408 class C2(int):
3409 def __new__(cls, a, b, val=0):
3410 return super(C2, cls).__new__(cls, val)
3411 def __getnewargs__(self):
3412 return (self.a, self.b, int(self))
3413 def __init__(self, a, b, val=0):
3414 self.a = a
3415 self.b = b
3416 def __repr__(self):
3417 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3418
3419 global C3
3420 class C3(object):
3421 def __init__(self, foo):
3422 self.foo = foo
3423 def __getstate__(self):
3424 return self.foo
3425 def __setstate__(self, foo):
3426 self.foo = foo
3427
3428 global C4classic, C4
3429 class C4classic: # classic
3430 pass
3431 class C4(C4classic, object): # mixed inheritance
3432 pass
3433
3434 for p in pickle, cPickle:
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003435 for bin in range(p.HIGHEST_PROTOCOL + 1):
Georg Brandl48545522008-02-02 10:12:36 +00003436 for cls in C, C1, C2:
3437 s = p.dumps(cls, bin)
3438 cls2 = p.loads(s)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003439 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003440
3441 a = C1(1, 2); a.append(42); a.append(24)
3442 b = C2("hello", "world", 42)
3443 s = p.dumps((a, b), bin)
3444 x, y = p.loads(s)
3445 self.assertEqual(x.__class__, a.__class__)
3446 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3447 self.assertEqual(y.__class__, b.__class__)
3448 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3449 self.assertEqual(repr(x), repr(a))
3450 self.assertEqual(repr(y), repr(b))
3451 # Test for __getstate__ and __setstate__ on new style class
3452 u = C3(42)
3453 s = p.dumps(u, bin)
3454 v = p.loads(s)
3455 self.assertEqual(u.__class__, v.__class__)
3456 self.assertEqual(u.foo, v.foo)
3457 # Test for picklability of hybrid class
3458 u = C4()
3459 u.foo = 42
3460 s = p.dumps(u, bin)
3461 v = p.loads(s)
3462 self.assertEqual(u.__class__, v.__class__)
3463 self.assertEqual(u.foo, v.foo)
3464
3465 # Testing copy.deepcopy()
3466 import copy
3467 for cls in C, C1, C2:
3468 cls2 = copy.deepcopy(cls)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003469 self.assertIs(cls2, cls)
Georg Brandl48545522008-02-02 10:12:36 +00003470
3471 a = C1(1, 2); a.append(42); a.append(24)
3472 b = C2("hello", "world", 42)
3473 x, y = copy.deepcopy((a, b))
3474 self.assertEqual(x.__class__, a.__class__)
3475 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3476 self.assertEqual(y.__class__, b.__class__)
3477 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3478 self.assertEqual(repr(x), repr(a))
3479 self.assertEqual(repr(y), repr(b))
3480
3481 def test_pickle_slots(self):
3482 # Testing pickling of classes with __slots__ ...
3483 import pickle, cPickle
3484 # Pickling of classes with __slots__ but without __getstate__ should fail
3485 global B, C, D, E
3486 class B(object):
3487 pass
3488 for base in [object, B]:
3489 class C(base):
3490 __slots__ = ['a']
3491 class D(C):
3492 pass
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003493 for proto in range(2):
3494 try:
3495 pickle.dumps(C(), proto)
3496 except TypeError:
3497 pass
3498 else:
3499 self.fail("should fail: pickle C instance - %s" % base)
3500 try:
3501 cPickle.dumps(C(), proto)
3502 except TypeError:
3503 pass
3504 else:
3505 self.fail("should fail: cPickle C instance - %s" % base)
3506 try:
3507 pickle.dumps(C(), proto)
3508 except TypeError:
3509 pass
3510 else:
3511 self.fail("should fail: pickle D instance - %s" % base)
3512 try:
3513 cPickle.dumps(D(), proto)
3514 except TypeError:
3515 pass
3516 else:
3517 self.fail("should fail: cPickle D instance - %s" % base)
Georg Brandl48545522008-02-02 10:12:36 +00003518 # Give C a nice generic __getstate__ and __setstate__
3519 class C(base):
3520 __slots__ = ['a']
3521 def __getstate__(self):
3522 try:
3523 d = self.__dict__.copy()
3524 except AttributeError:
3525 d = {}
3526 for cls in self.__class__.__mro__:
3527 for sn in cls.__dict__.get('__slots__', ()):
3528 try:
3529 d[sn] = getattr(self, sn)
3530 except AttributeError:
3531 pass
3532 return d
3533 def __setstate__(self, d):
3534 for k, v in d.items():
3535 setattr(self, k, v)
3536 class D(C):
3537 pass
3538 # Now it should work
3539 x = C()
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003540 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3541 y = pickle.loads(pickle.dumps(x, proto))
3542 self.assertNotHasAttr(y, 'a')
3543 y = cPickle.loads(cPickle.dumps(x, proto))
3544 self.assertNotHasAttr(y, 'a')
Georg Brandl48545522008-02-02 10:12:36 +00003545 x.a = 42
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003546 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3547 y = pickle.loads(pickle.dumps(x, proto))
3548 self.assertEqual(y.a, 42)
3549 y = cPickle.loads(cPickle.dumps(x, proto))
3550 self.assertEqual(y.a, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003551 x = D()
3552 x.a = 42
3553 x.b = 100
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003554 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3555 y = pickle.loads(pickle.dumps(x, proto))
3556 self.assertEqual(y.a + y.b, 142)
3557 y = cPickle.loads(cPickle.dumps(x, proto))
3558 self.assertEqual(y.a + y.b, 142)
Georg Brandl48545522008-02-02 10:12:36 +00003559 # A subclass that adds a slot should also work
3560 class E(C):
3561 __slots__ = ['b']
3562 x = E()
3563 x.a = 42
3564 x.b = "foo"
Serhiy Storchaka655720e2014-12-15 14:02:43 +02003565 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3566 y = pickle.loads(pickle.dumps(x, proto))
3567 self.assertEqual(y.a, x.a)
3568 self.assertEqual(y.b, x.b)
3569 y = cPickle.loads(cPickle.dumps(x, proto))
3570 self.assertEqual(y.a, x.a)
3571 self.assertEqual(y.b, x.b)
Georg Brandl48545522008-02-02 10:12:36 +00003572
3573 def test_binary_operator_override(self):
3574 # Testing overrides of binary operations...
3575 class I(int):
3576 def __repr__(self):
3577 return "I(%r)" % int(self)
3578 def __add__(self, other):
3579 return I(int(self) + int(other))
3580 __radd__ = __add__
3581 def __pow__(self, other, mod=None):
3582 if mod is None:
3583 return I(pow(int(self), int(other)))
3584 else:
3585 return I(pow(int(self), int(other), int(mod)))
3586 def __rpow__(self, other, mod=None):
3587 if mod is None:
3588 return I(pow(int(other), int(self), mod))
3589 else:
3590 return I(pow(int(other), int(self), int(mod)))
3591
3592 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3593 self.assertEqual(repr(I(1) + 2), "I(3)")
3594 self.assertEqual(repr(1 + I(2)), "I(3)")
3595 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3596 self.assertEqual(repr(2 ** I(3)), "I(8)")
3597 self.assertEqual(repr(I(2) ** 3), "I(8)")
3598 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3599 class S(str):
3600 def __eq__(self, other):
3601 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003602 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003603
3604 def test_subclass_propagation(self):
3605 # Testing propagation of slot functions to subclasses...
3606 class A(object):
3607 pass
3608 class B(A):
3609 pass
3610 class C(A):
3611 pass
3612 class D(B, C):
3613 pass
3614 d = D()
3615 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3616 A.__hash__ = lambda self: 42
3617 self.assertEqual(hash(d), 42)
3618 C.__hash__ = lambda self: 314
3619 self.assertEqual(hash(d), 314)
3620 B.__hash__ = lambda self: 144
3621 self.assertEqual(hash(d), 144)
3622 D.__hash__ = lambda self: 100
3623 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003624 D.__hash__ = None
3625 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003626 del D.__hash__
3627 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003628 B.__hash__ = None
3629 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003630 del B.__hash__
3631 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003632 C.__hash__ = None
3633 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003634 del C.__hash__
3635 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003636 A.__hash__ = None
3637 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003638 del A.__hash__
3639 self.assertEqual(hash(d), orig_hash)
3640 d.foo = 42
3641 d.bar = 42
3642 self.assertEqual(d.foo, 42)
3643 self.assertEqual(d.bar, 42)
3644 def __getattribute__(self, name):
3645 if name == "foo":
3646 return 24
3647 return object.__getattribute__(self, name)
3648 A.__getattribute__ = __getattribute__
3649 self.assertEqual(d.foo, 24)
3650 self.assertEqual(d.bar, 42)
3651 def __getattr__(self, name):
3652 if name in ("spam", "foo", "bar"):
3653 return "hello"
3654 raise AttributeError, name
3655 B.__getattr__ = __getattr__
3656 self.assertEqual(d.spam, "hello")
3657 self.assertEqual(d.foo, 24)
3658 self.assertEqual(d.bar, 42)
3659 del A.__getattribute__
3660 self.assertEqual(d.foo, 42)
3661 del d.foo
3662 self.assertEqual(d.foo, "hello")
3663 self.assertEqual(d.bar, 42)
3664 del B.__getattr__
3665 try:
3666 d.foo
3667 except AttributeError:
3668 pass
3669 else:
3670 self.fail("d.foo should be undefined now")
3671
3672 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003673 class A(object):
3674 pass
3675 class B(A):
3676 pass
3677 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003678 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003679 A.__setitem__ = lambda *a: None # crash
3680
3681 def test_buffer_inheritance(self):
3682 # Testing that buffer interface is inherited ...
3683
3684 import binascii
3685 # SF bug [#470040] ParseTuple t# vs subclasses.
3686
3687 class MyStr(str):
3688 pass
3689 base = 'abc'
3690 m = MyStr(base)
3691 # b2a_hex uses the buffer interface to get its argument's value, via
3692 # PyArg_ParseTuple 't#' code.
3693 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3694
3695 # It's not clear that unicode will continue to support the character
3696 # buffer interface, and this test will fail if that's taken away.
3697 class MyUni(unicode):
3698 pass
3699 base = u'abc'
3700 m = MyUni(base)
3701 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3702
3703 class MyInt(int):
3704 pass
3705 m = MyInt(42)
3706 try:
3707 binascii.b2a_hex(m)
3708 self.fail('subclass of int should not have a buffer interface')
3709 except TypeError:
3710 pass
3711
3712 def test_str_of_str_subclass(self):
3713 # Testing __str__ defined in subclass of str ...
3714 import binascii
3715 import cStringIO
3716
3717 class octetstring(str):
3718 def __str__(self):
3719 return binascii.b2a_hex(self)
3720 def __repr__(self):
3721 return self + " repr"
3722
3723 o = octetstring('A')
3724 self.assertEqual(type(o), octetstring)
3725 self.assertEqual(type(str(o)), str)
3726 self.assertEqual(type(repr(o)), str)
3727 self.assertEqual(ord(o), 0x41)
3728 self.assertEqual(str(o), '41')
3729 self.assertEqual(repr(o), 'A repr')
3730 self.assertEqual(o.__str__(), '41')
3731 self.assertEqual(o.__repr__(), 'A repr')
3732
3733 capture = cStringIO.StringIO()
3734 # Calling str() or not exercises different internal paths.
3735 print >> capture, o
3736 print >> capture, str(o)
3737 self.assertEqual(capture.getvalue(), '41\n41\n')
3738 capture.close()
3739
3740 def test_keyword_arguments(self):
3741 # Testing keyword arguments to __init__, __call__...
3742 def f(a): return a
3743 self.assertEqual(f.__call__(a=42), 42)
3744 a = []
3745 list.__init__(a, sequence=[0, 1, 2])
3746 self.assertEqual(a, [0, 1, 2])
3747
3748 def test_recursive_call(self):
3749 # Testing recursive __call__() by setting to instance of class...
3750 class A(object):
3751 pass
3752
3753 A.__call__ = A()
3754 try:
3755 A()()
3756 except RuntimeError:
3757 pass
3758 else:
3759 self.fail("Recursion limit should have been reached for __call__()")
3760
3761 def test_delete_hook(self):
3762 # Testing __del__ hook...
3763 log = []
3764 class C(object):
3765 def __del__(self):
3766 log.append(1)
3767 c = C()
3768 self.assertEqual(log, [])
3769 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003770 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003771 self.assertEqual(log, [1])
3772
3773 class D(object): pass
3774 d = D()
3775 try: del d[0]
3776 except TypeError: pass
3777 else: self.fail("invalid del() didn't raise TypeError")
3778
3779 def test_hash_inheritance(self):
3780 # Testing hash of mutable subclasses...
3781
3782 class mydict(dict):
3783 pass
3784 d = mydict()
3785 try:
3786 hash(d)
3787 except TypeError:
3788 pass
3789 else:
3790 self.fail("hash() of dict subclass should fail")
3791
3792 class mylist(list):
3793 pass
3794 d = mylist()
3795 try:
3796 hash(d)
3797 except TypeError:
3798 pass
3799 else:
3800 self.fail("hash() of list subclass should fail")
3801
3802 def test_str_operations(self):
3803 try: 'a' + 5
3804 except TypeError: pass
3805 else: self.fail("'' + 5 doesn't raise TypeError")
3806
3807 try: ''.split('')
3808 except ValueError: pass
3809 else: self.fail("''.split('') doesn't raise ValueError")
3810
3811 try: ''.join([0])
3812 except TypeError: pass
3813 else: self.fail("''.join([0]) doesn't raise TypeError")
3814
3815 try: ''.rindex('5')
3816 except ValueError: pass
3817 else: self.fail("''.rindex('5') doesn't raise ValueError")
3818
3819 try: '%(n)s' % None
3820 except TypeError: pass
3821 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3822
3823 try: '%(n' % {}
3824 except ValueError: pass
3825 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3826
3827 try: '%*s' % ('abc')
3828 except TypeError: pass
3829 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3830
3831 try: '%*.*s' % ('abc', 5)
3832 except TypeError: pass
3833 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3834
3835 try: '%s' % (1, 2)
3836 except TypeError: pass
3837 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3838
3839 try: '%' % None
3840 except ValueError: pass
3841 else: self.fail("'%' % None doesn't raise ValueError")
3842
3843 self.assertEqual('534253'.isdigit(), 1)
3844 self.assertEqual('534253x'.isdigit(), 0)
3845 self.assertEqual('%c' % 5, '\x05')
3846 self.assertEqual('%c' % '5', '5')
3847
3848 def test_deepcopy_recursive(self):
3849 # Testing deepcopy of recursive objects...
3850 class Node:
3851 pass
3852 a = Node()
3853 b = Node()
3854 a.b = b
3855 b.a = a
3856 z = deepcopy(a) # This blew up before
3857
Martin Panterf2f1c572016-05-08 13:18:25 +00003858 def test_uninitialized_modules(self):
Georg Brandl48545522008-02-02 10:12:36 +00003859 # Testing uninitialized module objects...
3860 from types import ModuleType as M
3861 m = M.__new__(M)
3862 str(m)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02003863 self.assertNotHasAttr(m, "__name__")
3864 self.assertNotHasAttr(m, "__file__")
3865 self.assertNotHasAttr(m, "foo")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003866 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003867 m.foo = 1
3868 self.assertEqual(m.__dict__, {"foo": 1})
3869
3870 def test_funny_new(self):
3871 # Testing __new__ returning something unexpected...
3872 class C(object):
3873 def __new__(cls, arg):
3874 if isinstance(arg, str): return [1, 2, 3]
3875 elif isinstance(arg, int): return object.__new__(D)
3876 else: return object.__new__(cls)
3877 class D(C):
3878 def __init__(self, arg):
3879 self.foo = arg
3880 self.assertEqual(C("1"), [1, 2, 3])
3881 self.assertEqual(D("1"), [1, 2, 3])
3882 d = D(None)
3883 self.assertEqual(d.foo, None)
3884 d = C(1)
3885 self.assertEqual(isinstance(d, D), True)
3886 self.assertEqual(d.foo, 1)
3887 d = D(1)
3888 self.assertEqual(isinstance(d, D), True)
3889 self.assertEqual(d.foo, 1)
3890
Serhiy Storchaka7117d352016-12-14 19:48:38 +02003891 class C(object):
3892 @staticmethod
3893 def __new__(*args):
3894 return args
3895 self.assertEqual(C(1, 2), (C, 1, 2))
3896 class D(C):
3897 pass
3898 self.assertEqual(D(1, 2), (D, 1, 2))
3899
3900 class C(object):
3901 @classmethod
3902 def __new__(*args):
3903 return args
3904 self.assertEqual(C(1, 2), (C, C, 1, 2))
3905 class D(C):
3906 pass
3907 self.assertEqual(D(1, 2), (D, D, 1, 2))
3908
Georg Brandl48545522008-02-02 10:12:36 +00003909 def test_imul_bug(self):
3910 # Testing for __imul__ problems...
3911 # SF bug 544647
3912 class C(object):
3913 def __imul__(self, other):
3914 return (self, other)
3915 x = C()
3916 y = x
3917 y *= 1.0
3918 self.assertEqual(y, (x, 1.0))
3919 y = x
3920 y *= 2
3921 self.assertEqual(y, (x, 2))
3922 y = x
3923 y *= 3L
3924 self.assertEqual(y, (x, 3L))
3925 y = x
3926 y *= 1L<<100
3927 self.assertEqual(y, (x, 1L<<100))
3928 y = x
3929 y *= None
3930 self.assertEqual(y, (x, None))
3931 y = x
3932 y *= "foo"
3933 self.assertEqual(y, (x, "foo"))
3934
3935 def test_copy_setstate(self):
3936 # Testing that copy.*copy() correctly uses __setstate__...
3937 import copy
3938 class C(object):
3939 def __init__(self, foo=None):
3940 self.foo = foo
3941 self.__foo = foo
3942 def setfoo(self, foo=None):
3943 self.foo = foo
3944 def getfoo(self):
3945 return self.__foo
3946 def __getstate__(self):
3947 return [self.foo]
3948 def __setstate__(self_, lst):
3949 self.assertEqual(len(lst), 1)
3950 self_.__foo = self_.foo = lst[0]
3951 a = C(42)
3952 a.setfoo(24)
3953 self.assertEqual(a.foo, 24)
3954 self.assertEqual(a.getfoo(), 42)
3955 b = copy.copy(a)
3956 self.assertEqual(b.foo, 24)
3957 self.assertEqual(b.getfoo(), 24)
3958 b = copy.deepcopy(a)
3959 self.assertEqual(b.foo, 24)
3960 self.assertEqual(b.getfoo(), 24)
3961
3962 def test_slices(self):
3963 # Testing cases with slices and overridden __getitem__ ...
3964
3965 # Strings
3966 self.assertEqual("hello"[:4], "hell")
3967 self.assertEqual("hello"[slice(4)], "hell")
3968 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3969 class S(str):
3970 def __getitem__(self, x):
3971 return str.__getitem__(self, x)
3972 self.assertEqual(S("hello")[:4], "hell")
3973 self.assertEqual(S("hello")[slice(4)], "hell")
3974 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3975 # Tuples
3976 self.assertEqual((1,2,3)[:2], (1,2))
3977 self.assertEqual((1,2,3)[slice(2)], (1,2))
3978 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3979 class T(tuple):
3980 def __getitem__(self, x):
3981 return tuple.__getitem__(self, x)
3982 self.assertEqual(T((1,2,3))[:2], (1,2))
3983 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3984 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3985 # Lists
3986 self.assertEqual([1,2,3][:2], [1,2])
3987 self.assertEqual([1,2,3][slice(2)], [1,2])
3988 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3989 class L(list):
3990 def __getitem__(self, x):
3991 return list.__getitem__(self, x)
3992 self.assertEqual(L([1,2,3])[:2], [1,2])
3993 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3994 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3995 # Now do lists and __setitem__
3996 a = L([1,2,3])
3997 a[slice(1, 3)] = [3,2]
3998 self.assertEqual(a, [1,3,2])
3999 a[slice(0, 2, 1)] = [3,1]
4000 self.assertEqual(a, [3,1,2])
4001 a.__setitem__(slice(1, 3), [2,1])
4002 self.assertEqual(a, [3,2,1])
4003 a.__setitem__(slice(0, 2, 1), [2,3])
4004 self.assertEqual(a, [2,3,1])
4005
4006 def test_subtype_resurrection(self):
4007 # Testing resurrection of new-style instance...
4008
4009 class C(object):
4010 container = []
4011
4012 def __del__(self):
4013 # resurrect the instance
4014 C.container.append(self)
4015
4016 c = C()
4017 c.attr = 42
4018
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004019 # The most interesting thing here is whether this blows up, due to
4020 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
4021 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00004022 del c
4023
4024 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004025 # the last container slot works: that will attempt to delete c again,
4026 # which will cause c to get appended back to the container again
4027 # "during" the del. (On non-CPython implementations, however, __del__
4028 # is typically not called again.)
4029 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004030 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004031 del C.container[-1]
4032 if test_support.check_impl_detail():
4033 test_support.gc_collect()
4034 self.assertEqual(len(C.container), 1)
4035 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00004036
4037 # Make c mortal again, so that the test framework with -l doesn't report
4038 # it as a leak.
4039 del C.__del__
4040
4041 def test_slots_trash(self):
4042 # Testing slot trash...
4043 # Deallocating deeply nested slotted trash caused stack overflows
4044 class trash(object):
4045 __slots__ = ['x']
4046 def __init__(self, x):
4047 self.x = x
4048 o = None
4049 for i in xrange(50000):
4050 o = trash(o)
4051 del o
4052
4053 def test_slots_multiple_inheritance(self):
4054 # SF bug 575229, multiple inheritance w/ slots dumps core
4055 class A(object):
4056 __slots__=()
4057 class B(object):
4058 pass
4059 class C(A,B) :
4060 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004061 if test_support.check_impl_detail():
4062 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004063 self.assertHasAttr(C, '__dict__')
4064 self.assertHasAttr(C, '__weakref__')
Georg Brandl48545522008-02-02 10:12:36 +00004065 C().x = 2
4066
4067 def test_rmul(self):
4068 # Testing correct invocation of __rmul__...
4069 # SF patch 592646
4070 class C(object):
4071 def __mul__(self, other):
4072 return "mul"
4073 def __rmul__(self, other):
4074 return "rmul"
4075 a = C()
4076 self.assertEqual(a*2, "mul")
4077 self.assertEqual(a*2.2, "mul")
4078 self.assertEqual(2*a, "rmul")
4079 self.assertEqual(2.2*a, "rmul")
4080
4081 def test_ipow(self):
4082 # Testing correct invocation of __ipow__...
4083 # [SF bug 620179]
4084 class C(object):
4085 def __ipow__(self, other):
4086 pass
4087 a = C()
4088 a **= 2
4089
4090 def test_mutable_bases(self):
4091 # Testing mutable bases...
4092
4093 # stuff that should work:
4094 class C(object):
4095 pass
4096 class C2(object):
4097 def __getattribute__(self, attr):
4098 if attr == 'a':
4099 return 2
4100 else:
4101 return super(C2, self).__getattribute__(attr)
4102 def meth(self):
4103 return 1
4104 class D(C):
4105 pass
4106 class E(D):
4107 pass
4108 d = D()
4109 e = E()
4110 D.__bases__ = (C,)
4111 D.__bases__ = (C2,)
4112 self.assertEqual(d.meth(), 1)
4113 self.assertEqual(e.meth(), 1)
4114 self.assertEqual(d.a, 2)
4115 self.assertEqual(e.a, 2)
4116 self.assertEqual(C2.__subclasses__(), [D])
4117
Georg Brandl48545522008-02-02 10:12:36 +00004118 try:
4119 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004120 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00004121 pass
4122 else:
4123 self.fail("shouldn't be able to delete .__bases__")
4124
4125 try:
4126 D.__bases__ = ()
4127 except TypeError, msg:
4128 if str(msg) == "a new-style class can't have only classic bases":
4129 self.fail("wrong error message for .__bases__ = ()")
4130 else:
4131 self.fail("shouldn't be able to set .__bases__ to ()")
4132
4133 try:
4134 D.__bases__ = (D,)
4135 except TypeError:
4136 pass
4137 else:
4138 # actually, we'll have crashed by here...
4139 self.fail("shouldn't be able to create inheritance cycles")
4140
4141 try:
4142 D.__bases__ = (C, C)
4143 except TypeError:
4144 pass
4145 else:
4146 self.fail("didn't detect repeated base classes")
4147
4148 try:
4149 D.__bases__ = (E,)
4150 except TypeError:
4151 pass
4152 else:
4153 self.fail("shouldn't be able to create inheritance cycles")
4154
4155 # let's throw a classic class into the mix:
4156 class Classic:
4157 def meth2(self):
4158 return 3
4159
4160 D.__bases__ = (C, Classic)
4161
4162 self.assertEqual(d.meth2(), 3)
4163 self.assertEqual(e.meth2(), 3)
4164 try:
4165 d.a
4166 except AttributeError:
4167 pass
4168 else:
4169 self.fail("attribute should have vanished")
4170
4171 try:
4172 D.__bases__ = (Classic,)
4173 except TypeError:
4174 pass
4175 else:
4176 self.fail("new-style class must have a new-style base")
4177
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004178 def test_builtin_bases(self):
4179 # Make sure all the builtin types can have their base queried without
4180 # segfaulting. See issue #5787.
4181 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
4182 if isinstance(tp, type)]
4183 for tp in builtin_types:
4184 object.__getattribute__(tp, "__bases__")
4185 if tp is not object:
4186 self.assertEqual(len(tp.__bases__), 1, tp)
4187
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00004188 class L(list):
4189 pass
4190
4191 class C(object):
4192 pass
4193
4194 class D(C):
4195 pass
4196
4197 try:
4198 L.__bases__ = (dict,)
4199 except TypeError:
4200 pass
4201 else:
4202 self.fail("shouldn't turn list subclass into dict subclass")
4203
4204 try:
4205 list.__bases__ = (dict,)
4206 except TypeError:
4207 pass
4208 else:
4209 self.fail("shouldn't be able to assign to list.__bases__")
4210
4211 try:
4212 D.__bases__ = (C, list)
4213 except TypeError:
4214 pass
4215 else:
4216 assert 0, "best_base calculation found wanting"
4217
Benjamin Peterson77d12ec2015-10-06 19:36:54 -07004218 def test_unsubclassable_types(self):
4219 with self.assertRaises(TypeError):
4220 class X(types.NoneType):
4221 pass
4222 with self.assertRaises(TypeError):
4223 class X(object, types.NoneType):
4224 pass
4225 with self.assertRaises(TypeError):
4226 class X(types.NoneType, object):
4227 pass
4228 class O(object):
4229 pass
4230 with self.assertRaises(TypeError):
4231 class X(O, types.NoneType):
4232 pass
4233 with self.assertRaises(TypeError):
4234 class X(types.NoneType, O):
4235 pass
4236
4237 class X(object):
4238 pass
4239 with self.assertRaises(TypeError):
4240 X.__bases__ = types.NoneType,
4241 with self.assertRaises(TypeError):
4242 X.__bases__ = object, types.NoneType
4243 with self.assertRaises(TypeError):
4244 X.__bases__ = types.NoneType, object
4245 with self.assertRaises(TypeError):
4246 X.__bases__ = O, types.NoneType
4247 with self.assertRaises(TypeError):
4248 X.__bases__ = types.NoneType, O
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004249
Georg Brandl48545522008-02-02 10:12:36 +00004250 def test_mutable_bases_with_failing_mro(self):
4251 # Testing mutable bases with failing mro...
4252 class WorkOnce(type):
4253 def __new__(self, name, bases, ns):
4254 self.flag = 0
4255 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4256 def mro(self):
4257 if self.flag > 0:
4258 raise RuntimeError, "bozo"
4259 else:
4260 self.flag += 1
4261 return type.mro(self)
4262
4263 class WorkAlways(type):
4264 def mro(self):
4265 # this is here to make sure that .mro()s aren't called
4266 # with an exception set (which was possible at one point).
4267 # An error message will be printed in a debug build.
4268 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004269 return type.mro(self)
4270
Georg Brandl48545522008-02-02 10:12:36 +00004271 class C(object):
4272 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004273
Georg Brandl48545522008-02-02 10:12:36 +00004274 class C2(object):
4275 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004276
Georg Brandl48545522008-02-02 10:12:36 +00004277 class D(C):
4278 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004279
Georg Brandl48545522008-02-02 10:12:36 +00004280 class E(D):
4281 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004282
Georg Brandl48545522008-02-02 10:12:36 +00004283 class F(D):
4284 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004285
Georg Brandl48545522008-02-02 10:12:36 +00004286 class G(D):
4287 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004288
Georg Brandl48545522008-02-02 10:12:36 +00004289 # Immediate subclasses have their mro's adjusted in alphabetical
4290 # order, so E's will get adjusted before adjusting F's fails. We
4291 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004292
Georg Brandl48545522008-02-02 10:12:36 +00004293 E_mro_before = E.__mro__
4294 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004295
Armin Rigofd163f92005-12-29 15:59:19 +00004296 try:
Georg Brandl48545522008-02-02 10:12:36 +00004297 D.__bases__ = (C2,)
4298 except RuntimeError:
4299 self.assertEqual(E.__mro__, E_mro_before)
4300 self.assertEqual(D.__mro__, D_mro_before)
4301 else:
4302 self.fail("exception not propagated")
4303
4304 def test_mutable_bases_catch_mro_conflict(self):
4305 # Testing mutable bases catch mro conflict...
4306 class A(object):
4307 pass
4308
4309 class B(object):
4310 pass
4311
4312 class C(A, B):
4313 pass
4314
4315 class D(A, B):
4316 pass
4317
4318 class E(C, D):
4319 pass
4320
4321 try:
4322 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004323 except TypeError:
4324 pass
4325 else:
Georg Brandl48545522008-02-02 10:12:36 +00004326 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004327
Georg Brandl48545522008-02-02 10:12:36 +00004328 def test_mutable_names(self):
4329 # Testing mutable names...
4330 class C(object):
4331 pass
4332
4333 # C.__module__ could be 'test_descr' or '__main__'
4334 mod = C.__module__
4335
4336 C.__name__ = 'D'
4337 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4338
4339 C.__name__ = 'D.E'
4340 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4341
Mark Dickinsonf794b142013-04-13 15:19:05 +01004342 def test_evil_type_name(self):
4343 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4344 # execution while the type structure was not in a sane state, and a
4345 # possible segmentation fault as a result. See bug #16447.
4346 class Nasty(str):
4347 def __del__(self):
4348 C.__name__ = "other"
4349
4350 class C(object):
4351 pass
4352
4353 C.__name__ = Nasty("abc")
4354 C.__name__ = "normal"
4355
Georg Brandl48545522008-02-02 10:12:36 +00004356 def test_subclass_right_op(self):
4357 # Testing correct dispatch of subclass overloading __r<op>__...
4358
4359 # This code tests various cases where right-dispatch of a subclass
4360 # should be preferred over left-dispatch of a base class.
4361
4362 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4363
4364 class B(int):
4365 def __floordiv__(self, other):
4366 return "B.__floordiv__"
4367 def __rfloordiv__(self, other):
4368 return "B.__rfloordiv__"
4369
4370 self.assertEqual(B(1) // 1, "B.__floordiv__")
4371 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4372
4373 # Case 2: subclass of object; this is just the baseline for case 3
4374
4375 class C(object):
4376 def __floordiv__(self, other):
4377 return "C.__floordiv__"
4378 def __rfloordiv__(self, other):
4379 return "C.__rfloordiv__"
4380
4381 self.assertEqual(C() // 1, "C.__floordiv__")
4382 self.assertEqual(1 // C(), "C.__rfloordiv__")
4383
4384 # Case 3: subclass of new-style class; here it gets interesting
4385
4386 class D(C):
4387 def __floordiv__(self, other):
4388 return "D.__floordiv__"
4389 def __rfloordiv__(self, other):
4390 return "D.__rfloordiv__"
4391
4392 self.assertEqual(D() // C(), "D.__floordiv__")
4393 self.assertEqual(C() // D(), "D.__rfloordiv__")
4394
4395 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4396
4397 class E(C):
4398 pass
4399
4400 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4401
4402 self.assertEqual(E() // 1, "C.__floordiv__")
4403 self.assertEqual(1 // E(), "C.__rfloordiv__")
4404 self.assertEqual(E() // C(), "C.__floordiv__")
4405 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4406
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004407 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004408 def test_meth_class_get(self):
4409 # Testing __get__ method of METH_CLASS C methods...
4410 # Full coverage of descrobject.c::classmethod_get()
4411
4412 # Baseline
4413 arg = [1, 2, 3]
4414 res = {1: None, 2: None, 3: None}
4415 self.assertEqual(dict.fromkeys(arg), res)
4416 self.assertEqual({}.fromkeys(arg), res)
4417
4418 # Now get the descriptor
4419 descr = dict.__dict__["fromkeys"]
4420
4421 # More baseline using the descriptor directly
4422 self.assertEqual(descr.__get__(None, dict)(arg), res)
4423 self.assertEqual(descr.__get__({})(arg), res)
4424
4425 # Now check various error cases
4426 try:
4427 descr.__get__(None, None)
4428 except TypeError:
4429 pass
4430 else:
4431 self.fail("shouldn't have allowed descr.__get__(None, None)")
4432 try:
4433 descr.__get__(42)
4434 except TypeError:
4435 pass
4436 else:
4437 self.fail("shouldn't have allowed descr.__get__(42)")
4438 try:
4439 descr.__get__(None, 42)
4440 except TypeError:
4441 pass
4442 else:
4443 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4444 try:
4445 descr.__get__(None, int)
4446 except TypeError:
4447 pass
4448 else:
4449 self.fail("shouldn't have allowed descr.__get__(None, int)")
4450
4451 def test_isinst_isclass(self):
4452 # Testing proxy isinstance() and isclass()...
4453 class Proxy(object):
4454 def __init__(self, obj):
4455 self.__obj = obj
4456 def __getattribute__(self, name):
4457 if name.startswith("_Proxy__"):
4458 return object.__getattribute__(self, name)
4459 else:
4460 return getattr(self.__obj, name)
4461 # Test with a classic class
4462 class C:
4463 pass
4464 a = C()
4465 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004466 self.assertIsInstance(a, C) # Baseline
4467 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004468 # Test with a classic subclass
4469 class D(C):
4470 pass
4471 a = D()
4472 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004473 self.assertIsInstance(a, C) # Baseline
4474 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004475 # Test with a new-style class
4476 class C(object):
4477 pass
4478 a = C()
4479 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004480 self.assertIsInstance(a, C) # Baseline
4481 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004482 # Test with a new-style subclass
4483 class D(C):
4484 pass
4485 a = D()
4486 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004487 self.assertIsInstance(a, C) # Baseline
4488 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004489
4490 def test_proxy_super(self):
4491 # Testing super() for a proxy object...
4492 class Proxy(object):
4493 def __init__(self, obj):
4494 self.__obj = obj
4495 def __getattribute__(self, name):
4496 if name.startswith("_Proxy__"):
4497 return object.__getattribute__(self, name)
4498 else:
4499 return getattr(self.__obj, name)
4500
4501 class B(object):
4502 def f(self):
4503 return "B.f"
4504
4505 class C(B):
4506 def f(self):
4507 return super(C, self).f() + "->C.f"
4508
4509 obj = C()
4510 p = Proxy(obj)
4511 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4512
4513 def test_carloverre(self):
4514 # Testing prohibition of Carlo Verre's hack...
4515 try:
4516 object.__setattr__(str, "foo", 42)
4517 except TypeError:
4518 pass
4519 else:
Ezio Melottic2077b02011-03-16 12:34:31 +02004520 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl48545522008-02-02 10:12:36 +00004521 try:
4522 object.__delattr__(str, "lower")
4523 except TypeError:
4524 pass
4525 else:
4526 self.fail("Carlo Verre __delattr__ succeeded!")
4527
4528 def test_weakref_segfault(self):
4529 # Testing weakref segfault...
4530 # SF 742911
4531 import weakref
4532
4533 class Provoker:
4534 def __init__(self, referrent):
4535 self.ref = weakref.ref(referrent)
4536
4537 def __del__(self):
4538 x = self.ref()
4539
4540 class Oops(object):
4541 pass
4542
4543 o = Oops()
4544 o.whatever = Provoker(o)
4545 del o
4546
4547 def test_wrapper_segfault(self):
4548 # SF 927248: deeply nested wrappers could cause stack overflow
4549 f = lambda:None
4550 for i in xrange(1000000):
4551 f = f.__call__
4552 f = None
4553
4554 def test_file_fault(self):
4555 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004556 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004557 class StdoutGuard:
4558 def __getattr__(self, attr):
4559 sys.stdout = sys.__stdout__
4560 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4561 sys.stdout = StdoutGuard()
4562 try:
4563 print "Oops!"
4564 except RuntimeError:
4565 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004566 finally:
4567 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004568
4569 def test_vicious_descriptor_nonsense(self):
4570 # Testing vicious_descriptor_nonsense...
4571
4572 # A potential segfault spotted by Thomas Wouters in mail to
4573 # python-dev 2003-04-17, turned into an example & fixed by Michael
4574 # Hudson just less than four months later...
4575
4576 class Evil(object):
4577 def __hash__(self):
4578 return hash('attr')
4579 def __eq__(self, other):
4580 del C.attr
4581 return 0
4582
4583 class Descr(object):
4584 def __get__(self, ob, type=None):
4585 return 1
4586
4587 class C(object):
4588 attr = Descr()
4589
4590 c = C()
4591 c.__dict__[Evil()] = 0
4592
4593 self.assertEqual(c.attr, 1)
4594 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004595 test_support.gc_collect()
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004596 self.assertNotHasAttr(c, 'attr')
Georg Brandl48545522008-02-02 10:12:36 +00004597
4598 def test_init(self):
4599 # SF 1155938
4600 class Foo(object):
4601 def __init__(self):
4602 return 10
4603 try:
4604 Foo()
4605 except TypeError:
4606 pass
4607 else:
4608 self.fail("did not test __init__() for None return")
4609
4610 def test_method_wrapper(self):
4611 # Testing method-wrapper objects...
4612 # <type 'method-wrapper'> did not support any reflection before 2.5
4613
4614 l = []
4615 self.assertEqual(l.__add__, l.__add__)
4616 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004617 self.assertNotEqual(l.__add__, [5].__add__)
4618 self.assertNotEqual(l.__add__, l.__mul__)
4619 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004620 if hasattr(l.__add__, '__self__'):
4621 # CPython
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004622 self.assertIs(l.__add__.__self__, l)
4623 self.assertIs(l.__add__.__objclass__, list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004624 else:
4625 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004626 self.assertIs(l.__add__.im_self, l)
4627 self.assertIs(l.__add__.im_class, list)
Georg Brandl48545522008-02-02 10:12:36 +00004628 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4629 try:
4630 hash(l.__add__)
4631 except TypeError:
4632 pass
4633 else:
4634 self.fail("no TypeError from hash([].__add__)")
4635
4636 t = ()
4637 t += (7,)
4638 self.assertEqual(t.__add__, (7,).__add__)
4639 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4640
4641 def test_not_implemented(self):
4642 # Testing NotImplemented...
4643 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004644 import operator
4645
4646 def specialmethod(self, other):
4647 return NotImplemented
4648
4649 def check(expr, x, y):
4650 try:
4651 exec expr in {'x': x, 'y': y, 'operator': operator}
4652 except TypeError:
4653 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004654 else:
Georg Brandl48545522008-02-02 10:12:36 +00004655 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004656
Georg Brandl48545522008-02-02 10:12:36 +00004657 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4658 # TypeErrors
4659 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4660 # ValueErrors instead of TypeErrors
4661 for metaclass in [type, types.ClassType]:
4662 for name, expr, iexpr in [
4663 ('__add__', 'x + y', 'x += y'),
4664 ('__sub__', 'x - y', 'x -= y'),
4665 ('__mul__', 'x * y', 'x *= y'),
4666 ('__truediv__', 'operator.truediv(x, y)', None),
4667 ('__floordiv__', 'operator.floordiv(x, y)', None),
4668 ('__div__', 'x / y', 'x /= y'),
4669 ('__mod__', 'x % y', 'x %= y'),
4670 ('__divmod__', 'divmod(x, y)', None),
4671 ('__pow__', 'x ** y', 'x **= y'),
4672 ('__lshift__', 'x << y', 'x <<= y'),
4673 ('__rshift__', 'x >> y', 'x >>= y'),
4674 ('__and__', 'x & y', 'x &= y'),
4675 ('__or__', 'x | y', 'x |= y'),
4676 ('__xor__', 'x ^ y', 'x ^= y'),
4677 ('__coerce__', 'coerce(x, y)', None)]:
4678 if name == '__coerce__':
4679 rname = name
4680 else:
4681 rname = '__r' + name[2:]
4682 A = metaclass('A', (), {name: specialmethod})
4683 B = metaclass('B', (), {rname: specialmethod})
4684 a = A()
4685 b = B()
4686 check(expr, a, a)
4687 check(expr, a, b)
4688 check(expr, b, a)
4689 check(expr, b, b)
4690 check(expr, a, N1)
4691 check(expr, a, N2)
4692 check(expr, N1, b)
4693 check(expr, N2, b)
4694 if iexpr:
4695 check(iexpr, a, a)
4696 check(iexpr, a, b)
4697 check(iexpr, b, a)
4698 check(iexpr, b, b)
4699 check(iexpr, a, N1)
4700 check(iexpr, a, N2)
4701 iname = '__i' + name[2:]
4702 C = metaclass('C', (), {iname: specialmethod})
4703 c = C()
4704 check(iexpr, c, a)
4705 check(iexpr, c, b)
4706 check(iexpr, c, N1)
4707 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004708
Georg Brandl48545522008-02-02 10:12:36 +00004709 def test_assign_slice(self):
4710 # ceval.c's assign_slice used to check for
4711 # tp->tp_as_sequence->sq_slice instead of
4712 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004713
Georg Brandl48545522008-02-02 10:12:36 +00004714 class C(object):
4715 def __setslice__(self, start, stop, value):
4716 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004717
Georg Brandl48545522008-02-02 10:12:36 +00004718 c = C()
4719 c[1:2] = 3
4720 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004721
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004722 def test_set_and_no_get(self):
4723 # See
4724 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4725 class Descr(object):
4726
4727 def __init__(self, name):
4728 self.name = name
4729
4730 def __set__(self, obj, value):
4731 obj.__dict__[self.name] = value
4732 descr = Descr("a")
4733
4734 class X(object):
4735 a = descr
4736
4737 x = X()
4738 self.assertIs(x.a, descr)
4739 x.a = 42
4740 self.assertEqual(x.a, 42)
4741
Benjamin Peterson42d59472010-02-06 20:14:10 +00004742 # Also check type_getattro for correctness.
4743 class Meta(type):
4744 pass
4745 class X(object):
4746 __metaclass__ = Meta
4747 X.a = 42
4748 Meta.a = Descr("a")
4749 self.assertEqual(X.a, 42)
4750
Benjamin Peterson273c2332008-11-17 22:39:09 +00004751 def test_getattr_hooks(self):
4752 # issue 4230
4753
4754 class Descriptor(object):
4755 counter = 0
4756 def __get__(self, obj, objtype=None):
4757 def getter(name):
4758 self.counter += 1
4759 raise AttributeError(name)
4760 return getter
4761
4762 descr = Descriptor()
4763 class A(object):
4764 __getattribute__ = descr
4765 class B(object):
4766 __getattr__ = descr
4767 class C(object):
4768 __getattribute__ = descr
4769 __getattr__ = descr
4770
4771 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004772 self.assertEqual(descr.counter, 1)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004773 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004774 self.assertEqual(descr.counter, 2)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004775 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004776 self.assertEqual(descr.counter, 4)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004777
Benjamin Peterson273c2332008-11-17 22:39:09 +00004778 class EvilGetattribute(object):
4779 # This used to segfault
4780 def __getattr__(self, name):
4781 raise AttributeError(name)
4782 def __getattribute__(self, name):
4783 del EvilGetattribute.__getattr__
4784 for i in range(5):
4785 gc.collect()
4786 raise AttributeError(name)
4787
4788 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4789
Benjamin Peterson6e7832b2012-03-16 09:32:59 -05004790 def test_type___getattribute__(self):
4791 self.assertRaises(TypeError, type.__getattribute__, list, type)
4792
Benjamin Peterson9b911ca2011-01-12 15:49:47 +00004793 def test_abstractmethods(self):
4794 # type pretends not to have __abstractmethods__.
4795 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4796 class meta(type):
4797 pass
4798 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4799 class X(object):
4800 pass
4801 with self.assertRaises(AttributeError):
4802 del X.__abstractmethods__
4803
Victor Stinnere363ec12011-05-01 23:43:37 +02004804 def test_proxy_call(self):
4805 class FakeStr(object):
4806 __class__ = str
4807
4808 fake_str = FakeStr()
4809 # isinstance() reads __class__ on new style classes
Serhiy Storchaka000b4c52013-11-17 23:39:24 +02004810 self.assertIsInstance(fake_str, str)
Victor Stinnere363ec12011-05-01 23:43:37 +02004811
4812 # call a method descriptor
4813 with self.assertRaises(TypeError):
4814 str.split(fake_str)
4815
4816 # call a slot wrapper descriptor
4817 with self.assertRaises(TypeError):
4818 str.__add__(fake_str, "abc")
4819
Antoine Pitrou304f0f92011-07-15 21:22:50 +02004820 def test_repr_as_str(self):
4821 # Issue #11603: crash or infinite loop when rebinding __str__ as
4822 # __repr__.
4823 class Foo(object):
4824 pass
4825 Foo.__repr__ = Foo.__str__
4826 foo = Foo()
Benjamin Petersond157a4c2012-04-24 11:06:25 -04004827 self.assertRaises(RuntimeError, str, foo)
4828 self.assertRaises(RuntimeError, repr, foo)
4829
4830 def test_mixing_slot_wrappers(self):
4831 class X(dict):
4832 __setattr__ = dict.__setitem__
4833 x = X()
4834 x.y = 42
4835 self.assertEqual(x["y"], 42)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004836
Benjamin Petersona8d45852012-03-07 18:41:11 -06004837 def test_cycle_through_dict(self):
4838 # See bug #1469629
4839 class X(dict):
4840 def __init__(self):
4841 dict.__init__(self)
4842 self.__dict__ = self
4843 x = X()
4844 x.attr = 42
4845 wr = weakref.ref(x)
4846 del x
4847 test_support.gc_collect()
4848 self.assertIsNone(wr())
4849 for o in gc.get_objects():
4850 self.assertIsNot(type(o), X)
4851
Benjamin Petersondd171ea2016-01-18 21:18:49 -08004852
Georg Brandl48545522008-02-02 10:12:36 +00004853class DictProxyTests(unittest.TestCase):
4854 def setUp(self):
4855 class C(object):
4856 def meth(self):
4857 pass
4858 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004859
Raymond Hettingerbf7a2662011-06-30 00:44:36 +01004860 def test_repr(self):
4861 self.assertIn('dict_proxy({', repr(vars(self.C)))
4862 self.assertIn("'meth':", repr(vars(self.C)))
4863
Georg Brandl48545522008-02-02 10:12:36 +00004864 def test_iter_keys(self):
4865 # Testing dict-proxy iterkeys...
4866 keys = [ key for key in self.C.__dict__.iterkeys() ]
4867 keys.sort()
Ezio Melotti2623a372010-11-21 13:34:58 +00004868 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl48545522008-02-02 10:12:36 +00004869 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004870
Georg Brandl48545522008-02-02 10:12:36 +00004871 def test_iter_values(self):
4872 # Testing dict-proxy itervalues...
4873 values = [ values for values in self.C.__dict__.itervalues() ]
4874 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004875
Georg Brandl48545522008-02-02 10:12:36 +00004876 def test_iter_items(self):
4877 # Testing dict-proxy iteritems...
4878 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4879 keys.sort()
4880 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4881 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004882
Georg Brandl48545522008-02-02 10:12:36 +00004883 def test_dict_type_with_metaclass(self):
4884 # Testing type of __dict__ when __metaclass__ set...
4885 class B(object):
4886 pass
4887 class M(type):
4888 pass
4889 class C:
4890 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4891 __metaclass__ = M
4892 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004893
Guido van Rossum9acc3872008-01-23 23:23:43 +00004894
Georg Brandl48545522008-02-02 10:12:36 +00004895class PTypesLongInitTest(unittest.TestCase):
4896 # This is in its own TestCase so that it can be run before any other tests.
4897 def test_pytype_long_ready(self):
4898 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004899
Georg Brandl48545522008-02-02 10:12:36 +00004900 # This dumps core when SF bug 551412 isn't fixed --
4901 # but only when test_descr.py is run separately.
4902 # (That can't be helped -- as soon as PyType_Ready()
4903 # is called for PyLong_Type, the bug is gone.)
4904 class UserLong(object):
4905 def __pow__(self, *args):
4906 pass
4907 try:
4908 pow(0L, UserLong(), 0L)
4909 except:
4910 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004911
Georg Brandl48545522008-02-02 10:12:36 +00004912 # Another segfault only when run early
4913 # (before PyType_Ready(tuple) is called)
4914 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004915
4916
Serhiy Storchakaee1b24c2015-11-25 18:35:33 +02004917class PicklingTests(unittest.TestCase):
4918
4919 def test_issue24097(self):
4920 # Slot name is freed inside __getattr__ and is later used.
4921 class S(str): # Not interned
4922 pass
4923 class A(object):
4924 __slotnames__ = [S('spam')]
4925 def __getattr__(self, attr):
4926 if attr == 'spam':
4927 A.__slotnames__[:] = [S('spam')]
4928 return 42
4929 else:
4930 raise AttributeError
4931
4932 import copy_reg
4933 expected = (copy_reg.__newobj__, (A,), ({}, {'spam': 42}), None, None)
4934 self.assertEqual(A().__reduce__(2), expected)
4935
4936
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004937def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004938 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4939 DeprecationWarning)]
4940 if sys.py3kwarning:
4941 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004942 ("classic (int|long) division", DeprecationWarning),
4943 ("coerce.. not supported", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004944 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4945 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004946 # Run all local test cases, with PTypesLongInitTest first.
4947 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
Serhiy Storchakaee1b24c2015-11-25 18:35:33 +02004948 ClassPropertiesAndMethods, DictProxyTests,
4949 PicklingTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004950
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004951if __name__ == "__main__":
4952 test_main()