blob: 8c75ec304f7804c9c6821e59bc83a2d99cf1784e [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01002import copyreg
Benjamin Peterson52c42432012-03-07 18:41:11 -06003import gc
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004import itertools
5import math
6import pickle
Raymond Hettinger51f46882020-12-18 16:53:50 -08007import random
8import string
Benjamin Petersona5758c02009-05-09 18:15:04 +00009import sys
Guido van Rossum360e4b82007-05-14 22:51:27 +000010import types
Georg Brandl479a7e72008-02-05 18:13:15 +000011import unittest
Serhiy Storchaka5adfac22016-12-02 08:42:43 +020012import warnings
Benjamin Peterson52c42432012-03-07 18:41:11 -060013import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +000014
Georg Brandl479a7e72008-02-05 18:13:15 +000015from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +000017
jdemeyer5a306202018-10-19 23:50:06 +020018try:
19 import _testcapi
20except ImportError:
21 _testcapi = None
22
Tim Peters6d6c1a32001-08-02 04:15:00 +000023
Georg Brandl479a7e72008-02-05 18:13:15 +000024class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000025
Georg Brandl479a7e72008-02-05 18:13:15 +000026 def __init__(self, *args, **kwargs):
27 unittest.TestCase.__init__(self, *args, **kwargs)
28 self.binops = {
29 'add': '+',
30 'sub': '-',
31 'mul': '*',
Serhiy Storchakac2ccce72015-03-12 22:01:30 +020032 'matmul': '@',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +020033 'truediv': '/',
34 'floordiv': '//',
Georg Brandl479a7e72008-02-05 18:13:15 +000035 'divmod': 'divmod',
36 'pow': '**',
37 'lshift': '<<',
38 'rshift': '>>',
39 'and': '&',
40 'xor': '^',
41 'or': '|',
42 'cmp': 'cmp',
43 'lt': '<',
44 'le': '<=',
45 'eq': '==',
46 'ne': '!=',
47 'gt': '>',
48 'ge': '>=',
49 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000050
Georg Brandl479a7e72008-02-05 18:13:15 +000051 for name, expr in list(self.binops.items()):
52 if expr.islower():
53 expr = expr + "(a, b)"
54 else:
55 expr = 'a %s b' % expr
56 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000057
Georg Brandl479a7e72008-02-05 18:13:15 +000058 self.unops = {
59 'pos': '+',
60 'neg': '-',
61 'abs': 'abs',
62 'invert': '~',
63 'int': 'int',
64 'float': 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +000065 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl479a7e72008-02-05 18:13:15 +000067 for name, expr in list(self.unops.items()):
68 if expr.islower():
69 expr = expr + "(a)"
70 else:
71 expr = '%s a' % expr
72 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000073
Georg Brandl479a7e72008-02-05 18:13:15 +000074 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
75 d = {'a': a}
76 self.assertEqual(eval(expr, d), res)
77 t = type(a)
78 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000079
Georg Brandl479a7e72008-02-05 18:13:15 +000080 # Find method in parent class
81 while meth not in t.__dict__:
82 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000083 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
84 # method object; the getattr() below obtains its underlying function.
85 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000086 self.assertEqual(m(a), res)
87 bm = getattr(a, meth)
88 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000089
Georg Brandl479a7e72008-02-05 18:13:15 +000090 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
91 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000092
Georg Brandl479a7e72008-02-05 18:13:15 +000093 self.assertEqual(eval(expr, d), res)
94 t = type(a)
95 m = getattr(t, meth)
96 while meth not in t.__dict__:
97 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000098 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
99 # method object; the getattr() below obtains its underlying function.
100 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000101 self.assertEqual(m(a, b), res)
102 bm = getattr(a, meth)
103 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000104
Georg Brandl479a7e72008-02-05 18:13:15 +0000105 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
106 d = {'a': a, 'b': b, 'c': c}
107 self.assertEqual(eval(expr, d), res)
108 t = type(a)
109 m = getattr(t, meth)
110 while meth not in t.__dict__:
111 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000112 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
113 # method object; the getattr() below obtains its underlying function.
114 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000115 self.assertEqual(m(a, slice(b, c)), res)
116 bm = getattr(a, meth)
117 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000118
Georg Brandl479a7e72008-02-05 18:13:15 +0000119 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
120 d = {'a': deepcopy(a), 'b': b}
121 exec(stmt, d)
122 self.assertEqual(d['a'], res)
123 t = type(a)
124 m = getattr(t, meth)
125 while meth not in t.__dict__:
126 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000127 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
128 # method object; the getattr() below obtains its underlying function.
129 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000130 d['a'] = deepcopy(a)
131 m(d['a'], b)
132 self.assertEqual(d['a'], res)
133 d['a'] = deepcopy(a)
134 bm = getattr(d['a'], meth)
135 bm(b)
136 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000137
Georg Brandl479a7e72008-02-05 18:13:15 +0000138 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
139 d = {'a': deepcopy(a), 'b': b, 'c': c}
140 exec(stmt, d)
141 self.assertEqual(d['a'], res)
142 t = type(a)
143 m = getattr(t, meth)
144 while meth not in t.__dict__:
145 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000146 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
147 # method object; the getattr() below obtains its underlying function.
148 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000149 d['a'] = deepcopy(a)
150 m(d['a'], b, c)
151 self.assertEqual(d['a'], res)
152 d['a'] = deepcopy(a)
153 bm = getattr(d['a'], meth)
154 bm(b, c)
155 self.assertEqual(d['a'], res)
156
157 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
158 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
159 exec(stmt, dictionary)
160 self.assertEqual(dictionary['a'], res)
161 t = type(a)
162 while meth not in t.__dict__:
163 t = t.__bases__[0]
164 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000165 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
166 # method object; the getattr() below obtains its underlying function.
167 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000168 dictionary['a'] = deepcopy(a)
169 m(dictionary['a'], slice(b, c), d)
170 self.assertEqual(dictionary['a'], res)
171 dictionary['a'] = deepcopy(a)
172 bm = getattr(dictionary['a'], meth)
173 bm(slice(b, c), d)
174 self.assertEqual(dictionary['a'], res)
175
176 def test_lists(self):
177 # Testing list operations...
178 # Asserts are within individual test methods
179 self.binop_test([1], [2], [1,2], "a+b", "__add__")
180 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
181 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
182 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
183 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
184 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
185 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
186 self.unop_test([1,2,3], 3, "len(a)", "__len__")
187 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
188 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
189 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
190 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
191 "__setitem__")
192
193 def test_dicts(self):
194 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000195 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
196 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
197 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
198
199 d = {1:2, 3:4}
200 l1 = []
201 for i in list(d.keys()):
202 l1.append(i)
203 l = []
204 for i in iter(d):
205 l.append(i)
206 self.assertEqual(l, l1)
207 l = []
208 for i in d.__iter__():
209 l.append(i)
210 self.assertEqual(l, l1)
211 l = []
212 for i in dict.__iter__(d):
213 l.append(i)
214 self.assertEqual(l, l1)
215 d = {1:2, 3:4}
216 self.unop_test(d, 2, "len(a)", "__len__")
217 self.assertEqual(eval(repr(d), {}), d)
218 self.assertEqual(eval(d.__repr__(), {}), d)
219 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
220 "__setitem__")
221
222 # Tests for unary and binary operators
223 def number_operators(self, a, b, skip=[]):
224 dict = {'a': a, 'b': b}
225
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200226 for name, expr in self.binops.items():
Georg Brandl479a7e72008-02-05 18:13:15 +0000227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.binop_test(a, b, res, expr, name)
232
233 for name, expr in list(self.unops.items()):
234 if name not in skip:
235 name = "__%s__" % name
236 if hasattr(a, name):
237 res = eval(expr, dict)
238 self.unop_test(a, res, expr, name)
239
240 def test_ints(self):
241 # Testing int operations...
242 self.number_operators(100, 3)
243 # The following crashes in Python 2.2
244 self.assertEqual((1).__bool__(), 1)
245 self.assertEqual((0).__bool__(), 0)
246 # This returns 'NotImplemented' in Python 2.2
247 class C(int):
248 def __add__(self, other):
249 return NotImplemented
250 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000251 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000252 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000253 except TypeError:
254 pass
255 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000256 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000257
Georg Brandl479a7e72008-02-05 18:13:15 +0000258 def test_floats(self):
259 # Testing float operations...
260 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000261
Georg Brandl479a7e72008-02-05 18:13:15 +0000262 def test_complexes(self):
263 # Testing complex operations...
264 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000265 'int', 'float',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200266 'floordiv', 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000267
Georg Brandl479a7e72008-02-05 18:13:15 +0000268 class Number(complex):
269 __slots__ = ['prec']
270 def __new__(cls, *args, **kwds):
271 result = complex.__new__(cls, *args)
272 result.prec = kwds.get('prec', 12)
273 return result
274 def __repr__(self):
275 prec = self.prec
276 if self.imag == 0.0:
277 return "%.*g" % (prec, self.real)
278 if self.real == 0.0:
279 return "%.*gj" % (prec, self.imag)
280 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
281 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000282
Georg Brandl479a7e72008-02-05 18:13:15 +0000283 a = Number(3.14, prec=6)
284 self.assertEqual(repr(a), "3.14")
285 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000286
Georg Brandl479a7e72008-02-05 18:13:15 +0000287 a = Number(a, prec=2)
288 self.assertEqual(repr(a), "3.1")
289 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000290
Georg Brandl479a7e72008-02-05 18:13:15 +0000291 a = Number(234.5)
292 self.assertEqual(repr(a), "234.5")
293 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000294
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000295 def test_explicit_reverse_methods(self):
296 # see issue 9930
297 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
298 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
299
Benjamin Petersone549ead2009-03-28 21:42:05 +0000300 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000301 def test_spam_lists(self):
302 # Testing spamlist operations...
303 import copy, xxsubtype as spam
304
305 def spamlist(l, memo=None):
306 import xxsubtype as spam
307 return spam.spamlist(l)
308
309 # This is an ugly hack:
310 copy._deepcopy_dispatch[spam.spamlist] = spamlist
311
312 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
313 "__add__")
314 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
315 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
316 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
317 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
318 "__getitem__")
319 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
320 "__iadd__")
321 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
322 "__imul__")
323 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
324 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
325 "__mul__")
326 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
327 "__rmul__")
328 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
329 "__setitem__")
330 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
331 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
332 # Test subclassing
333 class C(spam.spamlist):
334 def foo(self): return 1
335 a = C()
336 self.assertEqual(a, [])
337 self.assertEqual(a.foo(), 1)
338 a.append(100)
339 self.assertEqual(a, [100])
340 self.assertEqual(a.getstate(), 0)
341 a.setstate(42)
342 self.assertEqual(a.getstate(), 42)
343
Benjamin Petersone549ead2009-03-28 21:42:05 +0000344 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000345 def test_spam_dicts(self):
346 # Testing spamdict operations...
347 import copy, xxsubtype as spam
348 def spamdict(d, memo=None):
349 import xxsubtype as spam
350 sd = spam.spamdict()
351 for k, v in list(d.items()):
352 sd[k] = v
353 return sd
354 # This is an ugly hack:
355 copy._deepcopy_dispatch[spam.spamdict] = spamdict
356
Georg Brandl479a7e72008-02-05 18:13:15 +0000357 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
358 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
359 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
360 d = spamdict({1:2,3:4})
361 l1 = []
362 for i in list(d.keys()):
363 l1.append(i)
364 l = []
365 for i in iter(d):
366 l.append(i)
367 self.assertEqual(l, l1)
368 l = []
369 for i in d.__iter__():
370 l.append(i)
371 self.assertEqual(l, l1)
372 l = []
373 for i in type(spamdict({})).__iter__(d):
374 l.append(i)
375 self.assertEqual(l, l1)
376 straightd = {1:2, 3:4}
377 spamd = spamdict(straightd)
378 self.unop_test(spamd, 2, "len(a)", "__len__")
379 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
380 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
381 "a[b]=c", "__setitem__")
382 # Test subclassing
383 class C(spam.spamdict):
384 def foo(self): return 1
385 a = C()
386 self.assertEqual(list(a.items()), [])
387 self.assertEqual(a.foo(), 1)
388 a['foo'] = 'bar'
389 self.assertEqual(list(a.items()), [('foo', 'bar')])
390 self.assertEqual(a.getstate(), 0)
391 a.setstate(100)
392 self.assertEqual(a.getstate(), 100)
393
Zackery Spytz05f16412019-05-28 06:55:29 -0600394 def test_wrap_lenfunc_bad_cast(self):
395 self.assertEqual(range(sys.maxsize).__len__(), sys.maxsize)
396
397
Georg Brandl479a7e72008-02-05 18:13:15 +0000398class ClassPropertiesAndMethods(unittest.TestCase):
399
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200400 def assertHasAttr(self, obj, name):
401 self.assertTrue(hasattr(obj, name),
402 '%r has no attribute %r' % (obj, name))
403
404 def assertNotHasAttr(self, obj, name):
405 self.assertFalse(hasattr(obj, name),
406 '%r has unexpected attribute %r' % (obj, name))
407
Georg Brandl479a7e72008-02-05 18:13:15 +0000408 def test_python_dicts(self):
409 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000410 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000411 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000412 d = dict()
413 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200414 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000415 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000416 class C(dict):
417 state = -1
418 def __init__(self_local, *a, **kw):
419 if a:
420 self.assertEqual(len(a), 1)
421 self_local.state = a[0]
422 if kw:
423 for k, v in list(kw.items()):
424 self_local[v] = k
425 def __getitem__(self, key):
426 return self.get(key, 0)
427 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000428 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000429 dict.__setitem__(self_local, key, value)
430 def setstate(self, state):
431 self.state = state
432 def getstate(self):
433 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000434 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000435 a1 = C(12)
436 self.assertEqual(a1.state, 12)
437 a2 = C(foo=1, bar=2)
438 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
439 a = C()
440 self.assertEqual(a.state, -1)
441 self.assertEqual(a.getstate(), -1)
442 a.setstate(0)
443 self.assertEqual(a.state, 0)
444 self.assertEqual(a.getstate(), 0)
445 a.setstate(10)
446 self.assertEqual(a.state, 10)
447 self.assertEqual(a.getstate(), 10)
448 self.assertEqual(a[42], 0)
449 a[42] = 24
450 self.assertEqual(a[42], 24)
451 N = 50
452 for i in range(N):
453 a[i] = C()
454 for j in range(N):
455 a[i][j] = i*j
456 for i in range(N):
457 for j in range(N):
458 self.assertEqual(a[i][j], i*j)
459
460 def test_python_lists(self):
461 # Testing Python subclass of list...
462 class C(list):
463 def __getitem__(self, i):
464 if isinstance(i, slice):
465 return i.start, i.stop
466 return list.__getitem__(self, i) + 100
467 a = C()
468 a.extend([0,1,2])
469 self.assertEqual(a[0], 100)
470 self.assertEqual(a[1], 101)
471 self.assertEqual(a[2], 102)
472 self.assertEqual(a[100:200], (100,200))
473
474 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000475 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000476 class C(metaclass=type):
477 def __init__(self):
478 self.__state = 0
479 def getstate(self):
480 return self.__state
481 def setstate(self, state):
482 self.__state = state
483 a = C()
484 self.assertEqual(a.getstate(), 0)
485 a.setstate(10)
486 self.assertEqual(a.getstate(), 10)
487 class _metaclass(type):
488 def myself(cls): return cls
489 class D(metaclass=_metaclass):
490 pass
491 self.assertEqual(D.myself(), D)
492 d = D()
493 self.assertEqual(d.__class__, D)
494 class M1(type):
495 def __new__(cls, name, bases, dict):
496 dict['__spam__'] = 1
497 return type.__new__(cls, name, bases, dict)
498 class C(metaclass=M1):
499 pass
500 self.assertEqual(C.__spam__, 1)
501 c = C()
502 self.assertEqual(c.__spam__, 1)
503
504 class _instance(object):
505 pass
506 class M2(object):
507 @staticmethod
508 def __new__(cls, name, bases, dict):
509 self = object.__new__(cls)
510 self.name = name
511 self.bases = bases
512 self.dict = dict
513 return self
514 def __call__(self):
515 it = _instance()
516 # Early binding of methods
517 for key in self.dict:
518 if key.startswith("__"):
519 continue
520 setattr(it, key, self.dict[key].__get__(it, self))
521 return it
522 class C(metaclass=M2):
523 def spam(self):
524 return 42
525 self.assertEqual(C.name, 'C')
526 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000527 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000528 c = C()
529 self.assertEqual(c.spam(), 42)
530
531 # More metaclass examples
532
533 class autosuper(type):
534 # Automatically add __super to the class
535 # This trick only works for dynamic classes
536 def __new__(metaclass, name, bases, dict):
537 cls = super(autosuper, metaclass).__new__(metaclass,
538 name, bases, dict)
539 # Name mangling for __super removes leading underscores
540 while name[:1] == "_":
541 name = name[1:]
542 if name:
543 name = "_%s__super" % name
544 else:
545 name = "__super"
546 setattr(cls, name, super(cls))
547 return cls
548 class A(metaclass=autosuper):
549 def meth(self):
550 return "A"
551 class B(A):
552 def meth(self):
553 return "B" + self.__super.meth()
554 class C(A):
555 def meth(self):
556 return "C" + self.__super.meth()
557 class D(C, B):
558 def meth(self):
559 return "D" + self.__super.meth()
560 self.assertEqual(D().meth(), "DCBA")
561 class E(B, C):
562 def meth(self):
563 return "E" + self.__super.meth()
564 self.assertEqual(E().meth(), "EBCA")
565
566 class autoproperty(type):
567 # Automatically create property attributes when methods
568 # named _get_x and/or _set_x are found
569 def __new__(metaclass, name, bases, dict):
570 hits = {}
571 for key, val in dict.items():
572 if key.startswith("_get_"):
573 key = key[5:]
574 get, set = hits.get(key, (None, None))
575 get = val
576 hits[key] = get, set
577 elif key.startswith("_set_"):
578 key = key[5:]
579 get, set = hits.get(key, (None, None))
580 set = val
581 hits[key] = get, set
582 for key, (get, set) in hits.items():
583 dict[key] = property(get, set)
584 return super(autoproperty, metaclass).__new__(metaclass,
585 name, bases, dict)
586 class A(metaclass=autoproperty):
587 def _get_x(self):
588 return -self.__x
589 def _set_x(self, x):
590 self.__x = -x
591 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200592 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000593 a.x = 12
594 self.assertEqual(a.x, 12)
595 self.assertEqual(a._A__x, -12)
596
597 class multimetaclass(autoproperty, autosuper):
598 # Merge of multiple cooperating metaclasses
599 pass
600 class A(metaclass=multimetaclass):
601 def _get_x(self):
602 return "A"
603 class B(A):
604 def _get_x(self):
605 return "B" + self.__super._get_x()
606 class C(A):
607 def _get_x(self):
608 return "C" + self.__super._get_x()
609 class D(C, B):
610 def _get_x(self):
611 return "D" + self.__super._get_x()
612 self.assertEqual(D().x, "DCBA")
613
614 # Make sure type(x) doesn't call x.__class__.__init__
615 class T(type):
616 counter = 0
617 def __init__(self, *args):
618 T.counter += 1
619 class C(metaclass=T):
620 pass
621 self.assertEqual(T.counter, 1)
622 a = C()
623 self.assertEqual(type(a), C)
624 self.assertEqual(T.counter, 1)
625
626 class C(object): pass
627 c = C()
628 try: c()
629 except TypeError: pass
630 else: self.fail("calling object w/o call method should raise "
631 "TypeError")
632
633 # Testing code to find most derived baseclass
634 class A(type):
635 def __new__(*args, **kwargs):
636 return type.__new__(*args, **kwargs)
637
638 class B(object):
639 pass
640
641 class C(object, metaclass=A):
642 pass
643
644 # The most derived metaclass of D is A rather than type.
645 class D(B, C):
646 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000647 self.assertIs(A, type(D))
648
649 # issue1294232: correct metaclass calculation
650 new_calls = [] # to check the order of __new__ calls
651 class AMeta(type):
652 @staticmethod
653 def __new__(mcls, name, bases, ns):
654 new_calls.append('AMeta')
655 return super().__new__(mcls, name, bases, ns)
656 @classmethod
657 def __prepare__(mcls, name, bases):
658 return {}
659
660 class BMeta(AMeta):
661 @staticmethod
662 def __new__(mcls, name, bases, ns):
663 new_calls.append('BMeta')
664 return super().__new__(mcls, name, bases, ns)
665 @classmethod
666 def __prepare__(mcls, name, bases):
667 ns = super().__prepare__(name, bases)
668 ns['BMeta_was_here'] = True
669 return ns
670
671 class A(metaclass=AMeta):
672 pass
673 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000674 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000675
676 class B(metaclass=BMeta):
677 pass
678 # BMeta.__new__ calls AMeta.__new__ with super:
679 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000680 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000681
682 class C(A, B):
683 pass
684 # The most derived metaclass is BMeta:
685 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000686 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000687 # BMeta.__prepare__ should've been called:
688 self.assertIn('BMeta_was_here', C.__dict__)
689
690 # The order of the bases shouldn't matter:
691 class C2(B, A):
692 pass
693 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000694 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000695 self.assertIn('BMeta_was_here', C2.__dict__)
696
697 # Check correct metaclass calculation when a metaclass is declared:
698 class D(C, metaclass=type):
699 pass
700 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000701 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000702 self.assertIn('BMeta_was_here', D.__dict__)
703
704 class E(C, metaclass=AMeta):
705 pass
706 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000707 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000708 self.assertIn('BMeta_was_here', E.__dict__)
709
710 # Special case: the given metaclass isn't a class,
711 # so there is no metaclass calculation.
712 marker = object()
713 def func(*args, **kwargs):
714 return marker
715 class X(metaclass=func):
716 pass
717 class Y(object, metaclass=func):
718 pass
719 class Z(D, metaclass=func):
720 pass
721 self.assertIs(marker, X)
722 self.assertIs(marker, Y)
723 self.assertIs(marker, Z)
724
725 # The given metaclass is a class,
726 # but not a descendant of type.
727 prepare_calls = [] # to track __prepare__ calls
728 class ANotMeta:
729 def __new__(mcls, *args, **kwargs):
730 new_calls.append('ANotMeta')
731 return super().__new__(mcls)
732 @classmethod
733 def __prepare__(mcls, name, bases):
734 prepare_calls.append('ANotMeta')
735 return {}
736 class BNotMeta(ANotMeta):
737 def __new__(mcls, *args, **kwargs):
738 new_calls.append('BNotMeta')
739 return super().__new__(mcls)
740 @classmethod
741 def __prepare__(mcls, name, bases):
742 prepare_calls.append('BNotMeta')
743 return super().__prepare__(name, bases)
744
745 class A(metaclass=ANotMeta):
746 pass
747 self.assertIs(ANotMeta, type(A))
748 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000749 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000750 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000751 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000752
753 class B(metaclass=BNotMeta):
754 pass
755 self.assertIs(BNotMeta, type(B))
756 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000757 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000758 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000759 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000760
761 class C(A, B):
762 pass
763 self.assertIs(BNotMeta, type(C))
764 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000765 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000766 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000767 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000768
769 class C2(B, A):
770 pass
771 self.assertIs(BNotMeta, type(C2))
772 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000773 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000774 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000775 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000776
777 # This is a TypeError, because of a metaclass conflict:
778 # BNotMeta is neither a subclass, nor a superclass of type
779 with self.assertRaises(TypeError):
780 class D(C, metaclass=type):
781 pass
782
783 class E(C, metaclass=ANotMeta):
784 pass
785 self.assertIs(BNotMeta, type(E))
786 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000787 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000788 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000789 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000790
791 class F(object(), C):
792 pass
793 self.assertIs(BNotMeta, type(F))
794 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000795 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000796 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000797 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000798
799 class F2(C, object()):
800 pass
801 self.assertIs(BNotMeta, type(F2))
802 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000803 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000804 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000805 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000806
807 # TypeError: BNotMeta is neither a
808 # subclass, nor a superclass of int
809 with self.assertRaises(TypeError):
810 class X(C, int()):
811 pass
812 with self.assertRaises(TypeError):
813 class X(int(), C):
814 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000815
816 def test_module_subclasses(self):
817 # Testing Python subclass of module...
818 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000819 MT = type(sys)
820 class MM(MT):
821 def __init__(self, name):
822 MT.__init__(self, name)
823 def __getattribute__(self, name):
824 log.append(("getattr", name))
825 return MT.__getattribute__(self, name)
826 def __setattr__(self, name, value):
827 log.append(("setattr", name, value))
828 MT.__setattr__(self, name, value)
829 def __delattr__(self, name):
830 log.append(("delattr", name))
831 MT.__delattr__(self, name)
832 a = MM("a")
833 a.foo = 12
834 x = a.foo
835 del a.foo
836 self.assertEqual(log, [("setattr", "foo", 12),
837 ("getattr", "foo"),
838 ("delattr", "foo")])
839
840 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000841 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000842 class Module(types.ModuleType, str):
843 pass
844 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000845 pass
846 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000847 self.fail("inheriting from ModuleType and str at the same time "
848 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000849
Raymond Hettinger51f46882020-12-18 16:53:50 -0800850 # Issue 34805: Verify that definition order is retained
851 def random_name():
852 return ''.join(random.choices(string.ascii_letters, k=10))
853 class A:
854 pass
855 subclasses = [type(random_name(), (A,), {}) for i in range(100)]
856 self.assertEqual(A.__subclasses__(), subclasses)
857
Georg Brandl479a7e72008-02-05 18:13:15 +0000858 def test_multiple_inheritance(self):
859 # Testing multiple inheritance...
860 class C(object):
861 def __init__(self):
862 self.__state = 0
863 def getstate(self):
864 return self.__state
865 def setstate(self, state):
866 self.__state = state
867 a = C()
868 self.assertEqual(a.getstate(), 0)
869 a.setstate(10)
870 self.assertEqual(a.getstate(), 10)
871 class D(dict, C):
872 def __init__(self):
873 type({}).__init__(self)
874 C.__init__(self)
875 d = D()
876 self.assertEqual(list(d.keys()), [])
877 d["hello"] = "world"
878 self.assertEqual(list(d.items()), [("hello", "world")])
879 self.assertEqual(d["hello"], "world")
880 self.assertEqual(d.getstate(), 0)
881 d.setstate(10)
882 self.assertEqual(d.getstate(), 10)
883 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000884
Georg Brandl479a7e72008-02-05 18:13:15 +0000885 # SF bug #442833
886 class Node(object):
887 def __int__(self):
888 return int(self.foo())
889 def foo(self):
890 return "23"
891 class Frag(Node, list):
892 def foo(self):
893 return "42"
894 self.assertEqual(Node().__int__(), 23)
895 self.assertEqual(int(Node()), 23)
896 self.assertEqual(Frag().__int__(), 42)
897 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000898
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700899 def test_diamond_inheritance(self):
Georg Brandl479a7e72008-02-05 18:13:15 +0000900 # Testing multiple inheritance special cases...
901 class A(object):
902 def spam(self): return "A"
903 self.assertEqual(A().spam(), "A")
904 class B(A):
905 def boo(self): return "B"
906 def spam(self): return "B"
907 self.assertEqual(B().spam(), "B")
908 self.assertEqual(B().boo(), "B")
909 class C(A):
910 def boo(self): return "C"
911 self.assertEqual(C().spam(), "A")
912 self.assertEqual(C().boo(), "C")
913 class D(B, C): pass
914 self.assertEqual(D().spam(), "B")
915 self.assertEqual(D().boo(), "B")
916 self.assertEqual(D.__mro__, (D, B, C, A, object))
917 class E(C, B): pass
918 self.assertEqual(E().spam(), "B")
919 self.assertEqual(E().boo(), "C")
920 self.assertEqual(E.__mro__, (E, C, B, A, object))
921 # MRO order disagreement
922 try:
923 class F(D, E): pass
924 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000925 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000926 else:
927 self.fail("expected MRO order disagreement (F)")
928 try:
929 class G(E, D): pass
930 except TypeError:
931 pass
932 else:
933 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000934
Georg Brandl479a7e72008-02-05 18:13:15 +0000935 # see thread python-dev/2002-October/029035.html
936 def test_ex5_from_c3_switch(self):
937 # Testing ex5 from C3 switch discussion...
938 class A(object): pass
939 class B(object): pass
940 class C(object): pass
941 class X(A): pass
942 class Y(A): pass
943 class Z(X,B,Y,C): pass
944 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000945
Georg Brandl479a7e72008-02-05 18:13:15 +0000946 # see "A Monotonic Superclass Linearization for Dylan",
947 # by Kim Barrett et al. (OOPSLA 1996)
948 def test_monotonicity(self):
949 # Testing MRO monotonicity...
950 class Boat(object): pass
951 class DayBoat(Boat): pass
952 class WheelBoat(Boat): pass
953 class EngineLess(DayBoat): pass
954 class SmallMultihull(DayBoat): pass
955 class PedalWheelBoat(EngineLess,WheelBoat): pass
956 class SmallCatamaran(SmallMultihull): pass
957 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000958
Georg Brandl479a7e72008-02-05 18:13:15 +0000959 self.assertEqual(PedalWheelBoat.__mro__,
960 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
961 self.assertEqual(SmallCatamaran.__mro__,
962 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
963 self.assertEqual(Pedalo.__mro__,
964 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
965 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000966
Georg Brandl479a7e72008-02-05 18:13:15 +0000967 # see "A Monotonic Superclass Linearization for Dylan",
968 # by Kim Barrett et al. (OOPSLA 1996)
969 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200970 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000971 class Pane(object): pass
972 class ScrollingMixin(object): pass
973 class EditingMixin(object): pass
974 class ScrollablePane(Pane,ScrollingMixin): pass
975 class EditablePane(Pane,EditingMixin): pass
976 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000977
Georg Brandl479a7e72008-02-05 18:13:15 +0000978 self.assertEqual(EditableScrollablePane.__mro__,
979 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
980 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000981
Georg Brandl479a7e72008-02-05 18:13:15 +0000982 def test_mro_disagreement(self):
983 # Testing error messages for MRO disagreement...
984 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000985order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000986
Georg Brandl479a7e72008-02-05 18:13:15 +0000987 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000988 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 callable(*args)
990 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000991 # the exact msg is generally considered an impl detail
992 if support.check_impl_detail():
993 if not str(msg).startswith(expected):
994 self.fail("Message %r, expected %r" %
995 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000996 else:
997 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000998
Georg Brandl479a7e72008-02-05 18:13:15 +0000999 class A(object): pass
1000 class B(A): pass
1001 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +00001002
Georg Brandl479a7e72008-02-05 18:13:15 +00001003 # Test some very simple errors
1004 raises(TypeError, "duplicate base class A",
1005 type, "X", (A, A), {})
1006 raises(TypeError, mro_err_msg,
1007 type, "X", (A, B), {})
1008 raises(TypeError, mro_err_msg,
1009 type, "X", (A, C, B), {})
1010 # Test a slightly more complex error
1011 class GridLayout(object): pass
1012 class HorizontalGrid(GridLayout): pass
1013 class VerticalGrid(GridLayout): pass
1014 class HVGrid(HorizontalGrid, VerticalGrid): pass
1015 class VHGrid(VerticalGrid, HorizontalGrid): pass
1016 raises(TypeError, mro_err_msg,
1017 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +00001018
Georg Brandl479a7e72008-02-05 18:13:15 +00001019 def test_object_class(self):
1020 # Testing object class...
1021 a = object()
1022 self.assertEqual(a.__class__, object)
1023 self.assertEqual(type(a), object)
1024 b = object()
1025 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001026 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001027 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001028 a.foo = 12
1029 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001030 pass
1031 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001032 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001033 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001034
Georg Brandl479a7e72008-02-05 18:13:15 +00001035 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001036 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001037 x = Cdict()
1038 self.assertEqual(x.__dict__, {})
1039 x.foo = 1
1040 self.assertEqual(x.foo, 1)
1041 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001043 def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1044 class SubType(types.ModuleType):
1045 a = 1
1046
1047 m = types.ModuleType("m")
1048 self.assertTrue(m.__class__ is types.ModuleType)
1049 self.assertFalse(hasattr(m, "a"))
1050
1051 m.__class__ = SubType
1052 self.assertTrue(m.__class__ is SubType)
1053 self.assertTrue(hasattr(m, "a"))
1054
1055 m.__class__ = types.ModuleType
1056 self.assertTrue(m.__class__ is types.ModuleType)
1057 self.assertFalse(hasattr(m, "a"))
1058
Guido van Rossum7d293ee2015-09-04 20:54:07 -07001059 # Make sure that builtin immutable objects don't support __class__
1060 # assignment, because the object instances may be interned.
1061 # We set __slots__ = () to ensure that the subclasses are
1062 # memory-layout compatible, and thus otherwise reasonable candidates
1063 # for __class__ assignment.
1064
1065 # The following types have immutable instances, but are not
1066 # subclassable and thus don't need to be checked:
1067 # NoneType, bool
1068
1069 class MyInt(int):
1070 __slots__ = ()
1071 with self.assertRaises(TypeError):
1072 (1).__class__ = MyInt
1073
1074 class MyFloat(float):
1075 __slots__ = ()
1076 with self.assertRaises(TypeError):
1077 (1.0).__class__ = MyFloat
1078
1079 class MyComplex(complex):
1080 __slots__ = ()
1081 with self.assertRaises(TypeError):
1082 (1 + 2j).__class__ = MyComplex
1083
1084 class MyStr(str):
1085 __slots__ = ()
1086 with self.assertRaises(TypeError):
1087 "a".__class__ = MyStr
1088
1089 class MyBytes(bytes):
1090 __slots__ = ()
1091 with self.assertRaises(TypeError):
1092 b"a".__class__ = MyBytes
1093
1094 class MyTuple(tuple):
1095 __slots__ = ()
1096 with self.assertRaises(TypeError):
1097 ().__class__ = MyTuple
1098
1099 class MyFrozenSet(frozenset):
1100 __slots__ = ()
1101 with self.assertRaises(TypeError):
1102 frozenset().__class__ = MyFrozenSet
1103
Georg Brandl479a7e72008-02-05 18:13:15 +00001104 def test_slots(self):
1105 # Testing __slots__...
1106 class C0(object):
1107 __slots__ = []
1108 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001109 self.assertNotHasAttr(x, "__dict__")
1110 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001111
1112 class C1(object):
1113 __slots__ = ['a']
1114 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001115 self.assertNotHasAttr(x, "__dict__")
1116 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001117 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001118 self.assertEqual(x.a, 1)
1119 x.a = None
1120 self.assertEqual(x.a, None)
1121 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001122 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001123
Georg Brandl479a7e72008-02-05 18:13:15 +00001124 class C3(object):
1125 __slots__ = ['a', 'b', 'c']
1126 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001127 self.assertNotHasAttr(x, "__dict__")
1128 self.assertNotHasAttr(x, 'a')
1129 self.assertNotHasAttr(x, 'b')
1130 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001131 x.a = 1
1132 x.b = 2
1133 x.c = 3
1134 self.assertEqual(x.a, 1)
1135 self.assertEqual(x.b, 2)
1136 self.assertEqual(x.c, 3)
1137
1138 class C4(object):
1139 """Validate name mangling"""
1140 __slots__ = ['__a']
1141 def __init__(self, value):
1142 self.__a = value
1143 def get(self):
1144 return self.__a
1145 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001146 self.assertNotHasAttr(x, '__dict__')
1147 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001148 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001149 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001150 x.__a = 6
1151 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001152 pass
1153 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001154 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001155
Georg Brandl479a7e72008-02-05 18:13:15 +00001156 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001157 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001158 class C(object):
1159 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001160 except TypeError:
1161 pass
1162 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001163 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001164 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001165 class C(object):
1166 __slots__ = ["foo bar"]
1167 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001168 pass
1169 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001170 self.fail("['foo bar'] slots not caught")
1171 try:
1172 class C(object):
1173 __slots__ = ["foo\0bar"]
1174 except TypeError:
1175 pass
1176 else:
1177 self.fail("['foo\\0bar'] slots not caught")
1178 try:
1179 class C(object):
1180 __slots__ = ["1"]
1181 except TypeError:
1182 pass
1183 else:
1184 self.fail("['1'] slots not caught")
1185 try:
1186 class C(object):
1187 __slots__ = [""]
1188 except TypeError:
1189 pass
1190 else:
1191 self.fail("[''] slots not caught")
1192 class C(object):
1193 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1194 # XXX(nnorwitz): was there supposed to be something tested
1195 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001196
Georg Brandl479a7e72008-02-05 18:13:15 +00001197 # Test a single string is not expanded as a sequence.
1198 class C(object):
1199 __slots__ = "abc"
1200 c = C()
1201 c.abc = 5
1202 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001203
Georg Brandl479a7e72008-02-05 18:13:15 +00001204 # Test unicode slot names
1205 # Test a single unicode string is not expanded as a sequence.
1206 class C(object):
1207 __slots__ = "abc"
1208 c = C()
1209 c.abc = 5
1210 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001211
Georg Brandl479a7e72008-02-05 18:13:15 +00001212 # _unicode_to_string used to modify slots in certain circumstances
1213 slots = ("foo", "bar")
1214 class C(object):
1215 __slots__ = slots
1216 x = C()
1217 x.foo = 5
1218 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001219 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001220 # this used to leak references
1221 try:
1222 class C(object):
1223 __slots__ = [chr(128)]
1224 except (TypeError, UnicodeEncodeError):
1225 pass
1226 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001227 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001228
Georg Brandl479a7e72008-02-05 18:13:15 +00001229 # Test leaks
1230 class Counted(object):
1231 counter = 0 # counts the number of instances alive
1232 def __init__(self):
1233 Counted.counter += 1
1234 def __del__(self):
1235 Counted.counter -= 1
1236 class C(object):
1237 __slots__ = ['a', 'b', 'c']
1238 x = C()
1239 x.a = Counted()
1240 x.b = Counted()
1241 x.c = Counted()
1242 self.assertEqual(Counted.counter, 3)
1243 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001244 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001245 self.assertEqual(Counted.counter, 0)
1246 class D(C):
1247 pass
1248 x = D()
1249 x.a = Counted()
1250 x.z = Counted()
1251 self.assertEqual(Counted.counter, 2)
1252 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001253 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001254 self.assertEqual(Counted.counter, 0)
1255 class E(D):
1256 __slots__ = ['e']
1257 x = E()
1258 x.a = Counted()
1259 x.z = Counted()
1260 x.e = Counted()
1261 self.assertEqual(Counted.counter, 3)
1262 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001263 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001264 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001265
Georg Brandl479a7e72008-02-05 18:13:15 +00001266 # Test cyclical leaks [SF bug 519621]
1267 class F(object):
1268 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001269 s = F()
1270 s.a = [Counted(), s]
1271 self.assertEqual(Counted.counter, 1)
1272 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001273 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001274 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001275
Georg Brandl479a7e72008-02-05 18:13:15 +00001276 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001277 if hasattr(gc, 'get_objects'):
1278 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001279 def __eq__(self, other):
1280 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001281 g = G()
1282 orig_objects = len(gc.get_objects())
1283 for i in range(10):
1284 g==g
1285 new_objects = len(gc.get_objects())
1286 self.assertEqual(orig_objects, new_objects)
1287
Georg Brandl479a7e72008-02-05 18:13:15 +00001288 class H(object):
1289 __slots__ = ['a', 'b']
1290 def __init__(self):
1291 self.a = 1
1292 self.b = 2
1293 def __del__(self_):
1294 self.assertEqual(self_.a, 1)
1295 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001296 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001297 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001298 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001299 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001300
Benjamin Petersond12362a2009-12-30 19:44:54 +00001301 class X(object):
1302 __slots__ = "a"
1303 with self.assertRaises(AttributeError):
1304 del X().a
1305
Georg Brandl479a7e72008-02-05 18:13:15 +00001306 def test_slots_special(self):
1307 # Testing __dict__ and __weakref__ in __slots__...
1308 class D(object):
1309 __slots__ = ["__dict__"]
1310 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001311 self.assertHasAttr(a, "__dict__")
1312 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001313 a.foo = 42
1314 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001315
Georg Brandl479a7e72008-02-05 18:13:15 +00001316 class W(object):
1317 __slots__ = ["__weakref__"]
1318 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001319 self.assertHasAttr(a, "__weakref__")
1320 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001321 try:
1322 a.foo = 42
1323 except AttributeError:
1324 pass
1325 else:
1326 self.fail("shouldn't be allowed to set a.foo")
1327
1328 class C1(W, D):
1329 __slots__ = []
1330 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001331 self.assertHasAttr(a, "__dict__")
1332 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001333 a.foo = 42
1334 self.assertEqual(a.__dict__, {"foo": 42})
1335
1336 class C2(D, W):
1337 __slots__ = []
1338 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001339 self.assertHasAttr(a, "__dict__")
1340 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001341 a.foo = 42
1342 self.assertEqual(a.__dict__, {"foo": 42})
1343
Xiang Zhangc393ee82017-03-08 11:18:49 +08001344 def test_slots_special2(self):
1345 # Testing __qualname__ and __classcell__ in __slots__
1346 class Meta(type):
1347 def __new__(cls, name, bases, namespace, attr):
1348 self.assertIn(attr, namespace)
1349 return super().__new__(cls, name, bases, namespace)
1350
1351 class C1:
1352 def __init__(self):
1353 self.b = 42
1354 class C2(C1, metaclass=Meta, attr="__classcell__"):
1355 __slots__ = ["__classcell__"]
1356 def __init__(self):
1357 super().__init__()
1358 self.assertIsInstance(C2.__dict__["__classcell__"],
1359 types.MemberDescriptorType)
1360 c = C2()
1361 self.assertEqual(c.b, 42)
1362 self.assertNotHasAttr(c, "__classcell__")
1363 c.__classcell__ = 42
1364 self.assertEqual(c.__classcell__, 42)
1365 with self.assertRaises(TypeError):
1366 class C3:
1367 __classcell__ = 42
1368 __slots__ = ["__classcell__"]
1369
1370 class Q1(metaclass=Meta, attr="__qualname__"):
1371 __slots__ = ["__qualname__"]
1372 self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
1373 self.assertIsInstance(Q1.__dict__["__qualname__"],
1374 types.MemberDescriptorType)
1375 q = Q1()
1376 self.assertNotHasAttr(q, "__qualname__")
1377 q.__qualname__ = "q"
1378 self.assertEqual(q.__qualname__, "q")
1379 with self.assertRaises(TypeError):
1380 class Q2:
1381 __qualname__ = object()
1382 __slots__ = ["__qualname__"]
1383
Christian Heimesa156e092008-02-16 07:38:31 +00001384 def test_slots_descriptor(self):
1385 # Issue2115: slot descriptors did not correctly check
1386 # the type of the given object
1387 import abc
1388 class MyABC(metaclass=abc.ABCMeta):
1389 __slots__ = "a"
1390
1391 class Unrelated(object):
1392 pass
1393 MyABC.register(Unrelated)
1394
1395 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001396 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001397
1398 # This used to crash
1399 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1400
Georg Brandl479a7e72008-02-05 18:13:15 +00001401 def test_dynamics(self):
1402 # Testing class attribute propagation...
1403 class D(object):
1404 pass
1405 class E(D):
1406 pass
1407 class F(D):
1408 pass
1409 D.foo = 1
1410 self.assertEqual(D.foo, 1)
1411 # Test that dynamic attributes are inherited
1412 self.assertEqual(E.foo, 1)
1413 self.assertEqual(F.foo, 1)
1414 # Test dynamic instances
1415 class C(object):
1416 pass
1417 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001418 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001419 C.foobar = 2
1420 self.assertEqual(a.foobar, 2)
1421 C.method = lambda self: 42
1422 self.assertEqual(a.method(), 42)
1423 C.__repr__ = lambda self: "C()"
1424 self.assertEqual(repr(a), "C()")
1425 C.__int__ = lambda self: 100
1426 self.assertEqual(int(a), 100)
1427 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001428 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001429 def mygetattr(self, name):
1430 if name == "spam":
1431 return "spam"
1432 raise AttributeError
1433 C.__getattr__ = mygetattr
1434 self.assertEqual(a.spam, "spam")
1435 a.new = 12
1436 self.assertEqual(a.new, 12)
1437 def mysetattr(self, name, value):
1438 if name == "spam":
1439 raise AttributeError
1440 return object.__setattr__(self, name, value)
1441 C.__setattr__ = mysetattr
1442 try:
1443 a.spam = "not spam"
1444 except AttributeError:
1445 pass
1446 else:
1447 self.fail("expected AttributeError")
1448 self.assertEqual(a.spam, "spam")
1449 class D(C):
1450 pass
1451 d = D()
1452 d.foo = 1
1453 self.assertEqual(d.foo, 1)
1454
1455 # Test handling of int*seq and seq*int
1456 class I(int):
1457 pass
1458 self.assertEqual("a"*I(2), "aa")
1459 self.assertEqual(I(2)*"a", "aa")
1460 self.assertEqual(2*I(3), 6)
1461 self.assertEqual(I(3)*2, 6)
1462 self.assertEqual(I(3)*I(2), 6)
1463
Georg Brandl479a7e72008-02-05 18:13:15 +00001464 # Test comparison of classes with dynamic metaclasses
1465 class dynamicmetaclass(type):
1466 pass
1467 class someclass(metaclass=dynamicmetaclass):
1468 pass
1469 self.assertNotEqual(someclass, object)
1470
1471 def test_errors(self):
1472 # Testing errors...
1473 try:
1474 class C(list, dict):
1475 pass
1476 except TypeError:
1477 pass
1478 else:
1479 self.fail("inheritance from both list and dict should be illegal")
1480
1481 try:
1482 class C(object, None):
1483 pass
1484 except TypeError:
1485 pass
1486 else:
1487 self.fail("inheritance from non-type should be illegal")
1488 class Classic:
1489 pass
1490
1491 try:
1492 class C(type(len)):
1493 pass
1494 except TypeError:
1495 pass
1496 else:
1497 self.fail("inheritance from CFunction should be illegal")
1498
1499 try:
1500 class C(object):
1501 __slots__ = 1
1502 except TypeError:
1503 pass
1504 else:
1505 self.fail("__slots__ = 1 should be illegal")
1506
1507 try:
1508 class C(object):
1509 __slots__ = [1]
1510 except TypeError:
1511 pass
1512 else:
1513 self.fail("__slots__ = [1] should be illegal")
1514
1515 class M1(type):
1516 pass
1517 class M2(type):
1518 pass
1519 class A1(object, metaclass=M1):
1520 pass
1521 class A2(object, metaclass=M2):
1522 pass
1523 try:
1524 class B(A1, A2):
1525 pass
1526 except TypeError:
1527 pass
1528 else:
1529 self.fail("finding the most derived metaclass should have failed")
1530
1531 def test_classmethods(self):
1532 # Testing class methods...
1533 class C(object):
1534 def foo(*a): return a
1535 goo = classmethod(foo)
1536 c = C()
1537 self.assertEqual(C.goo(1), (C, 1))
1538 self.assertEqual(c.goo(1), (C, 1))
1539 self.assertEqual(c.foo(1), (c, 1))
1540 class D(C):
1541 pass
1542 d = D()
1543 self.assertEqual(D.goo(1), (D, 1))
1544 self.assertEqual(d.goo(1), (D, 1))
1545 self.assertEqual(d.foo(1), (d, 1))
1546 self.assertEqual(D.foo(d, 1), (d, 1))
1547 # Test for a specific crash (SF bug 528132)
1548 def f(cls, arg): return (cls, arg)
1549 ff = classmethod(f)
1550 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1551 self.assertEqual(ff.__get__(0)(42), (int, 42))
1552
1553 # Test super() with classmethods (SF bug 535444)
1554 self.assertEqual(C.goo.__self__, C)
1555 self.assertEqual(D.goo.__self__, D)
1556 self.assertEqual(super(D,D).goo.__self__, D)
1557 self.assertEqual(super(D,d).goo.__self__, D)
1558 self.assertEqual(super(D,D).goo(), (D,))
1559 self.assertEqual(super(D,d).goo(), (D,))
1560
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001561 # Verify that a non-callable will raise
1562 meth = classmethod(1).__get__(1)
1563 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001564
1565 # Verify that classmethod() doesn't allow keyword args
1566 try:
1567 classmethod(f, kw=1)
1568 except TypeError:
1569 pass
1570 else:
1571 self.fail("classmethod shouldn't accept keyword args")
1572
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001573 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001574 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001575 cm.x = 42
1576 self.assertEqual(cm.x, 42)
1577 self.assertEqual(cm.__dict__, {"x" : 42})
1578 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001579 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001580
Oren Milmand019bc82018-02-13 12:28:33 +02001581 @support.refcount_test
1582 def test_refleaks_in_classmethod___init__(self):
1583 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1584 cm = classmethod(None)
1585 refs_before = gettotalrefcount()
1586 for i in range(100):
1587 cm.__init__(None)
1588 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1589
Benjamin Petersone549ead2009-03-28 21:42:05 +00001590 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001591 def test_classmethods_in_c(self):
1592 # Testing C-based class methods...
1593 import xxsubtype as spam
1594 a = (1, 2, 3)
1595 d = {'abc': 123}
1596 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1597 self.assertEqual(x, spam.spamlist)
1598 self.assertEqual(a, a1)
1599 self.assertEqual(d, d1)
1600 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1601 self.assertEqual(x, spam.spamlist)
1602 self.assertEqual(a, a1)
1603 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001604 spam_cm = spam.spamlist.__dict__['classmeth']
1605 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1606 self.assertEqual(x2, spam.spamlist)
1607 self.assertEqual(a2, a1)
1608 self.assertEqual(d2, d1)
1609 class SubSpam(spam.spamlist): pass
1610 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1611 self.assertEqual(x2, SubSpam)
1612 self.assertEqual(a2, a1)
1613 self.assertEqual(d2, d1)
Inada Naoki871309c2019-03-26 18:26:33 +09001614
1615 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001616 spam_cm()
Inada Naoki871309c2019-03-26 18:26:33 +09001617 self.assertEqual(
1618 str(cm.exception),
1619 "descriptor 'classmeth' of 'xxsubtype.spamlist' "
1620 "object needs an argument")
1621
1622 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001623 spam_cm(spam.spamlist())
Inada Naoki871309c2019-03-26 18:26:33 +09001624 self.assertEqual(
1625 str(cm.exception),
Jeroen Demeyer3f345c32019-06-07 12:20:24 +02001626 "descriptor 'classmeth' for type 'xxsubtype.spamlist' "
1627 "needs a type, not a 'xxsubtype.spamlist' as arg 2")
Inada Naoki871309c2019-03-26 18:26:33 +09001628
1629 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001630 spam_cm(list)
Inada Naoki62f95882019-04-01 17:56:11 +09001631 expected_errmsg = (
Inada Naoki871309c2019-03-26 18:26:33 +09001632 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
1633 "but received 'list'")
Inada Naoki62f95882019-04-01 17:56:11 +09001634 self.assertEqual(str(cm.exception), expected_errmsg)
1635
1636 with self.assertRaises(TypeError) as cm:
1637 spam_cm.__get__(None, list)
1638 self.assertEqual(str(cm.exception), expected_errmsg)
Georg Brandl479a7e72008-02-05 18:13:15 +00001639
1640 def test_staticmethods(self):
1641 # Testing static methods...
1642 class C(object):
1643 def foo(*a): return a
1644 goo = staticmethod(foo)
1645 c = C()
1646 self.assertEqual(C.goo(1), (1,))
1647 self.assertEqual(c.goo(1), (1,))
1648 self.assertEqual(c.foo(1), (c, 1,))
1649 class D(C):
1650 pass
1651 d = D()
1652 self.assertEqual(D.goo(1), (1,))
1653 self.assertEqual(d.goo(1), (1,))
1654 self.assertEqual(d.foo(1), (d, 1))
1655 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001656 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001657 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001658 sm.x = 42
1659 self.assertEqual(sm.x, 42)
1660 self.assertEqual(sm.__dict__, {"x" : 42})
1661 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001662 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001663
Oren Milmand019bc82018-02-13 12:28:33 +02001664 @support.refcount_test
1665 def test_refleaks_in_staticmethod___init__(self):
1666 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1667 sm = staticmethod(None)
1668 refs_before = gettotalrefcount()
1669 for i in range(100):
1670 sm.__init__(None)
1671 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1672
Benjamin Petersone549ead2009-03-28 21:42:05 +00001673 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001674 def test_staticmethods_in_c(self):
1675 # Testing C-based static methods...
1676 import xxsubtype as spam
1677 a = (1, 2, 3)
1678 d = {"abc": 123}
1679 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1680 self.assertEqual(x, None)
1681 self.assertEqual(a, a1)
1682 self.assertEqual(d, d1)
1683 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1684 self.assertEqual(x, None)
1685 self.assertEqual(a, a1)
1686 self.assertEqual(d, d1)
1687
1688 def test_classic(self):
1689 # Testing classic classes...
1690 class C:
1691 def foo(*a): return a
1692 goo = classmethod(foo)
1693 c = C()
1694 self.assertEqual(C.goo(1), (C, 1))
1695 self.assertEqual(c.goo(1), (C, 1))
1696 self.assertEqual(c.foo(1), (c, 1))
1697 class D(C):
1698 pass
1699 d = D()
1700 self.assertEqual(D.goo(1), (D, 1))
1701 self.assertEqual(d.goo(1), (D, 1))
1702 self.assertEqual(d.foo(1), (d, 1))
1703 self.assertEqual(D.foo(d, 1), (d, 1))
1704 class E: # *not* subclassing from C
1705 foo = C.foo
1706 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001707 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001708
1709 def test_compattr(self):
1710 # Testing computed attributes...
1711 class C(object):
1712 class computed_attribute(object):
1713 def __init__(self, get, set=None, delete=None):
1714 self.__get = get
1715 self.__set = set
1716 self.__delete = delete
1717 def __get__(self, obj, type=None):
1718 return self.__get(obj)
1719 def __set__(self, obj, value):
1720 return self.__set(obj, value)
1721 def __delete__(self, obj):
1722 return self.__delete(obj)
1723 def __init__(self):
1724 self.__x = 0
1725 def __get_x(self):
1726 x = self.__x
1727 self.__x = x+1
1728 return x
1729 def __set_x(self, x):
1730 self.__x = x
1731 def __delete_x(self):
1732 del self.__x
1733 x = computed_attribute(__get_x, __set_x, __delete_x)
1734 a = C()
1735 self.assertEqual(a.x, 0)
1736 self.assertEqual(a.x, 1)
1737 a.x = 10
1738 self.assertEqual(a.x, 10)
1739 self.assertEqual(a.x, 11)
1740 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001741 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001742
1743 def test_newslots(self):
1744 # Testing __new__ slot override...
1745 class C(list):
1746 def __new__(cls):
1747 self = list.__new__(cls)
1748 self.foo = 1
1749 return self
1750 def __init__(self):
1751 self.foo = self.foo + 2
1752 a = C()
1753 self.assertEqual(a.foo, 3)
1754 self.assertEqual(a.__class__, C)
1755 class D(C):
1756 pass
1757 b = D()
1758 self.assertEqual(b.foo, 3)
1759 self.assertEqual(b.__class__, D)
1760
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001761 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001762 def test_bad_new(self):
1763 self.assertRaises(TypeError, object.__new__)
1764 self.assertRaises(TypeError, object.__new__, '')
1765 self.assertRaises(TypeError, list.__new__, object)
1766 self.assertRaises(TypeError, object.__new__, list)
1767 class C(object):
1768 __new__ = list.__new__
1769 self.assertRaises(TypeError, C)
1770 class C(list):
1771 __new__ = object.__new__
1772 self.assertRaises(TypeError, C)
1773
1774 def test_object_new(self):
1775 class A(object):
1776 pass
1777 object.__new__(A)
1778 self.assertRaises(TypeError, object.__new__, A, 5)
1779 object.__init__(A())
1780 self.assertRaises(TypeError, object.__init__, A(), 5)
1781
1782 class A(object):
1783 def __init__(self, foo):
1784 self.foo = foo
1785 object.__new__(A)
1786 object.__new__(A, 5)
1787 object.__init__(A(3))
1788 self.assertRaises(TypeError, object.__init__, A(3), 5)
1789
1790 class A(object):
1791 def __new__(cls, foo):
1792 return object.__new__(cls)
1793 object.__new__(A)
1794 self.assertRaises(TypeError, object.__new__, A, 5)
1795 object.__init__(A(3))
1796 object.__init__(A(3), 5)
1797
1798 class A(object):
1799 def __new__(cls, foo):
1800 return object.__new__(cls)
1801 def __init__(self, foo):
1802 self.foo = foo
1803 object.__new__(A)
1804 self.assertRaises(TypeError, object.__new__, A, 5)
1805 object.__init__(A(3))
1806 self.assertRaises(TypeError, object.__init__, A(3), 5)
1807
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001808 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001809 def test_restored_object_new(self):
1810 class A(object):
1811 def __new__(cls, *args, **kwargs):
1812 raise AssertionError
1813 self.assertRaises(AssertionError, A)
1814 class B(A):
1815 __new__ = object.__new__
1816 def __init__(self, foo):
1817 self.foo = foo
1818 with warnings.catch_warnings():
1819 warnings.simplefilter('error', DeprecationWarning)
1820 b = B(3)
1821 self.assertEqual(b.foo, 3)
1822 self.assertEqual(b.__class__, B)
1823 del B.__new__
1824 self.assertRaises(AssertionError, B)
1825 del A.__new__
1826 with warnings.catch_warnings():
1827 warnings.simplefilter('error', DeprecationWarning)
1828 b = B(3)
1829 self.assertEqual(b.foo, 3)
1830 self.assertEqual(b.__class__, B)
1831
Georg Brandl479a7e72008-02-05 18:13:15 +00001832 def test_altmro(self):
1833 # Testing mro() and overriding it...
1834 class A(object):
1835 def f(self): return "A"
1836 class B(A):
1837 pass
1838 class C(A):
1839 def f(self): return "C"
1840 class D(B, C):
1841 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001842 self.assertEqual(A.mro(), [A, object])
1843 self.assertEqual(A.__mro__, (A, object))
1844 self.assertEqual(B.mro(), [B, A, object])
1845 self.assertEqual(B.__mro__, (B, A, object))
1846 self.assertEqual(C.mro(), [C, A, object])
1847 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001848 self.assertEqual(D.mro(), [D, B, C, A, object])
1849 self.assertEqual(D.__mro__, (D, B, C, A, object))
1850 self.assertEqual(D().f(), "C")
1851
1852 class PerverseMetaType(type):
1853 def mro(cls):
1854 L = type.mro(cls)
1855 L.reverse()
1856 return L
1857 class X(D,B,C,A, metaclass=PerverseMetaType):
1858 pass
1859 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1860 self.assertEqual(X().f(), "A")
1861
1862 try:
1863 class _metaclass(type):
1864 def mro(self):
1865 return [self, dict, object]
1866 class X(object, metaclass=_metaclass):
1867 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001868 # In CPython, the class creation above already raises
1869 # TypeError, as a protection against the fact that
1870 # instances of X would segfault it. In other Python
1871 # implementations it would be ok to let the class X
1872 # be created, but instead get a clean TypeError on the
1873 # __setitem__ below.
1874 x = object.__new__(X)
1875 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001876 except TypeError:
1877 pass
1878 else:
1879 self.fail("devious mro() return not caught")
1880
1881 try:
1882 class _metaclass(type):
1883 def mro(self):
1884 return [1]
1885 class X(object, metaclass=_metaclass):
1886 pass
1887 except TypeError:
1888 pass
1889 else:
1890 self.fail("non-class mro() return not caught")
1891
1892 try:
1893 class _metaclass(type):
1894 def mro(self):
1895 return 1
1896 class X(object, metaclass=_metaclass):
1897 pass
1898 except TypeError:
1899 pass
1900 else:
1901 self.fail("non-sequence mro() return not caught")
1902
1903 def test_overloading(self):
1904 # Testing operator overloading...
1905
1906 class B(object):
1907 "Intermediate class because object doesn't have a __setattr__"
1908
1909 class C(B):
1910 def __getattr__(self, name):
1911 if name == "foo":
1912 return ("getattr", name)
1913 else:
1914 raise AttributeError
1915 def __setattr__(self, name, value):
1916 if name == "foo":
1917 self.setattr = (name, value)
1918 else:
1919 return B.__setattr__(self, name, value)
1920 def __delattr__(self, name):
1921 if name == "foo":
1922 self.delattr = name
1923 else:
1924 return B.__delattr__(self, name)
1925
1926 def __getitem__(self, key):
1927 return ("getitem", key)
1928 def __setitem__(self, key, value):
1929 self.setitem = (key, value)
1930 def __delitem__(self, key):
1931 self.delitem = key
1932
1933 a = C()
1934 self.assertEqual(a.foo, ("getattr", "foo"))
1935 a.foo = 12
1936 self.assertEqual(a.setattr, ("foo", 12))
1937 del a.foo
1938 self.assertEqual(a.delattr, "foo")
1939
1940 self.assertEqual(a[12], ("getitem", 12))
1941 a[12] = 21
1942 self.assertEqual(a.setitem, (12, 21))
1943 del a[12]
1944 self.assertEqual(a.delitem, 12)
1945
1946 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1947 a[0:10] = "foo"
1948 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1949 del a[0:10]
1950 self.assertEqual(a.delitem, (slice(0, 10)))
1951
1952 def test_methods(self):
1953 # Testing methods...
1954 class C(object):
1955 def __init__(self, x):
1956 self.x = x
1957 def foo(self):
1958 return self.x
1959 c1 = C(1)
1960 self.assertEqual(c1.foo(), 1)
1961 class D(C):
1962 boo = C.foo
1963 goo = c1.foo
1964 d2 = D(2)
1965 self.assertEqual(d2.foo(), 2)
1966 self.assertEqual(d2.boo(), 2)
1967 self.assertEqual(d2.goo(), 1)
1968 class E(object):
1969 foo = C.foo
1970 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001971 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001972
Inada Naoki62f95882019-04-01 17:56:11 +09001973 @support.impl_detail("testing error message from implementation")
1974 def test_methods_in_c(self):
1975 # This test checks error messages in builtin method descriptor.
1976 # It is allowed that other Python implementations use
1977 # different error messages.
1978 set_add = set.add
1979
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01001980 expected_errmsg = "unbound method set.add() needs an argument"
Inada Naoki62f95882019-04-01 17:56:11 +09001981
1982 with self.assertRaises(TypeError) as cm:
1983 set_add()
1984 self.assertEqual(cm.exception.args[0], expected_errmsg)
1985
1986 expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"
1987
1988 with self.assertRaises(TypeError) as cm:
1989 set_add(0)
1990 self.assertEqual(cm.exception.args[0], expected_errmsg)
1991
1992 with self.assertRaises(TypeError) as cm:
1993 set_add.__get__(0)
1994 self.assertEqual(cm.exception.args[0], expected_errmsg)
1995
Benjamin Peterson224205f2009-05-08 03:25:19 +00001996 def test_special_method_lookup(self):
1997 # The lookup of special methods bypasses __getattr__ and
1998 # __getattribute__, but they still can be descriptors.
1999
2000 def run_context(manager):
2001 with manager:
2002 pass
2003 def iden(self):
2004 return self
2005 def hello(self):
2006 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00002007 def empty_seq(self):
2008 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04002009 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00002010 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00002011 def complex_num(self):
2012 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00002013 def stop(self):
2014 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002015 def return_true(self, thing=None):
2016 return True
2017 def do_isinstance(obj):
2018 return isinstance(int, obj)
2019 def do_issubclass(obj):
2020 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00002021 def do_dict_missing(checker):
2022 class DictSub(checker.__class__, dict):
2023 pass
2024 self.assertEqual(DictSub()["hi"], 4)
2025 def some_number(self_, key):
2026 self.assertEqual(key, "hi")
2027 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002028 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002029 def format_impl(self, spec):
2030 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00002031
2032 # It would be nice to have every special method tested here, but I'm
2033 # only listing the ones I can remember outside of typeobject.c, since it
2034 # does it right.
2035 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002036 ("__bytes__", bytes, hello, set(), {}),
2037 ("__reversed__", reversed, empty_seq, set(), {}),
2038 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00002039 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002040 ("__sizeof__", sys.getsizeof, zero, set(), {}),
2041 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00002042 ("__missing__", do_dict_missing, some_number,
2043 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002044 ("__subclasscheck__", do_issubclass, return_true,
2045 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002046 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
2047 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00002048 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002049 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002050 ("__floor__", math.floor, zero, set(), {}),
2051 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04002052 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00002053 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05002054 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002055 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00002056 ]
2057
2058 class Checker(object):
2059 def __getattr__(self, attr, test=self):
2060 test.fail("__getattr__ called with {0}".format(attr))
2061 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002062 if attr not in ok:
2063 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00002064 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002065 class SpecialDescr(object):
2066 def __init__(self, impl):
2067 self.impl = impl
2068 def __get__(self, obj, owner):
2069 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002070 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002071 class MyException(Exception):
2072 pass
2073 class ErrDescr(object):
2074 def __get__(self, obj, owner):
2075 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00002076
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002077 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00002078 class X(Checker):
2079 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002080 for attr, obj in env.items():
2081 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002082 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002083 runner(X())
2084
2085 record = []
2086 class X(Checker):
2087 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002088 for attr, obj in env.items():
2089 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002090 setattr(X, name, SpecialDescr(meth_impl))
2091 runner(X())
2092 self.assertEqual(record, [1], name)
2093
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002094 class X(Checker):
2095 pass
2096 for attr, obj in env.items():
2097 setattr(X, attr, obj)
2098 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002099 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002100
Georg Brandl479a7e72008-02-05 18:13:15 +00002101 def test_specials(self):
2102 # Testing special operators...
2103 # Test operators like __hash__ for which a built-in default exists
2104
2105 # Test the default behavior for static classes
2106 class C(object):
2107 def __getitem__(self, i):
2108 if 0 <= i < 10: return i
2109 raise IndexError
2110 c1 = C()
2111 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002112 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002113 self.assertNotEqual(id(c1), id(c2))
2114 hash(c1)
2115 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002116 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002117 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002118 self.assertFalse(c1 != c1)
2119 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002120 # Note that the module name appears in str/repr, and that varies
2121 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002122 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002123 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002124 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002125 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002126 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002127 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002128 # Test the default behavior for dynamic classes
2129 class D(object):
2130 def __getitem__(self, i):
2131 if 0 <= i < 10: return i
2132 raise IndexError
2133 d1 = D()
2134 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002135 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002136 self.assertNotEqual(id(d1), id(d2))
2137 hash(d1)
2138 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002139 self.assertEqual(d1, d1)
2140 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002141 self.assertFalse(d1 != d1)
2142 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002143 # Note that the module name appears in str/repr, and that varies
2144 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002145 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002146 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002147 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002148 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002149 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002150 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002151 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002152 class Proxy(object):
2153 def __init__(self, x):
2154 self.x = x
2155 def __bool__(self):
2156 return not not self.x
2157 def __hash__(self):
2158 return hash(self.x)
2159 def __eq__(self, other):
2160 return self.x == other
2161 def __ne__(self, other):
2162 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002163 def __ge__(self, other):
2164 return self.x >= other
2165 def __gt__(self, other):
2166 return self.x > other
2167 def __le__(self, other):
2168 return self.x <= other
2169 def __lt__(self, other):
2170 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002171 def __str__(self):
2172 return "Proxy:%s" % self.x
2173 def __repr__(self):
2174 return "Proxy(%r)" % self.x
2175 def __contains__(self, value):
2176 return value in self.x
2177 p0 = Proxy(0)
2178 p1 = Proxy(1)
2179 p_1 = Proxy(-1)
2180 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002181 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002182 self.assertEqual(hash(p0), hash(0))
2183 self.assertEqual(p0, p0)
2184 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002185 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002186 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002187 self.assertTrue(p0 < p1)
2188 self.assertTrue(p0 <= p1)
2189 self.assertTrue(p1 > p0)
2190 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002191 self.assertEqual(str(p0), "Proxy:0")
2192 self.assertEqual(repr(p0), "Proxy(0)")
2193 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002194 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002195 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002196 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002197 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002198
Georg Brandl479a7e72008-02-05 18:13:15 +00002199 def test_weakrefs(self):
2200 # Testing weak references...
2201 import weakref
2202 class C(object):
2203 pass
2204 c = C()
2205 r = weakref.ref(c)
2206 self.assertEqual(r(), c)
2207 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002208 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002209 self.assertEqual(r(), None)
2210 del r
2211 class NoWeak(object):
2212 __slots__ = ['foo']
2213 no = NoWeak()
2214 try:
2215 weakref.ref(no)
2216 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002217 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002218 else:
2219 self.fail("weakref.ref(no) should be illegal")
2220 class Weak(object):
2221 __slots__ = ['foo', '__weakref__']
2222 yes = Weak()
2223 r = weakref.ref(yes)
2224 self.assertEqual(r(), yes)
2225 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002226 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002227 self.assertEqual(r(), None)
2228 del r
2229
2230 def test_properties(self):
2231 # Testing property...
2232 class C(object):
2233 def getx(self):
2234 return self.__x
2235 def setx(self, value):
2236 self.__x = value
2237 def delx(self):
2238 del self.__x
2239 x = property(getx, setx, delx, doc="I'm the x property.")
2240 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002241 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002242 a.x = 42
2243 self.assertEqual(a._C__x, 42)
2244 self.assertEqual(a.x, 42)
2245 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002246 self.assertNotHasAttr(a, "x")
2247 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002248 C.x.__set__(a, 100)
2249 self.assertEqual(C.x.__get__(a), 100)
2250 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002251 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002252
2253 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002254 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002255
2256 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002257 self.assertIn("__doc__", attrs)
2258 self.assertIn("fget", attrs)
2259 self.assertIn("fset", attrs)
2260 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002261
2262 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002263 self.assertIs(raw.fget, C.__dict__['getx'])
2264 self.assertIs(raw.fset, C.__dict__['setx'])
2265 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002266
Raymond Hettingereac503a2015-05-13 01:09:59 -07002267 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002268 try:
2269 setattr(raw, attr, 42)
2270 except AttributeError as msg:
2271 if str(msg).find('readonly') < 0:
2272 self.fail("when setting readonly attr %r on a property, "
2273 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2274 else:
2275 self.fail("expected AttributeError from trying to set readonly %r "
2276 "attr on a property" % attr)
2277
Raymond Hettingereac503a2015-05-13 01:09:59 -07002278 raw.__doc__ = 42
2279 self.assertEqual(raw.__doc__, 42)
2280
Georg Brandl479a7e72008-02-05 18:13:15 +00002281 class D(object):
2282 __getitem__ = property(lambda s: 1/0)
2283
2284 d = D()
2285 try:
2286 for i in d:
2287 str(i)
2288 except ZeroDivisionError:
2289 pass
2290 else:
2291 self.fail("expected ZeroDivisionError from bad property")
2292
R. David Murray378c0cf2010-02-24 01:46:21 +00002293 @unittest.skipIf(sys.flags.optimize >= 2,
2294 "Docstrings are omitted with -O2 and above")
2295 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002296 class E(object):
2297 def getter(self):
2298 "getter method"
2299 return 0
2300 def setter(self_, value):
2301 "setter method"
2302 pass
2303 prop = property(getter)
2304 self.assertEqual(prop.__doc__, "getter method")
2305 prop2 = property(fset=setter)
2306 self.assertEqual(prop2.__doc__, None)
2307
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002308 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002309 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002310 # this segfaulted in 2.5b2
2311 try:
2312 import _testcapi
2313 except ImportError:
2314 pass
2315 else:
2316 class X(object):
2317 p = property(_testcapi.test_with_docstring)
2318
2319 def test_properties_plus(self):
2320 class C(object):
2321 foo = property(doc="hello")
2322 @foo.getter
2323 def foo(self):
2324 return self._foo
2325 @foo.setter
2326 def foo(self, value):
2327 self._foo = abs(value)
2328 @foo.deleter
2329 def foo(self):
2330 del self._foo
2331 c = C()
2332 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002333 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002334 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002335 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002336 self.assertEqual(c._foo, 42)
2337 self.assertEqual(c.foo, 42)
2338 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002339 self.assertNotHasAttr(c, '_foo')
2340 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002341
2342 class D(C):
2343 @C.foo.deleter
2344 def foo(self):
2345 try:
2346 del self._foo
2347 except AttributeError:
2348 pass
2349 d = D()
2350 d.foo = 24
2351 self.assertEqual(d.foo, 24)
2352 del d.foo
2353 del d.foo
2354
2355 class E(object):
2356 @property
2357 def foo(self):
2358 return self._foo
2359 @foo.setter
2360 def foo(self, value):
2361 raise RuntimeError
2362 @foo.setter
2363 def foo(self, value):
2364 self._foo = abs(value)
2365 @foo.deleter
2366 def foo(self, value=None):
2367 del self._foo
2368
2369 e = E()
2370 e.foo = -42
2371 self.assertEqual(e.foo, 42)
2372 del e.foo
2373
2374 class F(E):
2375 @E.foo.deleter
2376 def foo(self):
2377 del self._foo
2378 @foo.setter
2379 def foo(self, value):
2380 self._foo = max(0, value)
2381 f = F()
2382 f.foo = -10
2383 self.assertEqual(f.foo, 0)
2384 del f.foo
2385
2386 def test_dict_constructors(self):
2387 # Testing dict constructor ...
2388 d = dict()
2389 self.assertEqual(d, {})
2390 d = dict({})
2391 self.assertEqual(d, {})
2392 d = dict({1: 2, 'a': 'b'})
2393 self.assertEqual(d, {1: 2, 'a': 'b'})
2394 self.assertEqual(d, dict(list(d.items())))
2395 self.assertEqual(d, dict(iter(d.items())))
2396 d = dict({'one':1, 'two':2})
2397 self.assertEqual(d, dict(one=1, two=2))
2398 self.assertEqual(d, dict(**d))
2399 self.assertEqual(d, dict({"one": 1}, two=2))
2400 self.assertEqual(d, dict([("two", 2)], one=1))
2401 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2402 self.assertEqual(d, dict(**d))
2403
2404 for badarg in 0, 0, 0j, "0", [0], (0,):
2405 try:
2406 dict(badarg)
2407 except TypeError:
2408 pass
2409 except ValueError:
2410 if badarg == "0":
2411 # It's a sequence, and its elements are also sequences (gotta
2412 # love strings <wink>), but they aren't of length 2, so this
2413 # one seemed better as a ValueError than a TypeError.
2414 pass
2415 else:
2416 self.fail("no TypeError from dict(%r)" % badarg)
2417 else:
2418 self.fail("no TypeError from dict(%r)" % badarg)
2419
2420 try:
2421 dict({}, {})
2422 except TypeError:
2423 pass
2424 else:
2425 self.fail("no TypeError from dict({}, {})")
2426
2427 class Mapping:
2428 # Lacks a .keys() method; will be added later.
2429 dict = {1:2, 3:4, 'a':1j}
2430
2431 try:
2432 dict(Mapping())
2433 except TypeError:
2434 pass
2435 else:
2436 self.fail("no TypeError from dict(incomplete mapping)")
2437
2438 Mapping.keys = lambda self: list(self.dict.keys())
2439 Mapping.__getitem__ = lambda self, i: self.dict[i]
2440 d = dict(Mapping())
2441 self.assertEqual(d, Mapping.dict)
2442
2443 # Init from sequence of iterable objects, each producing a 2-sequence.
2444 class AddressBookEntry:
2445 def __init__(self, first, last):
2446 self.first = first
2447 self.last = last
2448 def __iter__(self):
2449 return iter([self.first, self.last])
2450
2451 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2452 AddressBookEntry('Barry', 'Peters'),
2453 AddressBookEntry('Tim', 'Peters'),
2454 AddressBookEntry('Barry', 'Warsaw')])
2455 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2456
2457 d = dict(zip(range(4), range(1, 5)))
2458 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2459
2460 # Bad sequence lengths.
2461 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2462 try:
2463 dict(bad)
2464 except ValueError:
2465 pass
2466 else:
2467 self.fail("no ValueError from dict(%r)" % bad)
2468
2469 def test_dir(self):
2470 # Testing dir() ...
2471 junk = 12
2472 self.assertEqual(dir(), ['junk', 'self'])
2473 del junk
2474
2475 # Just make sure these don't blow up!
2476 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2477 dir(arg)
2478
2479 # Test dir on new-style classes. Since these have object as a
2480 # base class, a lot more gets sucked in.
2481 def interesting(strings):
2482 return [s for s in strings if not s.startswith('_')]
2483
2484 class C(object):
2485 Cdata = 1
2486 def Cmethod(self): pass
2487
2488 cstuff = ['Cdata', 'Cmethod']
2489 self.assertEqual(interesting(dir(C)), cstuff)
2490
2491 c = C()
2492 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002493 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002494
2495 c.cdata = 2
2496 c.cmethod = lambda self: 0
2497 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002498 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002499
2500 class A(C):
2501 Adata = 1
2502 def Amethod(self): pass
2503
2504 astuff = ['Adata', 'Amethod'] + cstuff
2505 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002506 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002507 a = A()
2508 self.assertEqual(interesting(dir(a)), astuff)
2509 a.adata = 42
2510 a.amethod = lambda self: 3
2511 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002512 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002513
2514 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002515 class M(type(sys)):
2516 pass
2517 minstance = M("m")
2518 minstance.b = 2
2519 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002520 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002521 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002522 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002523 self.assertEqual(names, ['a', 'b'])
2524
2525 class M2(M):
2526 def getdict(self):
2527 return "Not a dict!"
2528 __dict__ = property(getdict)
2529
2530 m2instance = M2("m2")
2531 m2instance.b = 2
2532 m2instance.a = 1
2533 self.assertEqual(m2instance.__dict__, "Not a dict!")
2534 try:
2535 dir(m2instance)
2536 except TypeError:
2537 pass
2538
MojoVampire469325c2020-03-03 18:50:17 +00002539 # Two essentially featureless objects, (Ellipsis just inherits stuff
2540 # from object.
2541 self.assertEqual(dir(object()), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002542
2543 # Nasty test case for proxied objects
2544 class Wrapper(object):
2545 def __init__(self, obj):
2546 self.__obj = obj
2547 def __repr__(self):
2548 return "Wrapper(%s)" % repr(self.__obj)
2549 def __getitem__(self, key):
2550 return Wrapper(self.__obj[key])
2551 def __len__(self):
2552 return len(self.__obj)
2553 def __getattr__(self, name):
2554 return Wrapper(getattr(self.__obj, name))
2555
2556 class C(object):
2557 def __getclass(self):
2558 return Wrapper(type(self))
2559 __class__ = property(__getclass)
2560
2561 dir(C()) # This used to segfault
2562
2563 def test_supers(self):
2564 # Testing super...
2565
2566 class A(object):
2567 def meth(self, a):
2568 return "A(%r)" % a
2569
2570 self.assertEqual(A().meth(1), "A(1)")
2571
2572 class B(A):
2573 def __init__(self):
2574 self.__super = super(B, self)
2575 def meth(self, a):
2576 return "B(%r)" % a + self.__super.meth(a)
2577
2578 self.assertEqual(B().meth(2), "B(2)A(2)")
2579
2580 class C(A):
2581 def meth(self, a):
2582 return "C(%r)" % a + self.__super.meth(a)
2583 C._C__super = super(C)
2584
2585 self.assertEqual(C().meth(3), "C(3)A(3)")
2586
2587 class D(C, B):
2588 def meth(self, a):
2589 return "D(%r)" % a + super(D, self).meth(a)
2590
2591 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2592
2593 # Test for subclassing super
2594
2595 class mysuper(super):
2596 def __init__(self, *args):
2597 return super(mysuper, self).__init__(*args)
2598
2599 class E(D):
2600 def meth(self, a):
2601 return "E(%r)" % a + mysuper(E, self).meth(a)
2602
2603 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2604
2605 class F(E):
2606 def meth(self, a):
2607 s = self.__super # == mysuper(F, self)
2608 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2609 F._F__super = mysuper(F)
2610
2611 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2612
2613 # Make sure certain errors are raised
2614
2615 try:
2616 super(D, 42)
2617 except TypeError:
2618 pass
2619 else:
2620 self.fail("shouldn't allow super(D, 42)")
2621
2622 try:
2623 super(D, C())
2624 except TypeError:
2625 pass
2626 else:
2627 self.fail("shouldn't allow super(D, C())")
2628
2629 try:
2630 super(D).__get__(12)
2631 except TypeError:
2632 pass
2633 else:
2634 self.fail("shouldn't allow super(D).__get__(12)")
2635
2636 try:
2637 super(D).__get__(C())
2638 except TypeError:
2639 pass
2640 else:
2641 self.fail("shouldn't allow super(D).__get__(C())")
2642
2643 # Make sure data descriptors can be overridden and accessed via super
2644 # (new feature in Python 2.3)
2645
2646 class DDbase(object):
2647 def getx(self): return 42
2648 x = property(getx)
2649
2650 class DDsub(DDbase):
2651 def getx(self): return "hello"
2652 x = property(getx)
2653
2654 dd = DDsub()
2655 self.assertEqual(dd.x, "hello")
2656 self.assertEqual(super(DDsub, dd).x, 42)
2657
2658 # Ensure that super() lookup of descriptor from classmethod
2659 # works (SF ID# 743627)
2660
2661 class Base(object):
2662 aProp = property(lambda self: "foo")
2663
2664 class Sub(Base):
2665 @classmethod
2666 def test(klass):
2667 return super(Sub,klass).aProp
2668
2669 self.assertEqual(Sub.test(), Base.aProp)
2670
2671 # Verify that super() doesn't allow keyword args
Zackery Spytz6b2e3252019-08-26 16:41:11 -06002672 with self.assertRaises(TypeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002673 super(Base, kw=1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002674
2675 def test_basic_inheritance(self):
2676 # Testing inheritance from basic types...
2677
2678 class hexint(int):
2679 def __repr__(self):
2680 return hex(self)
2681 def __add__(self, other):
2682 return hexint(int.__add__(self, other))
2683 # (Note that overriding __radd__ doesn't work,
2684 # because the int type gets first dibs.)
2685 self.assertEqual(repr(hexint(7) + 9), "0x10")
2686 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2687 a = hexint(12345)
2688 self.assertEqual(a, 12345)
2689 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002690 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002691 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002692 self.assertIs((+a).__class__, int)
2693 self.assertIs((a >> 0).__class__, int)
2694 self.assertIs((a << 0).__class__, int)
2695 self.assertIs((hexint(0) << 12).__class__, int)
2696 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002697
2698 class octlong(int):
2699 __slots__ = []
2700 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002701 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002702 def __add__(self, other):
2703 return self.__class__(super(octlong, self).__add__(other))
2704 __radd__ = __add__
2705 self.assertEqual(str(octlong(3) + 5), "0o10")
2706 # (Note that overriding __radd__ here only seems to work
2707 # because the example uses a short int left argument.)
2708 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2709 a = octlong(12345)
2710 self.assertEqual(a, 12345)
2711 self.assertEqual(int(a), 12345)
2712 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002713 self.assertIs(int(a).__class__, int)
2714 self.assertIs((+a).__class__, int)
2715 self.assertIs((-a).__class__, int)
2716 self.assertIs((-octlong(0)).__class__, int)
2717 self.assertIs((a >> 0).__class__, int)
2718 self.assertIs((a << 0).__class__, int)
2719 self.assertIs((a - 0).__class__, int)
2720 self.assertIs((a * 1).__class__, int)
2721 self.assertIs((a ** 1).__class__, int)
2722 self.assertIs((a // 1).__class__, int)
2723 self.assertIs((1 * a).__class__, int)
2724 self.assertIs((a | 0).__class__, int)
2725 self.assertIs((a ^ 0).__class__, int)
2726 self.assertIs((a & -1).__class__, int)
2727 self.assertIs((octlong(0) << 12).__class__, int)
2728 self.assertIs((octlong(0) >> 12).__class__, int)
2729 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002730
2731 # Because octlong overrides __add__, we can't check the absence of +0
2732 # optimizations using octlong.
2733 class longclone(int):
2734 pass
2735 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002736 self.assertIs((a + 0).__class__, int)
2737 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002738
2739 # Check that negative clones don't segfault
2740 a = longclone(-1)
2741 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002742 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002743
2744 class precfloat(float):
2745 __slots__ = ['prec']
2746 def __init__(self, value=0.0, prec=12):
2747 self.prec = int(prec)
2748 def __repr__(self):
2749 return "%.*g" % (self.prec, self)
2750 self.assertEqual(repr(precfloat(1.1)), "1.1")
2751 a = precfloat(12345)
2752 self.assertEqual(a, 12345.0)
2753 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002754 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002755 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002756 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002757
2758 class madcomplex(complex):
2759 def __repr__(self):
2760 return "%.17gj%+.17g" % (self.imag, self.real)
2761 a = madcomplex(-3, 4)
2762 self.assertEqual(repr(a), "4j-3")
2763 base = complex(-3, 4)
2764 self.assertEqual(base.__class__, complex)
2765 self.assertEqual(a, base)
2766 self.assertEqual(complex(a), base)
2767 self.assertEqual(complex(a).__class__, complex)
2768 a = madcomplex(a) # just trying another form of the constructor
2769 self.assertEqual(repr(a), "4j-3")
2770 self.assertEqual(a, base)
2771 self.assertEqual(complex(a), base)
2772 self.assertEqual(complex(a).__class__, complex)
2773 self.assertEqual(hash(a), hash(base))
2774 self.assertEqual((+a).__class__, complex)
2775 self.assertEqual((a + 0).__class__, complex)
2776 self.assertEqual(a + 0, base)
2777 self.assertEqual((a - 0).__class__, complex)
2778 self.assertEqual(a - 0, base)
2779 self.assertEqual((a * 1).__class__, complex)
2780 self.assertEqual(a * 1, base)
2781 self.assertEqual((a / 1).__class__, complex)
2782 self.assertEqual(a / 1, base)
2783
2784 class madtuple(tuple):
2785 _rev = None
2786 def rev(self):
2787 if self._rev is not None:
2788 return self._rev
2789 L = list(self)
2790 L.reverse()
2791 self._rev = self.__class__(L)
2792 return self._rev
2793 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2794 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2795 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2796 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2797 for i in range(512):
2798 t = madtuple(range(i))
2799 u = t.rev()
2800 v = u.rev()
2801 self.assertEqual(v, t)
2802 a = madtuple((1,2,3,4,5))
2803 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002804 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002805 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002806 self.assertIs(a[:].__class__, tuple)
2807 self.assertIs((a * 1).__class__, tuple)
2808 self.assertIs((a * 0).__class__, tuple)
2809 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002810 a = madtuple(())
2811 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002812 self.assertIs(tuple(a).__class__, tuple)
2813 self.assertIs((a + a).__class__, tuple)
2814 self.assertIs((a * 0).__class__, tuple)
2815 self.assertIs((a * 1).__class__, tuple)
2816 self.assertIs((a * 2).__class__, tuple)
2817 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002818
2819 class madstring(str):
2820 _rev = None
2821 def rev(self):
2822 if self._rev is not None:
2823 return self._rev
2824 L = list(self)
2825 L.reverse()
2826 self._rev = self.__class__("".join(L))
2827 return self._rev
2828 s = madstring("abcdefghijklmnopqrstuvwxyz")
2829 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2830 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2831 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2832 for i in range(256):
2833 s = madstring("".join(map(chr, range(i))))
2834 t = s.rev()
2835 u = t.rev()
2836 self.assertEqual(u, s)
2837 s = madstring("12345")
2838 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002839 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002840
2841 base = "\x00" * 5
2842 s = madstring(base)
2843 self.assertEqual(s, base)
2844 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002845 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002846 self.assertEqual(hash(s), hash(base))
2847 self.assertEqual({s: 1}[base], 1)
2848 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002849 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002850 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002851 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002852 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002853 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002854 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002855 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002856 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002858 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002859 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002860 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002861 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002862 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002864 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002865 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002866 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002867 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002868 self.assertEqual(s.rstrip(), base)
2869 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002870 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002871 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002872 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002873 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002874 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002875 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002876 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002877 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002878 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002879 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002880 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002881 self.assertEqual(s.lower(), base)
2882
2883 class madunicode(str):
2884 _rev = None
2885 def rev(self):
2886 if self._rev is not None:
2887 return self._rev
2888 L = list(self)
2889 L.reverse()
2890 self._rev = self.__class__("".join(L))
2891 return self._rev
2892 u = madunicode("ABCDEF")
2893 self.assertEqual(u, "ABCDEF")
2894 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2895 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2896 base = "12345"
2897 u = madunicode(base)
2898 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002899 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002900 self.assertEqual(hash(u), hash(base))
2901 self.assertEqual({u: 1}[base], 1)
2902 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002903 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002904 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002905 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002906 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002907 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002909 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002910 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002911 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002912 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002913 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002915 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002916 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002917 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002918 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002919 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002920 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002921 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002922 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002923 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002924 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002925 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002926 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002927 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002928 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002929 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002930 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002931 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002932 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002933 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002934 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002935 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002936 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002937 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002938 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002939 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002940 self.assertEqual(u[0:0], "")
2941
2942 class sublist(list):
2943 pass
2944 a = sublist(range(5))
2945 self.assertEqual(a, list(range(5)))
2946 a.append("hello")
2947 self.assertEqual(a, list(range(5)) + ["hello"])
2948 a[5] = 5
2949 self.assertEqual(a, list(range(6)))
2950 a.extend(range(6, 20))
2951 self.assertEqual(a, list(range(20)))
2952 a[-5:] = []
2953 self.assertEqual(a, list(range(15)))
2954 del a[10:15]
2955 self.assertEqual(len(a), 10)
2956 self.assertEqual(a, list(range(10)))
2957 self.assertEqual(list(a), list(range(10)))
2958 self.assertEqual(a[0], 0)
2959 self.assertEqual(a[9], 9)
2960 self.assertEqual(a[-10], 0)
2961 self.assertEqual(a[-1], 9)
2962 self.assertEqual(a[:5], list(range(5)))
2963
2964 ## class CountedInput(file):
2965 ## """Counts lines read by self.readline().
2966 ##
2967 ## self.lineno is the 0-based ordinal of the last line read, up to
2968 ## a maximum of one greater than the number of lines in the file.
2969 ##
2970 ## self.ateof is true if and only if the final "" line has been read,
2971 ## at which point self.lineno stops incrementing, and further calls
2972 ## to readline() continue to return "".
2973 ## """
2974 ##
2975 ## lineno = 0
2976 ## ateof = 0
2977 ## def readline(self):
2978 ## if self.ateof:
2979 ## return ""
2980 ## s = file.readline(self)
2981 ## # Next line works too.
2982 ## # s = super(CountedInput, self).readline()
2983 ## self.lineno += 1
2984 ## if s == "":
2985 ## self.ateof = 1
2986 ## return s
2987 ##
Hai Shifcce8c62020-08-08 05:55:35 +08002988 ## f = file(name=os_helper.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002989 ## lines = ['a\n', 'b\n', 'c\n']
2990 ## try:
2991 ## f.writelines(lines)
2992 ## f.close()
Hai Shifcce8c62020-08-08 05:55:35 +08002993 ## f = CountedInput(os_helper.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002994 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2995 ## got = f.readline()
2996 ## self.assertEqual(expected, got)
2997 ## self.assertEqual(f.lineno, i)
2998 ## self.assertEqual(f.ateof, (i > len(lines)))
2999 ## f.close()
3000 ## finally:
3001 ## try:
3002 ## f.close()
3003 ## except:
3004 ## pass
Hai Shifcce8c62020-08-08 05:55:35 +08003005 ## os_helper.unlink(os_helper.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00003006
3007 def test_keywords(self):
3008 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003009 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3010 int(x=1)
3011 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3012 float(x=2)
3013 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3014 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003015 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
3016 self.assertEqual(str(object=500), '500')
3017 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003018 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3019 tuple(sequence=range(3))
3020 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3021 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00003022 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
3023
3024 for constructor in (int, float, int, complex, str, str,
3025 tuple, list):
3026 try:
3027 constructor(bogus_keyword_arg=1)
3028 except TypeError:
3029 pass
3030 else:
3031 self.fail("expected TypeError from bogus keyword argument to %r"
3032 % constructor)
3033
3034 def test_str_subclass_as_dict_key(self):
3035 # Testing a str subclass used as dict key ..
3036
3037 class cistr(str):
Min ho Kim39d87b52019-08-31 06:21:19 +10003038 """Subclass of str that computes __eq__ case-insensitively.
Georg Brandl479a7e72008-02-05 18:13:15 +00003039
3040 Also computes a hash code of the string in canonical form.
3041 """
3042
3043 def __init__(self, value):
3044 self.canonical = value.lower()
3045 self.hashcode = hash(self.canonical)
3046
3047 def __eq__(self, other):
3048 if not isinstance(other, cistr):
3049 other = cistr(other)
3050 return self.canonical == other.canonical
3051
3052 def __hash__(self):
3053 return self.hashcode
3054
3055 self.assertEqual(cistr('ABC'), 'abc')
3056 self.assertEqual('aBc', cistr('ABC'))
3057 self.assertEqual(str(cistr('ABC')), 'ABC')
3058
3059 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3060 self.assertEqual(d[cistr('one')], 1)
3061 self.assertEqual(d[cistr('tWo')], 2)
3062 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00003063 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003064 self.assertEqual(d.get(cistr('thrEE')), 3)
3065
3066 def test_classic_comparisons(self):
3067 # Testing classic comparisons...
3068 class classic:
3069 pass
3070
3071 for base in (classic, int, object):
3072 class C(base):
3073 def __init__(self, value):
3074 self.value = int(value)
3075 def __eq__(self, other):
3076 if isinstance(other, C):
3077 return self.value == other.value
3078 if isinstance(other, int) or isinstance(other, int):
3079 return self.value == other
3080 return NotImplemented
3081 def __ne__(self, other):
3082 if isinstance(other, C):
3083 return self.value != other.value
3084 if isinstance(other, int) or isinstance(other, int):
3085 return self.value != other
3086 return NotImplemented
3087 def __lt__(self, other):
3088 if isinstance(other, C):
3089 return self.value < other.value
3090 if isinstance(other, int) or isinstance(other, int):
3091 return self.value < other
3092 return NotImplemented
3093 def __le__(self, other):
3094 if isinstance(other, C):
3095 return self.value <= other.value
3096 if isinstance(other, int) or isinstance(other, int):
3097 return self.value <= other
3098 return NotImplemented
3099 def __gt__(self, other):
3100 if isinstance(other, C):
3101 return self.value > other.value
3102 if isinstance(other, int) or isinstance(other, int):
3103 return self.value > other
3104 return NotImplemented
3105 def __ge__(self, other):
3106 if isinstance(other, C):
3107 return self.value >= other.value
3108 if isinstance(other, int) or isinstance(other, int):
3109 return self.value >= other
3110 return NotImplemented
3111
3112 c1 = C(1)
3113 c2 = C(2)
3114 c3 = C(3)
3115 self.assertEqual(c1, 1)
3116 c = {1: c1, 2: c2, 3: c3}
3117 for x in 1, 2, 3:
3118 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003119 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003120 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003121 eval("x %s y" % op),
3122 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003123 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003124 eval("x %s y" % op),
3125 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003126 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003127 eval("x %s y" % op),
3128 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003129
3130 def test_rich_comparisons(self):
3131 # Testing rich comparisons...
3132 class Z(complex):
3133 pass
3134 z = Z(1)
3135 self.assertEqual(z, 1+0j)
3136 self.assertEqual(1+0j, z)
3137 class ZZ(complex):
3138 def __eq__(self, other):
3139 try:
3140 return abs(self - other) <= 1e-6
3141 except:
3142 return NotImplemented
3143 zz = ZZ(1.0000003)
3144 self.assertEqual(zz, 1+0j)
3145 self.assertEqual(1+0j, zz)
3146
3147 class classic:
3148 pass
3149 for base in (classic, int, object, list):
3150 class C(base):
3151 def __init__(self, value):
3152 self.value = int(value)
3153 def __cmp__(self_, other):
3154 self.fail("shouldn't call __cmp__")
3155 def __eq__(self, other):
3156 if isinstance(other, C):
3157 return self.value == other.value
3158 if isinstance(other, int) or isinstance(other, int):
3159 return self.value == other
3160 return NotImplemented
3161 def __ne__(self, other):
3162 if isinstance(other, C):
3163 return self.value != other.value
3164 if isinstance(other, int) or isinstance(other, int):
3165 return self.value != other
3166 return NotImplemented
3167 def __lt__(self, other):
3168 if isinstance(other, C):
3169 return self.value < other.value
3170 if isinstance(other, int) or isinstance(other, int):
3171 return self.value < other
3172 return NotImplemented
3173 def __le__(self, other):
3174 if isinstance(other, C):
3175 return self.value <= other.value
3176 if isinstance(other, int) or isinstance(other, int):
3177 return self.value <= other
3178 return NotImplemented
3179 def __gt__(self, other):
3180 if isinstance(other, C):
3181 return self.value > other.value
3182 if isinstance(other, int) or isinstance(other, int):
3183 return self.value > other
3184 return NotImplemented
3185 def __ge__(self, other):
3186 if isinstance(other, C):
3187 return self.value >= other.value
3188 if isinstance(other, int) or isinstance(other, int):
3189 return self.value >= other
3190 return NotImplemented
3191 c1 = C(1)
3192 c2 = C(2)
3193 c3 = C(3)
3194 self.assertEqual(c1, 1)
3195 c = {1: c1, 2: c2, 3: c3}
3196 for x in 1, 2, 3:
3197 for y in 1, 2, 3:
3198 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003199 self.assertEqual(eval("c[x] %s c[y]" % op),
3200 eval("x %s y" % op),
3201 "x=%d, y=%d" % (x, y))
3202 self.assertEqual(eval("c[x] %s y" % op),
3203 eval("x %s y" % op),
3204 "x=%d, y=%d" % (x, y))
3205 self.assertEqual(eval("x %s c[y]" % op),
3206 eval("x %s y" % op),
3207 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003208
3209 def test_descrdoc(self):
3210 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003211 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003212 def check(descr, what):
3213 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003214 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003215 check(complex.real, "the real part of a complex number") # member descriptor
3216
3217 def test_doc_descriptor(self):
3218 # Testing __doc__ descriptor...
3219 # SF bug 542984
3220 class DocDescr(object):
3221 def __get__(self, object, otype):
3222 if object:
3223 object = object.__class__.__name__ + ' instance'
3224 if otype:
3225 otype = otype.__name__
3226 return 'object=%s; type=%s' % (object, otype)
3227 class OldClass:
3228 __doc__ = DocDescr()
3229 class NewClass(object):
3230 __doc__ = DocDescr()
3231 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3232 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3233 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3234 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3235
3236 def test_set_class(self):
3237 # Testing __class__ assignment...
3238 class C(object): pass
3239 class D(object): pass
3240 class E(object): pass
3241 class F(D, E): pass
3242 for cls in C, D, E, F:
3243 for cls2 in C, D, E, F:
3244 x = cls()
3245 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003246 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003247 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003248 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003249 def cant(x, C):
3250 try:
3251 x.__class__ = C
3252 except TypeError:
3253 pass
3254 else:
3255 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3256 try:
3257 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003258 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003259 pass
3260 else:
3261 self.fail("shouldn't allow del %r.__class__" % x)
3262 cant(C(), list)
3263 cant(list(), C)
3264 cant(C(), 1)
3265 cant(C(), object)
3266 cant(object(), list)
3267 cant(list(), object)
3268 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003269 cant(True, int)
3270 cant(2, bool)
3271 o = object()
3272 cant(o, type(1))
3273 cant(o, type(None))
3274 del o
3275 class G(object):
3276 __slots__ = ["a", "b"]
3277 class H(object):
3278 __slots__ = ["b", "a"]
3279 class I(object):
3280 __slots__ = ["a", "b"]
3281 class J(object):
3282 __slots__ = ["c", "b"]
3283 class K(object):
3284 __slots__ = ["a", "b", "d"]
3285 class L(H):
3286 __slots__ = ["e"]
3287 class M(I):
3288 __slots__ = ["e"]
3289 class N(J):
3290 __slots__ = ["__weakref__"]
3291 class P(J):
3292 __slots__ = ["__dict__"]
3293 class Q(J):
3294 pass
3295 class R(J):
3296 __slots__ = ["__dict__", "__weakref__"]
3297
3298 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3299 x = cls()
3300 x.a = 1
3301 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003302 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003303 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3304 self.assertEqual(x.a, 1)
3305 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003306 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003307 "assigning %r as __class__ for %r silently failed" % (cls, x))
3308 self.assertEqual(x.a, 1)
3309 for cls in G, J, K, L, M, N, P, R, list, Int:
3310 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3311 if cls is cls2:
3312 continue
3313 cant(cls(), cls2)
3314
Benjamin Peterson193152c2009-04-25 01:08:45 +00003315 # Issue5283: when __class__ changes in __del__, the wrong
3316 # type gets DECREF'd.
3317 class O(object):
3318 pass
3319 class A(object):
3320 def __del__(self):
3321 self.__class__ = O
3322 l = [A() for x in range(100)]
3323 del l
3324
Georg Brandl479a7e72008-02-05 18:13:15 +00003325 def test_set_dict(self):
3326 # Testing __dict__ assignment...
3327 class C(object): pass
3328 a = C()
3329 a.__dict__ = {'b': 1}
3330 self.assertEqual(a.b, 1)
3331 def cant(x, dict):
3332 try:
3333 x.__dict__ = dict
3334 except (AttributeError, TypeError):
3335 pass
3336 else:
3337 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3338 cant(a, None)
3339 cant(a, [])
3340 cant(a, 1)
3341 del a.__dict__ # Deleting __dict__ is allowed
3342
3343 class Base(object):
3344 pass
3345 def verify_dict_readonly(x):
3346 """
3347 x has to be an instance of a class inheriting from Base.
3348 """
3349 cant(x, {})
3350 try:
3351 del x.__dict__
3352 except (AttributeError, TypeError):
3353 pass
3354 else:
3355 self.fail("shouldn't allow del %r.__dict__" % x)
3356 dict_descr = Base.__dict__["__dict__"]
3357 try:
3358 dict_descr.__set__(x, {})
3359 except (AttributeError, TypeError):
3360 pass
3361 else:
3362 self.fail("dict_descr allowed access to %r's dict" % x)
3363
3364 # Classes don't allow __dict__ assignment and have readonly dicts
3365 class Meta1(type, Base):
3366 pass
3367 class Meta2(Base, type):
3368 pass
3369 class D(object, metaclass=Meta1):
3370 pass
3371 class E(object, metaclass=Meta2):
3372 pass
3373 for cls in C, D, E:
3374 verify_dict_readonly(cls)
3375 class_dict = cls.__dict__
3376 try:
3377 class_dict["spam"] = "eggs"
3378 except TypeError:
3379 pass
3380 else:
3381 self.fail("%r's __dict__ can be modified" % cls)
3382
3383 # Modules also disallow __dict__ assignment
3384 class Module1(types.ModuleType, Base):
3385 pass
3386 class Module2(Base, types.ModuleType):
3387 pass
3388 for ModuleType in Module1, Module2:
3389 mod = ModuleType("spam")
3390 verify_dict_readonly(mod)
3391 mod.__dict__["spam"] = "eggs"
3392
3393 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003394 # (at least not any more than regular exception's __dict__ can
3395 # be deleted; on CPython it is not the case, whereas on PyPy they
3396 # can, just like any other new-style instance's __dict__.)
3397 def can_delete_dict(e):
3398 try:
3399 del e.__dict__
3400 except (TypeError, AttributeError):
3401 return False
3402 else:
3403 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003404 class Exception1(Exception, Base):
3405 pass
3406 class Exception2(Base, Exception):
3407 pass
3408 for ExceptionType in Exception, Exception1, Exception2:
3409 e = ExceptionType()
3410 e.__dict__ = {"a": 1}
3411 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003412 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003413
Georg Brandl479a7e72008-02-05 18:13:15 +00003414 def test_binary_operator_override(self):
3415 # Testing overrides of binary operations...
3416 class I(int):
3417 def __repr__(self):
3418 return "I(%r)" % int(self)
3419 def __add__(self, other):
3420 return I(int(self) + int(other))
3421 __radd__ = __add__
3422 def __pow__(self, other, mod=None):
3423 if mod is None:
3424 return I(pow(int(self), int(other)))
3425 else:
3426 return I(pow(int(self), int(other), int(mod)))
3427 def __rpow__(self, other, mod=None):
3428 if mod is None:
3429 return I(pow(int(other), int(self), mod))
3430 else:
3431 return I(pow(int(other), int(self), int(mod)))
3432
3433 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3434 self.assertEqual(repr(I(1) + 2), "I(3)")
3435 self.assertEqual(repr(1 + I(2)), "I(3)")
3436 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3437 self.assertEqual(repr(2 ** I(3)), "I(8)")
3438 self.assertEqual(repr(I(2) ** 3), "I(8)")
3439 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3440 class S(str):
3441 def __eq__(self, other):
3442 return self.lower() == other.lower()
3443
3444 def test_subclass_propagation(self):
3445 # Testing propagation of slot functions to subclasses...
3446 class A(object):
3447 pass
3448 class B(A):
3449 pass
3450 class C(A):
3451 pass
3452 class D(B, C):
3453 pass
3454 d = D()
3455 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3456 A.__hash__ = lambda self: 42
3457 self.assertEqual(hash(d), 42)
3458 C.__hash__ = lambda self: 314
3459 self.assertEqual(hash(d), 314)
3460 B.__hash__ = lambda self: 144
3461 self.assertEqual(hash(d), 144)
3462 D.__hash__ = lambda self: 100
3463 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003464 D.__hash__ = None
3465 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003466 del D.__hash__
3467 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003468 B.__hash__ = None
3469 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003470 del B.__hash__
3471 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003472 C.__hash__ = None
3473 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003474 del C.__hash__
3475 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003476 A.__hash__ = None
3477 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003478 del A.__hash__
3479 self.assertEqual(hash(d), orig_hash)
3480 d.foo = 42
3481 d.bar = 42
3482 self.assertEqual(d.foo, 42)
3483 self.assertEqual(d.bar, 42)
3484 def __getattribute__(self, name):
3485 if name == "foo":
3486 return 24
3487 return object.__getattribute__(self, name)
3488 A.__getattribute__ = __getattribute__
3489 self.assertEqual(d.foo, 24)
3490 self.assertEqual(d.bar, 42)
3491 def __getattr__(self, name):
3492 if name in ("spam", "foo", "bar"):
3493 return "hello"
3494 raise AttributeError(name)
3495 B.__getattr__ = __getattr__
3496 self.assertEqual(d.spam, "hello")
3497 self.assertEqual(d.foo, 24)
3498 self.assertEqual(d.bar, 42)
3499 del A.__getattribute__
3500 self.assertEqual(d.foo, 42)
3501 del d.foo
3502 self.assertEqual(d.foo, "hello")
3503 self.assertEqual(d.bar, 42)
3504 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003505 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003506 d.foo
3507 except AttributeError:
3508 pass
3509 else:
3510 self.fail("d.foo should be undefined now")
3511
3512 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003513 class A(object):
3514 pass
3515 class B(A):
3516 pass
3517 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003518 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003519 A.__setitem__ = lambda *a: None # crash
3520
3521 def test_buffer_inheritance(self):
3522 # Testing that buffer interface is inherited ...
3523
3524 import binascii
3525 # SF bug [#470040] ParseTuple t# vs subclasses.
3526
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003527 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003528 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003529 base = b'abc'
3530 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003531 # b2a_hex uses the buffer interface to get its argument's value, via
3532 # PyArg_ParseTuple 't#' code.
3533 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3534
Georg Brandl479a7e72008-02-05 18:13:15 +00003535 class MyInt(int):
3536 pass
3537 m = MyInt(42)
3538 try:
3539 binascii.b2a_hex(m)
3540 self.fail('subclass of int should not have a buffer interface')
3541 except TypeError:
3542 pass
3543
3544 def test_str_of_str_subclass(self):
3545 # Testing __str__ defined in subclass of str ...
3546 import binascii
3547 import io
3548
3549 class octetstring(str):
3550 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003551 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003552 def __repr__(self):
3553 return self + " repr"
3554
3555 o = octetstring('A')
3556 self.assertEqual(type(o), octetstring)
3557 self.assertEqual(type(str(o)), str)
3558 self.assertEqual(type(repr(o)), str)
3559 self.assertEqual(ord(o), 0x41)
3560 self.assertEqual(str(o), '41')
3561 self.assertEqual(repr(o), 'A repr')
3562 self.assertEqual(o.__str__(), '41')
3563 self.assertEqual(o.__repr__(), 'A repr')
3564
Georg Brandl479a7e72008-02-05 18:13:15 +00003565 def test_keyword_arguments(self):
3566 # Testing keyword arguments to __init__, __call__...
3567 def f(a): return a
3568 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003569 ba = bytearray()
3570 bytearray.__init__(ba, 'abc\xbd\u20ac',
3571 encoding='latin1', errors='replace')
3572 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003573
3574 def test_recursive_call(self):
3575 # Testing recursive __call__() by setting to instance of class...
3576 class A(object):
3577 pass
3578
3579 A.__call__ = A()
3580 try:
3581 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003582 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003583 pass
3584 else:
3585 self.fail("Recursion limit should have been reached for __call__()")
3586
3587 def test_delete_hook(self):
3588 # Testing __del__ hook...
3589 log = []
3590 class C(object):
3591 def __del__(self):
3592 log.append(1)
3593 c = C()
3594 self.assertEqual(log, [])
3595 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003596 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003597 self.assertEqual(log, [1])
3598
3599 class D(object): pass
3600 d = D()
3601 try: del d[0]
3602 except TypeError: pass
3603 else: self.fail("invalid del() didn't raise TypeError")
3604
3605 def test_hash_inheritance(self):
3606 # Testing hash of mutable subclasses...
3607
3608 class mydict(dict):
3609 pass
3610 d = mydict()
3611 try:
3612 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003613 except TypeError:
3614 pass
3615 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003616 self.fail("hash() of dict subclass should fail")
3617
3618 class mylist(list):
3619 pass
3620 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003621 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003622 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003623 except TypeError:
3624 pass
3625 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003626 self.fail("hash() of list subclass should fail")
3627
3628 def test_str_operations(self):
3629 try: 'a' + 5
3630 except TypeError: pass
3631 else: self.fail("'' + 5 doesn't raise TypeError")
3632
3633 try: ''.split('')
3634 except ValueError: pass
3635 else: self.fail("''.split('') doesn't raise ValueError")
3636
3637 try: ''.join([0])
3638 except TypeError: pass
3639 else: self.fail("''.join([0]) doesn't raise TypeError")
3640
3641 try: ''.rindex('5')
3642 except ValueError: pass
3643 else: self.fail("''.rindex('5') doesn't raise ValueError")
3644
3645 try: '%(n)s' % None
3646 except TypeError: pass
3647 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3648
3649 try: '%(n' % {}
3650 except ValueError: pass
3651 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3652
3653 try: '%*s' % ('abc')
3654 except TypeError: pass
3655 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3656
3657 try: '%*.*s' % ('abc', 5)
3658 except TypeError: pass
3659 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3660
3661 try: '%s' % (1, 2)
3662 except TypeError: pass
3663 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3664
3665 try: '%' % None
3666 except ValueError: pass
3667 else: self.fail("'%' % None doesn't raise ValueError")
3668
3669 self.assertEqual('534253'.isdigit(), 1)
3670 self.assertEqual('534253x'.isdigit(), 0)
3671 self.assertEqual('%c' % 5, '\x05')
3672 self.assertEqual('%c' % '5', '5')
3673
3674 def test_deepcopy_recursive(self):
3675 # Testing deepcopy of recursive objects...
3676 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003677 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003678 a = Node()
3679 b = Node()
3680 a.b = b
3681 b.a = a
3682 z = deepcopy(a) # This blew up before
3683
Martin Panterf05641642016-05-08 13:48:10 +00003684 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003685 # Testing uninitialized module objects...
3686 from types import ModuleType as M
3687 m = M.__new__(M)
3688 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003689 self.assertNotHasAttr(m, "__name__")
3690 self.assertNotHasAttr(m, "__file__")
3691 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003692 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003693 m.foo = 1
3694 self.assertEqual(m.__dict__, {"foo": 1})
3695
3696 def test_funny_new(self):
3697 # Testing __new__ returning something unexpected...
3698 class C(object):
3699 def __new__(cls, arg):
3700 if isinstance(arg, str): return [1, 2, 3]
3701 elif isinstance(arg, int): return object.__new__(D)
3702 else: return object.__new__(cls)
3703 class D(C):
3704 def __init__(self, arg):
3705 self.foo = arg
3706 self.assertEqual(C("1"), [1, 2, 3])
3707 self.assertEqual(D("1"), [1, 2, 3])
3708 d = D(None)
3709 self.assertEqual(d.foo, None)
3710 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003711 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003712 self.assertEqual(d.foo, 1)
3713 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003714 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003715 self.assertEqual(d.foo, 1)
3716
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003717 class C(object):
3718 @staticmethod
3719 def __new__(*args):
3720 return args
3721 self.assertEqual(C(1, 2), (C, 1, 2))
3722 class D(C):
3723 pass
3724 self.assertEqual(D(1, 2), (D, 1, 2))
3725
3726 class C(object):
3727 @classmethod
3728 def __new__(*args):
3729 return args
3730 self.assertEqual(C(1, 2), (C, C, 1, 2))
3731 class D(C):
3732 pass
3733 self.assertEqual(D(1, 2), (D, D, 1, 2))
3734
Georg Brandl479a7e72008-02-05 18:13:15 +00003735 def test_imul_bug(self):
3736 # Testing for __imul__ problems...
3737 # SF bug 544647
3738 class C(object):
3739 def __imul__(self, other):
3740 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003741 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003742 y = x
3743 y *= 1.0
3744 self.assertEqual(y, (x, 1.0))
3745 y = x
3746 y *= 2
3747 self.assertEqual(y, (x, 2))
3748 y = x
3749 y *= 3
3750 self.assertEqual(y, (x, 3))
3751 y = x
3752 y *= 1<<100
3753 self.assertEqual(y, (x, 1<<100))
3754 y = x
3755 y *= None
3756 self.assertEqual(y, (x, None))
3757 y = x
3758 y *= "foo"
3759 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003760
Georg Brandl479a7e72008-02-05 18:13:15 +00003761 def test_copy_setstate(self):
3762 # Testing that copy.*copy() correctly uses __setstate__...
3763 import copy
3764 class C(object):
3765 def __init__(self, foo=None):
3766 self.foo = foo
3767 self.__foo = foo
3768 def setfoo(self, foo=None):
3769 self.foo = foo
3770 def getfoo(self):
3771 return self.__foo
3772 def __getstate__(self):
3773 return [self.foo]
3774 def __setstate__(self_, lst):
3775 self.assertEqual(len(lst), 1)
3776 self_.__foo = self_.foo = lst[0]
3777 a = C(42)
3778 a.setfoo(24)
3779 self.assertEqual(a.foo, 24)
3780 self.assertEqual(a.getfoo(), 42)
3781 b = copy.copy(a)
3782 self.assertEqual(b.foo, 24)
3783 self.assertEqual(b.getfoo(), 24)
3784 b = copy.deepcopy(a)
3785 self.assertEqual(b.foo, 24)
3786 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003787
Georg Brandl479a7e72008-02-05 18:13:15 +00003788 def test_slices(self):
3789 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003790
Georg Brandl479a7e72008-02-05 18:13:15 +00003791 # Strings
3792 self.assertEqual("hello"[:4], "hell")
3793 self.assertEqual("hello"[slice(4)], "hell")
3794 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3795 class S(str):
3796 def __getitem__(self, x):
3797 return str.__getitem__(self, x)
3798 self.assertEqual(S("hello")[:4], "hell")
3799 self.assertEqual(S("hello")[slice(4)], "hell")
3800 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3801 # Tuples
3802 self.assertEqual((1,2,3)[:2], (1,2))
3803 self.assertEqual((1,2,3)[slice(2)], (1,2))
3804 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3805 class T(tuple):
3806 def __getitem__(self, x):
3807 return tuple.__getitem__(self, x)
3808 self.assertEqual(T((1,2,3))[:2], (1,2))
3809 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3810 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3811 # Lists
3812 self.assertEqual([1,2,3][:2], [1,2])
3813 self.assertEqual([1,2,3][slice(2)], [1,2])
3814 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3815 class L(list):
3816 def __getitem__(self, x):
3817 return list.__getitem__(self, x)
3818 self.assertEqual(L([1,2,3])[:2], [1,2])
3819 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3820 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3821 # Now do lists and __setitem__
3822 a = L([1,2,3])
3823 a[slice(1, 3)] = [3,2]
3824 self.assertEqual(a, [1,3,2])
3825 a[slice(0, 2, 1)] = [3,1]
3826 self.assertEqual(a, [3,1,2])
3827 a.__setitem__(slice(1, 3), [2,1])
3828 self.assertEqual(a, [3,2,1])
3829 a.__setitem__(slice(0, 2, 1), [2,3])
3830 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003831
Georg Brandl479a7e72008-02-05 18:13:15 +00003832 def test_subtype_resurrection(self):
3833 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003834
Georg Brandl479a7e72008-02-05 18:13:15 +00003835 class C(object):
3836 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003837
Georg Brandl479a7e72008-02-05 18:13:15 +00003838 def __del__(self):
3839 # resurrect the instance
3840 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003841
Georg Brandl479a7e72008-02-05 18:13:15 +00003842 c = C()
3843 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003844
Benjamin Petersone549ead2009-03-28 21:42:05 +00003845 # The most interesting thing here is whether this blows up, due to
3846 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3847 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003848 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003849
Benjamin Petersone549ead2009-03-28 21:42:05 +00003850 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003851 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003852
Georg Brandl479a7e72008-02-05 18:13:15 +00003853 # Make c mortal again, so that the test framework with -l doesn't report
3854 # it as a leak.
3855 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003856
Georg Brandl479a7e72008-02-05 18:13:15 +00003857 def test_slots_trash(self):
3858 # Testing slot trash...
3859 # Deallocating deeply nested slotted trash caused stack overflows
3860 class trash(object):
3861 __slots__ = ['x']
3862 def __init__(self, x):
3863 self.x = x
3864 o = None
3865 for i in range(50000):
3866 o = trash(o)
3867 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003868
Georg Brandl479a7e72008-02-05 18:13:15 +00003869 def test_slots_multiple_inheritance(self):
3870 # SF bug 575229, multiple inheritance w/ slots dumps core
3871 class A(object):
3872 __slots__=()
3873 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003874 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003875 class C(A,B) :
3876 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003877 if support.check_impl_detail():
3878 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003879 self.assertHasAttr(C, '__dict__')
3880 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003881 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003882
Georg Brandl479a7e72008-02-05 18:13:15 +00003883 def test_rmul(self):
3884 # Testing correct invocation of __rmul__...
3885 # SF patch 592646
3886 class C(object):
3887 def __mul__(self, other):
3888 return "mul"
3889 def __rmul__(self, other):
3890 return "rmul"
3891 a = C()
3892 self.assertEqual(a*2, "mul")
3893 self.assertEqual(a*2.2, "mul")
3894 self.assertEqual(2*a, "rmul")
3895 self.assertEqual(2.2*a, "rmul")
3896
3897 def test_ipow(self):
3898 # Testing correct invocation of __ipow__...
3899 # [SF bug 620179]
3900 class C(object):
3901 def __ipow__(self, other):
3902 pass
3903 a = C()
3904 a **= 2
3905
Alexcc02b4f2021-02-26 21:58:39 +02003906 def test_ipow_returns_not_implemented(self):
3907 class A:
3908 def __ipow__(self, other):
3909 return NotImplemented
3910
3911 class B(A):
3912 def __rpow__(self, other):
3913 return 1
3914
3915 class C(A):
3916 def __pow__(self, other):
3917 return 2
3918 a = A()
3919 b = B()
3920 c = C()
3921
3922 a **= b
3923 self.assertEqual(a, 1)
3924
3925 c **= b
3926 self.assertEqual(c, 2)
3927
3928 def test_no_ipow(self):
3929 class B:
3930 def __rpow__(self, other):
3931 return 1
3932
3933 a = object()
3934 b = B()
3935 a **= b
3936 self.assertEqual(a, 1)
3937
3938 def test_ipow_exception_text(self):
3939 x = None
3940 with self.assertRaises(TypeError) as cm:
3941 x **= 2
3942 self.assertIn('unsupported operand type(s) for **=', str(cm.exception))
3943
3944 with self.assertRaises(TypeError) as cm:
3945 y = x ** 2
3946 self.assertIn('unsupported operand type(s) for **', str(cm.exception))
3947
Georg Brandl479a7e72008-02-05 18:13:15 +00003948 def test_mutable_bases(self):
3949 # Testing mutable bases...
3950
3951 # stuff that should work:
3952 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003953 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003954 class C2(object):
3955 def __getattribute__(self, attr):
3956 if attr == 'a':
3957 return 2
3958 else:
3959 return super(C2, self).__getattribute__(attr)
3960 def meth(self):
3961 return 1
3962 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003963 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003964 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003965 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003966 d = D()
3967 e = E()
3968 D.__bases__ = (C,)
3969 D.__bases__ = (C2,)
3970 self.assertEqual(d.meth(), 1)
3971 self.assertEqual(e.meth(), 1)
3972 self.assertEqual(d.a, 2)
3973 self.assertEqual(e.a, 2)
3974 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003975
Georg Brandl479a7e72008-02-05 18:13:15 +00003976 try:
3977 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003978 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003979 pass
3980 else:
3981 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003982
Georg Brandl479a7e72008-02-05 18:13:15 +00003983 try:
3984 D.__bases__ = ()
3985 except TypeError as msg:
3986 if str(msg) == "a new-style class can't have only classic bases":
3987 self.fail("wrong error message for .__bases__ = ()")
3988 else:
3989 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003990
Georg Brandl479a7e72008-02-05 18:13:15 +00003991 try:
3992 D.__bases__ = (D,)
3993 except TypeError:
3994 pass
3995 else:
3996 # actually, we'll have crashed by here...
3997 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003998
Georg Brandl479a7e72008-02-05 18:13:15 +00003999 try:
4000 D.__bases__ = (C, C)
4001 except TypeError:
4002 pass
4003 else:
4004 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004005
Georg Brandl479a7e72008-02-05 18:13:15 +00004006 try:
4007 D.__bases__ = (E,)
4008 except TypeError:
4009 pass
4010 else:
4011 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00004012
Benjamin Petersonae937c02009-04-18 20:54:08 +00004013 def test_builtin_bases(self):
4014 # Make sure all the builtin types can have their base queried without
4015 # segfaulting. See issue #5787.
4016 builtin_types = [tp for tp in builtins.__dict__.values()
4017 if isinstance(tp, type)]
4018 for tp in builtin_types:
4019 object.__getattribute__(tp, "__bases__")
4020 if tp is not object:
4021 self.assertEqual(len(tp.__bases__), 1, tp)
4022
Benjamin Peterson25c95f12009-05-08 20:42:26 +00004023 class L(list):
4024 pass
4025
4026 class C(object):
4027 pass
4028
4029 class D(C):
4030 pass
4031
4032 try:
4033 L.__bases__ = (dict,)
4034 except TypeError:
4035 pass
4036 else:
4037 self.fail("shouldn't turn list subclass into dict subclass")
4038
4039 try:
4040 list.__bases__ = (dict,)
4041 except TypeError:
4042 pass
4043 else:
4044 self.fail("shouldn't be able to assign to list.__bases__")
4045
4046 try:
4047 D.__bases__ = (C, list)
4048 except TypeError:
4049 pass
4050 else:
4051 assert 0, "best_base calculation found wanting"
4052
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07004053 def test_unsubclassable_types(self):
4054 with self.assertRaises(TypeError):
4055 class X(type(None)):
4056 pass
4057 with self.assertRaises(TypeError):
4058 class X(object, type(None)):
4059 pass
4060 with self.assertRaises(TypeError):
4061 class X(type(None), object):
4062 pass
4063 class O(object):
4064 pass
4065 with self.assertRaises(TypeError):
4066 class X(O, type(None)):
4067 pass
4068 with self.assertRaises(TypeError):
4069 class X(type(None), O):
4070 pass
4071
4072 class X(object):
4073 pass
4074 with self.assertRaises(TypeError):
4075 X.__bases__ = type(None),
4076 with self.assertRaises(TypeError):
4077 X.__bases__ = object, type(None)
4078 with self.assertRaises(TypeError):
4079 X.__bases__ = type(None), object
4080 with self.assertRaises(TypeError):
4081 X.__bases__ = O, type(None)
4082 with self.assertRaises(TypeError):
4083 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00004084
Georg Brandl479a7e72008-02-05 18:13:15 +00004085 def test_mutable_bases_with_failing_mro(self):
4086 # Testing mutable bases with failing mro...
4087 class WorkOnce(type):
4088 def __new__(self, name, bases, ns):
4089 self.flag = 0
4090 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4091 def mro(self):
4092 if self.flag > 0:
4093 raise RuntimeError("bozo")
4094 else:
4095 self.flag += 1
4096 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004097
Georg Brandl479a7e72008-02-05 18:13:15 +00004098 class WorkAlways(type):
4099 def mro(self):
4100 # this is here to make sure that .mro()s aren't called
4101 # with an exception set (which was possible at one point).
4102 # An error message will be printed in a debug build.
4103 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004104 return type.mro(self)
4105
Georg Brandl479a7e72008-02-05 18:13:15 +00004106 class C(object):
4107 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004108
Georg Brandl479a7e72008-02-05 18:13:15 +00004109 class C2(object):
4110 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004111
Georg Brandl479a7e72008-02-05 18:13:15 +00004112 class D(C):
4113 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004114
Georg Brandl479a7e72008-02-05 18:13:15 +00004115 class E(D):
4116 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004117
Georg Brandl479a7e72008-02-05 18:13:15 +00004118 class F(D, metaclass=WorkOnce):
4119 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004120
Georg Brandl479a7e72008-02-05 18:13:15 +00004121 class G(D, metaclass=WorkAlways):
4122 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004123
Georg Brandl479a7e72008-02-05 18:13:15 +00004124 # Immediate subclasses have their mro's adjusted in alphabetical
4125 # order, so E's will get adjusted before adjusting F's fails. We
4126 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004127
Georg Brandl479a7e72008-02-05 18:13:15 +00004128 E_mro_before = E.__mro__
4129 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004130
Armin Rigofd163f92005-12-29 15:59:19 +00004131 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004132 D.__bases__ = (C2,)
4133 except RuntimeError:
4134 self.assertEqual(E.__mro__, E_mro_before)
4135 self.assertEqual(D.__mro__, D_mro_before)
4136 else:
4137 self.fail("exception not propagated")
4138
4139 def test_mutable_bases_catch_mro_conflict(self):
4140 # Testing mutable bases catch mro conflict...
4141 class A(object):
4142 pass
4143
4144 class B(object):
4145 pass
4146
4147 class C(A, B):
4148 pass
4149
4150 class D(A, B):
4151 pass
4152
4153 class E(C, D):
4154 pass
4155
4156 try:
4157 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004158 except TypeError:
4159 pass
4160 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004161 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004162
Georg Brandl479a7e72008-02-05 18:13:15 +00004163 def test_mutable_names(self):
4164 # Testing mutable names...
4165 class C(object):
4166 pass
4167
4168 # C.__module__ could be 'test_descr' or '__main__'
4169 mod = C.__module__
4170
4171 C.__name__ = 'D'
4172 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4173
4174 C.__name__ = 'D.E'
4175 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4176
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004177 def test_evil_type_name(self):
4178 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4179 # execution while the type structure was not in a sane state, and a
4180 # possible segmentation fault as a result. See bug #16447.
4181 class Nasty(str):
4182 def __del__(self):
4183 C.__name__ = "other"
4184
4185 class C:
4186 pass
4187
4188 C.__name__ = Nasty("abc")
4189 C.__name__ = "normal"
4190
Georg Brandl479a7e72008-02-05 18:13:15 +00004191 def test_subclass_right_op(self):
4192 # Testing correct dispatch of subclass overloading __r<op>__...
4193
4194 # This code tests various cases where right-dispatch of a subclass
4195 # should be preferred over left-dispatch of a base class.
4196
4197 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4198
4199 class B(int):
4200 def __floordiv__(self, other):
4201 return "B.__floordiv__"
4202 def __rfloordiv__(self, other):
4203 return "B.__rfloordiv__"
4204
4205 self.assertEqual(B(1) // 1, "B.__floordiv__")
4206 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4207
4208 # Case 2: subclass of object; this is just the baseline for case 3
4209
4210 class C(object):
4211 def __floordiv__(self, other):
4212 return "C.__floordiv__"
4213 def __rfloordiv__(self, other):
4214 return "C.__rfloordiv__"
4215
4216 self.assertEqual(C() // 1, "C.__floordiv__")
4217 self.assertEqual(1 // C(), "C.__rfloordiv__")
4218
4219 # Case 3: subclass of new-style class; here it gets interesting
4220
4221 class D(C):
4222 def __floordiv__(self, other):
4223 return "D.__floordiv__"
4224 def __rfloordiv__(self, other):
4225 return "D.__rfloordiv__"
4226
4227 self.assertEqual(D() // C(), "D.__floordiv__")
4228 self.assertEqual(C() // D(), "D.__rfloordiv__")
4229
4230 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4231
4232 class E(C):
4233 pass
4234
4235 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4236
4237 self.assertEqual(E() // 1, "C.__floordiv__")
4238 self.assertEqual(1 // E(), "C.__rfloordiv__")
4239 self.assertEqual(E() // C(), "C.__floordiv__")
4240 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4241
Benjamin Petersone549ead2009-03-28 21:42:05 +00004242 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004243 def test_meth_class_get(self):
4244 # Testing __get__ method of METH_CLASS C methods...
4245 # Full coverage of descrobject.c::classmethod_get()
4246
4247 # Baseline
4248 arg = [1, 2, 3]
4249 res = {1: None, 2: None, 3: None}
4250 self.assertEqual(dict.fromkeys(arg), res)
4251 self.assertEqual({}.fromkeys(arg), res)
4252
4253 # Now get the descriptor
4254 descr = dict.__dict__["fromkeys"]
4255
4256 # More baseline using the descriptor directly
4257 self.assertEqual(descr.__get__(None, dict)(arg), res)
4258 self.assertEqual(descr.__get__({})(arg), res)
4259
4260 # Now check various error cases
4261 try:
4262 descr.__get__(None, None)
4263 except TypeError:
4264 pass
4265 else:
4266 self.fail("shouldn't have allowed descr.__get__(None, None)")
4267 try:
4268 descr.__get__(42)
4269 except TypeError:
4270 pass
4271 else:
4272 self.fail("shouldn't have allowed descr.__get__(42)")
4273 try:
4274 descr.__get__(None, 42)
4275 except TypeError:
4276 pass
4277 else:
4278 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4279 try:
4280 descr.__get__(None, int)
4281 except TypeError:
4282 pass
4283 else:
4284 self.fail("shouldn't have allowed descr.__get__(None, int)")
4285
4286 def test_isinst_isclass(self):
4287 # Testing proxy isinstance() and isclass()...
4288 class Proxy(object):
4289 def __init__(self, obj):
4290 self.__obj = obj
4291 def __getattribute__(self, name):
4292 if name.startswith("_Proxy__"):
4293 return object.__getattribute__(self, name)
4294 else:
4295 return getattr(self.__obj, name)
4296 # Test with a classic class
4297 class C:
4298 pass
4299 a = C()
4300 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004301 self.assertIsInstance(a, C) # Baseline
4302 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004303 # Test with a classic subclass
4304 class D(C):
4305 pass
4306 a = D()
4307 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004308 self.assertIsInstance(a, C) # Baseline
4309 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004310 # Test with a new-style class
4311 class C(object):
4312 pass
4313 a = C()
4314 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004315 self.assertIsInstance(a, C) # Baseline
4316 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004317 # Test with a new-style subclass
4318 class D(C):
4319 pass
4320 a = D()
4321 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004322 self.assertIsInstance(a, C) # Baseline
4323 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004324
4325 def test_proxy_super(self):
4326 # Testing super() for a proxy object...
4327 class Proxy(object):
4328 def __init__(self, obj):
4329 self.__obj = obj
4330 def __getattribute__(self, name):
4331 if name.startswith("_Proxy__"):
4332 return object.__getattribute__(self, name)
4333 else:
4334 return getattr(self.__obj, name)
4335
4336 class B(object):
4337 def f(self):
4338 return "B.f"
4339
4340 class C(B):
4341 def f(self):
4342 return super(C, self).f() + "->C.f"
4343
4344 obj = C()
4345 p = Proxy(obj)
4346 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4347
4348 def test_carloverre(self):
4349 # Testing prohibition of Carlo Verre's hack...
4350 try:
4351 object.__setattr__(str, "foo", 42)
4352 except TypeError:
4353 pass
4354 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004355 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004356 try:
4357 object.__delattr__(str, "lower")
4358 except TypeError:
4359 pass
4360 else:
4361 self.fail("Carlo Verre __delattr__ succeeded!")
4362
scoderc53b3102020-07-18 23:19:50 +02004363 def test_carloverre_multi_inherit_valid(self):
4364 class A(type):
4365 def __setattr__(cls, key, value):
4366 type.__setattr__(cls, key, value)
4367
4368 class B:
4369 pass
4370
4371 class C(B, A):
4372 pass
4373
4374 obj = C('D', (object,), {})
4375 try:
4376 obj.test = True
4377 except TypeError:
4378 self.fail("setattr through direct base types should be legal")
4379
4380 def test_carloverre_multi_inherit_invalid(self):
4381 class A(type):
4382 def __setattr__(cls, key, value):
4383 object.__setattr__(cls, key, value) # this should fail!
4384
4385 class B:
4386 pass
4387
4388 class C(B, A):
4389 pass
4390
4391 obj = C('D', (object,), {})
4392 try:
4393 obj.test = True
4394 except TypeError:
4395 pass
4396 else:
4397 self.fail("setattr through indirect base types should be rejected")
4398
Georg Brandl479a7e72008-02-05 18:13:15 +00004399 def test_weakref_segfault(self):
4400 # Testing weakref segfault...
4401 # SF 742911
4402 import weakref
4403
4404 class Provoker:
4405 def __init__(self, referrent):
4406 self.ref = weakref.ref(referrent)
4407
4408 def __del__(self):
4409 x = self.ref()
4410
4411 class Oops(object):
4412 pass
4413
4414 o = Oops()
4415 o.whatever = Provoker(o)
4416 del o
4417
4418 def test_wrapper_segfault(self):
4419 # SF 927248: deeply nested wrappers could cause stack overflow
4420 f = lambda:None
4421 for i in range(1000000):
4422 f = f.__call__
4423 f = None
4424
4425 def test_file_fault(self):
4426 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004427 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004428 class StdoutGuard:
4429 def __getattr__(self, attr):
4430 sys.stdout = sys.__stdout__
4431 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4432 sys.stdout = StdoutGuard()
4433 try:
4434 print("Oops!")
4435 except RuntimeError:
4436 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004437 finally:
4438 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004439
4440 def test_vicious_descriptor_nonsense(self):
4441 # Testing vicious_descriptor_nonsense...
4442
4443 # A potential segfault spotted by Thomas Wouters in mail to
4444 # python-dev 2003-04-17, turned into an example & fixed by Michael
4445 # Hudson just less than four months later...
4446
4447 class Evil(object):
4448 def __hash__(self):
4449 return hash('attr')
4450 def __eq__(self, other):
Serhiy Storchakaff3d39f2019-02-26 08:03:21 +02004451 try:
4452 del C.attr
4453 except AttributeError:
4454 # possible race condition
4455 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00004456 return 0
4457
4458 class Descr(object):
4459 def __get__(self, ob, type=None):
4460 return 1
4461
4462 class C(object):
4463 attr = Descr()
4464
4465 c = C()
4466 c.__dict__[Evil()] = 0
4467
4468 self.assertEqual(c.attr, 1)
4469 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004470 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004471 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004472
4473 def test_init(self):
4474 # SF 1155938
4475 class Foo(object):
4476 def __init__(self):
4477 return 10
4478 try:
4479 Foo()
4480 except TypeError:
4481 pass
4482 else:
4483 self.fail("did not test __init__() for None return")
4484
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004485 def assertNotOrderable(self, a, b):
4486 with self.assertRaises(TypeError):
4487 a < b
4488 with self.assertRaises(TypeError):
4489 a > b
4490 with self.assertRaises(TypeError):
4491 a <= b
4492 with self.assertRaises(TypeError):
4493 a >= b
4494
Georg Brandl479a7e72008-02-05 18:13:15 +00004495 def test_method_wrapper(self):
4496 # Testing method-wrapper objects...
4497 # <type 'method-wrapper'> did not support any reflection before 2.5
Georg Brandl479a7e72008-02-05 18:13:15 +00004498 l = []
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004499 self.assertTrue(l.__add__ == l.__add__)
4500 self.assertFalse(l.__add__ != l.__add__)
4501 self.assertFalse(l.__add__ == [].__add__)
4502 self.assertTrue(l.__add__ != [].__add__)
4503 self.assertFalse(l.__add__ == l.__mul__)
4504 self.assertTrue(l.__add__ != l.__mul__)
4505 self.assertNotOrderable(l.__add__, l.__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004506 self.assertEqual(l.__add__.__name__, '__add__')
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004507 self.assertIs(l.__add__.__self__, l)
4508 self.assertIs(l.__add__.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004509 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004510 # hash([].__add__) should not be based on hash([])
4511 hash(l.__add__)
Georg Brandl479a7e72008-02-05 18:13:15 +00004512
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004513 def test_builtin_function_or_method(self):
4514 # Not really belonging to test_descr, but introspection and
4515 # comparison on <type 'builtin_function_or_method'> seems not
4516 # to be tested elsewhere
4517 l = []
4518 self.assertTrue(l.append == l.append)
4519 self.assertFalse(l.append != l.append)
4520 self.assertFalse(l.append == [].append)
4521 self.assertTrue(l.append != [].append)
4522 self.assertFalse(l.append == l.pop)
4523 self.assertTrue(l.append != l.pop)
4524 self.assertNotOrderable(l.append, l.append)
4525 self.assertEqual(l.append.__name__, 'append')
4526 self.assertIs(l.append.__self__, l)
4527 # self.assertIs(l.append.__objclass__, list) --- could be added?
4528 self.assertEqual(l.append.__doc__, list.append.__doc__)
4529 # hash([].append) should not be based on hash([])
4530 hash(l.append)
4531
4532 def test_special_unbound_method_types(self):
4533 # Testing objects of <type 'wrapper_descriptor'>...
4534 self.assertTrue(list.__add__ == list.__add__)
4535 self.assertFalse(list.__add__ != list.__add__)
4536 self.assertFalse(list.__add__ == list.__mul__)
4537 self.assertTrue(list.__add__ != list.__mul__)
4538 self.assertNotOrderable(list.__add__, list.__add__)
4539 self.assertEqual(list.__add__.__name__, '__add__')
4540 self.assertIs(list.__add__.__objclass__, list)
4541
4542 # Testing objects of <type 'method_descriptor'>...
4543 self.assertTrue(list.append == list.append)
4544 self.assertFalse(list.append != list.append)
4545 self.assertFalse(list.append == list.pop)
4546 self.assertTrue(list.append != list.pop)
4547 self.assertNotOrderable(list.append, list.append)
4548 self.assertEqual(list.append.__name__, 'append')
4549 self.assertIs(list.append.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004550
4551 def test_not_implemented(self):
4552 # Testing NotImplemented...
4553 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004554 import operator
4555
4556 def specialmethod(self, other):
4557 return NotImplemented
4558
4559 def check(expr, x, y):
4560 try:
4561 exec(expr, {'x': x, 'y': y, 'operator': operator})
4562 except TypeError:
4563 pass
4564 else:
4565 self.fail("no TypeError from %r" % (expr,))
4566
4567 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4568 # TypeErrors
4569 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4570 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004571 for name, expr, iexpr in [
4572 ('__add__', 'x + y', 'x += y'),
4573 ('__sub__', 'x - y', 'x -= y'),
4574 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004575 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004576 ('__truediv__', 'x / y', 'x /= y'),
4577 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004578 ('__mod__', 'x % y', 'x %= y'),
4579 ('__divmod__', 'divmod(x, y)', None),
4580 ('__pow__', 'x ** y', 'x **= y'),
4581 ('__lshift__', 'x << y', 'x <<= y'),
4582 ('__rshift__', 'x >> y', 'x >>= y'),
4583 ('__and__', 'x & y', 'x &= y'),
4584 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004585 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004586 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004587 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004588 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004589 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004590 check(expr, a, N1)
4591 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004592 if iexpr:
4593 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004594 check(iexpr, a, N1)
4595 check(iexpr, a, N2)
4596 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004597 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004598 c = C()
4599 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004600 check(iexpr, c, N1)
4601 check(iexpr, c, N2)
4602
Georg Brandl479a7e72008-02-05 18:13:15 +00004603 def test_assign_slice(self):
4604 # ceval.c's assign_slice used to check for
4605 # tp->tp_as_sequence->sq_slice instead of
4606 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004607
Georg Brandl479a7e72008-02-05 18:13:15 +00004608 class C(object):
4609 def __setitem__(self, idx, value):
4610 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004611
Georg Brandl479a7e72008-02-05 18:13:15 +00004612 c = C()
4613 c[1:2] = 3
4614 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004615
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004616 def test_set_and_no_get(self):
4617 # See
4618 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4619 class Descr(object):
4620
4621 def __init__(self, name):
4622 self.name = name
4623
4624 def __set__(self, obj, value):
4625 obj.__dict__[self.name] = value
4626 descr = Descr("a")
4627
4628 class X(object):
4629 a = descr
4630
4631 x = X()
4632 self.assertIs(x.a, descr)
4633 x.a = 42
4634 self.assertEqual(x.a, 42)
4635
Benjamin Peterson21896a32010-03-21 22:03:03 +00004636 # Also check type_getattro for correctness.
4637 class Meta(type):
4638 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004639 class X(metaclass=Meta):
4640 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004641 X.a = 42
4642 Meta.a = Descr("a")
4643 self.assertEqual(X.a, 42)
4644
Benjamin Peterson9262b842008-11-17 22:45:50 +00004645 def test_getattr_hooks(self):
4646 # issue 4230
4647
4648 class Descriptor(object):
4649 counter = 0
4650 def __get__(self, obj, objtype=None):
4651 def getter(name):
4652 self.counter += 1
4653 raise AttributeError(name)
4654 return getter
4655
4656 descr = Descriptor()
4657 class A(object):
4658 __getattribute__ = descr
4659 class B(object):
4660 __getattr__ = descr
4661 class C(object):
4662 __getattribute__ = descr
4663 __getattr__ = descr
4664
4665 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004666 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004667 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004668 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004669 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004670 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004671
Benjamin Peterson9262b842008-11-17 22:45:50 +00004672 class EvilGetattribute(object):
4673 # This used to segfault
4674 def __getattr__(self, name):
4675 raise AttributeError(name)
4676 def __getattribute__(self, name):
4677 del EvilGetattribute.__getattr__
4678 for i in range(5):
4679 gc.collect()
4680 raise AttributeError(name)
4681
4682 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4683
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004684 def test_type___getattribute__(self):
4685 self.assertRaises(TypeError, type.__getattribute__, list, type)
4686
Benjamin Peterson477ba912011-01-12 15:34:01 +00004687 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004688 # type pretends not to have __abstractmethods__.
4689 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4690 class meta(type):
4691 pass
4692 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004693 class X(object):
4694 pass
4695 with self.assertRaises(AttributeError):
4696 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004697
Victor Stinner3249dec2011-05-01 23:19:15 +02004698 def test_proxy_call(self):
4699 class FakeStr:
4700 __class__ = str
4701
4702 fake_str = FakeStr()
4703 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004704 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004705
4706 # call a method descriptor
4707 with self.assertRaises(TypeError):
4708 str.split(fake_str)
4709
4710 # call a slot wrapper descriptor
4711 with self.assertRaises(TypeError):
4712 str.__add__(fake_str, "abc")
4713
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004714 def test_repr_as_str(self):
4715 # Issue #11603: crash or infinite loop when rebinding __str__ as
4716 # __repr__.
4717 class Foo:
4718 pass
4719 Foo.__repr__ = Foo.__str__
4720 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004721 self.assertRaises(RecursionError, str, foo)
4722 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004723
4724 def test_mixing_slot_wrappers(self):
4725 class X(dict):
4726 __setattr__ = dict.__setitem__
Jeroen Demeyer2e9954d2019-06-17 13:53:21 +02004727 __neg__ = dict.copy
Benjamin Peterson7b166872012-04-24 11:06:25 -04004728 x = X()
4729 x.y = 42
4730 self.assertEqual(x["y"], 42)
Jeroen Demeyer2e9954d2019-06-17 13:53:21 +02004731 self.assertEqual(x, -x)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004732
Jeroen Demeyer57ea3352019-09-10 13:21:57 +02004733 def test_wrong_class_slot_wrapper(self):
4734 # Check bpo-37619: a wrapper descriptor taken from the wrong class
4735 # should raise an exception instead of silently being ignored
4736 class A(int):
4737 __eq__ = str.__eq__
4738 __add__ = str.__add__
4739 a = A()
4740 with self.assertRaises(TypeError):
4741 a == a
4742 with self.assertRaises(TypeError):
4743 a + a
4744
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004745 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004746 with self.assertRaises(ValueError) as cm:
4747 class X:
4748 __slots__ = ["foo"]
4749 foo = None
4750 m = str(cm.exception)
4751 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4752
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004753 def test_set_doc(self):
4754 class X:
4755 "elephant"
4756 X.__doc__ = "banana"
4757 self.assertEqual(X.__doc__, "banana")
4758 with self.assertRaises(TypeError) as cm:
4759 type(list).__dict__["__doc__"].__set__(list, "blah")
4760 self.assertIn("can't set list.__doc__", str(cm.exception))
4761 with self.assertRaises(TypeError) as cm:
4762 type(X).__dict__["__doc__"].__delete__(X)
4763 self.assertIn("can't delete X.__doc__", str(cm.exception))
4764 self.assertEqual(X.__doc__, "banana")
4765
Antoine Pitrou9d574812011-12-12 13:47:25 +01004766 def test_qualname(self):
4767 descriptors = [str.lower, complex.real, float.real, int.__add__]
4768 types = ['method', 'member', 'getset', 'wrapper']
4769
4770 # make sure we have an example of each type of descriptor
4771 for d, n in zip(descriptors, types):
4772 self.assertEqual(type(d).__name__, n + '_descriptor')
4773
4774 for d in descriptors:
4775 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4776 self.assertEqual(d.__qualname__, qualname)
4777
4778 self.assertEqual(str.lower.__qualname__, 'str.lower')
4779 self.assertEqual(complex.real.__qualname__, 'complex.real')
4780 self.assertEqual(float.real.__qualname__, 'float.real')
4781 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4782
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004783 class X:
4784 pass
4785 with self.assertRaises(TypeError):
4786 del X.__qualname__
4787
4788 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4789 str, 'Oink')
4790
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004791 global Y
4792 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004793 class Inside:
4794 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004795 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004796 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004797
Victor Stinner6f738742012-02-25 01:22:36 +01004798 def test_qualname_dict(self):
4799 ns = {'__qualname__': 'some.name'}
4800 tp = type('Foo', (), ns)
4801 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004802 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004803 self.assertEqual(ns, {'__qualname__': 'some.name'})
4804
4805 ns = {'__qualname__': 1}
4806 self.assertRaises(TypeError, type, 'Foo', (), ns)
4807
Benjamin Peterson52c42432012-03-07 18:41:11 -06004808 def test_cycle_through_dict(self):
4809 # See bug #1469629
4810 class X(dict):
4811 def __init__(self):
4812 dict.__init__(self)
4813 self.__dict__ = self
4814 x = X()
4815 x.attr = 42
4816 wr = weakref.ref(x)
4817 del x
4818 support.gc_collect()
4819 self.assertIsNone(wr())
4820 for o in gc.get_objects():
4821 self.assertIsNot(type(o), X)
4822
Benjamin Peterson96384b92012-03-17 00:05:44 -05004823 def test_object_new_and_init_with_parameters(self):
4824 # See issue #1683368
4825 class OverrideNeither:
4826 pass
4827 self.assertRaises(TypeError, OverrideNeither, 1)
4828 self.assertRaises(TypeError, OverrideNeither, kw=1)
4829 class OverrideNew:
4830 def __new__(cls, foo, kw=0, *args, **kwds):
4831 return object.__new__(cls, *args, **kwds)
4832 class OverrideInit:
4833 def __init__(self, foo, kw=0, *args, **kwargs):
4834 return object.__init__(self, *args, **kwargs)
4835 class OverrideBoth(OverrideNew, OverrideInit):
4836 pass
4837 for case in OverrideNew, OverrideInit, OverrideBoth:
4838 case(1)
4839 case(1, kw=2)
4840 self.assertRaises(TypeError, case, 1, 2, 3)
4841 self.assertRaises(TypeError, case, 1, 2, foo=3)
4842
Benjamin Petersondf813792014-03-17 15:57:17 -05004843 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4844 class Base:
4845 pass
4846 class Sub(Base):
4847 pass
4848 self.assertIn("__dict__", Base.__dict__)
4849 self.assertNotIn("__dict__", Sub.__dict__)
4850
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004851 def test_bound_method_repr(self):
4852 class Foo:
4853 def method(self):
4854 pass
4855 self.assertRegex(repr(Foo().method),
4856 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4857
4858
4859 class Base:
4860 def method(self):
4861 pass
4862 class Derived1(Base):
4863 pass
4864 class Derived2(Base):
4865 def method(self):
4866 pass
4867 base = Base()
4868 derived1 = Derived1()
4869 derived2 = Derived2()
4870 super_d2 = super(Derived2, derived2)
4871 self.assertRegex(repr(base.method),
4872 r"<bound method .*Base\.method of <.*Base object at .*>>")
4873 self.assertRegex(repr(derived1.method),
4874 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4875 self.assertRegex(repr(derived2.method),
4876 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4877 self.assertRegex(repr(super_d2.method),
4878 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4879
4880 class Foo:
4881 @classmethod
4882 def method(cls):
4883 pass
4884 foo = Foo()
4885 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004886 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004887 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004888 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004889
4890
4891 class MyCallable:
4892 def __call__(self, arg):
4893 pass
4894 func = MyCallable() # func has no __name__ or __qualname__ attributes
4895 instance = object()
4896 method = types.MethodType(func, instance)
4897 self.assertRegex(repr(method),
4898 r"<bound method \? of <object object at .*>>")
4899 func.__name__ = "name"
4900 self.assertRegex(repr(method),
4901 r"<bound method name of <object object at .*>>")
4902 func.__qualname__ = "qualname"
4903 self.assertRegex(repr(method),
4904 r"<bound method qualname of <object object at .*>>")
4905
jdemeyer5a306202018-10-19 23:50:06 +02004906 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4907 def test_bpo25750(self):
4908 # bpo-25750: calling a descriptor (implemented as built-in
4909 # function with METH_FASTCALL) should not crash CPython if the
4910 # descriptor deletes itself from the class.
4911 class Descr:
4912 __get__ = _testcapi.bad_get
4913
4914 class X:
4915 descr = Descr()
4916 def __new__(cls):
4917 cls.descr = None
4918 # Create this large list to corrupt some unused memory
4919 cls.lst = [2**i for i in range(10000)]
4920 X.descr
4921
Antoine Pitrou9d574812011-12-12 13:47:25 +01004922
Georg Brandl479a7e72008-02-05 18:13:15 +00004923class DictProxyTests(unittest.TestCase):
4924 def setUp(self):
4925 class C(object):
4926 def meth(self):
4927 pass
4928 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004929
Brett Cannon7a540732011-02-22 03:04:06 +00004930 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4931 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004932 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004933 # Testing dict-proxy keys...
4934 it = self.C.__dict__.keys()
4935 self.assertNotIsInstance(it, list)
4936 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004937 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004938 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004939 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004940
Brett Cannon7a540732011-02-22 03:04:06 +00004941 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4942 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004943 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004944 # Testing dict-proxy values...
4945 it = self.C.__dict__.values()
4946 self.assertNotIsInstance(it, list)
4947 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004948 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004949
Brett Cannon7a540732011-02-22 03:04:06 +00004950 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4951 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004952 def test_iter_items(self):
4953 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004954 it = self.C.__dict__.items()
4955 self.assertNotIsInstance(it, list)
4956 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004957 keys.sort()
4958 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004959 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004960
Georg Brandl479a7e72008-02-05 18:13:15 +00004961 def test_dict_type_with_metaclass(self):
4962 # Testing type of __dict__ when metaclass set...
4963 class B(object):
4964 pass
4965 class M(type):
4966 pass
4967 class C(metaclass=M):
4968 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4969 pass
4970 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004971
Ezio Melottiac53ab62010-12-18 14:59:43 +00004972 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004973 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004974 # We can't blindly compare with the repr of another dict as ordering
4975 # of keys and values is arbitrary and may differ.
4976 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004977 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004978 self.assertTrue(r.endswith(')'), r)
4979 for k, v in self.C.__dict__.items():
4980 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004981
Christian Heimesbbffeb62008-01-24 09:42:52 +00004982
Georg Brandl479a7e72008-02-05 18:13:15 +00004983class PTypesLongInitTest(unittest.TestCase):
4984 # This is in its own TestCase so that it can be run before any other tests.
4985 def test_pytype_long_ready(self):
4986 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004987
Georg Brandl479a7e72008-02-05 18:13:15 +00004988 # This dumps core when SF bug 551412 isn't fixed --
4989 # but only when test_descr.py is run separately.
4990 # (That can't be helped -- as soon as PyType_Ready()
4991 # is called for PyLong_Type, the bug is gone.)
4992 class UserLong(object):
4993 def __pow__(self, *args):
4994 pass
4995 try:
4996 pow(0, UserLong(), 0)
4997 except:
4998 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004999
Georg Brandl479a7e72008-02-05 18:13:15 +00005000 # Another segfault only when run early
5001 # (before PyType_Ready(tuple) is called)
5002 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00005003
5004
Victor Stinnerd74782b2012-03-09 00:39:08 +01005005class MiscTests(unittest.TestCase):
5006 def test_type_lookup_mro_reference(self):
5007 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
5008 # the type MRO because it may be modified during the lookup, if
5009 # __bases__ is set during the lookup for example.
5010 class MyKey(object):
5011 def __hash__(self):
5012 return hash('mykey')
5013
5014 def __eq__(self, other):
5015 X.__bases__ = (Base2,)
5016
5017 class Base(object):
5018 mykey = 'from Base'
5019 mykey2 = 'from Base'
5020
5021 class Base2(object):
5022 mykey = 'from Base2'
5023 mykey2 = 'from Base2'
5024
5025 X = type('X', (Base,), {MyKey(): 5})
5026 # mykey is read from Base
5027 self.assertEqual(X.mykey, 'from Base')
5028 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
5029 self.assertEqual(X.mykey2, 'from Base2')
5030
5031
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005032class PicklingTests(unittest.TestCase):
5033
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005034 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005035 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02005036 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005037 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02005038 if kwargs:
5039 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
5040 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005041 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02005042 self.assertEqual(reduce_value[0], copyreg.__newobj__)
5043 self.assertEqual(reduce_value[1], (type(obj),) + args)
5044 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005045 if listitems is not None:
5046 self.assertListEqual(list(reduce_value[3]), listitems)
5047 else:
5048 self.assertIsNone(reduce_value[3])
5049 if dictitems is not None:
5050 self.assertDictEqual(dict(reduce_value[4]), dictitems)
5051 else:
5052 self.assertIsNone(reduce_value[4])
5053 else:
5054 base_type = type(obj).__base__
5055 reduce_value = (copyreg._reconstructor,
5056 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005057 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005058 None if base_type is object else base_type(obj)))
5059 if state is not None:
5060 reduce_value += (state,)
5061 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
5062 self.assertEqual(obj.__reduce__(), reduce_value)
5063
5064 def test_reduce(self):
5065 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5066 args = (-101, "spam")
5067 kwargs = {'bacon': -201, 'fish': -301}
5068 state = {'cheese': -401}
5069
5070 class C1:
5071 def __getnewargs__(self):
5072 return args
5073 obj = C1()
5074 for proto in protocols:
5075 self._check_reduce(proto, obj, args)
5076
5077 for name, value in state.items():
5078 setattr(obj, name, value)
5079 for proto in protocols:
5080 self._check_reduce(proto, obj, args, state=state)
5081
5082 class C2:
5083 def __getnewargs__(self):
5084 return "bad args"
5085 obj = C2()
5086 for proto in protocols:
5087 if proto >= 2:
5088 with self.assertRaises(TypeError):
5089 obj.__reduce_ex__(proto)
5090
5091 class C3:
5092 def __getnewargs_ex__(self):
5093 return (args, kwargs)
5094 obj = C3()
5095 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03005096 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005097 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005098
5099 class C4:
5100 def __getnewargs_ex__(self):
5101 return (args, "bad dict")
5102 class C5:
5103 def __getnewargs_ex__(self):
5104 return ("bad tuple", kwargs)
5105 class C6:
5106 def __getnewargs_ex__(self):
5107 return ()
5108 class C7:
5109 def __getnewargs_ex__(self):
5110 return "bad args"
5111 for proto in protocols:
5112 for cls in C4, C5, C6, C7:
5113 obj = cls()
5114 if proto >= 2:
5115 with self.assertRaises((TypeError, ValueError)):
5116 obj.__reduce_ex__(proto)
5117
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005118 class C9:
5119 def __getnewargs_ex__(self):
5120 return (args, {})
5121 obj = C9()
5122 for proto in protocols:
5123 self._check_reduce(proto, obj, args)
5124
5125 class C10:
5126 def __getnewargs_ex__(self):
5127 raise IndexError
5128 obj = C10()
5129 for proto in protocols:
5130 if proto >= 2:
5131 with self.assertRaises(IndexError):
5132 obj.__reduce_ex__(proto)
5133
5134 class C11:
5135 def __getstate__(self):
5136 return state
5137 obj = C11()
5138 for proto in protocols:
5139 self._check_reduce(proto, obj, state=state)
5140
5141 class C12:
5142 def __getstate__(self):
5143 return "not dict"
5144 obj = C12()
5145 for proto in protocols:
5146 self._check_reduce(proto, obj, state="not dict")
5147
5148 class C13:
5149 def __getstate__(self):
5150 raise IndexError
5151 obj = C13()
5152 for proto in protocols:
5153 with self.assertRaises(IndexError):
5154 obj.__reduce_ex__(proto)
5155 if proto < 2:
5156 with self.assertRaises(IndexError):
5157 obj.__reduce__()
5158
5159 class C14:
5160 __slots__ = tuple(state)
5161 def __init__(self):
5162 for name, value in state.items():
5163 setattr(self, name, value)
5164
5165 obj = C14()
5166 for proto in protocols:
5167 if proto >= 2:
5168 self._check_reduce(proto, obj, state=(None, state))
5169 else:
5170 with self.assertRaises(TypeError):
5171 obj.__reduce_ex__(proto)
5172 with self.assertRaises(TypeError):
5173 obj.__reduce__()
5174
5175 class C15(dict):
5176 pass
5177 obj = C15({"quebec": -601})
5178 for proto in protocols:
5179 self._check_reduce(proto, obj, dictitems=dict(obj))
5180
5181 class C16(list):
5182 pass
5183 obj = C16(["yukon"])
5184 for proto in protocols:
5185 self._check_reduce(proto, obj, listitems=list(obj))
5186
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005187 def test_special_method_lookup(self):
5188 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5189 class Picky:
5190 def __getstate__(self):
5191 return {}
5192
5193 def __getattr__(self, attr):
5194 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5195 raise AssertionError(attr)
5196 return None
5197 for protocol in protocols:
5198 state = {} if protocol >= 2 else None
5199 self._check_reduce(protocol, Picky(), state=state)
5200
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005201 def _assert_is_copy(self, obj, objcopy, msg=None):
5202 """Utility method to verify if two objects are copies of each others.
5203 """
5204 if msg is None:
5205 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5206 if type(obj).__repr__ is object.__repr__:
5207 # We have this limitation for now because we use the object's repr
5208 # to help us verify that the two objects are copies. This allows
5209 # us to delegate the non-generic verification logic to the objects
5210 # themselves.
5211 raise ValueError("object passed to _assert_is_copy must " +
5212 "override the __repr__ method.")
5213 self.assertIsNot(obj, objcopy, msg=msg)
5214 self.assertIs(type(obj), type(objcopy), msg=msg)
5215 if hasattr(obj, '__dict__'):
5216 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5217 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5218 if hasattr(obj, '__slots__'):
5219 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5220 for slot in obj.__slots__:
5221 self.assertEqual(
5222 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5223 self.assertEqual(getattr(obj, slot, None),
5224 getattr(objcopy, slot, None), msg=msg)
5225 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5226
5227 @staticmethod
5228 def _generate_pickle_copiers():
5229 """Utility method to generate the many possible pickle configurations.
5230 """
5231 class PickleCopier:
5232 "This class copies object using pickle."
5233 def __init__(self, proto, dumps, loads):
5234 self.proto = proto
5235 self.dumps = dumps
5236 self.loads = loads
5237 def copy(self, obj):
5238 return self.loads(self.dumps(obj, self.proto))
5239 def __repr__(self):
5240 # We try to be as descriptive as possible here since this is
5241 # the string which we will allow us to tell the pickle
5242 # configuration we are using during debugging.
5243 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5244 .format(self.proto,
5245 self.dumps.__module__, self.dumps.__qualname__,
5246 self.loads.__module__, self.loads.__qualname__))
5247 return (PickleCopier(*args) for args in
5248 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5249 {pickle.dumps, pickle._dumps},
5250 {pickle.loads, pickle._loads}))
5251
5252 def test_pickle_slots(self):
5253 # Tests pickling of classes with __slots__.
5254
5255 # Pickling of classes with __slots__ but without __getstate__ should
5256 # fail (if using protocol 0 or 1)
5257 global C
5258 class C:
5259 __slots__ = ['a']
5260 with self.assertRaises(TypeError):
5261 pickle.dumps(C(), 0)
5262
5263 global D
5264 class D(C):
5265 pass
5266 with self.assertRaises(TypeError):
5267 pickle.dumps(D(), 0)
5268
5269 class C:
5270 "A class with __getstate__ and __setstate__ implemented."
5271 __slots__ = ['a']
5272 def __getstate__(self):
5273 state = getattr(self, '__dict__', {}).copy()
5274 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005275 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005276 try:
5277 state[slot] = getattr(self, slot)
5278 except AttributeError:
5279 pass
5280 return state
5281 def __setstate__(self, state):
5282 for k, v in state.items():
5283 setattr(self, k, v)
5284 def __repr__(self):
5285 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5286
5287 class D(C):
5288 "A subclass of a class with slots."
5289 pass
5290
5291 global E
5292 class E(C):
5293 "A subclass with an extra slot."
5294 __slots__ = ['b']
5295
5296 # Now it should work
5297 for pickle_copier in self._generate_pickle_copiers():
5298 with self.subTest(pickle_copier=pickle_copier):
5299 x = C()
5300 y = pickle_copier.copy(x)
5301 self._assert_is_copy(x, y)
5302
5303 x.a = 42
5304 y = pickle_copier.copy(x)
5305 self._assert_is_copy(x, y)
5306
5307 x = D()
5308 x.a = 42
5309 x.b = 100
5310 y = pickle_copier.copy(x)
5311 self._assert_is_copy(x, y)
5312
5313 x = E()
5314 x.a = 42
5315 x.b = "foo"
5316 y = pickle_copier.copy(x)
5317 self._assert_is_copy(x, y)
5318
5319 def test_reduce_copying(self):
5320 # Tests pickling and copying new-style classes and objects.
5321 global C1
5322 class C1:
5323 "The state of this class is copyable via its instance dict."
5324 ARGS = (1, 2)
5325 NEED_DICT_COPYING = True
5326 def __init__(self, a, b):
5327 super().__init__()
5328 self.a = a
5329 self.b = b
5330 def __repr__(self):
5331 return "C1(%r, %r)" % (self.a, self.b)
5332
5333 global C2
5334 class C2(list):
5335 "A list subclass copyable via __getnewargs__."
5336 ARGS = (1, 2)
5337 NEED_DICT_COPYING = False
5338 def __new__(cls, a, b):
5339 self = super().__new__(cls)
5340 self.a = a
5341 self.b = b
5342 return self
5343 def __init__(self, *args):
5344 super().__init__()
5345 # This helps testing that __init__ is not called during the
5346 # unpickling process, which would cause extra appends.
5347 self.append("cheese")
5348 @classmethod
5349 def __getnewargs__(cls):
5350 return cls.ARGS
5351 def __repr__(self):
5352 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5353
5354 global C3
5355 class C3(list):
5356 "A list subclass copyable via __getstate__."
5357 ARGS = (1, 2)
5358 NEED_DICT_COPYING = False
5359 def __init__(self, a, b):
5360 self.a = a
5361 self.b = b
5362 # This helps testing that __init__ is not called during the
5363 # unpickling process, which would cause extra appends.
5364 self.append("cheese")
5365 @classmethod
5366 def __getstate__(cls):
5367 return cls.ARGS
5368 def __setstate__(self, state):
5369 a, b = state
5370 self.a = a
5371 self.b = b
5372 def __repr__(self):
5373 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5374
5375 global C4
5376 class C4(int):
5377 "An int subclass copyable via __getnewargs__."
5378 ARGS = ("hello", "world", 1)
5379 NEED_DICT_COPYING = False
5380 def __new__(cls, a, b, value):
5381 self = super().__new__(cls, value)
5382 self.a = a
5383 self.b = b
5384 return self
5385 @classmethod
5386 def __getnewargs__(cls):
5387 return cls.ARGS
5388 def __repr__(self):
5389 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5390
5391 global C5
5392 class C5(int):
5393 "An int subclass copyable via __getnewargs_ex__."
5394 ARGS = (1, 2)
5395 KWARGS = {'value': 3}
5396 NEED_DICT_COPYING = False
5397 def __new__(cls, a, b, *, value=0):
5398 self = super().__new__(cls, value)
5399 self.a = a
5400 self.b = b
5401 return self
5402 @classmethod
5403 def __getnewargs_ex__(cls):
5404 return (cls.ARGS, cls.KWARGS)
5405 def __repr__(self):
5406 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5407
5408 test_classes = (C1, C2, C3, C4, C5)
5409 # Testing copying through pickle
5410 pickle_copiers = self._generate_pickle_copiers()
5411 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5412 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5413 kwargs = getattr(cls, 'KWARGS', {})
5414 obj = cls(*cls.ARGS, **kwargs)
5415 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005416 objcopy = pickle_copier.copy(obj)
5417 self._assert_is_copy(obj, objcopy)
5418 # For test classes that supports this, make sure we didn't go
5419 # around the reduce protocol by simply copying the attribute
5420 # dictionary. We clear attributes using the previous copy to
5421 # not mutate the original argument.
5422 if proto >= 2 and not cls.NEED_DICT_COPYING:
5423 objcopy.__dict__.clear()
5424 objcopy2 = pickle_copier.copy(objcopy)
5425 self._assert_is_copy(obj, objcopy2)
5426
5427 # Testing copying through copy.deepcopy()
5428 for cls in test_classes:
5429 with self.subTest(cls=cls):
5430 kwargs = getattr(cls, 'KWARGS', {})
5431 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005432 objcopy = deepcopy(obj)
5433 self._assert_is_copy(obj, objcopy)
5434 # For test classes that supports this, make sure we didn't go
5435 # around the reduce protocol by simply copying the attribute
5436 # dictionary. We clear attributes using the previous copy to
5437 # not mutate the original argument.
5438 if not cls.NEED_DICT_COPYING:
5439 objcopy.__dict__.clear()
5440 objcopy2 = deepcopy(objcopy)
5441 self._assert_is_copy(obj, objcopy2)
5442
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005443 def test_issue24097(self):
5444 # Slot name is freed inside __getattr__ and is later used.
5445 class S(str): # Not interned
5446 pass
5447 class A:
5448 __slotnames__ = [S('spam')]
5449 def __getattr__(self, attr):
5450 if attr == 'spam':
5451 A.__slotnames__[:] = [S('spam')]
5452 return 42
5453 else:
5454 raise AttributeError
5455
5456 import copyreg
5457 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005458 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5459
5460 def test_object_reduce(self):
5461 # Issue #29914
5462 # __reduce__() takes no arguments
5463 object().__reduce__()
5464 with self.assertRaises(TypeError):
5465 object().__reduce__(0)
5466 # __reduce_ex__() takes one integer argument
5467 object().__reduce_ex__(0)
5468 with self.assertRaises(TypeError):
5469 object().__reduce_ex__()
5470 with self.assertRaises(TypeError):
5471 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005472
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005473
Benjamin Peterson2a605342014-03-17 16:20:12 -05005474class SharedKeyTests(unittest.TestCase):
5475
5476 @support.cpython_only
5477 def test_subclasses(self):
5478 # Verify that subclasses can share keys (per PEP 412)
5479 class A:
5480 pass
5481 class B(A):
5482 pass
5483
5484 a, b = A(), B()
5485 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
Inada Naokif2a18672019-03-12 17:25:44 +09005486 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005487 # Initial hash table can contain at most 5 elements.
5488 # Set 6 attributes to cause internal resizing.
5489 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005490 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5491 a2 = A()
5492 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
Inada Naokif2a18672019-03-12 17:25:44 +09005493 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005494 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Inada Naokif2a18672019-03-12 17:25:44 +09005495 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
Benjamin Peterson2a605342014-03-17 16:20:12 -05005496
5497
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005498class DebugHelperMeta(type):
5499 """
5500 Sets default __doc__ and simplifies repr() output.
5501 """
5502 def __new__(mcls, name, bases, attrs):
5503 if attrs.get('__doc__') is None:
5504 attrs['__doc__'] = name # helps when debugging with gdb
5505 return type.__new__(mcls, name, bases, attrs)
5506 def __repr__(cls):
5507 return repr(cls.__name__)
5508
5509
5510class MroTest(unittest.TestCase):
5511 """
5512 Regressions for some bugs revealed through
5513 mcsl.mro() customization (typeobject.c: mro_internal()) and
5514 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5515 """
5516
5517 def setUp(self):
5518 self.step = 0
5519 self.ready = False
5520
5521 def step_until(self, limit):
5522 ret = (self.step < limit)
5523 if ret:
5524 self.step += 1
5525 return ret
5526
5527 def test_incomplete_set_bases_on_self(self):
5528 """
5529 type_set_bases must be aware that type->tp_mro can be NULL.
5530 """
5531 class M(DebugHelperMeta):
5532 def mro(cls):
5533 if self.step_until(1):
5534 assert cls.__mro__ is None
5535 cls.__bases__ += ()
5536
5537 return type.mro(cls)
5538
5539 class A(metaclass=M):
5540 pass
5541
5542 def test_reent_set_bases_on_base(self):
5543 """
5544 Deep reentrancy must not over-decref old_mro.
5545 """
5546 class M(DebugHelperMeta):
5547 def mro(cls):
5548 if cls.__mro__ is not None and cls.__name__ == 'B':
5549 # 4-5 steps are usually enough to make it crash somewhere
5550 if self.step_until(10):
5551 A.__bases__ += ()
5552
5553 return type.mro(cls)
5554
5555 class A(metaclass=M):
5556 pass
5557 class B(A):
5558 pass
5559 B.__bases__ += ()
5560
5561 def test_reent_set_bases_on_direct_base(self):
5562 """
5563 Similar to test_reent_set_bases_on_base, but may crash differently.
5564 """
5565 class M(DebugHelperMeta):
5566 def mro(cls):
5567 base = cls.__bases__[0]
5568 if base is not object:
5569 if self.step_until(5):
5570 base.__bases__ += ()
5571
5572 return type.mro(cls)
5573
5574 class A(metaclass=M):
5575 pass
5576 class B(A):
5577 pass
5578 class C(B):
5579 pass
5580
5581 def test_reent_set_bases_tp_base_cycle(self):
5582 """
5583 type_set_bases must check for an inheritance cycle not only through
5584 MRO of the type, which may be not yet updated in case of reentrance,
5585 but also through tp_base chain, which is assigned before diving into
5586 inner calls to mro().
5587
5588 Otherwise, the following snippet can loop forever:
5589 do {
5590 // ...
5591 type = type->tp_base;
5592 } while (type != NULL);
5593
5594 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5595 would not be happy in that case, causing a stack overflow.
5596 """
5597 class M(DebugHelperMeta):
5598 def mro(cls):
5599 if self.ready:
5600 if cls.__name__ == 'B1':
5601 B2.__bases__ = (B1,)
5602 if cls.__name__ == 'B2':
5603 B1.__bases__ = (B2,)
5604 return type.mro(cls)
5605
5606 class A(metaclass=M):
5607 pass
5608 class B1(A):
5609 pass
5610 class B2(A):
5611 pass
5612
5613 self.ready = True
5614 with self.assertRaises(TypeError):
5615 B1.__bases__ += ()
5616
5617 def test_tp_subclasses_cycle_in_update_slots(self):
5618 """
5619 type_set_bases must check for reentrancy upon finishing its job
5620 by updating tp_subclasses of old/new bases of the type.
5621 Otherwise, an implicit inheritance cycle through tp_subclasses
5622 can break functions that recurse on elements of that field
5623 (like recurse_down_subclasses and mro_hierarchy) eventually
5624 leading to a stack overflow.
5625 """
5626 class M(DebugHelperMeta):
5627 def mro(cls):
5628 if self.ready and cls.__name__ == 'C':
5629 self.ready = False
5630 C.__bases__ = (B2,)
5631 return type.mro(cls)
5632
5633 class A(metaclass=M):
5634 pass
5635 class B1(A):
5636 pass
5637 class B2(A):
5638 pass
5639 class C(A):
5640 pass
5641
5642 self.ready = True
5643 C.__bases__ = (B1,)
5644 B1.__bases__ = (C,)
5645
5646 self.assertEqual(C.__bases__, (B2,))
5647 self.assertEqual(B2.__subclasses__(), [C])
5648 self.assertEqual(B1.__subclasses__(), [])
5649
5650 self.assertEqual(B1.__bases__, (C,))
5651 self.assertEqual(C.__subclasses__(), [B1])
5652
5653 def test_tp_subclasses_cycle_error_return_path(self):
5654 """
5655 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5656 a code path executed on error (goto bail).
5657 """
5658 class E(Exception):
5659 pass
5660 class M(DebugHelperMeta):
5661 def mro(cls):
5662 if self.ready and cls.__name__ == 'C':
5663 if C.__bases__ == (B2,):
5664 self.ready = False
5665 else:
5666 C.__bases__ = (B2,)
5667 raise E
5668 return type.mro(cls)
5669
5670 class A(metaclass=M):
5671 pass
5672 class B1(A):
5673 pass
5674 class B2(A):
5675 pass
5676 class C(A):
5677 pass
5678
5679 self.ready = True
5680 with self.assertRaises(E):
5681 C.__bases__ = (B1,)
5682 B1.__bases__ = (C,)
5683
5684 self.assertEqual(C.__bases__, (B2,))
5685 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5686
5687 def test_incomplete_extend(self):
5688 """
5689 Extending an unitialized type with type->tp_mro == NULL must
5690 throw a reasonable TypeError exception, instead of failing
5691 with PyErr_BadInternalCall.
5692 """
5693 class M(DebugHelperMeta):
5694 def mro(cls):
5695 if cls.__mro__ is None and cls.__name__ != 'X':
5696 with self.assertRaises(TypeError):
5697 class X(cls):
5698 pass
5699
5700 return type.mro(cls)
5701
5702 class A(metaclass=M):
5703 pass
5704
5705 def test_incomplete_super(self):
5706 """
5707 Attrubute lookup on a super object must be aware that
5708 its target type can be uninitialized (type->tp_mro == NULL).
5709 """
5710 class M(DebugHelperMeta):
5711 def mro(cls):
5712 if cls.__mro__ is None:
5713 with self.assertRaises(AttributeError):
5714 super(cls, cls).xxx
5715
5716 return type.mro(cls)
5717
5718 class A(metaclass=M):
5719 pass
5720
5721
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005722def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005723 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005724 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005725 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005726 MiscTests, PicklingTests, SharedKeyTests,
5727 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005728
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005729if __name__ == "__main__":
5730 test_main()