blob: 3cb923ed0520a3aa6d49cab1b76155003731722a [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)
Victor Stinner507a5742021-04-09 17:51:22 +02001548 def f(cls, arg):
1549 "f docstring"
1550 return (cls, arg)
Georg Brandl479a7e72008-02-05 18:13:15 +00001551 ff = classmethod(f)
1552 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1553 self.assertEqual(ff.__get__(0)(42), (int, 42))
1554
1555 # Test super() with classmethods (SF bug 535444)
1556 self.assertEqual(C.goo.__self__, C)
1557 self.assertEqual(D.goo.__self__, D)
1558 self.assertEqual(super(D,D).goo.__self__, D)
1559 self.assertEqual(super(D,d).goo.__self__, D)
1560 self.assertEqual(super(D,D).goo(), (D,))
1561 self.assertEqual(super(D,d).goo(), (D,))
1562
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001563 # Verify that a non-callable will raise
1564 meth = classmethod(1).__get__(1)
1565 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001566
1567 # Verify that classmethod() doesn't allow keyword args
1568 try:
1569 classmethod(f, kw=1)
1570 except TypeError:
1571 pass
1572 else:
1573 self.fail("classmethod shouldn't accept keyword args")
1574
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001575 cm = classmethod(f)
Victor Stinner507a5742021-04-09 17:51:22 +02001576 cm_dict = {'__annotations__': {},
1577 '__doc__': "f docstring",
1578 '__module__': __name__,
1579 '__name__': 'f',
1580 '__qualname__': f.__qualname__}
1581 self.assertEqual(cm.__dict__, cm_dict)
1582
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001583 cm.x = 42
1584 self.assertEqual(cm.x, 42)
Victor Stinner507a5742021-04-09 17:51:22 +02001585 self.assertEqual(cm.__dict__, {"x" : 42, **cm_dict})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001586 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001587 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001588
Oren Milmand019bc82018-02-13 12:28:33 +02001589 @support.refcount_test
1590 def test_refleaks_in_classmethod___init__(self):
1591 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1592 cm = classmethod(None)
1593 refs_before = gettotalrefcount()
1594 for i in range(100):
1595 cm.__init__(None)
1596 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1597
Benjamin Petersone549ead2009-03-28 21:42:05 +00001598 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001599 def test_classmethods_in_c(self):
1600 # Testing C-based class methods...
1601 import xxsubtype as spam
1602 a = (1, 2, 3)
1603 d = {'abc': 123}
1604 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1605 self.assertEqual(x, spam.spamlist)
1606 self.assertEqual(a, a1)
1607 self.assertEqual(d, d1)
1608 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1609 self.assertEqual(x, spam.spamlist)
1610 self.assertEqual(a, a1)
1611 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001612 spam_cm = spam.spamlist.__dict__['classmeth']
1613 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1614 self.assertEqual(x2, spam.spamlist)
1615 self.assertEqual(a2, a1)
1616 self.assertEqual(d2, d1)
1617 class SubSpam(spam.spamlist): pass
1618 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1619 self.assertEqual(x2, SubSpam)
1620 self.assertEqual(a2, a1)
1621 self.assertEqual(d2, d1)
Inada Naoki871309c2019-03-26 18:26:33 +09001622
1623 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001624 spam_cm()
Inada Naoki871309c2019-03-26 18:26:33 +09001625 self.assertEqual(
1626 str(cm.exception),
1627 "descriptor 'classmeth' of 'xxsubtype.spamlist' "
1628 "object needs an argument")
1629
1630 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001631 spam_cm(spam.spamlist())
Inada Naoki871309c2019-03-26 18:26:33 +09001632 self.assertEqual(
1633 str(cm.exception),
Jeroen Demeyer3f345c32019-06-07 12:20:24 +02001634 "descriptor 'classmeth' for type 'xxsubtype.spamlist' "
1635 "needs a type, not a 'xxsubtype.spamlist' as arg 2")
Inada Naoki871309c2019-03-26 18:26:33 +09001636
1637 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001638 spam_cm(list)
Inada Naoki62f95882019-04-01 17:56:11 +09001639 expected_errmsg = (
Inada Naoki871309c2019-03-26 18:26:33 +09001640 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
1641 "but received 'list'")
Inada Naoki62f95882019-04-01 17:56:11 +09001642 self.assertEqual(str(cm.exception), expected_errmsg)
1643
1644 with self.assertRaises(TypeError) as cm:
1645 spam_cm.__get__(None, list)
1646 self.assertEqual(str(cm.exception), expected_errmsg)
Georg Brandl479a7e72008-02-05 18:13:15 +00001647
1648 def test_staticmethods(self):
1649 # Testing static methods...
1650 class C(object):
1651 def foo(*a): return a
1652 goo = staticmethod(foo)
1653 c = C()
1654 self.assertEqual(C.goo(1), (1,))
1655 self.assertEqual(c.goo(1), (1,))
1656 self.assertEqual(c.foo(1), (c, 1,))
1657 class D(C):
1658 pass
1659 d = D()
1660 self.assertEqual(D.goo(1), (1,))
1661 self.assertEqual(d.goo(1), (1,))
1662 self.assertEqual(d.foo(1), (d, 1))
1663 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001664 sm = staticmethod(None)
Victor Stinner507a5742021-04-09 17:51:22 +02001665 self.assertEqual(sm.__dict__, {'__doc__': None})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001666 sm.x = 42
1667 self.assertEqual(sm.x, 42)
Victor Stinner507a5742021-04-09 17:51:22 +02001668 self.assertEqual(sm.__dict__, {"x" : 42, '__doc__': None})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001669 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001670 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001671
Oren Milmand019bc82018-02-13 12:28:33 +02001672 @support.refcount_test
1673 def test_refleaks_in_staticmethod___init__(self):
1674 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1675 sm = staticmethod(None)
1676 refs_before = gettotalrefcount()
1677 for i in range(100):
1678 sm.__init__(None)
1679 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1680
Benjamin Petersone549ead2009-03-28 21:42:05 +00001681 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001682 def test_staticmethods_in_c(self):
1683 # Testing C-based static methods...
1684 import xxsubtype as spam
1685 a = (1, 2, 3)
1686 d = {"abc": 123}
1687 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1688 self.assertEqual(x, None)
1689 self.assertEqual(a, a1)
1690 self.assertEqual(d, d1)
1691 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1692 self.assertEqual(x, None)
1693 self.assertEqual(a, a1)
1694 self.assertEqual(d, d1)
1695
1696 def test_classic(self):
1697 # Testing classic classes...
1698 class C:
1699 def foo(*a): return a
1700 goo = classmethod(foo)
1701 c = C()
1702 self.assertEqual(C.goo(1), (C, 1))
1703 self.assertEqual(c.goo(1), (C, 1))
1704 self.assertEqual(c.foo(1), (c, 1))
1705 class D(C):
1706 pass
1707 d = D()
1708 self.assertEqual(D.goo(1), (D, 1))
1709 self.assertEqual(d.goo(1), (D, 1))
1710 self.assertEqual(d.foo(1), (d, 1))
1711 self.assertEqual(D.foo(d, 1), (d, 1))
1712 class E: # *not* subclassing from C
1713 foo = C.foo
1714 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001715 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001716
1717 def test_compattr(self):
1718 # Testing computed attributes...
1719 class C(object):
1720 class computed_attribute(object):
1721 def __init__(self, get, set=None, delete=None):
1722 self.__get = get
1723 self.__set = set
1724 self.__delete = delete
1725 def __get__(self, obj, type=None):
1726 return self.__get(obj)
1727 def __set__(self, obj, value):
1728 return self.__set(obj, value)
1729 def __delete__(self, obj):
1730 return self.__delete(obj)
1731 def __init__(self):
1732 self.__x = 0
1733 def __get_x(self):
1734 x = self.__x
1735 self.__x = x+1
1736 return x
1737 def __set_x(self, x):
1738 self.__x = x
1739 def __delete_x(self):
1740 del self.__x
1741 x = computed_attribute(__get_x, __set_x, __delete_x)
1742 a = C()
1743 self.assertEqual(a.x, 0)
1744 self.assertEqual(a.x, 1)
1745 a.x = 10
1746 self.assertEqual(a.x, 10)
1747 self.assertEqual(a.x, 11)
1748 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001749 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001750
1751 def test_newslots(self):
1752 # Testing __new__ slot override...
1753 class C(list):
1754 def __new__(cls):
1755 self = list.__new__(cls)
1756 self.foo = 1
1757 return self
1758 def __init__(self):
1759 self.foo = self.foo + 2
1760 a = C()
1761 self.assertEqual(a.foo, 3)
1762 self.assertEqual(a.__class__, C)
1763 class D(C):
1764 pass
1765 b = D()
1766 self.assertEqual(b.foo, 3)
1767 self.assertEqual(b.__class__, D)
1768
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001769 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001770 def test_bad_new(self):
1771 self.assertRaises(TypeError, object.__new__)
1772 self.assertRaises(TypeError, object.__new__, '')
1773 self.assertRaises(TypeError, list.__new__, object)
1774 self.assertRaises(TypeError, object.__new__, list)
1775 class C(object):
1776 __new__ = list.__new__
1777 self.assertRaises(TypeError, C)
1778 class C(list):
1779 __new__ = object.__new__
1780 self.assertRaises(TypeError, C)
1781
1782 def test_object_new(self):
1783 class A(object):
1784 pass
1785 object.__new__(A)
1786 self.assertRaises(TypeError, object.__new__, A, 5)
1787 object.__init__(A())
1788 self.assertRaises(TypeError, object.__init__, A(), 5)
1789
1790 class A(object):
1791 def __init__(self, foo):
1792 self.foo = foo
1793 object.__new__(A)
1794 object.__new__(A, 5)
1795 object.__init__(A(3))
1796 self.assertRaises(TypeError, object.__init__, A(3), 5)
1797
1798 class A(object):
1799 def __new__(cls, foo):
1800 return object.__new__(cls)
1801 object.__new__(A)
1802 self.assertRaises(TypeError, object.__new__, A, 5)
1803 object.__init__(A(3))
1804 object.__init__(A(3), 5)
1805
1806 class A(object):
1807 def __new__(cls, foo):
1808 return object.__new__(cls)
1809 def __init__(self, foo):
1810 self.foo = foo
1811 object.__new__(A)
1812 self.assertRaises(TypeError, object.__new__, A, 5)
1813 object.__init__(A(3))
1814 self.assertRaises(TypeError, object.__init__, A(3), 5)
1815
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001816 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001817 def test_restored_object_new(self):
1818 class A(object):
1819 def __new__(cls, *args, **kwargs):
1820 raise AssertionError
1821 self.assertRaises(AssertionError, A)
1822 class B(A):
1823 __new__ = object.__new__
1824 def __init__(self, foo):
1825 self.foo = foo
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 del B.__new__
1832 self.assertRaises(AssertionError, B)
1833 del A.__new__
1834 with warnings.catch_warnings():
1835 warnings.simplefilter('error', DeprecationWarning)
1836 b = B(3)
1837 self.assertEqual(b.foo, 3)
1838 self.assertEqual(b.__class__, B)
1839
Georg Brandl479a7e72008-02-05 18:13:15 +00001840 def test_altmro(self):
1841 # Testing mro() and overriding it...
1842 class A(object):
1843 def f(self): return "A"
1844 class B(A):
1845 pass
1846 class C(A):
1847 def f(self): return "C"
1848 class D(B, C):
1849 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001850 self.assertEqual(A.mro(), [A, object])
1851 self.assertEqual(A.__mro__, (A, object))
1852 self.assertEqual(B.mro(), [B, A, object])
1853 self.assertEqual(B.__mro__, (B, A, object))
1854 self.assertEqual(C.mro(), [C, A, object])
1855 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001856 self.assertEqual(D.mro(), [D, B, C, A, object])
1857 self.assertEqual(D.__mro__, (D, B, C, A, object))
1858 self.assertEqual(D().f(), "C")
1859
1860 class PerverseMetaType(type):
1861 def mro(cls):
1862 L = type.mro(cls)
1863 L.reverse()
1864 return L
1865 class X(D,B,C,A, metaclass=PerverseMetaType):
1866 pass
1867 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1868 self.assertEqual(X().f(), "A")
1869
1870 try:
1871 class _metaclass(type):
1872 def mro(self):
1873 return [self, dict, object]
1874 class X(object, metaclass=_metaclass):
1875 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001876 # In CPython, the class creation above already raises
1877 # TypeError, as a protection against the fact that
1878 # instances of X would segfault it. In other Python
1879 # implementations it would be ok to let the class X
1880 # be created, but instead get a clean TypeError on the
1881 # __setitem__ below.
1882 x = object.__new__(X)
1883 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001884 except TypeError:
1885 pass
1886 else:
1887 self.fail("devious mro() return not caught")
1888
1889 try:
1890 class _metaclass(type):
1891 def mro(self):
1892 return [1]
1893 class X(object, metaclass=_metaclass):
1894 pass
1895 except TypeError:
1896 pass
1897 else:
1898 self.fail("non-class mro() return not caught")
1899
1900 try:
1901 class _metaclass(type):
1902 def mro(self):
1903 return 1
1904 class X(object, metaclass=_metaclass):
1905 pass
1906 except TypeError:
1907 pass
1908 else:
1909 self.fail("non-sequence mro() return not caught")
1910
1911 def test_overloading(self):
1912 # Testing operator overloading...
1913
1914 class B(object):
1915 "Intermediate class because object doesn't have a __setattr__"
1916
1917 class C(B):
1918 def __getattr__(self, name):
1919 if name == "foo":
1920 return ("getattr", name)
1921 else:
1922 raise AttributeError
1923 def __setattr__(self, name, value):
1924 if name == "foo":
1925 self.setattr = (name, value)
1926 else:
1927 return B.__setattr__(self, name, value)
1928 def __delattr__(self, name):
1929 if name == "foo":
1930 self.delattr = name
1931 else:
1932 return B.__delattr__(self, name)
1933
1934 def __getitem__(self, key):
1935 return ("getitem", key)
1936 def __setitem__(self, key, value):
1937 self.setitem = (key, value)
1938 def __delitem__(self, key):
1939 self.delitem = key
1940
1941 a = C()
1942 self.assertEqual(a.foo, ("getattr", "foo"))
1943 a.foo = 12
1944 self.assertEqual(a.setattr, ("foo", 12))
1945 del a.foo
1946 self.assertEqual(a.delattr, "foo")
1947
1948 self.assertEqual(a[12], ("getitem", 12))
1949 a[12] = 21
1950 self.assertEqual(a.setitem, (12, 21))
1951 del a[12]
1952 self.assertEqual(a.delitem, 12)
1953
1954 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1955 a[0:10] = "foo"
1956 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1957 del a[0:10]
1958 self.assertEqual(a.delitem, (slice(0, 10)))
1959
1960 def test_methods(self):
1961 # Testing methods...
1962 class C(object):
1963 def __init__(self, x):
1964 self.x = x
1965 def foo(self):
1966 return self.x
1967 c1 = C(1)
1968 self.assertEqual(c1.foo(), 1)
1969 class D(C):
1970 boo = C.foo
1971 goo = c1.foo
1972 d2 = D(2)
1973 self.assertEqual(d2.foo(), 2)
1974 self.assertEqual(d2.boo(), 2)
1975 self.assertEqual(d2.goo(), 1)
1976 class E(object):
1977 foo = C.foo
1978 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001979 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001980
Inada Naoki62f95882019-04-01 17:56:11 +09001981 @support.impl_detail("testing error message from implementation")
1982 def test_methods_in_c(self):
1983 # This test checks error messages in builtin method descriptor.
1984 # It is allowed that other Python implementations use
1985 # different error messages.
1986 set_add = set.add
1987
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01001988 expected_errmsg = "unbound method set.add() needs an argument"
Inada Naoki62f95882019-04-01 17:56:11 +09001989
1990 with self.assertRaises(TypeError) as cm:
1991 set_add()
1992 self.assertEqual(cm.exception.args[0], expected_errmsg)
1993
1994 expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"
1995
1996 with self.assertRaises(TypeError) as cm:
1997 set_add(0)
1998 self.assertEqual(cm.exception.args[0], expected_errmsg)
1999
2000 with self.assertRaises(TypeError) as cm:
2001 set_add.__get__(0)
2002 self.assertEqual(cm.exception.args[0], expected_errmsg)
2003
Benjamin Peterson224205f2009-05-08 03:25:19 +00002004 def test_special_method_lookup(self):
2005 # The lookup of special methods bypasses __getattr__ and
2006 # __getattribute__, but they still can be descriptors.
2007
2008 def run_context(manager):
2009 with manager:
2010 pass
2011 def iden(self):
2012 return self
2013 def hello(self):
2014 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00002015 def empty_seq(self):
2016 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04002017 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00002018 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00002019 def complex_num(self):
2020 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00002021 def stop(self):
2022 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002023 def return_true(self, thing=None):
2024 return True
2025 def do_isinstance(obj):
2026 return isinstance(int, obj)
2027 def do_issubclass(obj):
2028 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00002029 def do_dict_missing(checker):
2030 class DictSub(checker.__class__, dict):
2031 pass
2032 self.assertEqual(DictSub()["hi"], 4)
2033 def some_number(self_, key):
2034 self.assertEqual(key, "hi")
2035 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002036 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002037 def format_impl(self, spec):
2038 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00002039
2040 # It would be nice to have every special method tested here, but I'm
2041 # only listing the ones I can remember outside of typeobject.c, since it
2042 # does it right.
2043 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002044 ("__bytes__", bytes, hello, set(), {}),
2045 ("__reversed__", reversed, empty_seq, set(), {}),
2046 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00002047 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002048 ("__sizeof__", sys.getsizeof, zero, set(), {}),
2049 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00002050 ("__missing__", do_dict_missing, some_number,
2051 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002052 ("__subclasscheck__", do_issubclass, return_true,
2053 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002054 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
2055 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00002056 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002057 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002058 ("__floor__", math.floor, zero, set(), {}),
2059 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04002060 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00002061 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05002062 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002063 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00002064 ]
2065
2066 class Checker(object):
2067 def __getattr__(self, attr, test=self):
2068 test.fail("__getattr__ called with {0}".format(attr))
2069 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002070 if attr not in ok:
2071 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00002072 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002073 class SpecialDescr(object):
2074 def __init__(self, impl):
2075 self.impl = impl
2076 def __get__(self, obj, owner):
2077 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002078 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002079 class MyException(Exception):
2080 pass
2081 class ErrDescr(object):
2082 def __get__(self, obj, owner):
2083 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00002084
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002085 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00002086 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 Peterson8a282d12009-05-08 18:18:45 +00002090 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002091 runner(X())
2092
2093 record = []
2094 class X(Checker):
2095 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002096 for attr, obj in env.items():
2097 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002098 setattr(X, name, SpecialDescr(meth_impl))
2099 runner(X())
2100 self.assertEqual(record, [1], name)
2101
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002102 class X(Checker):
2103 pass
2104 for attr, obj in env.items():
2105 setattr(X, attr, obj)
2106 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002107 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002108
Georg Brandl479a7e72008-02-05 18:13:15 +00002109 def test_specials(self):
2110 # Testing special operators...
2111 # Test operators like __hash__ for which a built-in default exists
2112
2113 # Test the default behavior for static classes
2114 class C(object):
2115 def __getitem__(self, i):
2116 if 0 <= i < 10: return i
2117 raise IndexError
2118 c1 = C()
2119 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002120 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002121 self.assertNotEqual(id(c1), id(c2))
2122 hash(c1)
2123 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002124 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002125 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002126 self.assertFalse(c1 != c1)
2127 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002128 # Note that the module name appears in str/repr, and that varies
2129 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002130 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002131 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002132 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002133 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002134 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002135 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002136 # Test the default behavior for dynamic classes
2137 class D(object):
2138 def __getitem__(self, i):
2139 if 0 <= i < 10: return i
2140 raise IndexError
2141 d1 = D()
2142 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002143 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002144 self.assertNotEqual(id(d1), id(d2))
2145 hash(d1)
2146 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002147 self.assertEqual(d1, d1)
2148 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002149 self.assertFalse(d1 != d1)
2150 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002151 # Note that the module name appears in str/repr, and that varies
2152 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002153 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002154 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002155 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002156 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002157 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002158 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002159 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002160 class Proxy(object):
2161 def __init__(self, x):
2162 self.x = x
2163 def __bool__(self):
2164 return not not self.x
2165 def __hash__(self):
2166 return hash(self.x)
2167 def __eq__(self, other):
2168 return self.x == other
2169 def __ne__(self, other):
2170 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002171 def __ge__(self, other):
2172 return self.x >= other
2173 def __gt__(self, other):
2174 return self.x > other
2175 def __le__(self, other):
2176 return self.x <= other
2177 def __lt__(self, other):
2178 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002179 def __str__(self):
2180 return "Proxy:%s" % self.x
2181 def __repr__(self):
2182 return "Proxy(%r)" % self.x
2183 def __contains__(self, value):
2184 return value in self.x
2185 p0 = Proxy(0)
2186 p1 = Proxy(1)
2187 p_1 = Proxy(-1)
2188 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002189 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002190 self.assertEqual(hash(p0), hash(0))
2191 self.assertEqual(p0, p0)
2192 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002193 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002194 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002195 self.assertTrue(p0 < p1)
2196 self.assertTrue(p0 <= p1)
2197 self.assertTrue(p1 > p0)
2198 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002199 self.assertEqual(str(p0), "Proxy:0")
2200 self.assertEqual(repr(p0), "Proxy(0)")
2201 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002202 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002203 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002204 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002205 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002206
Georg Brandl479a7e72008-02-05 18:13:15 +00002207 def test_weakrefs(self):
2208 # Testing weak references...
2209 import weakref
2210 class C(object):
2211 pass
2212 c = C()
2213 r = weakref.ref(c)
2214 self.assertEqual(r(), c)
2215 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002216 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002217 self.assertEqual(r(), None)
2218 del r
2219 class NoWeak(object):
2220 __slots__ = ['foo']
2221 no = NoWeak()
2222 try:
2223 weakref.ref(no)
2224 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002225 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002226 else:
2227 self.fail("weakref.ref(no) should be illegal")
2228 class Weak(object):
2229 __slots__ = ['foo', '__weakref__']
2230 yes = Weak()
2231 r = weakref.ref(yes)
2232 self.assertEqual(r(), yes)
2233 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002234 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002235 self.assertEqual(r(), None)
2236 del r
2237
2238 def test_properties(self):
2239 # Testing property...
2240 class C(object):
2241 def getx(self):
2242 return self.__x
2243 def setx(self, value):
2244 self.__x = value
2245 def delx(self):
2246 del self.__x
2247 x = property(getx, setx, delx, doc="I'm the x property.")
2248 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002249 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002250 a.x = 42
2251 self.assertEqual(a._C__x, 42)
2252 self.assertEqual(a.x, 42)
2253 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002254 self.assertNotHasAttr(a, "x")
2255 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002256 C.x.__set__(a, 100)
2257 self.assertEqual(C.x.__get__(a), 100)
2258 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002259 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002260
2261 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002262 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002263
2264 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002265 self.assertIn("__doc__", attrs)
2266 self.assertIn("fget", attrs)
2267 self.assertIn("fset", attrs)
2268 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002269
2270 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002271 self.assertIs(raw.fget, C.__dict__['getx'])
2272 self.assertIs(raw.fset, C.__dict__['setx'])
2273 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002274
Raymond Hettingereac503a2015-05-13 01:09:59 -07002275 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002276 try:
2277 setattr(raw, attr, 42)
2278 except AttributeError as msg:
2279 if str(msg).find('readonly') < 0:
2280 self.fail("when setting readonly attr %r on a property, "
2281 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2282 else:
2283 self.fail("expected AttributeError from trying to set readonly %r "
2284 "attr on a property" % attr)
2285
Raymond Hettingereac503a2015-05-13 01:09:59 -07002286 raw.__doc__ = 42
2287 self.assertEqual(raw.__doc__, 42)
2288
Georg Brandl479a7e72008-02-05 18:13:15 +00002289 class D(object):
2290 __getitem__ = property(lambda s: 1/0)
2291
2292 d = D()
2293 try:
2294 for i in d:
2295 str(i)
2296 except ZeroDivisionError:
2297 pass
2298 else:
2299 self.fail("expected ZeroDivisionError from bad property")
2300
R. David Murray378c0cf2010-02-24 01:46:21 +00002301 @unittest.skipIf(sys.flags.optimize >= 2,
2302 "Docstrings are omitted with -O2 and above")
2303 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002304 class E(object):
2305 def getter(self):
2306 "getter method"
2307 return 0
2308 def setter(self_, value):
2309 "setter method"
2310 pass
2311 prop = property(getter)
2312 self.assertEqual(prop.__doc__, "getter method")
2313 prop2 = property(fset=setter)
2314 self.assertEqual(prop2.__doc__, None)
2315
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002316 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002317 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002318 # this segfaulted in 2.5b2
2319 try:
2320 import _testcapi
2321 except ImportError:
2322 pass
2323 else:
2324 class X(object):
2325 p = property(_testcapi.test_with_docstring)
2326
2327 def test_properties_plus(self):
2328 class C(object):
2329 foo = property(doc="hello")
2330 @foo.getter
2331 def foo(self):
2332 return self._foo
2333 @foo.setter
2334 def foo(self, value):
2335 self._foo = abs(value)
2336 @foo.deleter
2337 def foo(self):
2338 del self._foo
2339 c = C()
2340 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002341 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002342 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002343 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002344 self.assertEqual(c._foo, 42)
2345 self.assertEqual(c.foo, 42)
2346 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002347 self.assertNotHasAttr(c, '_foo')
2348 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002349
2350 class D(C):
2351 @C.foo.deleter
2352 def foo(self):
2353 try:
2354 del self._foo
2355 except AttributeError:
2356 pass
2357 d = D()
2358 d.foo = 24
2359 self.assertEqual(d.foo, 24)
2360 del d.foo
2361 del d.foo
2362
2363 class E(object):
2364 @property
2365 def foo(self):
2366 return self._foo
2367 @foo.setter
2368 def foo(self, value):
2369 raise RuntimeError
2370 @foo.setter
2371 def foo(self, value):
2372 self._foo = abs(value)
2373 @foo.deleter
2374 def foo(self, value=None):
2375 del self._foo
2376
2377 e = E()
2378 e.foo = -42
2379 self.assertEqual(e.foo, 42)
2380 del e.foo
2381
2382 class F(E):
2383 @E.foo.deleter
2384 def foo(self):
2385 del self._foo
2386 @foo.setter
2387 def foo(self, value):
2388 self._foo = max(0, value)
2389 f = F()
2390 f.foo = -10
2391 self.assertEqual(f.foo, 0)
2392 del f.foo
2393
2394 def test_dict_constructors(self):
2395 # Testing dict constructor ...
2396 d = dict()
2397 self.assertEqual(d, {})
2398 d = dict({})
2399 self.assertEqual(d, {})
2400 d = dict({1: 2, 'a': 'b'})
2401 self.assertEqual(d, {1: 2, 'a': 'b'})
2402 self.assertEqual(d, dict(list(d.items())))
2403 self.assertEqual(d, dict(iter(d.items())))
2404 d = dict({'one':1, 'two':2})
2405 self.assertEqual(d, dict(one=1, two=2))
2406 self.assertEqual(d, dict(**d))
2407 self.assertEqual(d, dict({"one": 1}, two=2))
2408 self.assertEqual(d, dict([("two", 2)], one=1))
2409 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2410 self.assertEqual(d, dict(**d))
2411
2412 for badarg in 0, 0, 0j, "0", [0], (0,):
2413 try:
2414 dict(badarg)
2415 except TypeError:
2416 pass
2417 except ValueError:
2418 if badarg == "0":
2419 # It's a sequence, and its elements are also sequences (gotta
2420 # love strings <wink>), but they aren't of length 2, so this
2421 # one seemed better as a ValueError than a TypeError.
2422 pass
2423 else:
2424 self.fail("no TypeError from dict(%r)" % badarg)
2425 else:
2426 self.fail("no TypeError from dict(%r)" % badarg)
2427
2428 try:
2429 dict({}, {})
2430 except TypeError:
2431 pass
2432 else:
2433 self.fail("no TypeError from dict({}, {})")
2434
2435 class Mapping:
2436 # Lacks a .keys() method; will be added later.
2437 dict = {1:2, 3:4, 'a':1j}
2438
2439 try:
2440 dict(Mapping())
2441 except TypeError:
2442 pass
2443 else:
2444 self.fail("no TypeError from dict(incomplete mapping)")
2445
2446 Mapping.keys = lambda self: list(self.dict.keys())
2447 Mapping.__getitem__ = lambda self, i: self.dict[i]
2448 d = dict(Mapping())
2449 self.assertEqual(d, Mapping.dict)
2450
2451 # Init from sequence of iterable objects, each producing a 2-sequence.
2452 class AddressBookEntry:
2453 def __init__(self, first, last):
2454 self.first = first
2455 self.last = last
2456 def __iter__(self):
2457 return iter([self.first, self.last])
2458
2459 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2460 AddressBookEntry('Barry', 'Peters'),
2461 AddressBookEntry('Tim', 'Peters'),
2462 AddressBookEntry('Barry', 'Warsaw')])
2463 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2464
2465 d = dict(zip(range(4), range(1, 5)))
2466 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2467
2468 # Bad sequence lengths.
2469 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2470 try:
2471 dict(bad)
2472 except ValueError:
2473 pass
2474 else:
2475 self.fail("no ValueError from dict(%r)" % bad)
2476
2477 def test_dir(self):
2478 # Testing dir() ...
2479 junk = 12
2480 self.assertEqual(dir(), ['junk', 'self'])
2481 del junk
2482
2483 # Just make sure these don't blow up!
2484 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2485 dir(arg)
2486
2487 # Test dir on new-style classes. Since these have object as a
2488 # base class, a lot more gets sucked in.
2489 def interesting(strings):
2490 return [s for s in strings if not s.startswith('_')]
2491
2492 class C(object):
2493 Cdata = 1
2494 def Cmethod(self): pass
2495
2496 cstuff = ['Cdata', 'Cmethod']
2497 self.assertEqual(interesting(dir(C)), cstuff)
2498
2499 c = C()
2500 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002501 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002502
2503 c.cdata = 2
2504 c.cmethod = lambda self: 0
2505 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002506 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002507
2508 class A(C):
2509 Adata = 1
2510 def Amethod(self): pass
2511
2512 astuff = ['Adata', 'Amethod'] + cstuff
2513 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002514 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002515 a = A()
2516 self.assertEqual(interesting(dir(a)), astuff)
2517 a.adata = 42
2518 a.amethod = lambda self: 3
2519 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002520 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002521
2522 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002523 class M(type(sys)):
2524 pass
2525 minstance = M("m")
2526 minstance.b = 2
2527 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002528 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002529 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002530 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002531 self.assertEqual(names, ['a', 'b'])
2532
2533 class M2(M):
2534 def getdict(self):
2535 return "Not a dict!"
2536 __dict__ = property(getdict)
2537
2538 m2instance = M2("m2")
2539 m2instance.b = 2
2540 m2instance.a = 1
2541 self.assertEqual(m2instance.__dict__, "Not a dict!")
2542 try:
2543 dir(m2instance)
2544 except TypeError:
2545 pass
2546
MojoVampire469325c2020-03-03 18:50:17 +00002547 # Two essentially featureless objects, (Ellipsis just inherits stuff
2548 # from object.
2549 self.assertEqual(dir(object()), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002550
2551 # Nasty test case for proxied objects
2552 class Wrapper(object):
2553 def __init__(self, obj):
2554 self.__obj = obj
2555 def __repr__(self):
2556 return "Wrapper(%s)" % repr(self.__obj)
2557 def __getitem__(self, key):
2558 return Wrapper(self.__obj[key])
2559 def __len__(self):
2560 return len(self.__obj)
2561 def __getattr__(self, name):
2562 return Wrapper(getattr(self.__obj, name))
2563
2564 class C(object):
2565 def __getclass(self):
2566 return Wrapper(type(self))
2567 __class__ = property(__getclass)
2568
2569 dir(C()) # This used to segfault
2570
2571 def test_supers(self):
2572 # Testing super...
2573
2574 class A(object):
2575 def meth(self, a):
2576 return "A(%r)" % a
2577
2578 self.assertEqual(A().meth(1), "A(1)")
2579
2580 class B(A):
2581 def __init__(self):
2582 self.__super = super(B, self)
2583 def meth(self, a):
2584 return "B(%r)" % a + self.__super.meth(a)
2585
2586 self.assertEqual(B().meth(2), "B(2)A(2)")
2587
2588 class C(A):
2589 def meth(self, a):
2590 return "C(%r)" % a + self.__super.meth(a)
2591 C._C__super = super(C)
2592
2593 self.assertEqual(C().meth(3), "C(3)A(3)")
2594
2595 class D(C, B):
2596 def meth(self, a):
2597 return "D(%r)" % a + super(D, self).meth(a)
2598
2599 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2600
2601 # Test for subclassing super
2602
2603 class mysuper(super):
2604 def __init__(self, *args):
2605 return super(mysuper, self).__init__(*args)
2606
2607 class E(D):
2608 def meth(self, a):
2609 return "E(%r)" % a + mysuper(E, self).meth(a)
2610
2611 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2612
2613 class F(E):
2614 def meth(self, a):
2615 s = self.__super # == mysuper(F, self)
2616 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2617 F._F__super = mysuper(F)
2618
2619 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2620
2621 # Make sure certain errors are raised
2622
2623 try:
2624 super(D, 42)
2625 except TypeError:
2626 pass
2627 else:
2628 self.fail("shouldn't allow super(D, 42)")
2629
2630 try:
2631 super(D, C())
2632 except TypeError:
2633 pass
2634 else:
2635 self.fail("shouldn't allow super(D, C())")
2636
2637 try:
2638 super(D).__get__(12)
2639 except TypeError:
2640 pass
2641 else:
2642 self.fail("shouldn't allow super(D).__get__(12)")
2643
2644 try:
2645 super(D).__get__(C())
2646 except TypeError:
2647 pass
2648 else:
2649 self.fail("shouldn't allow super(D).__get__(C())")
2650
2651 # Make sure data descriptors can be overridden and accessed via super
2652 # (new feature in Python 2.3)
2653
2654 class DDbase(object):
2655 def getx(self): return 42
2656 x = property(getx)
2657
2658 class DDsub(DDbase):
2659 def getx(self): return "hello"
2660 x = property(getx)
2661
2662 dd = DDsub()
2663 self.assertEqual(dd.x, "hello")
2664 self.assertEqual(super(DDsub, dd).x, 42)
2665
2666 # Ensure that super() lookup of descriptor from classmethod
2667 # works (SF ID# 743627)
2668
2669 class Base(object):
2670 aProp = property(lambda self: "foo")
2671
2672 class Sub(Base):
2673 @classmethod
2674 def test(klass):
2675 return super(Sub,klass).aProp
2676
2677 self.assertEqual(Sub.test(), Base.aProp)
2678
2679 # Verify that super() doesn't allow keyword args
Zackery Spytz6b2e3252019-08-26 16:41:11 -06002680 with self.assertRaises(TypeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002681 super(Base, kw=1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682
2683 def test_basic_inheritance(self):
2684 # Testing inheritance from basic types...
2685
2686 class hexint(int):
2687 def __repr__(self):
2688 return hex(self)
2689 def __add__(self, other):
2690 return hexint(int.__add__(self, other))
2691 # (Note that overriding __radd__ doesn't work,
2692 # because the int type gets first dibs.)
2693 self.assertEqual(repr(hexint(7) + 9), "0x10")
2694 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2695 a = hexint(12345)
2696 self.assertEqual(a, 12345)
2697 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002698 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002699 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002700 self.assertIs((+a).__class__, int)
2701 self.assertIs((a >> 0).__class__, int)
2702 self.assertIs((a << 0).__class__, int)
2703 self.assertIs((hexint(0) << 12).__class__, int)
2704 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002705
2706 class octlong(int):
2707 __slots__ = []
2708 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002709 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002710 def __add__(self, other):
2711 return self.__class__(super(octlong, self).__add__(other))
2712 __radd__ = __add__
2713 self.assertEqual(str(octlong(3) + 5), "0o10")
2714 # (Note that overriding __radd__ here only seems to work
2715 # because the example uses a short int left argument.)
2716 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2717 a = octlong(12345)
2718 self.assertEqual(a, 12345)
2719 self.assertEqual(int(a), 12345)
2720 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002721 self.assertIs(int(a).__class__, int)
2722 self.assertIs((+a).__class__, int)
2723 self.assertIs((-a).__class__, int)
2724 self.assertIs((-octlong(0)).__class__, int)
2725 self.assertIs((a >> 0).__class__, int)
2726 self.assertIs((a << 0).__class__, int)
2727 self.assertIs((a - 0).__class__, int)
2728 self.assertIs((a * 1).__class__, int)
2729 self.assertIs((a ** 1).__class__, int)
2730 self.assertIs((a // 1).__class__, int)
2731 self.assertIs((1 * a).__class__, int)
2732 self.assertIs((a | 0).__class__, int)
2733 self.assertIs((a ^ 0).__class__, int)
2734 self.assertIs((a & -1).__class__, int)
2735 self.assertIs((octlong(0) << 12).__class__, int)
2736 self.assertIs((octlong(0) >> 12).__class__, int)
2737 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002738
2739 # Because octlong overrides __add__, we can't check the absence of +0
2740 # optimizations using octlong.
2741 class longclone(int):
2742 pass
2743 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002744 self.assertIs((a + 0).__class__, int)
2745 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002746
2747 # Check that negative clones don't segfault
2748 a = longclone(-1)
2749 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002750 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002751
2752 class precfloat(float):
2753 __slots__ = ['prec']
2754 def __init__(self, value=0.0, prec=12):
2755 self.prec = int(prec)
2756 def __repr__(self):
2757 return "%.*g" % (self.prec, self)
2758 self.assertEqual(repr(precfloat(1.1)), "1.1")
2759 a = precfloat(12345)
2760 self.assertEqual(a, 12345.0)
2761 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002762 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002763 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002764 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002765
2766 class madcomplex(complex):
2767 def __repr__(self):
2768 return "%.17gj%+.17g" % (self.imag, self.real)
2769 a = madcomplex(-3, 4)
2770 self.assertEqual(repr(a), "4j-3")
2771 base = complex(-3, 4)
2772 self.assertEqual(base.__class__, complex)
2773 self.assertEqual(a, base)
2774 self.assertEqual(complex(a), base)
2775 self.assertEqual(complex(a).__class__, complex)
2776 a = madcomplex(a) # just trying another form of the constructor
2777 self.assertEqual(repr(a), "4j-3")
2778 self.assertEqual(a, base)
2779 self.assertEqual(complex(a), base)
2780 self.assertEqual(complex(a).__class__, complex)
2781 self.assertEqual(hash(a), hash(base))
2782 self.assertEqual((+a).__class__, complex)
2783 self.assertEqual((a + 0).__class__, complex)
2784 self.assertEqual(a + 0, base)
2785 self.assertEqual((a - 0).__class__, complex)
2786 self.assertEqual(a - 0, base)
2787 self.assertEqual((a * 1).__class__, complex)
2788 self.assertEqual(a * 1, base)
2789 self.assertEqual((a / 1).__class__, complex)
2790 self.assertEqual(a / 1, base)
2791
2792 class madtuple(tuple):
2793 _rev = None
2794 def rev(self):
2795 if self._rev is not None:
2796 return self._rev
2797 L = list(self)
2798 L.reverse()
2799 self._rev = self.__class__(L)
2800 return self._rev
2801 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2802 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2803 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2804 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2805 for i in range(512):
2806 t = madtuple(range(i))
2807 u = t.rev()
2808 v = u.rev()
2809 self.assertEqual(v, t)
2810 a = madtuple((1,2,3,4,5))
2811 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002812 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002813 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002814 self.assertIs(a[:].__class__, tuple)
2815 self.assertIs((a * 1).__class__, tuple)
2816 self.assertIs((a * 0).__class__, tuple)
2817 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002818 a = madtuple(())
2819 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002820 self.assertIs(tuple(a).__class__, tuple)
2821 self.assertIs((a + a).__class__, tuple)
2822 self.assertIs((a * 0).__class__, tuple)
2823 self.assertIs((a * 1).__class__, tuple)
2824 self.assertIs((a * 2).__class__, tuple)
2825 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002826
2827 class madstring(str):
2828 _rev = None
2829 def rev(self):
2830 if self._rev is not None:
2831 return self._rev
2832 L = list(self)
2833 L.reverse()
2834 self._rev = self.__class__("".join(L))
2835 return self._rev
2836 s = madstring("abcdefghijklmnopqrstuvwxyz")
2837 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2838 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2839 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2840 for i in range(256):
2841 s = madstring("".join(map(chr, range(i))))
2842 t = s.rev()
2843 u = t.rev()
2844 self.assertEqual(u, s)
2845 s = madstring("12345")
2846 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002847 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002848
2849 base = "\x00" * 5
2850 s = madstring(base)
2851 self.assertEqual(s, base)
2852 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002853 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002854 self.assertEqual(hash(s), hash(base))
2855 self.assertEqual({s: 1}[base], 1)
2856 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002858 self.assertEqual(s + "", 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).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002862 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002864 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002865 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002866 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002867 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002868 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002869 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002870 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002871 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002872 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002873 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002874 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002875 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002876 self.assertEqual(s.rstrip(), base)
2877 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002878 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002879 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002880 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002881 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002882 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002883 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002884 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002885 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002886 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002887 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002888 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002889 self.assertEqual(s.lower(), base)
2890
2891 class madunicode(str):
2892 _rev = None
2893 def rev(self):
2894 if self._rev is not None:
2895 return self._rev
2896 L = list(self)
2897 L.reverse()
2898 self._rev = self.__class__("".join(L))
2899 return self._rev
2900 u = madunicode("ABCDEF")
2901 self.assertEqual(u, "ABCDEF")
2902 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2903 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2904 base = "12345"
2905 u = madunicode(base)
2906 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002907 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 self.assertEqual(hash(u), hash(base))
2909 self.assertEqual({u: 1}[base], 1)
2910 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002911 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002912 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002913 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002915 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002916 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002917 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002918 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002919 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002920 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002921 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002922 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002923 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002924 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002925 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002926 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002927 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002928 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002929 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002930 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002931 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002932 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002933 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002934 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002935 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002936 self.assertEqual(u + "", 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).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002940 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002941 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002942 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002943 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002944 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002945 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002946 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002947 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002948 self.assertEqual(u[0:0], "")
2949
2950 class sublist(list):
2951 pass
2952 a = sublist(range(5))
2953 self.assertEqual(a, list(range(5)))
2954 a.append("hello")
2955 self.assertEqual(a, list(range(5)) + ["hello"])
2956 a[5] = 5
2957 self.assertEqual(a, list(range(6)))
2958 a.extend(range(6, 20))
2959 self.assertEqual(a, list(range(20)))
2960 a[-5:] = []
2961 self.assertEqual(a, list(range(15)))
2962 del a[10:15]
2963 self.assertEqual(len(a), 10)
2964 self.assertEqual(a, list(range(10)))
2965 self.assertEqual(list(a), list(range(10)))
2966 self.assertEqual(a[0], 0)
2967 self.assertEqual(a[9], 9)
2968 self.assertEqual(a[-10], 0)
2969 self.assertEqual(a[-1], 9)
2970 self.assertEqual(a[:5], list(range(5)))
2971
2972 ## class CountedInput(file):
2973 ## """Counts lines read by self.readline().
2974 ##
2975 ## self.lineno is the 0-based ordinal of the last line read, up to
2976 ## a maximum of one greater than the number of lines in the file.
2977 ##
2978 ## self.ateof is true if and only if the final "" line has been read,
2979 ## at which point self.lineno stops incrementing, and further calls
2980 ## to readline() continue to return "".
2981 ## """
2982 ##
2983 ## lineno = 0
2984 ## ateof = 0
2985 ## def readline(self):
2986 ## if self.ateof:
2987 ## return ""
2988 ## s = file.readline(self)
2989 ## # Next line works too.
2990 ## # s = super(CountedInput, self).readline()
2991 ## self.lineno += 1
2992 ## if s == "":
2993 ## self.ateof = 1
2994 ## return s
2995 ##
Hai Shifcce8c62020-08-08 05:55:35 +08002996 ## f = file(name=os_helper.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002997 ## lines = ['a\n', 'b\n', 'c\n']
2998 ## try:
2999 ## f.writelines(lines)
3000 ## f.close()
Hai Shifcce8c62020-08-08 05:55:35 +08003001 ## f = CountedInput(os_helper.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00003002 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
3003 ## got = f.readline()
3004 ## self.assertEqual(expected, got)
3005 ## self.assertEqual(f.lineno, i)
3006 ## self.assertEqual(f.ateof, (i > len(lines)))
3007 ## f.close()
3008 ## finally:
3009 ## try:
3010 ## f.close()
3011 ## except:
3012 ## pass
Hai Shifcce8c62020-08-08 05:55:35 +08003013 ## os_helper.unlink(os_helper.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00003014
3015 def test_keywords(self):
3016 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003017 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3018 int(x=1)
3019 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3020 float(x=2)
3021 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3022 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003023 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
3024 self.assertEqual(str(object=500), '500')
3025 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003026 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3027 tuple(sequence=range(3))
3028 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3029 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00003030 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
3031
3032 for constructor in (int, float, int, complex, str, str,
3033 tuple, list):
3034 try:
3035 constructor(bogus_keyword_arg=1)
3036 except TypeError:
3037 pass
3038 else:
3039 self.fail("expected TypeError from bogus keyword argument to %r"
3040 % constructor)
3041
3042 def test_str_subclass_as_dict_key(self):
3043 # Testing a str subclass used as dict key ..
3044
3045 class cistr(str):
Min ho Kim39d87b52019-08-31 06:21:19 +10003046 """Subclass of str that computes __eq__ case-insensitively.
Georg Brandl479a7e72008-02-05 18:13:15 +00003047
3048 Also computes a hash code of the string in canonical form.
3049 """
3050
3051 def __init__(self, value):
3052 self.canonical = value.lower()
3053 self.hashcode = hash(self.canonical)
3054
3055 def __eq__(self, other):
3056 if not isinstance(other, cistr):
3057 other = cistr(other)
3058 return self.canonical == other.canonical
3059
3060 def __hash__(self):
3061 return self.hashcode
3062
3063 self.assertEqual(cistr('ABC'), 'abc')
3064 self.assertEqual('aBc', cistr('ABC'))
3065 self.assertEqual(str(cistr('ABC')), 'ABC')
3066
3067 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3068 self.assertEqual(d[cistr('one')], 1)
3069 self.assertEqual(d[cistr('tWo')], 2)
3070 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00003071 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003072 self.assertEqual(d.get(cistr('thrEE')), 3)
3073
3074 def test_classic_comparisons(self):
3075 # Testing classic comparisons...
3076 class classic:
3077 pass
3078
3079 for base in (classic, int, object):
3080 class C(base):
3081 def __init__(self, value):
3082 self.value = int(value)
3083 def __eq__(self, other):
3084 if isinstance(other, C):
3085 return self.value == other.value
3086 if isinstance(other, int) or isinstance(other, int):
3087 return self.value == other
3088 return NotImplemented
3089 def __ne__(self, other):
3090 if isinstance(other, C):
3091 return self.value != other.value
3092 if isinstance(other, int) or isinstance(other, int):
3093 return self.value != other
3094 return NotImplemented
3095 def __lt__(self, other):
3096 if isinstance(other, C):
3097 return self.value < other.value
3098 if isinstance(other, int) or isinstance(other, int):
3099 return self.value < other
3100 return NotImplemented
3101 def __le__(self, other):
3102 if isinstance(other, C):
3103 return self.value <= other.value
3104 if isinstance(other, int) or isinstance(other, int):
3105 return self.value <= other
3106 return NotImplemented
3107 def __gt__(self, other):
3108 if isinstance(other, C):
3109 return self.value > other.value
3110 if isinstance(other, int) or isinstance(other, int):
3111 return self.value > other
3112 return NotImplemented
3113 def __ge__(self, other):
3114 if isinstance(other, C):
3115 return self.value >= other.value
3116 if isinstance(other, int) or isinstance(other, int):
3117 return self.value >= other
3118 return NotImplemented
3119
3120 c1 = C(1)
3121 c2 = C(2)
3122 c3 = C(3)
3123 self.assertEqual(c1, 1)
3124 c = {1: c1, 2: c2, 3: c3}
3125 for x in 1, 2, 3:
3126 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003127 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003128 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003129 eval("x %s y" % op),
3130 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003131 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003132 eval("x %s y" % op),
3133 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003134 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003135 eval("x %s y" % op),
3136 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003137
3138 def test_rich_comparisons(self):
3139 # Testing rich comparisons...
3140 class Z(complex):
3141 pass
3142 z = Z(1)
3143 self.assertEqual(z, 1+0j)
3144 self.assertEqual(1+0j, z)
3145 class ZZ(complex):
3146 def __eq__(self, other):
3147 try:
3148 return abs(self - other) <= 1e-6
3149 except:
3150 return NotImplemented
3151 zz = ZZ(1.0000003)
3152 self.assertEqual(zz, 1+0j)
3153 self.assertEqual(1+0j, zz)
3154
3155 class classic:
3156 pass
3157 for base in (classic, int, object, list):
3158 class C(base):
3159 def __init__(self, value):
3160 self.value = int(value)
3161 def __cmp__(self_, other):
3162 self.fail("shouldn't call __cmp__")
3163 def __eq__(self, other):
3164 if isinstance(other, C):
3165 return self.value == other.value
3166 if isinstance(other, int) or isinstance(other, int):
3167 return self.value == other
3168 return NotImplemented
3169 def __ne__(self, other):
3170 if isinstance(other, C):
3171 return self.value != other.value
3172 if isinstance(other, int) or isinstance(other, int):
3173 return self.value != other
3174 return NotImplemented
3175 def __lt__(self, other):
3176 if isinstance(other, C):
3177 return self.value < other.value
3178 if isinstance(other, int) or isinstance(other, int):
3179 return self.value < other
3180 return NotImplemented
3181 def __le__(self, other):
3182 if isinstance(other, C):
3183 return self.value <= other.value
3184 if isinstance(other, int) or isinstance(other, int):
3185 return self.value <= other
3186 return NotImplemented
3187 def __gt__(self, other):
3188 if isinstance(other, C):
3189 return self.value > other.value
3190 if isinstance(other, int) or isinstance(other, int):
3191 return self.value > other
3192 return NotImplemented
3193 def __ge__(self, other):
3194 if isinstance(other, C):
3195 return self.value >= other.value
3196 if isinstance(other, int) or isinstance(other, int):
3197 return self.value >= other
3198 return NotImplemented
3199 c1 = C(1)
3200 c2 = C(2)
3201 c3 = C(3)
3202 self.assertEqual(c1, 1)
3203 c = {1: c1, 2: c2, 3: c3}
3204 for x in 1, 2, 3:
3205 for y in 1, 2, 3:
3206 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003207 self.assertEqual(eval("c[x] %s c[y]" % op),
3208 eval("x %s y" % op),
3209 "x=%d, y=%d" % (x, y))
3210 self.assertEqual(eval("c[x] %s y" % op),
3211 eval("x %s y" % op),
3212 "x=%d, y=%d" % (x, y))
3213 self.assertEqual(eval("x %s c[y]" % op),
3214 eval("x %s y" % op),
3215 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003216
3217 def test_descrdoc(self):
3218 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003219 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003220 def check(descr, what):
3221 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003222 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003223 check(complex.real, "the real part of a complex number") # member descriptor
3224
3225 def test_doc_descriptor(self):
3226 # Testing __doc__ descriptor...
3227 # SF bug 542984
3228 class DocDescr(object):
3229 def __get__(self, object, otype):
3230 if object:
3231 object = object.__class__.__name__ + ' instance'
3232 if otype:
3233 otype = otype.__name__
3234 return 'object=%s; type=%s' % (object, otype)
3235 class OldClass:
3236 __doc__ = DocDescr()
3237 class NewClass(object):
3238 __doc__ = DocDescr()
3239 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3240 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3241 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3242 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3243
3244 def test_set_class(self):
3245 # Testing __class__ assignment...
3246 class C(object): pass
3247 class D(object): pass
3248 class E(object): pass
3249 class F(D, E): pass
3250 for cls in C, D, E, F:
3251 for cls2 in C, D, E, F:
3252 x = cls()
3253 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003254 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003255 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003256 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003257 def cant(x, C):
3258 try:
3259 x.__class__ = C
3260 except TypeError:
3261 pass
3262 else:
3263 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3264 try:
3265 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003266 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003267 pass
3268 else:
3269 self.fail("shouldn't allow del %r.__class__" % x)
3270 cant(C(), list)
3271 cant(list(), C)
3272 cant(C(), 1)
3273 cant(C(), object)
3274 cant(object(), list)
3275 cant(list(), object)
3276 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003277 cant(True, int)
3278 cant(2, bool)
3279 o = object()
3280 cant(o, type(1))
3281 cant(o, type(None))
3282 del o
3283 class G(object):
3284 __slots__ = ["a", "b"]
3285 class H(object):
3286 __slots__ = ["b", "a"]
3287 class I(object):
3288 __slots__ = ["a", "b"]
3289 class J(object):
3290 __slots__ = ["c", "b"]
3291 class K(object):
3292 __slots__ = ["a", "b", "d"]
3293 class L(H):
3294 __slots__ = ["e"]
3295 class M(I):
3296 __slots__ = ["e"]
3297 class N(J):
3298 __slots__ = ["__weakref__"]
3299 class P(J):
3300 __slots__ = ["__dict__"]
3301 class Q(J):
3302 pass
3303 class R(J):
3304 __slots__ = ["__dict__", "__weakref__"]
3305
3306 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3307 x = cls()
3308 x.a = 1
3309 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003310 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003311 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3312 self.assertEqual(x.a, 1)
3313 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003314 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003315 "assigning %r as __class__ for %r silently failed" % (cls, x))
3316 self.assertEqual(x.a, 1)
3317 for cls in G, J, K, L, M, N, P, R, list, Int:
3318 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3319 if cls is cls2:
3320 continue
3321 cant(cls(), cls2)
3322
Benjamin Peterson193152c2009-04-25 01:08:45 +00003323 # Issue5283: when __class__ changes in __del__, the wrong
3324 # type gets DECREF'd.
3325 class O(object):
3326 pass
3327 class A(object):
3328 def __del__(self):
3329 self.__class__ = O
3330 l = [A() for x in range(100)]
3331 del l
3332
Georg Brandl479a7e72008-02-05 18:13:15 +00003333 def test_set_dict(self):
3334 # Testing __dict__ assignment...
3335 class C(object): pass
3336 a = C()
3337 a.__dict__ = {'b': 1}
3338 self.assertEqual(a.b, 1)
3339 def cant(x, dict):
3340 try:
3341 x.__dict__ = dict
3342 except (AttributeError, TypeError):
3343 pass
3344 else:
3345 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3346 cant(a, None)
3347 cant(a, [])
3348 cant(a, 1)
3349 del a.__dict__ # Deleting __dict__ is allowed
3350
3351 class Base(object):
3352 pass
3353 def verify_dict_readonly(x):
3354 """
3355 x has to be an instance of a class inheriting from Base.
3356 """
3357 cant(x, {})
3358 try:
3359 del x.__dict__
3360 except (AttributeError, TypeError):
3361 pass
3362 else:
3363 self.fail("shouldn't allow del %r.__dict__" % x)
3364 dict_descr = Base.__dict__["__dict__"]
3365 try:
3366 dict_descr.__set__(x, {})
3367 except (AttributeError, TypeError):
3368 pass
3369 else:
3370 self.fail("dict_descr allowed access to %r's dict" % x)
3371
3372 # Classes don't allow __dict__ assignment and have readonly dicts
3373 class Meta1(type, Base):
3374 pass
3375 class Meta2(Base, type):
3376 pass
3377 class D(object, metaclass=Meta1):
3378 pass
3379 class E(object, metaclass=Meta2):
3380 pass
3381 for cls in C, D, E:
3382 verify_dict_readonly(cls)
3383 class_dict = cls.__dict__
3384 try:
3385 class_dict["spam"] = "eggs"
3386 except TypeError:
3387 pass
3388 else:
3389 self.fail("%r's __dict__ can be modified" % cls)
3390
3391 # Modules also disallow __dict__ assignment
3392 class Module1(types.ModuleType, Base):
3393 pass
3394 class Module2(Base, types.ModuleType):
3395 pass
3396 for ModuleType in Module1, Module2:
3397 mod = ModuleType("spam")
3398 verify_dict_readonly(mod)
3399 mod.__dict__["spam"] = "eggs"
3400
3401 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003402 # (at least not any more than regular exception's __dict__ can
3403 # be deleted; on CPython it is not the case, whereas on PyPy they
3404 # can, just like any other new-style instance's __dict__.)
3405 def can_delete_dict(e):
3406 try:
3407 del e.__dict__
3408 except (TypeError, AttributeError):
3409 return False
3410 else:
3411 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003412 class Exception1(Exception, Base):
3413 pass
3414 class Exception2(Base, Exception):
3415 pass
3416 for ExceptionType in Exception, Exception1, Exception2:
3417 e = ExceptionType()
3418 e.__dict__ = {"a": 1}
3419 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003420 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003421
Georg Brandl479a7e72008-02-05 18:13:15 +00003422 def test_binary_operator_override(self):
3423 # Testing overrides of binary operations...
3424 class I(int):
3425 def __repr__(self):
3426 return "I(%r)" % int(self)
3427 def __add__(self, other):
3428 return I(int(self) + int(other))
3429 __radd__ = __add__
3430 def __pow__(self, other, mod=None):
3431 if mod is None:
3432 return I(pow(int(self), int(other)))
3433 else:
3434 return I(pow(int(self), int(other), int(mod)))
3435 def __rpow__(self, other, mod=None):
3436 if mod is None:
3437 return I(pow(int(other), int(self), mod))
3438 else:
3439 return I(pow(int(other), int(self), int(mod)))
3440
3441 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3442 self.assertEqual(repr(I(1) + 2), "I(3)")
3443 self.assertEqual(repr(1 + I(2)), "I(3)")
3444 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3445 self.assertEqual(repr(2 ** I(3)), "I(8)")
3446 self.assertEqual(repr(I(2) ** 3), "I(8)")
3447 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3448 class S(str):
3449 def __eq__(self, other):
3450 return self.lower() == other.lower()
3451
3452 def test_subclass_propagation(self):
3453 # Testing propagation of slot functions to subclasses...
3454 class A(object):
3455 pass
3456 class B(A):
3457 pass
3458 class C(A):
3459 pass
3460 class D(B, C):
3461 pass
3462 d = D()
3463 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3464 A.__hash__ = lambda self: 42
3465 self.assertEqual(hash(d), 42)
3466 C.__hash__ = lambda self: 314
3467 self.assertEqual(hash(d), 314)
3468 B.__hash__ = lambda self: 144
3469 self.assertEqual(hash(d), 144)
3470 D.__hash__ = lambda self: 100
3471 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003472 D.__hash__ = None
3473 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003474 del D.__hash__
3475 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003476 B.__hash__ = None
3477 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003478 del B.__hash__
3479 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003480 C.__hash__ = None
3481 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003482 del C.__hash__
3483 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003484 A.__hash__ = None
3485 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003486 del A.__hash__
3487 self.assertEqual(hash(d), orig_hash)
3488 d.foo = 42
3489 d.bar = 42
3490 self.assertEqual(d.foo, 42)
3491 self.assertEqual(d.bar, 42)
3492 def __getattribute__(self, name):
3493 if name == "foo":
3494 return 24
3495 return object.__getattribute__(self, name)
3496 A.__getattribute__ = __getattribute__
3497 self.assertEqual(d.foo, 24)
3498 self.assertEqual(d.bar, 42)
3499 def __getattr__(self, name):
3500 if name in ("spam", "foo", "bar"):
3501 return "hello"
3502 raise AttributeError(name)
3503 B.__getattr__ = __getattr__
3504 self.assertEqual(d.spam, "hello")
3505 self.assertEqual(d.foo, 24)
3506 self.assertEqual(d.bar, 42)
3507 del A.__getattribute__
3508 self.assertEqual(d.foo, 42)
3509 del d.foo
3510 self.assertEqual(d.foo, "hello")
3511 self.assertEqual(d.bar, 42)
3512 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003513 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003514 d.foo
3515 except AttributeError:
3516 pass
3517 else:
3518 self.fail("d.foo should be undefined now")
3519
3520 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003521 class A(object):
3522 pass
3523 class B(A):
3524 pass
3525 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003526 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003527 A.__setitem__ = lambda *a: None # crash
3528
3529 def test_buffer_inheritance(self):
3530 # Testing that buffer interface is inherited ...
3531
3532 import binascii
3533 # SF bug [#470040] ParseTuple t# vs subclasses.
3534
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003535 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003536 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003537 base = b'abc'
3538 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003539 # b2a_hex uses the buffer interface to get its argument's value, via
3540 # PyArg_ParseTuple 't#' code.
3541 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3542
Georg Brandl479a7e72008-02-05 18:13:15 +00003543 class MyInt(int):
3544 pass
3545 m = MyInt(42)
3546 try:
3547 binascii.b2a_hex(m)
3548 self.fail('subclass of int should not have a buffer interface')
3549 except TypeError:
3550 pass
3551
3552 def test_str_of_str_subclass(self):
3553 # Testing __str__ defined in subclass of str ...
3554 import binascii
3555 import io
3556
3557 class octetstring(str):
3558 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003559 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003560 def __repr__(self):
3561 return self + " repr"
3562
3563 o = octetstring('A')
3564 self.assertEqual(type(o), octetstring)
3565 self.assertEqual(type(str(o)), str)
3566 self.assertEqual(type(repr(o)), str)
3567 self.assertEqual(ord(o), 0x41)
3568 self.assertEqual(str(o), '41')
3569 self.assertEqual(repr(o), 'A repr')
3570 self.assertEqual(o.__str__(), '41')
3571 self.assertEqual(o.__repr__(), 'A repr')
3572
Georg Brandl479a7e72008-02-05 18:13:15 +00003573 def test_keyword_arguments(self):
3574 # Testing keyword arguments to __init__, __call__...
3575 def f(a): return a
3576 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003577 ba = bytearray()
3578 bytearray.__init__(ba, 'abc\xbd\u20ac',
3579 encoding='latin1', errors='replace')
3580 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003581
3582 def test_recursive_call(self):
3583 # Testing recursive __call__() by setting to instance of class...
3584 class A(object):
3585 pass
3586
3587 A.__call__ = A()
3588 try:
3589 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003590 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003591 pass
3592 else:
3593 self.fail("Recursion limit should have been reached for __call__()")
3594
3595 def test_delete_hook(self):
3596 # Testing __del__ hook...
3597 log = []
3598 class C(object):
3599 def __del__(self):
3600 log.append(1)
3601 c = C()
3602 self.assertEqual(log, [])
3603 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003604 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003605 self.assertEqual(log, [1])
3606
3607 class D(object): pass
3608 d = D()
3609 try: del d[0]
3610 except TypeError: pass
3611 else: self.fail("invalid del() didn't raise TypeError")
3612
3613 def test_hash_inheritance(self):
3614 # Testing hash of mutable subclasses...
3615
3616 class mydict(dict):
3617 pass
3618 d = mydict()
3619 try:
3620 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003621 except TypeError:
3622 pass
3623 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003624 self.fail("hash() of dict subclass should fail")
3625
3626 class mylist(list):
3627 pass
3628 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003629 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003630 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003631 except TypeError:
3632 pass
3633 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003634 self.fail("hash() of list subclass should fail")
3635
3636 def test_str_operations(self):
3637 try: 'a' + 5
3638 except TypeError: pass
3639 else: self.fail("'' + 5 doesn't raise TypeError")
3640
3641 try: ''.split('')
3642 except ValueError: pass
3643 else: self.fail("''.split('') doesn't raise ValueError")
3644
3645 try: ''.join([0])
3646 except TypeError: pass
3647 else: self.fail("''.join([0]) doesn't raise TypeError")
3648
3649 try: ''.rindex('5')
3650 except ValueError: pass
3651 else: self.fail("''.rindex('5') doesn't raise ValueError")
3652
3653 try: '%(n)s' % None
3654 except TypeError: pass
3655 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3656
3657 try: '%(n' % {}
3658 except ValueError: pass
3659 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3660
3661 try: '%*s' % ('abc')
3662 except TypeError: pass
3663 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3664
3665 try: '%*.*s' % ('abc', 5)
3666 except TypeError: pass
3667 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3668
3669 try: '%s' % (1, 2)
3670 except TypeError: pass
3671 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3672
3673 try: '%' % None
3674 except ValueError: pass
3675 else: self.fail("'%' % None doesn't raise ValueError")
3676
3677 self.assertEqual('534253'.isdigit(), 1)
3678 self.assertEqual('534253x'.isdigit(), 0)
3679 self.assertEqual('%c' % 5, '\x05')
3680 self.assertEqual('%c' % '5', '5')
3681
3682 def test_deepcopy_recursive(self):
3683 # Testing deepcopy of recursive objects...
3684 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003685 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003686 a = Node()
3687 b = Node()
3688 a.b = b
3689 b.a = a
3690 z = deepcopy(a) # This blew up before
3691
Martin Panterf05641642016-05-08 13:48:10 +00003692 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003693 # Testing uninitialized module objects...
3694 from types import ModuleType as M
3695 m = M.__new__(M)
3696 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003697 self.assertNotHasAttr(m, "__name__")
3698 self.assertNotHasAttr(m, "__file__")
3699 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003700 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003701 m.foo = 1
3702 self.assertEqual(m.__dict__, {"foo": 1})
3703
3704 def test_funny_new(self):
3705 # Testing __new__ returning something unexpected...
3706 class C(object):
3707 def __new__(cls, arg):
3708 if isinstance(arg, str): return [1, 2, 3]
3709 elif isinstance(arg, int): return object.__new__(D)
3710 else: return object.__new__(cls)
3711 class D(C):
3712 def __init__(self, arg):
3713 self.foo = arg
3714 self.assertEqual(C("1"), [1, 2, 3])
3715 self.assertEqual(D("1"), [1, 2, 3])
3716 d = D(None)
3717 self.assertEqual(d.foo, None)
3718 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003719 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003720 self.assertEqual(d.foo, 1)
3721 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003722 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003723 self.assertEqual(d.foo, 1)
3724
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003725 class C(object):
3726 @staticmethod
3727 def __new__(*args):
3728 return args
3729 self.assertEqual(C(1, 2), (C, 1, 2))
3730 class D(C):
3731 pass
3732 self.assertEqual(D(1, 2), (D, 1, 2))
3733
3734 class C(object):
3735 @classmethod
3736 def __new__(*args):
3737 return args
3738 self.assertEqual(C(1, 2), (C, C, 1, 2))
3739 class D(C):
3740 pass
3741 self.assertEqual(D(1, 2), (D, D, 1, 2))
3742
Georg Brandl479a7e72008-02-05 18:13:15 +00003743 def test_imul_bug(self):
3744 # Testing for __imul__ problems...
3745 # SF bug 544647
3746 class C(object):
3747 def __imul__(self, other):
3748 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003749 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003750 y = x
3751 y *= 1.0
3752 self.assertEqual(y, (x, 1.0))
3753 y = x
3754 y *= 2
3755 self.assertEqual(y, (x, 2))
3756 y = x
3757 y *= 3
3758 self.assertEqual(y, (x, 3))
3759 y = x
3760 y *= 1<<100
3761 self.assertEqual(y, (x, 1<<100))
3762 y = x
3763 y *= None
3764 self.assertEqual(y, (x, None))
3765 y = x
3766 y *= "foo"
3767 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003768
Georg Brandl479a7e72008-02-05 18:13:15 +00003769 def test_copy_setstate(self):
3770 # Testing that copy.*copy() correctly uses __setstate__...
3771 import copy
3772 class C(object):
3773 def __init__(self, foo=None):
3774 self.foo = foo
3775 self.__foo = foo
3776 def setfoo(self, foo=None):
3777 self.foo = foo
3778 def getfoo(self):
3779 return self.__foo
3780 def __getstate__(self):
3781 return [self.foo]
3782 def __setstate__(self_, lst):
3783 self.assertEqual(len(lst), 1)
3784 self_.__foo = self_.foo = lst[0]
3785 a = C(42)
3786 a.setfoo(24)
3787 self.assertEqual(a.foo, 24)
3788 self.assertEqual(a.getfoo(), 42)
3789 b = copy.copy(a)
3790 self.assertEqual(b.foo, 24)
3791 self.assertEqual(b.getfoo(), 24)
3792 b = copy.deepcopy(a)
3793 self.assertEqual(b.foo, 24)
3794 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003795
Georg Brandl479a7e72008-02-05 18:13:15 +00003796 def test_slices(self):
3797 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003798
Georg Brandl479a7e72008-02-05 18:13:15 +00003799 # Strings
3800 self.assertEqual("hello"[:4], "hell")
3801 self.assertEqual("hello"[slice(4)], "hell")
3802 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3803 class S(str):
3804 def __getitem__(self, x):
3805 return str.__getitem__(self, x)
3806 self.assertEqual(S("hello")[:4], "hell")
3807 self.assertEqual(S("hello")[slice(4)], "hell")
3808 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3809 # Tuples
3810 self.assertEqual((1,2,3)[:2], (1,2))
3811 self.assertEqual((1,2,3)[slice(2)], (1,2))
3812 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3813 class T(tuple):
3814 def __getitem__(self, x):
3815 return tuple.__getitem__(self, x)
3816 self.assertEqual(T((1,2,3))[:2], (1,2))
3817 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3818 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3819 # Lists
3820 self.assertEqual([1,2,3][:2], [1,2])
3821 self.assertEqual([1,2,3][slice(2)], [1,2])
3822 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3823 class L(list):
3824 def __getitem__(self, x):
3825 return list.__getitem__(self, x)
3826 self.assertEqual(L([1,2,3])[:2], [1,2])
3827 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3828 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3829 # Now do lists and __setitem__
3830 a = L([1,2,3])
3831 a[slice(1, 3)] = [3,2]
3832 self.assertEqual(a, [1,3,2])
3833 a[slice(0, 2, 1)] = [3,1]
3834 self.assertEqual(a, [3,1,2])
3835 a.__setitem__(slice(1, 3), [2,1])
3836 self.assertEqual(a, [3,2,1])
3837 a.__setitem__(slice(0, 2, 1), [2,3])
3838 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003839
Georg Brandl479a7e72008-02-05 18:13:15 +00003840 def test_subtype_resurrection(self):
3841 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003842
Georg Brandl479a7e72008-02-05 18:13:15 +00003843 class C(object):
3844 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003845
Georg Brandl479a7e72008-02-05 18:13:15 +00003846 def __del__(self):
3847 # resurrect the instance
3848 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003849
Georg Brandl479a7e72008-02-05 18:13:15 +00003850 c = C()
3851 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003852
Benjamin Petersone549ead2009-03-28 21:42:05 +00003853 # The most interesting thing here is whether this blows up, due to
3854 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3855 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003856 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003857
Benjamin Petersone549ead2009-03-28 21:42:05 +00003858 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003859 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003860
Georg Brandl479a7e72008-02-05 18:13:15 +00003861 # Make c mortal again, so that the test framework with -l doesn't report
3862 # it as a leak.
3863 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003864
Georg Brandl479a7e72008-02-05 18:13:15 +00003865 def test_slots_trash(self):
3866 # Testing slot trash...
3867 # Deallocating deeply nested slotted trash caused stack overflows
3868 class trash(object):
3869 __slots__ = ['x']
3870 def __init__(self, x):
3871 self.x = x
3872 o = None
3873 for i in range(50000):
3874 o = trash(o)
3875 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003876
Georg Brandl479a7e72008-02-05 18:13:15 +00003877 def test_slots_multiple_inheritance(self):
3878 # SF bug 575229, multiple inheritance w/ slots dumps core
3879 class A(object):
3880 __slots__=()
3881 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003882 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003883 class C(A,B) :
3884 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003885 if support.check_impl_detail():
3886 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003887 self.assertHasAttr(C, '__dict__')
3888 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003889 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003890
Georg Brandl479a7e72008-02-05 18:13:15 +00003891 def test_rmul(self):
3892 # Testing correct invocation of __rmul__...
3893 # SF patch 592646
3894 class C(object):
3895 def __mul__(self, other):
3896 return "mul"
3897 def __rmul__(self, other):
3898 return "rmul"
3899 a = C()
3900 self.assertEqual(a*2, "mul")
3901 self.assertEqual(a*2.2, "mul")
3902 self.assertEqual(2*a, "rmul")
3903 self.assertEqual(2.2*a, "rmul")
3904
3905 def test_ipow(self):
3906 # Testing correct invocation of __ipow__...
3907 # [SF bug 620179]
3908 class C(object):
3909 def __ipow__(self, other):
3910 pass
3911 a = C()
3912 a **= 2
3913
Alexcc02b4f2021-02-26 21:58:39 +02003914 def test_ipow_returns_not_implemented(self):
3915 class A:
3916 def __ipow__(self, other):
3917 return NotImplemented
3918
3919 class B(A):
3920 def __rpow__(self, other):
3921 return 1
3922
3923 class C(A):
3924 def __pow__(self, other):
3925 return 2
3926 a = A()
3927 b = B()
3928 c = C()
3929
3930 a **= b
3931 self.assertEqual(a, 1)
3932
3933 c **= b
3934 self.assertEqual(c, 2)
3935
3936 def test_no_ipow(self):
3937 class B:
3938 def __rpow__(self, other):
3939 return 1
3940
3941 a = object()
3942 b = B()
3943 a **= b
3944 self.assertEqual(a, 1)
3945
3946 def test_ipow_exception_text(self):
3947 x = None
3948 with self.assertRaises(TypeError) as cm:
3949 x **= 2
3950 self.assertIn('unsupported operand type(s) for **=', str(cm.exception))
3951
3952 with self.assertRaises(TypeError) as cm:
3953 y = x ** 2
3954 self.assertIn('unsupported operand type(s) for **', str(cm.exception))
3955
Georg Brandl479a7e72008-02-05 18:13:15 +00003956 def test_mutable_bases(self):
3957 # Testing mutable bases...
3958
3959 # stuff that should work:
3960 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003961 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003962 class C2(object):
3963 def __getattribute__(self, attr):
3964 if attr == 'a':
3965 return 2
3966 else:
3967 return super(C2, self).__getattribute__(attr)
3968 def meth(self):
3969 return 1
3970 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003971 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003972 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003973 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003974 d = D()
3975 e = E()
3976 D.__bases__ = (C,)
3977 D.__bases__ = (C2,)
3978 self.assertEqual(d.meth(), 1)
3979 self.assertEqual(e.meth(), 1)
3980 self.assertEqual(d.a, 2)
3981 self.assertEqual(e.a, 2)
3982 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003983
Georg Brandl479a7e72008-02-05 18:13:15 +00003984 try:
3985 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003986 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003987 pass
3988 else:
3989 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003990
Georg Brandl479a7e72008-02-05 18:13:15 +00003991 try:
3992 D.__bases__ = ()
3993 except TypeError as msg:
3994 if str(msg) == "a new-style class can't have only classic bases":
3995 self.fail("wrong error message for .__bases__ = ()")
3996 else:
3997 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003998
Georg Brandl479a7e72008-02-05 18:13:15 +00003999 try:
4000 D.__bases__ = (D,)
4001 except TypeError:
4002 pass
4003 else:
4004 # actually, we'll have crashed by here...
4005 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00004006
Georg Brandl479a7e72008-02-05 18:13:15 +00004007 try:
4008 D.__bases__ = (C, C)
4009 except TypeError:
4010 pass
4011 else:
4012 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004013
Georg Brandl479a7e72008-02-05 18:13:15 +00004014 try:
4015 D.__bases__ = (E,)
4016 except TypeError:
4017 pass
4018 else:
4019 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00004020
Benjamin Petersonae937c02009-04-18 20:54:08 +00004021 def test_builtin_bases(self):
4022 # Make sure all the builtin types can have their base queried without
4023 # segfaulting. See issue #5787.
4024 builtin_types = [tp for tp in builtins.__dict__.values()
4025 if isinstance(tp, type)]
4026 for tp in builtin_types:
4027 object.__getattribute__(tp, "__bases__")
4028 if tp is not object:
4029 self.assertEqual(len(tp.__bases__), 1, tp)
4030
Benjamin Peterson25c95f12009-05-08 20:42:26 +00004031 class L(list):
4032 pass
4033
4034 class C(object):
4035 pass
4036
4037 class D(C):
4038 pass
4039
4040 try:
4041 L.__bases__ = (dict,)
4042 except TypeError:
4043 pass
4044 else:
4045 self.fail("shouldn't turn list subclass into dict subclass")
4046
4047 try:
4048 list.__bases__ = (dict,)
4049 except TypeError:
4050 pass
4051 else:
4052 self.fail("shouldn't be able to assign to list.__bases__")
4053
4054 try:
4055 D.__bases__ = (C, list)
4056 except TypeError:
4057 pass
4058 else:
4059 assert 0, "best_base calculation found wanting"
4060
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07004061 def test_unsubclassable_types(self):
4062 with self.assertRaises(TypeError):
4063 class X(type(None)):
4064 pass
4065 with self.assertRaises(TypeError):
4066 class X(object, type(None)):
4067 pass
4068 with self.assertRaises(TypeError):
4069 class X(type(None), object):
4070 pass
4071 class O(object):
4072 pass
4073 with self.assertRaises(TypeError):
4074 class X(O, type(None)):
4075 pass
4076 with self.assertRaises(TypeError):
4077 class X(type(None), O):
4078 pass
4079
4080 class X(object):
4081 pass
4082 with self.assertRaises(TypeError):
4083 X.__bases__ = type(None),
4084 with self.assertRaises(TypeError):
4085 X.__bases__ = object, type(None)
4086 with self.assertRaises(TypeError):
4087 X.__bases__ = type(None), object
4088 with self.assertRaises(TypeError):
4089 X.__bases__ = O, type(None)
4090 with self.assertRaises(TypeError):
4091 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00004092
Georg Brandl479a7e72008-02-05 18:13:15 +00004093 def test_mutable_bases_with_failing_mro(self):
4094 # Testing mutable bases with failing mro...
4095 class WorkOnce(type):
4096 def __new__(self, name, bases, ns):
4097 self.flag = 0
4098 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4099 def mro(self):
4100 if self.flag > 0:
4101 raise RuntimeError("bozo")
4102 else:
4103 self.flag += 1
4104 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004105
Georg Brandl479a7e72008-02-05 18:13:15 +00004106 class WorkAlways(type):
4107 def mro(self):
4108 # this is here to make sure that .mro()s aren't called
4109 # with an exception set (which was possible at one point).
4110 # An error message will be printed in a debug build.
4111 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004112 return type.mro(self)
4113
Georg Brandl479a7e72008-02-05 18:13:15 +00004114 class C(object):
4115 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004116
Georg Brandl479a7e72008-02-05 18:13:15 +00004117 class C2(object):
4118 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004119
Georg Brandl479a7e72008-02-05 18:13:15 +00004120 class D(C):
4121 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004122
Georg Brandl479a7e72008-02-05 18:13:15 +00004123 class E(D):
4124 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004125
Georg Brandl479a7e72008-02-05 18:13:15 +00004126 class F(D, metaclass=WorkOnce):
4127 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004128
Georg Brandl479a7e72008-02-05 18:13:15 +00004129 class G(D, metaclass=WorkAlways):
4130 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004131
Georg Brandl479a7e72008-02-05 18:13:15 +00004132 # Immediate subclasses have their mro's adjusted in alphabetical
4133 # order, so E's will get adjusted before adjusting F's fails. We
4134 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004135
Georg Brandl479a7e72008-02-05 18:13:15 +00004136 E_mro_before = E.__mro__
4137 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004138
Armin Rigofd163f92005-12-29 15:59:19 +00004139 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004140 D.__bases__ = (C2,)
4141 except RuntimeError:
4142 self.assertEqual(E.__mro__, E_mro_before)
4143 self.assertEqual(D.__mro__, D_mro_before)
4144 else:
4145 self.fail("exception not propagated")
4146
4147 def test_mutable_bases_catch_mro_conflict(self):
4148 # Testing mutable bases catch mro conflict...
4149 class A(object):
4150 pass
4151
4152 class B(object):
4153 pass
4154
4155 class C(A, B):
4156 pass
4157
4158 class D(A, B):
4159 pass
4160
4161 class E(C, D):
4162 pass
4163
4164 try:
4165 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004166 except TypeError:
4167 pass
4168 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004169 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004170
Georg Brandl479a7e72008-02-05 18:13:15 +00004171 def test_mutable_names(self):
4172 # Testing mutable names...
4173 class C(object):
4174 pass
4175
4176 # C.__module__ could be 'test_descr' or '__main__'
4177 mod = C.__module__
4178
4179 C.__name__ = 'D'
4180 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4181
4182 C.__name__ = 'D.E'
4183 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4184
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004185 def test_evil_type_name(self):
4186 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4187 # execution while the type structure was not in a sane state, and a
4188 # possible segmentation fault as a result. See bug #16447.
4189 class Nasty(str):
4190 def __del__(self):
4191 C.__name__ = "other"
4192
4193 class C:
4194 pass
4195
4196 C.__name__ = Nasty("abc")
4197 C.__name__ = "normal"
4198
Georg Brandl479a7e72008-02-05 18:13:15 +00004199 def test_subclass_right_op(self):
4200 # Testing correct dispatch of subclass overloading __r<op>__...
4201
4202 # This code tests various cases where right-dispatch of a subclass
4203 # should be preferred over left-dispatch of a base class.
4204
4205 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4206
4207 class B(int):
4208 def __floordiv__(self, other):
4209 return "B.__floordiv__"
4210 def __rfloordiv__(self, other):
4211 return "B.__rfloordiv__"
4212
4213 self.assertEqual(B(1) // 1, "B.__floordiv__")
4214 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4215
4216 # Case 2: subclass of object; this is just the baseline for case 3
4217
4218 class C(object):
4219 def __floordiv__(self, other):
4220 return "C.__floordiv__"
4221 def __rfloordiv__(self, other):
4222 return "C.__rfloordiv__"
4223
4224 self.assertEqual(C() // 1, "C.__floordiv__")
4225 self.assertEqual(1 // C(), "C.__rfloordiv__")
4226
4227 # Case 3: subclass of new-style class; here it gets interesting
4228
4229 class D(C):
4230 def __floordiv__(self, other):
4231 return "D.__floordiv__"
4232 def __rfloordiv__(self, other):
4233 return "D.__rfloordiv__"
4234
4235 self.assertEqual(D() // C(), "D.__floordiv__")
4236 self.assertEqual(C() // D(), "D.__rfloordiv__")
4237
4238 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4239
4240 class E(C):
4241 pass
4242
4243 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4244
4245 self.assertEqual(E() // 1, "C.__floordiv__")
4246 self.assertEqual(1 // E(), "C.__rfloordiv__")
4247 self.assertEqual(E() // C(), "C.__floordiv__")
4248 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4249
Benjamin Petersone549ead2009-03-28 21:42:05 +00004250 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004251 def test_meth_class_get(self):
4252 # Testing __get__ method of METH_CLASS C methods...
4253 # Full coverage of descrobject.c::classmethod_get()
4254
4255 # Baseline
4256 arg = [1, 2, 3]
4257 res = {1: None, 2: None, 3: None}
4258 self.assertEqual(dict.fromkeys(arg), res)
4259 self.assertEqual({}.fromkeys(arg), res)
4260
4261 # Now get the descriptor
4262 descr = dict.__dict__["fromkeys"]
4263
4264 # More baseline using the descriptor directly
4265 self.assertEqual(descr.__get__(None, dict)(arg), res)
4266 self.assertEqual(descr.__get__({})(arg), res)
4267
4268 # Now check various error cases
4269 try:
4270 descr.__get__(None, None)
4271 except TypeError:
4272 pass
4273 else:
4274 self.fail("shouldn't have allowed descr.__get__(None, None)")
4275 try:
4276 descr.__get__(42)
4277 except TypeError:
4278 pass
4279 else:
4280 self.fail("shouldn't have allowed descr.__get__(42)")
4281 try:
4282 descr.__get__(None, 42)
4283 except TypeError:
4284 pass
4285 else:
4286 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4287 try:
4288 descr.__get__(None, int)
4289 except TypeError:
4290 pass
4291 else:
4292 self.fail("shouldn't have allowed descr.__get__(None, int)")
4293
4294 def test_isinst_isclass(self):
4295 # Testing proxy isinstance() and isclass()...
4296 class Proxy(object):
4297 def __init__(self, obj):
4298 self.__obj = obj
4299 def __getattribute__(self, name):
4300 if name.startswith("_Proxy__"):
4301 return object.__getattribute__(self, name)
4302 else:
4303 return getattr(self.__obj, name)
4304 # Test with a classic class
4305 class C:
4306 pass
4307 a = C()
4308 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004309 self.assertIsInstance(a, C) # Baseline
4310 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004311 # Test with a classic subclass
4312 class D(C):
4313 pass
4314 a = D()
4315 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004316 self.assertIsInstance(a, C) # Baseline
4317 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004318 # Test with a new-style class
4319 class C(object):
4320 pass
4321 a = C()
4322 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004323 self.assertIsInstance(a, C) # Baseline
4324 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004325 # Test with a new-style subclass
4326 class D(C):
4327 pass
4328 a = D()
4329 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004330 self.assertIsInstance(a, C) # Baseline
4331 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004332
4333 def test_proxy_super(self):
4334 # Testing super() for a proxy object...
4335 class Proxy(object):
4336 def __init__(self, obj):
4337 self.__obj = obj
4338 def __getattribute__(self, name):
4339 if name.startswith("_Proxy__"):
4340 return object.__getattribute__(self, name)
4341 else:
4342 return getattr(self.__obj, name)
4343
4344 class B(object):
4345 def f(self):
4346 return "B.f"
4347
4348 class C(B):
4349 def f(self):
4350 return super(C, self).f() + "->C.f"
4351
4352 obj = C()
4353 p = Proxy(obj)
4354 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4355
4356 def test_carloverre(self):
4357 # Testing prohibition of Carlo Verre's hack...
4358 try:
4359 object.__setattr__(str, "foo", 42)
4360 except TypeError:
4361 pass
4362 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004363 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004364 try:
4365 object.__delattr__(str, "lower")
4366 except TypeError:
4367 pass
4368 else:
4369 self.fail("Carlo Verre __delattr__ succeeded!")
4370
scoderc53b3102020-07-18 23:19:50 +02004371 def test_carloverre_multi_inherit_valid(self):
4372 class A(type):
4373 def __setattr__(cls, key, value):
4374 type.__setattr__(cls, key, value)
4375
4376 class B:
4377 pass
4378
4379 class C(B, A):
4380 pass
4381
4382 obj = C('D', (object,), {})
4383 try:
4384 obj.test = True
4385 except TypeError:
4386 self.fail("setattr through direct base types should be legal")
4387
4388 def test_carloverre_multi_inherit_invalid(self):
4389 class A(type):
4390 def __setattr__(cls, key, value):
4391 object.__setattr__(cls, key, value) # this should fail!
4392
4393 class B:
4394 pass
4395
4396 class C(B, A):
4397 pass
4398
4399 obj = C('D', (object,), {})
4400 try:
4401 obj.test = True
4402 except TypeError:
4403 pass
4404 else:
4405 self.fail("setattr through indirect base types should be rejected")
4406
Georg Brandl479a7e72008-02-05 18:13:15 +00004407 def test_weakref_segfault(self):
4408 # Testing weakref segfault...
4409 # SF 742911
4410 import weakref
4411
4412 class Provoker:
4413 def __init__(self, referrent):
4414 self.ref = weakref.ref(referrent)
4415
4416 def __del__(self):
4417 x = self.ref()
4418
4419 class Oops(object):
4420 pass
4421
4422 o = Oops()
4423 o.whatever = Provoker(o)
4424 del o
4425
4426 def test_wrapper_segfault(self):
4427 # SF 927248: deeply nested wrappers could cause stack overflow
4428 f = lambda:None
4429 for i in range(1000000):
4430 f = f.__call__
4431 f = None
4432
4433 def test_file_fault(self):
4434 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004435 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004436 class StdoutGuard:
4437 def __getattr__(self, attr):
4438 sys.stdout = sys.__stdout__
4439 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4440 sys.stdout = StdoutGuard()
4441 try:
4442 print("Oops!")
4443 except RuntimeError:
4444 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004445 finally:
4446 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004447
4448 def test_vicious_descriptor_nonsense(self):
4449 # Testing vicious_descriptor_nonsense...
4450
4451 # A potential segfault spotted by Thomas Wouters in mail to
4452 # python-dev 2003-04-17, turned into an example & fixed by Michael
4453 # Hudson just less than four months later...
4454
4455 class Evil(object):
4456 def __hash__(self):
4457 return hash('attr')
4458 def __eq__(self, other):
Serhiy Storchakaff3d39f2019-02-26 08:03:21 +02004459 try:
4460 del C.attr
4461 except AttributeError:
4462 # possible race condition
4463 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00004464 return 0
4465
4466 class Descr(object):
4467 def __get__(self, ob, type=None):
4468 return 1
4469
4470 class C(object):
4471 attr = Descr()
4472
4473 c = C()
4474 c.__dict__[Evil()] = 0
4475
4476 self.assertEqual(c.attr, 1)
4477 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004478 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004479 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004480
4481 def test_init(self):
4482 # SF 1155938
4483 class Foo(object):
4484 def __init__(self):
4485 return 10
4486 try:
4487 Foo()
4488 except TypeError:
4489 pass
4490 else:
4491 self.fail("did not test __init__() for None return")
4492
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004493 def assertNotOrderable(self, a, b):
4494 with self.assertRaises(TypeError):
4495 a < b
4496 with self.assertRaises(TypeError):
4497 a > b
4498 with self.assertRaises(TypeError):
4499 a <= b
4500 with self.assertRaises(TypeError):
4501 a >= b
4502
Georg Brandl479a7e72008-02-05 18:13:15 +00004503 def test_method_wrapper(self):
4504 # Testing method-wrapper objects...
4505 # <type 'method-wrapper'> did not support any reflection before 2.5
Georg Brandl479a7e72008-02-05 18:13:15 +00004506 l = []
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004507 self.assertTrue(l.__add__ == l.__add__)
4508 self.assertFalse(l.__add__ != l.__add__)
4509 self.assertFalse(l.__add__ == [].__add__)
4510 self.assertTrue(l.__add__ != [].__add__)
4511 self.assertFalse(l.__add__ == l.__mul__)
4512 self.assertTrue(l.__add__ != l.__mul__)
4513 self.assertNotOrderable(l.__add__, l.__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004514 self.assertEqual(l.__add__.__name__, '__add__')
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004515 self.assertIs(l.__add__.__self__, l)
4516 self.assertIs(l.__add__.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004517 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004518 # hash([].__add__) should not be based on hash([])
4519 hash(l.__add__)
Georg Brandl479a7e72008-02-05 18:13:15 +00004520
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004521 def test_builtin_function_or_method(self):
4522 # Not really belonging to test_descr, but introspection and
4523 # comparison on <type 'builtin_function_or_method'> seems not
4524 # to be tested elsewhere
4525 l = []
4526 self.assertTrue(l.append == l.append)
4527 self.assertFalse(l.append != l.append)
4528 self.assertFalse(l.append == [].append)
4529 self.assertTrue(l.append != [].append)
4530 self.assertFalse(l.append == l.pop)
4531 self.assertTrue(l.append != l.pop)
4532 self.assertNotOrderable(l.append, l.append)
4533 self.assertEqual(l.append.__name__, 'append')
4534 self.assertIs(l.append.__self__, l)
4535 # self.assertIs(l.append.__objclass__, list) --- could be added?
4536 self.assertEqual(l.append.__doc__, list.append.__doc__)
4537 # hash([].append) should not be based on hash([])
4538 hash(l.append)
4539
4540 def test_special_unbound_method_types(self):
4541 # Testing objects of <type 'wrapper_descriptor'>...
4542 self.assertTrue(list.__add__ == list.__add__)
4543 self.assertFalse(list.__add__ != list.__add__)
4544 self.assertFalse(list.__add__ == list.__mul__)
4545 self.assertTrue(list.__add__ != list.__mul__)
4546 self.assertNotOrderable(list.__add__, list.__add__)
4547 self.assertEqual(list.__add__.__name__, '__add__')
4548 self.assertIs(list.__add__.__objclass__, list)
4549
4550 # Testing objects of <type 'method_descriptor'>...
4551 self.assertTrue(list.append == list.append)
4552 self.assertFalse(list.append != list.append)
4553 self.assertFalse(list.append == list.pop)
4554 self.assertTrue(list.append != list.pop)
4555 self.assertNotOrderable(list.append, list.append)
4556 self.assertEqual(list.append.__name__, 'append')
4557 self.assertIs(list.append.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004558
4559 def test_not_implemented(self):
4560 # Testing NotImplemented...
4561 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004562 import operator
4563
4564 def specialmethod(self, other):
4565 return NotImplemented
4566
4567 def check(expr, x, y):
4568 try:
4569 exec(expr, {'x': x, 'y': y, 'operator': operator})
4570 except TypeError:
4571 pass
4572 else:
4573 self.fail("no TypeError from %r" % (expr,))
4574
4575 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4576 # TypeErrors
4577 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4578 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004579 for name, expr, iexpr in [
4580 ('__add__', 'x + y', 'x += y'),
4581 ('__sub__', 'x - y', 'x -= y'),
4582 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004583 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004584 ('__truediv__', 'x / y', 'x /= y'),
4585 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004586 ('__mod__', 'x % y', 'x %= y'),
4587 ('__divmod__', 'divmod(x, y)', None),
4588 ('__pow__', 'x ** y', 'x **= y'),
4589 ('__lshift__', 'x << y', 'x <<= y'),
4590 ('__rshift__', 'x >> y', 'x >>= y'),
4591 ('__and__', 'x & y', 'x &= y'),
4592 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004593 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004594 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004595 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004596 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004597 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004598 check(expr, a, N1)
4599 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004600 if iexpr:
4601 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004602 check(iexpr, a, N1)
4603 check(iexpr, a, N2)
4604 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004605 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004606 c = C()
4607 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004608 check(iexpr, c, N1)
4609 check(iexpr, c, N2)
4610
Georg Brandl479a7e72008-02-05 18:13:15 +00004611 def test_assign_slice(self):
4612 # ceval.c's assign_slice used to check for
4613 # tp->tp_as_sequence->sq_slice instead of
4614 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004615
Georg Brandl479a7e72008-02-05 18:13:15 +00004616 class C(object):
4617 def __setitem__(self, idx, value):
4618 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004619
Georg Brandl479a7e72008-02-05 18:13:15 +00004620 c = C()
4621 c[1:2] = 3
4622 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004623
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004624 def test_set_and_no_get(self):
4625 # See
4626 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4627 class Descr(object):
4628
4629 def __init__(self, name):
4630 self.name = name
4631
4632 def __set__(self, obj, value):
4633 obj.__dict__[self.name] = value
4634 descr = Descr("a")
4635
4636 class X(object):
4637 a = descr
4638
4639 x = X()
4640 self.assertIs(x.a, descr)
4641 x.a = 42
4642 self.assertEqual(x.a, 42)
4643
Benjamin Peterson21896a32010-03-21 22:03:03 +00004644 # Also check type_getattro for correctness.
4645 class Meta(type):
4646 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004647 class X(metaclass=Meta):
4648 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004649 X.a = 42
4650 Meta.a = Descr("a")
4651 self.assertEqual(X.a, 42)
4652
Benjamin Peterson9262b842008-11-17 22:45:50 +00004653 def test_getattr_hooks(self):
4654 # issue 4230
4655
4656 class Descriptor(object):
4657 counter = 0
4658 def __get__(self, obj, objtype=None):
4659 def getter(name):
4660 self.counter += 1
4661 raise AttributeError(name)
4662 return getter
4663
4664 descr = Descriptor()
4665 class A(object):
4666 __getattribute__ = descr
4667 class B(object):
4668 __getattr__ = descr
4669 class C(object):
4670 __getattribute__ = descr
4671 __getattr__ = descr
4672
4673 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004674 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004675 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004676 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004677 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004678 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004679
Benjamin Peterson9262b842008-11-17 22:45:50 +00004680 class EvilGetattribute(object):
4681 # This used to segfault
4682 def __getattr__(self, name):
4683 raise AttributeError(name)
4684 def __getattribute__(self, name):
4685 del EvilGetattribute.__getattr__
4686 for i in range(5):
4687 gc.collect()
4688 raise AttributeError(name)
4689
4690 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4691
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004692 def test_type___getattribute__(self):
4693 self.assertRaises(TypeError, type.__getattribute__, list, type)
4694
Benjamin Peterson477ba912011-01-12 15:34:01 +00004695 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004696 # type pretends not to have __abstractmethods__.
4697 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4698 class meta(type):
4699 pass
4700 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004701 class X(object):
4702 pass
4703 with self.assertRaises(AttributeError):
4704 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004705
Victor Stinner3249dec2011-05-01 23:19:15 +02004706 def test_proxy_call(self):
4707 class FakeStr:
4708 __class__ = str
4709
4710 fake_str = FakeStr()
4711 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004712 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004713
4714 # call a method descriptor
4715 with self.assertRaises(TypeError):
4716 str.split(fake_str)
4717
4718 # call a slot wrapper descriptor
4719 with self.assertRaises(TypeError):
4720 str.__add__(fake_str, "abc")
4721
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004722 def test_repr_as_str(self):
4723 # Issue #11603: crash or infinite loop when rebinding __str__ as
4724 # __repr__.
4725 class Foo:
4726 pass
4727 Foo.__repr__ = Foo.__str__
4728 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004729 self.assertRaises(RecursionError, str, foo)
4730 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004731
4732 def test_mixing_slot_wrappers(self):
4733 class X(dict):
4734 __setattr__ = dict.__setitem__
Jeroen Demeyer2e9954d2019-06-17 13:53:21 +02004735 __neg__ = dict.copy
Benjamin Peterson7b166872012-04-24 11:06:25 -04004736 x = X()
4737 x.y = 42
4738 self.assertEqual(x["y"], 42)
Jeroen Demeyer2e9954d2019-06-17 13:53:21 +02004739 self.assertEqual(x, -x)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004740
Jeroen Demeyer57ea3352019-09-10 13:21:57 +02004741 def test_wrong_class_slot_wrapper(self):
4742 # Check bpo-37619: a wrapper descriptor taken from the wrong class
4743 # should raise an exception instead of silently being ignored
4744 class A(int):
4745 __eq__ = str.__eq__
4746 __add__ = str.__add__
4747 a = A()
4748 with self.assertRaises(TypeError):
4749 a == a
4750 with self.assertRaises(TypeError):
4751 a + a
4752
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004753 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004754 with self.assertRaises(ValueError) as cm:
4755 class X:
4756 __slots__ = ["foo"]
4757 foo = None
4758 m = str(cm.exception)
4759 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4760
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004761 def test_set_doc(self):
4762 class X:
4763 "elephant"
4764 X.__doc__ = "banana"
4765 self.assertEqual(X.__doc__, "banana")
Erlend Egeberg Aasland64141382021-04-30 15:25:43 +02004766
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004767 with self.assertRaises(TypeError) as cm:
4768 type(list).__dict__["__doc__"].__set__(list, "blah")
Erlend Egeberg Aasland64141382021-04-30 15:25:43 +02004769 self.assertIn("cannot set '__doc__' attribute of immutable type 'list'", str(cm.exception))
4770
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004771 with self.assertRaises(TypeError) as cm:
4772 type(X).__dict__["__doc__"].__delete__(X)
Erlend Egeberg Aasland64141382021-04-30 15:25:43 +02004773 self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception))
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004774 self.assertEqual(X.__doc__, "banana")
4775
Antoine Pitrou9d574812011-12-12 13:47:25 +01004776 def test_qualname(self):
4777 descriptors = [str.lower, complex.real, float.real, int.__add__]
4778 types = ['method', 'member', 'getset', 'wrapper']
4779
4780 # make sure we have an example of each type of descriptor
4781 for d, n in zip(descriptors, types):
4782 self.assertEqual(type(d).__name__, n + '_descriptor')
4783
4784 for d in descriptors:
4785 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4786 self.assertEqual(d.__qualname__, qualname)
4787
4788 self.assertEqual(str.lower.__qualname__, 'str.lower')
4789 self.assertEqual(complex.real.__qualname__, 'complex.real')
4790 self.assertEqual(float.real.__qualname__, 'float.real')
4791 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4792
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004793 class X:
4794 pass
4795 with self.assertRaises(TypeError):
4796 del X.__qualname__
4797
4798 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4799 str, 'Oink')
4800
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004801 global Y
4802 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004803 class Inside:
4804 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004805 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004806 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004807
Victor Stinner6f738742012-02-25 01:22:36 +01004808 def test_qualname_dict(self):
4809 ns = {'__qualname__': 'some.name'}
4810 tp = type('Foo', (), ns)
4811 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004812 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004813 self.assertEqual(ns, {'__qualname__': 'some.name'})
4814
4815 ns = {'__qualname__': 1}
4816 self.assertRaises(TypeError, type, 'Foo', (), ns)
4817
Benjamin Peterson52c42432012-03-07 18:41:11 -06004818 def test_cycle_through_dict(self):
4819 # See bug #1469629
4820 class X(dict):
4821 def __init__(self):
4822 dict.__init__(self)
4823 self.__dict__ = self
4824 x = X()
4825 x.attr = 42
4826 wr = weakref.ref(x)
4827 del x
4828 support.gc_collect()
4829 self.assertIsNone(wr())
4830 for o in gc.get_objects():
4831 self.assertIsNot(type(o), X)
4832
Benjamin Peterson96384b92012-03-17 00:05:44 -05004833 def test_object_new_and_init_with_parameters(self):
4834 # See issue #1683368
4835 class OverrideNeither:
4836 pass
4837 self.assertRaises(TypeError, OverrideNeither, 1)
4838 self.assertRaises(TypeError, OverrideNeither, kw=1)
4839 class OverrideNew:
4840 def __new__(cls, foo, kw=0, *args, **kwds):
4841 return object.__new__(cls, *args, **kwds)
4842 class OverrideInit:
4843 def __init__(self, foo, kw=0, *args, **kwargs):
4844 return object.__init__(self, *args, **kwargs)
4845 class OverrideBoth(OverrideNew, OverrideInit):
4846 pass
4847 for case in OverrideNew, OverrideInit, OverrideBoth:
4848 case(1)
4849 case(1, kw=2)
4850 self.assertRaises(TypeError, case, 1, 2, 3)
4851 self.assertRaises(TypeError, case, 1, 2, foo=3)
4852
Benjamin Petersondf813792014-03-17 15:57:17 -05004853 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4854 class Base:
4855 pass
4856 class Sub(Base):
4857 pass
4858 self.assertIn("__dict__", Base.__dict__)
4859 self.assertNotIn("__dict__", Sub.__dict__)
4860
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004861 def test_bound_method_repr(self):
4862 class Foo:
4863 def method(self):
4864 pass
4865 self.assertRegex(repr(Foo().method),
4866 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4867
4868
4869 class Base:
4870 def method(self):
4871 pass
4872 class Derived1(Base):
4873 pass
4874 class Derived2(Base):
4875 def method(self):
4876 pass
4877 base = Base()
4878 derived1 = Derived1()
4879 derived2 = Derived2()
4880 super_d2 = super(Derived2, derived2)
4881 self.assertRegex(repr(base.method),
4882 r"<bound method .*Base\.method of <.*Base object at .*>>")
4883 self.assertRegex(repr(derived1.method),
4884 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4885 self.assertRegex(repr(derived2.method),
4886 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4887 self.assertRegex(repr(super_d2.method),
4888 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4889
4890 class Foo:
4891 @classmethod
4892 def method(cls):
4893 pass
4894 foo = Foo()
4895 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004896 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004897 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004898 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004899
4900
4901 class MyCallable:
4902 def __call__(self, arg):
4903 pass
4904 func = MyCallable() # func has no __name__ or __qualname__ attributes
4905 instance = object()
4906 method = types.MethodType(func, instance)
4907 self.assertRegex(repr(method),
4908 r"<bound method \? of <object object at .*>>")
4909 func.__name__ = "name"
4910 self.assertRegex(repr(method),
4911 r"<bound method name of <object object at .*>>")
4912 func.__qualname__ = "qualname"
4913 self.assertRegex(repr(method),
4914 r"<bound method qualname of <object object at .*>>")
4915
jdemeyer5a306202018-10-19 23:50:06 +02004916 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4917 def test_bpo25750(self):
4918 # bpo-25750: calling a descriptor (implemented as built-in
4919 # function with METH_FASTCALL) should not crash CPython if the
4920 # descriptor deletes itself from the class.
4921 class Descr:
4922 __get__ = _testcapi.bad_get
4923
4924 class X:
4925 descr = Descr()
4926 def __new__(cls):
4927 cls.descr = None
4928 # Create this large list to corrupt some unused memory
4929 cls.lst = [2**i for i in range(10000)]
4930 X.descr
4931
Antoine Pitrou9d574812011-12-12 13:47:25 +01004932
Georg Brandl479a7e72008-02-05 18:13:15 +00004933class DictProxyTests(unittest.TestCase):
4934 def setUp(self):
4935 class C(object):
4936 def meth(self):
4937 pass
4938 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004939
Brett Cannon7a540732011-02-22 03:04:06 +00004940 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4941 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004942 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004943 # Testing dict-proxy keys...
4944 it = self.C.__dict__.keys()
4945 self.assertNotIsInstance(it, list)
4946 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004947 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004948 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004949 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004950
Brett Cannon7a540732011-02-22 03:04:06 +00004951 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4952 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004953 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004954 # Testing dict-proxy values...
4955 it = self.C.__dict__.values()
4956 self.assertNotIsInstance(it, list)
4957 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004958 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004959
Brett Cannon7a540732011-02-22 03:04:06 +00004960 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4961 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004962 def test_iter_items(self):
4963 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004964 it = self.C.__dict__.items()
4965 self.assertNotIsInstance(it, list)
4966 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004967 keys.sort()
4968 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004969 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004970
Georg Brandl479a7e72008-02-05 18:13:15 +00004971 def test_dict_type_with_metaclass(self):
4972 # Testing type of __dict__ when metaclass set...
4973 class B(object):
4974 pass
4975 class M(type):
4976 pass
4977 class C(metaclass=M):
4978 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4979 pass
4980 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004981
Ezio Melottiac53ab62010-12-18 14:59:43 +00004982 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004983 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004984 # We can't blindly compare with the repr of another dict as ordering
4985 # of keys and values is arbitrary and may differ.
4986 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004987 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004988 self.assertTrue(r.endswith(')'), r)
4989 for k, v in self.C.__dict__.items():
4990 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004991
Christian Heimesbbffeb62008-01-24 09:42:52 +00004992
Georg Brandl479a7e72008-02-05 18:13:15 +00004993class PTypesLongInitTest(unittest.TestCase):
4994 # This is in its own TestCase so that it can be run before any other tests.
4995 def test_pytype_long_ready(self):
4996 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004997
Georg Brandl479a7e72008-02-05 18:13:15 +00004998 # This dumps core when SF bug 551412 isn't fixed --
4999 # but only when test_descr.py is run separately.
5000 # (That can't be helped -- as soon as PyType_Ready()
5001 # is called for PyLong_Type, the bug is gone.)
5002 class UserLong(object):
5003 def __pow__(self, *args):
5004 pass
5005 try:
5006 pow(0, UserLong(), 0)
5007 except:
5008 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00005009
Georg Brandl479a7e72008-02-05 18:13:15 +00005010 # Another segfault only when run early
5011 # (before PyType_Ready(tuple) is called)
5012 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00005013
5014
Victor Stinnerd74782b2012-03-09 00:39:08 +01005015class MiscTests(unittest.TestCase):
5016 def test_type_lookup_mro_reference(self):
5017 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
5018 # the type MRO because it may be modified during the lookup, if
5019 # __bases__ is set during the lookup for example.
5020 class MyKey(object):
5021 def __hash__(self):
5022 return hash('mykey')
5023
5024 def __eq__(self, other):
5025 X.__bases__ = (Base2,)
5026
5027 class Base(object):
5028 mykey = 'from Base'
5029 mykey2 = 'from Base'
5030
5031 class Base2(object):
5032 mykey = 'from Base2'
5033 mykey2 = 'from Base2'
5034
5035 X = type('X', (Base,), {MyKey(): 5})
5036 # mykey is read from Base
5037 self.assertEqual(X.mykey, 'from Base')
5038 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
5039 self.assertEqual(X.mykey2, 'from Base2')
5040
5041
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005042class PicklingTests(unittest.TestCase):
5043
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005044 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005045 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02005046 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005047 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02005048 if kwargs:
5049 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
5050 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005051 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02005052 self.assertEqual(reduce_value[0], copyreg.__newobj__)
5053 self.assertEqual(reduce_value[1], (type(obj),) + args)
5054 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005055 if listitems is not None:
5056 self.assertListEqual(list(reduce_value[3]), listitems)
5057 else:
5058 self.assertIsNone(reduce_value[3])
5059 if dictitems is not None:
5060 self.assertDictEqual(dict(reduce_value[4]), dictitems)
5061 else:
5062 self.assertIsNone(reduce_value[4])
5063 else:
5064 base_type = type(obj).__base__
5065 reduce_value = (copyreg._reconstructor,
5066 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005067 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005068 None if base_type is object else base_type(obj)))
5069 if state is not None:
5070 reduce_value += (state,)
5071 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
5072 self.assertEqual(obj.__reduce__(), reduce_value)
5073
5074 def test_reduce(self):
5075 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5076 args = (-101, "spam")
5077 kwargs = {'bacon': -201, 'fish': -301}
5078 state = {'cheese': -401}
5079
5080 class C1:
5081 def __getnewargs__(self):
5082 return args
5083 obj = C1()
5084 for proto in protocols:
5085 self._check_reduce(proto, obj, args)
5086
5087 for name, value in state.items():
5088 setattr(obj, name, value)
5089 for proto in protocols:
5090 self._check_reduce(proto, obj, args, state=state)
5091
5092 class C2:
5093 def __getnewargs__(self):
5094 return "bad args"
5095 obj = C2()
5096 for proto in protocols:
5097 if proto >= 2:
5098 with self.assertRaises(TypeError):
5099 obj.__reduce_ex__(proto)
5100
5101 class C3:
5102 def __getnewargs_ex__(self):
5103 return (args, kwargs)
5104 obj = C3()
5105 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03005106 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005107 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005108
5109 class C4:
5110 def __getnewargs_ex__(self):
5111 return (args, "bad dict")
5112 class C5:
5113 def __getnewargs_ex__(self):
5114 return ("bad tuple", kwargs)
5115 class C6:
5116 def __getnewargs_ex__(self):
5117 return ()
5118 class C7:
5119 def __getnewargs_ex__(self):
5120 return "bad args"
5121 for proto in protocols:
5122 for cls in C4, C5, C6, C7:
5123 obj = cls()
5124 if proto >= 2:
5125 with self.assertRaises((TypeError, ValueError)):
5126 obj.__reduce_ex__(proto)
5127
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005128 class C9:
5129 def __getnewargs_ex__(self):
5130 return (args, {})
5131 obj = C9()
5132 for proto in protocols:
5133 self._check_reduce(proto, obj, args)
5134
5135 class C10:
5136 def __getnewargs_ex__(self):
5137 raise IndexError
5138 obj = C10()
5139 for proto in protocols:
5140 if proto >= 2:
5141 with self.assertRaises(IndexError):
5142 obj.__reduce_ex__(proto)
5143
5144 class C11:
5145 def __getstate__(self):
5146 return state
5147 obj = C11()
5148 for proto in protocols:
5149 self._check_reduce(proto, obj, state=state)
5150
5151 class C12:
5152 def __getstate__(self):
5153 return "not dict"
5154 obj = C12()
5155 for proto in protocols:
5156 self._check_reduce(proto, obj, state="not dict")
5157
5158 class C13:
5159 def __getstate__(self):
5160 raise IndexError
5161 obj = C13()
5162 for proto in protocols:
5163 with self.assertRaises(IndexError):
5164 obj.__reduce_ex__(proto)
5165 if proto < 2:
5166 with self.assertRaises(IndexError):
5167 obj.__reduce__()
5168
5169 class C14:
5170 __slots__ = tuple(state)
5171 def __init__(self):
5172 for name, value in state.items():
5173 setattr(self, name, value)
5174
5175 obj = C14()
5176 for proto in protocols:
5177 if proto >= 2:
5178 self._check_reduce(proto, obj, state=(None, state))
5179 else:
5180 with self.assertRaises(TypeError):
5181 obj.__reduce_ex__(proto)
5182 with self.assertRaises(TypeError):
5183 obj.__reduce__()
5184
5185 class C15(dict):
5186 pass
5187 obj = C15({"quebec": -601})
5188 for proto in protocols:
5189 self._check_reduce(proto, obj, dictitems=dict(obj))
5190
5191 class C16(list):
5192 pass
5193 obj = C16(["yukon"])
5194 for proto in protocols:
5195 self._check_reduce(proto, obj, listitems=list(obj))
5196
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005197 def test_special_method_lookup(self):
5198 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5199 class Picky:
5200 def __getstate__(self):
5201 return {}
5202
5203 def __getattr__(self, attr):
5204 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5205 raise AssertionError(attr)
5206 return None
5207 for protocol in protocols:
5208 state = {} if protocol >= 2 else None
5209 self._check_reduce(protocol, Picky(), state=state)
5210
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005211 def _assert_is_copy(self, obj, objcopy, msg=None):
5212 """Utility method to verify if two objects are copies of each others.
5213 """
5214 if msg is None:
5215 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5216 if type(obj).__repr__ is object.__repr__:
5217 # We have this limitation for now because we use the object's repr
5218 # to help us verify that the two objects are copies. This allows
5219 # us to delegate the non-generic verification logic to the objects
5220 # themselves.
5221 raise ValueError("object passed to _assert_is_copy must " +
5222 "override the __repr__ method.")
5223 self.assertIsNot(obj, objcopy, msg=msg)
5224 self.assertIs(type(obj), type(objcopy), msg=msg)
5225 if hasattr(obj, '__dict__'):
5226 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5227 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5228 if hasattr(obj, '__slots__'):
5229 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5230 for slot in obj.__slots__:
5231 self.assertEqual(
5232 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5233 self.assertEqual(getattr(obj, slot, None),
5234 getattr(objcopy, slot, None), msg=msg)
5235 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5236
5237 @staticmethod
5238 def _generate_pickle_copiers():
5239 """Utility method to generate the many possible pickle configurations.
5240 """
5241 class PickleCopier:
5242 "This class copies object using pickle."
5243 def __init__(self, proto, dumps, loads):
5244 self.proto = proto
5245 self.dumps = dumps
5246 self.loads = loads
5247 def copy(self, obj):
5248 return self.loads(self.dumps(obj, self.proto))
5249 def __repr__(self):
5250 # We try to be as descriptive as possible here since this is
5251 # the string which we will allow us to tell the pickle
5252 # configuration we are using during debugging.
5253 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5254 .format(self.proto,
5255 self.dumps.__module__, self.dumps.__qualname__,
5256 self.loads.__module__, self.loads.__qualname__))
5257 return (PickleCopier(*args) for args in
5258 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5259 {pickle.dumps, pickle._dumps},
5260 {pickle.loads, pickle._loads}))
5261
5262 def test_pickle_slots(self):
5263 # Tests pickling of classes with __slots__.
5264
5265 # Pickling of classes with __slots__ but without __getstate__ should
5266 # fail (if using protocol 0 or 1)
5267 global C
5268 class C:
5269 __slots__ = ['a']
5270 with self.assertRaises(TypeError):
5271 pickle.dumps(C(), 0)
5272
5273 global D
5274 class D(C):
5275 pass
5276 with self.assertRaises(TypeError):
5277 pickle.dumps(D(), 0)
5278
5279 class C:
5280 "A class with __getstate__ and __setstate__ implemented."
5281 __slots__ = ['a']
5282 def __getstate__(self):
5283 state = getattr(self, '__dict__', {}).copy()
5284 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005285 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005286 try:
5287 state[slot] = getattr(self, slot)
5288 except AttributeError:
5289 pass
5290 return state
5291 def __setstate__(self, state):
5292 for k, v in state.items():
5293 setattr(self, k, v)
5294 def __repr__(self):
5295 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5296
5297 class D(C):
5298 "A subclass of a class with slots."
5299 pass
5300
5301 global E
5302 class E(C):
5303 "A subclass with an extra slot."
5304 __slots__ = ['b']
5305
5306 # Now it should work
5307 for pickle_copier in self._generate_pickle_copiers():
5308 with self.subTest(pickle_copier=pickle_copier):
5309 x = C()
5310 y = pickle_copier.copy(x)
5311 self._assert_is_copy(x, y)
5312
5313 x.a = 42
5314 y = pickle_copier.copy(x)
5315 self._assert_is_copy(x, y)
5316
5317 x = D()
5318 x.a = 42
5319 x.b = 100
5320 y = pickle_copier.copy(x)
5321 self._assert_is_copy(x, y)
5322
5323 x = E()
5324 x.a = 42
5325 x.b = "foo"
5326 y = pickle_copier.copy(x)
5327 self._assert_is_copy(x, y)
5328
5329 def test_reduce_copying(self):
5330 # Tests pickling and copying new-style classes and objects.
5331 global C1
5332 class C1:
5333 "The state of this class is copyable via its instance dict."
5334 ARGS = (1, 2)
5335 NEED_DICT_COPYING = True
5336 def __init__(self, a, b):
5337 super().__init__()
5338 self.a = a
5339 self.b = b
5340 def __repr__(self):
5341 return "C1(%r, %r)" % (self.a, self.b)
5342
5343 global C2
5344 class C2(list):
5345 "A list subclass copyable via __getnewargs__."
5346 ARGS = (1, 2)
5347 NEED_DICT_COPYING = False
5348 def __new__(cls, a, b):
5349 self = super().__new__(cls)
5350 self.a = a
5351 self.b = b
5352 return self
5353 def __init__(self, *args):
5354 super().__init__()
5355 # This helps testing that __init__ is not called during the
5356 # unpickling process, which would cause extra appends.
5357 self.append("cheese")
5358 @classmethod
5359 def __getnewargs__(cls):
5360 return cls.ARGS
5361 def __repr__(self):
5362 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5363
5364 global C3
5365 class C3(list):
5366 "A list subclass copyable via __getstate__."
5367 ARGS = (1, 2)
5368 NEED_DICT_COPYING = False
5369 def __init__(self, a, b):
5370 self.a = a
5371 self.b = b
5372 # This helps testing that __init__ is not called during the
5373 # unpickling process, which would cause extra appends.
5374 self.append("cheese")
5375 @classmethod
5376 def __getstate__(cls):
5377 return cls.ARGS
5378 def __setstate__(self, state):
5379 a, b = state
5380 self.a = a
5381 self.b = b
5382 def __repr__(self):
5383 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5384
5385 global C4
5386 class C4(int):
5387 "An int subclass copyable via __getnewargs__."
5388 ARGS = ("hello", "world", 1)
5389 NEED_DICT_COPYING = False
5390 def __new__(cls, a, b, value):
5391 self = super().__new__(cls, value)
5392 self.a = a
5393 self.b = b
5394 return self
5395 @classmethod
5396 def __getnewargs__(cls):
5397 return cls.ARGS
5398 def __repr__(self):
5399 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5400
5401 global C5
5402 class C5(int):
5403 "An int subclass copyable via __getnewargs_ex__."
5404 ARGS = (1, 2)
5405 KWARGS = {'value': 3}
5406 NEED_DICT_COPYING = False
5407 def __new__(cls, a, b, *, value=0):
5408 self = super().__new__(cls, value)
5409 self.a = a
5410 self.b = b
5411 return self
5412 @classmethod
5413 def __getnewargs_ex__(cls):
5414 return (cls.ARGS, cls.KWARGS)
5415 def __repr__(self):
5416 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5417
5418 test_classes = (C1, C2, C3, C4, C5)
5419 # Testing copying through pickle
5420 pickle_copiers = self._generate_pickle_copiers()
5421 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5422 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5423 kwargs = getattr(cls, 'KWARGS', {})
5424 obj = cls(*cls.ARGS, **kwargs)
5425 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005426 objcopy = pickle_copier.copy(obj)
5427 self._assert_is_copy(obj, objcopy)
5428 # For test classes that supports this, make sure we didn't go
5429 # around the reduce protocol by simply copying the attribute
5430 # dictionary. We clear attributes using the previous copy to
5431 # not mutate the original argument.
5432 if proto >= 2 and not cls.NEED_DICT_COPYING:
5433 objcopy.__dict__.clear()
5434 objcopy2 = pickle_copier.copy(objcopy)
5435 self._assert_is_copy(obj, objcopy2)
5436
5437 # Testing copying through copy.deepcopy()
5438 for cls in test_classes:
5439 with self.subTest(cls=cls):
5440 kwargs = getattr(cls, 'KWARGS', {})
5441 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005442 objcopy = deepcopy(obj)
5443 self._assert_is_copy(obj, objcopy)
5444 # For test classes that supports this, make sure we didn't go
5445 # around the reduce protocol by simply copying the attribute
5446 # dictionary. We clear attributes using the previous copy to
5447 # not mutate the original argument.
5448 if not cls.NEED_DICT_COPYING:
5449 objcopy.__dict__.clear()
5450 objcopy2 = deepcopy(objcopy)
5451 self._assert_is_copy(obj, objcopy2)
5452
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005453 def test_issue24097(self):
5454 # Slot name is freed inside __getattr__ and is later used.
5455 class S(str): # Not interned
5456 pass
5457 class A:
5458 __slotnames__ = [S('spam')]
5459 def __getattr__(self, attr):
5460 if attr == 'spam':
5461 A.__slotnames__[:] = [S('spam')]
5462 return 42
5463 else:
5464 raise AttributeError
5465
5466 import copyreg
5467 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005468 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5469
5470 def test_object_reduce(self):
5471 # Issue #29914
5472 # __reduce__() takes no arguments
5473 object().__reduce__()
5474 with self.assertRaises(TypeError):
5475 object().__reduce__(0)
5476 # __reduce_ex__() takes one integer argument
5477 object().__reduce_ex__(0)
5478 with self.assertRaises(TypeError):
5479 object().__reduce_ex__()
5480 with self.assertRaises(TypeError):
5481 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005482
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005483
Benjamin Peterson2a605342014-03-17 16:20:12 -05005484class SharedKeyTests(unittest.TestCase):
5485
5486 @support.cpython_only
5487 def test_subclasses(self):
5488 # Verify that subclasses can share keys (per PEP 412)
5489 class A:
5490 pass
5491 class B(A):
5492 pass
5493
5494 a, b = A(), B()
5495 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
Inada Naokif2a18672019-03-12 17:25:44 +09005496 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005497 # Initial hash table can contain at most 5 elements.
5498 # Set 6 attributes to cause internal resizing.
5499 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005500 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5501 a2 = A()
5502 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
Inada Naokif2a18672019-03-12 17:25:44 +09005503 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005504 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Inada Naokif2a18672019-03-12 17:25:44 +09005505 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
Benjamin Peterson2a605342014-03-17 16:20:12 -05005506
5507
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005508class DebugHelperMeta(type):
5509 """
5510 Sets default __doc__ and simplifies repr() output.
5511 """
5512 def __new__(mcls, name, bases, attrs):
5513 if attrs.get('__doc__') is None:
5514 attrs['__doc__'] = name # helps when debugging with gdb
5515 return type.__new__(mcls, name, bases, attrs)
5516 def __repr__(cls):
5517 return repr(cls.__name__)
5518
5519
5520class MroTest(unittest.TestCase):
5521 """
5522 Regressions for some bugs revealed through
5523 mcsl.mro() customization (typeobject.c: mro_internal()) and
5524 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5525 """
5526
5527 def setUp(self):
5528 self.step = 0
5529 self.ready = False
5530
5531 def step_until(self, limit):
5532 ret = (self.step < limit)
5533 if ret:
5534 self.step += 1
5535 return ret
5536
5537 def test_incomplete_set_bases_on_self(self):
5538 """
5539 type_set_bases must be aware that type->tp_mro can be NULL.
5540 """
5541 class M(DebugHelperMeta):
5542 def mro(cls):
5543 if self.step_until(1):
5544 assert cls.__mro__ is None
5545 cls.__bases__ += ()
5546
5547 return type.mro(cls)
5548
5549 class A(metaclass=M):
5550 pass
5551
5552 def test_reent_set_bases_on_base(self):
5553 """
5554 Deep reentrancy must not over-decref old_mro.
5555 """
5556 class M(DebugHelperMeta):
5557 def mro(cls):
5558 if cls.__mro__ is not None and cls.__name__ == 'B':
5559 # 4-5 steps are usually enough to make it crash somewhere
5560 if self.step_until(10):
5561 A.__bases__ += ()
5562
5563 return type.mro(cls)
5564
5565 class A(metaclass=M):
5566 pass
5567 class B(A):
5568 pass
5569 B.__bases__ += ()
5570
5571 def test_reent_set_bases_on_direct_base(self):
5572 """
5573 Similar to test_reent_set_bases_on_base, but may crash differently.
5574 """
5575 class M(DebugHelperMeta):
5576 def mro(cls):
5577 base = cls.__bases__[0]
5578 if base is not object:
5579 if self.step_until(5):
5580 base.__bases__ += ()
5581
5582 return type.mro(cls)
5583
5584 class A(metaclass=M):
5585 pass
5586 class B(A):
5587 pass
5588 class C(B):
5589 pass
5590
5591 def test_reent_set_bases_tp_base_cycle(self):
5592 """
5593 type_set_bases must check for an inheritance cycle not only through
5594 MRO of the type, which may be not yet updated in case of reentrance,
5595 but also through tp_base chain, which is assigned before diving into
5596 inner calls to mro().
5597
5598 Otherwise, the following snippet can loop forever:
5599 do {
5600 // ...
5601 type = type->tp_base;
5602 } while (type != NULL);
5603
5604 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5605 would not be happy in that case, causing a stack overflow.
5606 """
5607 class M(DebugHelperMeta):
5608 def mro(cls):
5609 if self.ready:
5610 if cls.__name__ == 'B1':
5611 B2.__bases__ = (B1,)
5612 if cls.__name__ == 'B2':
5613 B1.__bases__ = (B2,)
5614 return type.mro(cls)
5615
5616 class A(metaclass=M):
5617 pass
5618 class B1(A):
5619 pass
5620 class B2(A):
5621 pass
5622
5623 self.ready = True
5624 with self.assertRaises(TypeError):
5625 B1.__bases__ += ()
5626
5627 def test_tp_subclasses_cycle_in_update_slots(self):
5628 """
5629 type_set_bases must check for reentrancy upon finishing its job
5630 by updating tp_subclasses of old/new bases of the type.
5631 Otherwise, an implicit inheritance cycle through tp_subclasses
5632 can break functions that recurse on elements of that field
5633 (like recurse_down_subclasses and mro_hierarchy) eventually
5634 leading to a stack overflow.
5635 """
5636 class M(DebugHelperMeta):
5637 def mro(cls):
5638 if self.ready and cls.__name__ == 'C':
5639 self.ready = False
5640 C.__bases__ = (B2,)
5641 return type.mro(cls)
5642
5643 class A(metaclass=M):
5644 pass
5645 class B1(A):
5646 pass
5647 class B2(A):
5648 pass
5649 class C(A):
5650 pass
5651
5652 self.ready = True
5653 C.__bases__ = (B1,)
5654 B1.__bases__ = (C,)
5655
5656 self.assertEqual(C.__bases__, (B2,))
5657 self.assertEqual(B2.__subclasses__(), [C])
5658 self.assertEqual(B1.__subclasses__(), [])
5659
5660 self.assertEqual(B1.__bases__, (C,))
5661 self.assertEqual(C.__subclasses__(), [B1])
5662
5663 def test_tp_subclasses_cycle_error_return_path(self):
5664 """
5665 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5666 a code path executed on error (goto bail).
5667 """
5668 class E(Exception):
5669 pass
5670 class M(DebugHelperMeta):
5671 def mro(cls):
5672 if self.ready and cls.__name__ == 'C':
5673 if C.__bases__ == (B2,):
5674 self.ready = False
5675 else:
5676 C.__bases__ = (B2,)
5677 raise E
5678 return type.mro(cls)
5679
5680 class A(metaclass=M):
5681 pass
5682 class B1(A):
5683 pass
5684 class B2(A):
5685 pass
5686 class C(A):
5687 pass
5688
5689 self.ready = True
5690 with self.assertRaises(E):
5691 C.__bases__ = (B1,)
5692 B1.__bases__ = (C,)
5693
5694 self.assertEqual(C.__bases__, (B2,))
5695 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5696
5697 def test_incomplete_extend(self):
5698 """
5699 Extending an unitialized type with type->tp_mro == NULL must
5700 throw a reasonable TypeError exception, instead of failing
5701 with PyErr_BadInternalCall.
5702 """
5703 class M(DebugHelperMeta):
5704 def mro(cls):
5705 if cls.__mro__ is None and cls.__name__ != 'X':
5706 with self.assertRaises(TypeError):
5707 class X(cls):
5708 pass
5709
5710 return type.mro(cls)
5711
5712 class A(metaclass=M):
5713 pass
5714
5715 def test_incomplete_super(self):
5716 """
5717 Attrubute lookup on a super object must be aware that
5718 its target type can be uninitialized (type->tp_mro == NULL).
5719 """
5720 class M(DebugHelperMeta):
5721 def mro(cls):
5722 if cls.__mro__ is None:
5723 with self.assertRaises(AttributeError):
5724 super(cls, cls).xxx
5725
5726 return type.mro(cls)
5727
5728 class A(metaclass=M):
5729 pass
5730
5731
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005732def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005733 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005734 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005735 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005736 MiscTests, PicklingTests, SharedKeyTests,
5737 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005738
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005739if __name__ == "__main__":
5740 test_main()