blob: 301a2d2a0fd29c5e5b6bbaf4c470be1172309eac [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
Benjamin Petersona5758c02009-05-09 18:15:04 +00007import sys
Guido van Rossum360e4b82007-05-14 22:51:27 +00008import types
Georg Brandl479a7e72008-02-05 18:13:15 +00009import unittest
Serhiy Storchaka5adfac22016-12-02 08:42:43 +020010import warnings
Benjamin Peterson52c42432012-03-07 18:41:11 -060011import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +000012
Georg Brandl479a7e72008-02-05 18:13:15 +000013from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +000015
jdemeyer5a306202018-10-19 23:50:06 +020016try:
17 import _testcapi
18except ImportError:
19 _testcapi = None
20
Tim Peters6d6c1a32001-08-02 04:15:00 +000021
Georg Brandl479a7e72008-02-05 18:13:15 +000022class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000023
Georg Brandl479a7e72008-02-05 18:13:15 +000024 def __init__(self, *args, **kwargs):
25 unittest.TestCase.__init__(self, *args, **kwargs)
26 self.binops = {
27 'add': '+',
28 'sub': '-',
29 'mul': '*',
Serhiy Storchakac2ccce72015-03-12 22:01:30 +020030 'matmul': '@',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +020031 'truediv': '/',
32 'floordiv': '//',
Georg Brandl479a7e72008-02-05 18:13:15 +000033 'divmod': 'divmod',
34 'pow': '**',
35 'lshift': '<<',
36 'rshift': '>>',
37 'and': '&',
38 'xor': '^',
39 'or': '|',
40 'cmp': 'cmp',
41 'lt': '<',
42 'le': '<=',
43 'eq': '==',
44 'ne': '!=',
45 'gt': '>',
46 'ge': '>=',
47 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000048
Georg Brandl479a7e72008-02-05 18:13:15 +000049 for name, expr in list(self.binops.items()):
50 if expr.islower():
51 expr = expr + "(a, b)"
52 else:
53 expr = 'a %s b' % expr
54 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000055
Georg Brandl479a7e72008-02-05 18:13:15 +000056 self.unops = {
57 'pos': '+',
58 'neg': '-',
59 'abs': 'abs',
60 'invert': '~',
61 'int': 'int',
62 'float': 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +000063 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000064
Georg Brandl479a7e72008-02-05 18:13:15 +000065 for name, expr in list(self.unops.items()):
66 if expr.islower():
67 expr = expr + "(a)"
68 else:
69 expr = '%s a' % expr
70 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000071
Georg Brandl479a7e72008-02-05 18:13:15 +000072 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
73 d = {'a': a}
74 self.assertEqual(eval(expr, d), res)
75 t = type(a)
76 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000077
Georg Brandl479a7e72008-02-05 18:13:15 +000078 # Find method in parent class
79 while meth not in t.__dict__:
80 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000081 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
82 # method object; the getattr() below obtains its underlying function.
83 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000084 self.assertEqual(m(a), res)
85 bm = getattr(a, meth)
86 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000087
Georg Brandl479a7e72008-02-05 18:13:15 +000088 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
89 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000090
Georg Brandl479a7e72008-02-05 18:13:15 +000091 self.assertEqual(eval(expr, d), res)
92 t = type(a)
93 m = getattr(t, meth)
94 while meth not in t.__dict__:
95 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000096 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
97 # method object; the getattr() below obtains its underlying function.
98 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000099 self.assertEqual(m(a, b), res)
100 bm = getattr(a, meth)
101 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000102
Georg Brandl479a7e72008-02-05 18:13:15 +0000103 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
104 d = {'a': a, 'b': b, 'c': c}
105 self.assertEqual(eval(expr, d), res)
106 t = type(a)
107 m = getattr(t, meth)
108 while meth not in t.__dict__:
109 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000110 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
111 # method object; the getattr() below obtains its underlying function.
112 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000113 self.assertEqual(m(a, slice(b, c)), res)
114 bm = getattr(a, meth)
115 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000116
Georg Brandl479a7e72008-02-05 18:13:15 +0000117 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
118 d = {'a': deepcopy(a), 'b': b}
119 exec(stmt, d)
120 self.assertEqual(d['a'], res)
121 t = type(a)
122 m = getattr(t, meth)
123 while meth not in t.__dict__:
124 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000125 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
126 # method object; the getattr() below obtains its underlying function.
127 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000128 d['a'] = deepcopy(a)
129 m(d['a'], b)
130 self.assertEqual(d['a'], res)
131 d['a'] = deepcopy(a)
132 bm = getattr(d['a'], meth)
133 bm(b)
134 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000135
Georg Brandl479a7e72008-02-05 18:13:15 +0000136 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
137 d = {'a': deepcopy(a), 'b': b, 'c': c}
138 exec(stmt, d)
139 self.assertEqual(d['a'], res)
140 t = type(a)
141 m = getattr(t, meth)
142 while meth not in t.__dict__:
143 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000144 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
145 # method object; the getattr() below obtains its underlying function.
146 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000147 d['a'] = deepcopy(a)
148 m(d['a'], b, c)
149 self.assertEqual(d['a'], res)
150 d['a'] = deepcopy(a)
151 bm = getattr(d['a'], meth)
152 bm(b, c)
153 self.assertEqual(d['a'], res)
154
155 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
156 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
157 exec(stmt, dictionary)
158 self.assertEqual(dictionary['a'], res)
159 t = type(a)
160 while meth not in t.__dict__:
161 t = t.__bases__[0]
162 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000163 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
164 # method object; the getattr() below obtains its underlying function.
165 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000166 dictionary['a'] = deepcopy(a)
167 m(dictionary['a'], slice(b, c), d)
168 self.assertEqual(dictionary['a'], res)
169 dictionary['a'] = deepcopy(a)
170 bm = getattr(dictionary['a'], meth)
171 bm(slice(b, c), d)
172 self.assertEqual(dictionary['a'], res)
173
174 def test_lists(self):
175 # Testing list operations...
176 # Asserts are within individual test methods
177 self.binop_test([1], [2], [1,2], "a+b", "__add__")
178 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
179 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
180 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
181 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
182 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
183 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
184 self.unop_test([1,2,3], 3, "len(a)", "__len__")
185 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
186 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
187 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
188 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
189 "__setitem__")
190
191 def test_dicts(self):
192 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000193 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
194 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
195 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
196
197 d = {1:2, 3:4}
198 l1 = []
199 for i in list(d.keys()):
200 l1.append(i)
201 l = []
202 for i in iter(d):
203 l.append(i)
204 self.assertEqual(l, l1)
205 l = []
206 for i in d.__iter__():
207 l.append(i)
208 self.assertEqual(l, l1)
209 l = []
210 for i in dict.__iter__(d):
211 l.append(i)
212 self.assertEqual(l, l1)
213 d = {1:2, 3:4}
214 self.unop_test(d, 2, "len(a)", "__len__")
215 self.assertEqual(eval(repr(d), {}), d)
216 self.assertEqual(eval(d.__repr__(), {}), d)
217 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
218 "__setitem__")
219
220 # Tests for unary and binary operators
221 def number_operators(self, a, b, skip=[]):
222 dict = {'a': a, 'b': b}
223
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200224 for name, expr in self.binops.items():
Georg Brandl479a7e72008-02-05 18:13:15 +0000225 if name not in skip:
226 name = "__%s__" % name
227 if hasattr(a, name):
228 res = eval(expr, dict)
229 self.binop_test(a, b, res, expr, name)
230
231 for name, expr in list(self.unops.items()):
232 if name not in skip:
233 name = "__%s__" % name
234 if hasattr(a, name):
235 res = eval(expr, dict)
236 self.unop_test(a, res, expr, name)
237
238 def test_ints(self):
239 # Testing int operations...
240 self.number_operators(100, 3)
241 # The following crashes in Python 2.2
242 self.assertEqual((1).__bool__(), 1)
243 self.assertEqual((0).__bool__(), 0)
244 # This returns 'NotImplemented' in Python 2.2
245 class C(int):
246 def __add__(self, other):
247 return NotImplemented
248 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000249 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000250 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000251 except TypeError:
252 pass
253 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000254 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000255
Georg Brandl479a7e72008-02-05 18:13:15 +0000256 def test_floats(self):
257 # Testing float operations...
258 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000259
Georg Brandl479a7e72008-02-05 18:13:15 +0000260 def test_complexes(self):
261 # Testing complex operations...
262 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000263 'int', 'float',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200264 'floordiv', 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000265
Georg Brandl479a7e72008-02-05 18:13:15 +0000266 class Number(complex):
267 __slots__ = ['prec']
268 def __new__(cls, *args, **kwds):
269 result = complex.__new__(cls, *args)
270 result.prec = kwds.get('prec', 12)
271 return result
272 def __repr__(self):
273 prec = self.prec
274 if self.imag == 0.0:
275 return "%.*g" % (prec, self.real)
276 if self.real == 0.0:
277 return "%.*gj" % (prec, self.imag)
278 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
279 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000280
Georg Brandl479a7e72008-02-05 18:13:15 +0000281 a = Number(3.14, prec=6)
282 self.assertEqual(repr(a), "3.14")
283 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000284
Georg Brandl479a7e72008-02-05 18:13:15 +0000285 a = Number(a, prec=2)
286 self.assertEqual(repr(a), "3.1")
287 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000288
Georg Brandl479a7e72008-02-05 18:13:15 +0000289 a = Number(234.5)
290 self.assertEqual(repr(a), "234.5")
291 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000292
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000293 def test_explicit_reverse_methods(self):
294 # see issue 9930
295 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
296 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
297
Benjamin Petersone549ead2009-03-28 21:42:05 +0000298 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000299 def test_spam_lists(self):
300 # Testing spamlist operations...
301 import copy, xxsubtype as spam
302
303 def spamlist(l, memo=None):
304 import xxsubtype as spam
305 return spam.spamlist(l)
306
307 # This is an ugly hack:
308 copy._deepcopy_dispatch[spam.spamlist] = spamlist
309
310 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
311 "__add__")
312 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
313 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
314 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
315 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
316 "__getitem__")
317 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
318 "__iadd__")
319 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
320 "__imul__")
321 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
322 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
323 "__mul__")
324 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
325 "__rmul__")
326 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
327 "__setitem__")
328 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
329 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
330 # Test subclassing
331 class C(spam.spamlist):
332 def foo(self): return 1
333 a = C()
334 self.assertEqual(a, [])
335 self.assertEqual(a.foo(), 1)
336 a.append(100)
337 self.assertEqual(a, [100])
338 self.assertEqual(a.getstate(), 0)
339 a.setstate(42)
340 self.assertEqual(a.getstate(), 42)
341
Benjamin Petersone549ead2009-03-28 21:42:05 +0000342 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000343 def test_spam_dicts(self):
344 # Testing spamdict operations...
345 import copy, xxsubtype as spam
346 def spamdict(d, memo=None):
347 import xxsubtype as spam
348 sd = spam.spamdict()
349 for k, v in list(d.items()):
350 sd[k] = v
351 return sd
352 # This is an ugly hack:
353 copy._deepcopy_dispatch[spam.spamdict] = spamdict
354
Georg Brandl479a7e72008-02-05 18:13:15 +0000355 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
356 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
357 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
358 d = spamdict({1:2,3:4})
359 l1 = []
360 for i in list(d.keys()):
361 l1.append(i)
362 l = []
363 for i in iter(d):
364 l.append(i)
365 self.assertEqual(l, l1)
366 l = []
367 for i in d.__iter__():
368 l.append(i)
369 self.assertEqual(l, l1)
370 l = []
371 for i in type(spamdict({})).__iter__(d):
372 l.append(i)
373 self.assertEqual(l, l1)
374 straightd = {1:2, 3:4}
375 spamd = spamdict(straightd)
376 self.unop_test(spamd, 2, "len(a)", "__len__")
377 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
378 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
379 "a[b]=c", "__setitem__")
380 # Test subclassing
381 class C(spam.spamdict):
382 def foo(self): return 1
383 a = C()
384 self.assertEqual(list(a.items()), [])
385 self.assertEqual(a.foo(), 1)
386 a['foo'] = 'bar'
387 self.assertEqual(list(a.items()), [('foo', 'bar')])
388 self.assertEqual(a.getstate(), 0)
389 a.setstate(100)
390 self.assertEqual(a.getstate(), 100)
391
Zackery Spytz05f16412019-05-28 06:55:29 -0600392 def test_wrap_lenfunc_bad_cast(self):
393 self.assertEqual(range(sys.maxsize).__len__(), sys.maxsize)
394
395
Georg Brandl479a7e72008-02-05 18:13:15 +0000396class ClassPropertiesAndMethods(unittest.TestCase):
397
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200398 def assertHasAttr(self, obj, name):
399 self.assertTrue(hasattr(obj, name),
400 '%r has no attribute %r' % (obj, name))
401
402 def assertNotHasAttr(self, obj, name):
403 self.assertFalse(hasattr(obj, name),
404 '%r has unexpected attribute %r' % (obj, name))
405
Georg Brandl479a7e72008-02-05 18:13:15 +0000406 def test_python_dicts(self):
407 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000408 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000409 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000410 d = dict()
411 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200412 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000413 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000414 class C(dict):
415 state = -1
416 def __init__(self_local, *a, **kw):
417 if a:
418 self.assertEqual(len(a), 1)
419 self_local.state = a[0]
420 if kw:
421 for k, v in list(kw.items()):
422 self_local[v] = k
423 def __getitem__(self, key):
424 return self.get(key, 0)
425 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000426 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000427 dict.__setitem__(self_local, key, value)
428 def setstate(self, state):
429 self.state = state
430 def getstate(self):
431 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000432 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000433 a1 = C(12)
434 self.assertEqual(a1.state, 12)
435 a2 = C(foo=1, bar=2)
436 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
437 a = C()
438 self.assertEqual(a.state, -1)
439 self.assertEqual(a.getstate(), -1)
440 a.setstate(0)
441 self.assertEqual(a.state, 0)
442 self.assertEqual(a.getstate(), 0)
443 a.setstate(10)
444 self.assertEqual(a.state, 10)
445 self.assertEqual(a.getstate(), 10)
446 self.assertEqual(a[42], 0)
447 a[42] = 24
448 self.assertEqual(a[42], 24)
449 N = 50
450 for i in range(N):
451 a[i] = C()
452 for j in range(N):
453 a[i][j] = i*j
454 for i in range(N):
455 for j in range(N):
456 self.assertEqual(a[i][j], i*j)
457
458 def test_python_lists(self):
459 # Testing Python subclass of list...
460 class C(list):
461 def __getitem__(self, i):
462 if isinstance(i, slice):
463 return i.start, i.stop
464 return list.__getitem__(self, i) + 100
465 a = C()
466 a.extend([0,1,2])
467 self.assertEqual(a[0], 100)
468 self.assertEqual(a[1], 101)
469 self.assertEqual(a[2], 102)
470 self.assertEqual(a[100:200], (100,200))
471
472 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000473 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000474 class C(metaclass=type):
475 def __init__(self):
476 self.__state = 0
477 def getstate(self):
478 return self.__state
479 def setstate(self, state):
480 self.__state = state
481 a = C()
482 self.assertEqual(a.getstate(), 0)
483 a.setstate(10)
484 self.assertEqual(a.getstate(), 10)
485 class _metaclass(type):
486 def myself(cls): return cls
487 class D(metaclass=_metaclass):
488 pass
489 self.assertEqual(D.myself(), D)
490 d = D()
491 self.assertEqual(d.__class__, D)
492 class M1(type):
493 def __new__(cls, name, bases, dict):
494 dict['__spam__'] = 1
495 return type.__new__(cls, name, bases, dict)
496 class C(metaclass=M1):
497 pass
498 self.assertEqual(C.__spam__, 1)
499 c = C()
500 self.assertEqual(c.__spam__, 1)
501
502 class _instance(object):
503 pass
504 class M2(object):
505 @staticmethod
506 def __new__(cls, name, bases, dict):
507 self = object.__new__(cls)
508 self.name = name
509 self.bases = bases
510 self.dict = dict
511 return self
512 def __call__(self):
513 it = _instance()
514 # Early binding of methods
515 for key in self.dict:
516 if key.startswith("__"):
517 continue
518 setattr(it, key, self.dict[key].__get__(it, self))
519 return it
520 class C(metaclass=M2):
521 def spam(self):
522 return 42
523 self.assertEqual(C.name, 'C')
524 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000525 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000526 c = C()
527 self.assertEqual(c.spam(), 42)
528
529 # More metaclass examples
530
531 class autosuper(type):
532 # Automatically add __super to the class
533 # This trick only works for dynamic classes
534 def __new__(metaclass, name, bases, dict):
535 cls = super(autosuper, metaclass).__new__(metaclass,
536 name, bases, dict)
537 # Name mangling for __super removes leading underscores
538 while name[:1] == "_":
539 name = name[1:]
540 if name:
541 name = "_%s__super" % name
542 else:
543 name = "__super"
544 setattr(cls, name, super(cls))
545 return cls
546 class A(metaclass=autosuper):
547 def meth(self):
548 return "A"
549 class B(A):
550 def meth(self):
551 return "B" + self.__super.meth()
552 class C(A):
553 def meth(self):
554 return "C" + self.__super.meth()
555 class D(C, B):
556 def meth(self):
557 return "D" + self.__super.meth()
558 self.assertEqual(D().meth(), "DCBA")
559 class E(B, C):
560 def meth(self):
561 return "E" + self.__super.meth()
562 self.assertEqual(E().meth(), "EBCA")
563
564 class autoproperty(type):
565 # Automatically create property attributes when methods
566 # named _get_x and/or _set_x are found
567 def __new__(metaclass, name, bases, dict):
568 hits = {}
569 for key, val in dict.items():
570 if key.startswith("_get_"):
571 key = key[5:]
572 get, set = hits.get(key, (None, None))
573 get = val
574 hits[key] = get, set
575 elif key.startswith("_set_"):
576 key = key[5:]
577 get, set = hits.get(key, (None, None))
578 set = val
579 hits[key] = get, set
580 for key, (get, set) in hits.items():
581 dict[key] = property(get, set)
582 return super(autoproperty, metaclass).__new__(metaclass,
583 name, bases, dict)
584 class A(metaclass=autoproperty):
585 def _get_x(self):
586 return -self.__x
587 def _set_x(self, x):
588 self.__x = -x
589 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200590 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000591 a.x = 12
592 self.assertEqual(a.x, 12)
593 self.assertEqual(a._A__x, -12)
594
595 class multimetaclass(autoproperty, autosuper):
596 # Merge of multiple cooperating metaclasses
597 pass
598 class A(metaclass=multimetaclass):
599 def _get_x(self):
600 return "A"
601 class B(A):
602 def _get_x(self):
603 return "B" + self.__super._get_x()
604 class C(A):
605 def _get_x(self):
606 return "C" + self.__super._get_x()
607 class D(C, B):
608 def _get_x(self):
609 return "D" + self.__super._get_x()
610 self.assertEqual(D().x, "DCBA")
611
612 # Make sure type(x) doesn't call x.__class__.__init__
613 class T(type):
614 counter = 0
615 def __init__(self, *args):
616 T.counter += 1
617 class C(metaclass=T):
618 pass
619 self.assertEqual(T.counter, 1)
620 a = C()
621 self.assertEqual(type(a), C)
622 self.assertEqual(T.counter, 1)
623
624 class C(object): pass
625 c = C()
626 try: c()
627 except TypeError: pass
628 else: self.fail("calling object w/o call method should raise "
629 "TypeError")
630
631 # Testing code to find most derived baseclass
632 class A(type):
633 def __new__(*args, **kwargs):
634 return type.__new__(*args, **kwargs)
635
636 class B(object):
637 pass
638
639 class C(object, metaclass=A):
640 pass
641
642 # The most derived metaclass of D is A rather than type.
643 class D(B, C):
644 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000645 self.assertIs(A, type(D))
646
647 # issue1294232: correct metaclass calculation
648 new_calls = [] # to check the order of __new__ calls
649 class AMeta(type):
650 @staticmethod
651 def __new__(mcls, name, bases, ns):
652 new_calls.append('AMeta')
653 return super().__new__(mcls, name, bases, ns)
654 @classmethod
655 def __prepare__(mcls, name, bases):
656 return {}
657
658 class BMeta(AMeta):
659 @staticmethod
660 def __new__(mcls, name, bases, ns):
661 new_calls.append('BMeta')
662 return super().__new__(mcls, name, bases, ns)
663 @classmethod
664 def __prepare__(mcls, name, bases):
665 ns = super().__prepare__(name, bases)
666 ns['BMeta_was_here'] = True
667 return ns
668
669 class A(metaclass=AMeta):
670 pass
671 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000672 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000673
674 class B(metaclass=BMeta):
675 pass
676 # BMeta.__new__ calls AMeta.__new__ with super:
677 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000678 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000679
680 class C(A, B):
681 pass
682 # The most derived metaclass is BMeta:
683 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000684 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000685 # BMeta.__prepare__ should've been called:
686 self.assertIn('BMeta_was_here', C.__dict__)
687
688 # The order of the bases shouldn't matter:
689 class C2(B, A):
690 pass
691 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000692 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000693 self.assertIn('BMeta_was_here', C2.__dict__)
694
695 # Check correct metaclass calculation when a metaclass is declared:
696 class D(C, metaclass=type):
697 pass
698 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000699 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000700 self.assertIn('BMeta_was_here', D.__dict__)
701
702 class E(C, metaclass=AMeta):
703 pass
704 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000705 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000706 self.assertIn('BMeta_was_here', E.__dict__)
707
708 # Special case: the given metaclass isn't a class,
709 # so there is no metaclass calculation.
710 marker = object()
711 def func(*args, **kwargs):
712 return marker
713 class X(metaclass=func):
714 pass
715 class Y(object, metaclass=func):
716 pass
717 class Z(D, metaclass=func):
718 pass
719 self.assertIs(marker, X)
720 self.assertIs(marker, Y)
721 self.assertIs(marker, Z)
722
723 # The given metaclass is a class,
724 # but not a descendant of type.
725 prepare_calls = [] # to track __prepare__ calls
726 class ANotMeta:
727 def __new__(mcls, *args, **kwargs):
728 new_calls.append('ANotMeta')
729 return super().__new__(mcls)
730 @classmethod
731 def __prepare__(mcls, name, bases):
732 prepare_calls.append('ANotMeta')
733 return {}
734 class BNotMeta(ANotMeta):
735 def __new__(mcls, *args, **kwargs):
736 new_calls.append('BNotMeta')
737 return super().__new__(mcls)
738 @classmethod
739 def __prepare__(mcls, name, bases):
740 prepare_calls.append('BNotMeta')
741 return super().__prepare__(name, bases)
742
743 class A(metaclass=ANotMeta):
744 pass
745 self.assertIs(ANotMeta, type(A))
746 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000747 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000748 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000749 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000750
751 class B(metaclass=BNotMeta):
752 pass
753 self.assertIs(BNotMeta, type(B))
754 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000755 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000756 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000757 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000758
759 class C(A, B):
760 pass
761 self.assertIs(BNotMeta, type(C))
762 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000763 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000764 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000765 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000766
767 class C2(B, A):
768 pass
769 self.assertIs(BNotMeta, type(C2))
770 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000771 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000772 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000773 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000774
775 # This is a TypeError, because of a metaclass conflict:
776 # BNotMeta is neither a subclass, nor a superclass of type
777 with self.assertRaises(TypeError):
778 class D(C, metaclass=type):
779 pass
780
781 class E(C, metaclass=ANotMeta):
782 pass
783 self.assertIs(BNotMeta, type(E))
784 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000785 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000786 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000787 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000788
789 class F(object(), C):
790 pass
791 self.assertIs(BNotMeta, type(F))
792 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000793 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000794 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000795 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000796
797 class F2(C, object()):
798 pass
799 self.assertIs(BNotMeta, type(F2))
800 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000801 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000802 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000803 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000804
805 # TypeError: BNotMeta is neither a
806 # subclass, nor a superclass of int
807 with self.assertRaises(TypeError):
808 class X(C, int()):
809 pass
810 with self.assertRaises(TypeError):
811 class X(int(), C):
812 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000813
814 def test_module_subclasses(self):
815 # Testing Python subclass of module...
816 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000817 MT = type(sys)
818 class MM(MT):
819 def __init__(self, name):
820 MT.__init__(self, name)
821 def __getattribute__(self, name):
822 log.append(("getattr", name))
823 return MT.__getattribute__(self, name)
824 def __setattr__(self, name, value):
825 log.append(("setattr", name, value))
826 MT.__setattr__(self, name, value)
827 def __delattr__(self, name):
828 log.append(("delattr", name))
829 MT.__delattr__(self, name)
830 a = MM("a")
831 a.foo = 12
832 x = a.foo
833 del a.foo
834 self.assertEqual(log, [("setattr", "foo", 12),
835 ("getattr", "foo"),
836 ("delattr", "foo")])
837
838 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000839 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000840 class Module(types.ModuleType, str):
841 pass
842 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000843 pass
844 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000845 self.fail("inheriting from ModuleType and str at the same time "
846 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000847
Georg Brandl479a7e72008-02-05 18:13:15 +0000848 def test_multiple_inheritance(self):
849 # Testing multiple inheritance...
850 class C(object):
851 def __init__(self):
852 self.__state = 0
853 def getstate(self):
854 return self.__state
855 def setstate(self, state):
856 self.__state = state
857 a = C()
858 self.assertEqual(a.getstate(), 0)
859 a.setstate(10)
860 self.assertEqual(a.getstate(), 10)
861 class D(dict, C):
862 def __init__(self):
863 type({}).__init__(self)
864 C.__init__(self)
865 d = D()
866 self.assertEqual(list(d.keys()), [])
867 d["hello"] = "world"
868 self.assertEqual(list(d.items()), [("hello", "world")])
869 self.assertEqual(d["hello"], "world")
870 self.assertEqual(d.getstate(), 0)
871 d.setstate(10)
872 self.assertEqual(d.getstate(), 10)
873 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000874
Georg Brandl479a7e72008-02-05 18:13:15 +0000875 # SF bug #442833
876 class Node(object):
877 def __int__(self):
878 return int(self.foo())
879 def foo(self):
880 return "23"
881 class Frag(Node, list):
882 def foo(self):
883 return "42"
884 self.assertEqual(Node().__int__(), 23)
885 self.assertEqual(int(Node()), 23)
886 self.assertEqual(Frag().__int__(), 42)
887 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000888
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700889 def test_diamond_inheritance(self):
Georg Brandl479a7e72008-02-05 18:13:15 +0000890 # Testing multiple inheritance special cases...
891 class A(object):
892 def spam(self): return "A"
893 self.assertEqual(A().spam(), "A")
894 class B(A):
895 def boo(self): return "B"
896 def spam(self): return "B"
897 self.assertEqual(B().spam(), "B")
898 self.assertEqual(B().boo(), "B")
899 class C(A):
900 def boo(self): return "C"
901 self.assertEqual(C().spam(), "A")
902 self.assertEqual(C().boo(), "C")
903 class D(B, C): pass
904 self.assertEqual(D().spam(), "B")
905 self.assertEqual(D().boo(), "B")
906 self.assertEqual(D.__mro__, (D, B, C, A, object))
907 class E(C, B): pass
908 self.assertEqual(E().spam(), "B")
909 self.assertEqual(E().boo(), "C")
910 self.assertEqual(E.__mro__, (E, C, B, A, object))
911 # MRO order disagreement
912 try:
913 class F(D, E): pass
914 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000915 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000916 else:
917 self.fail("expected MRO order disagreement (F)")
918 try:
919 class G(E, D): pass
920 except TypeError:
921 pass
922 else:
923 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000924
Georg Brandl479a7e72008-02-05 18:13:15 +0000925 # see thread python-dev/2002-October/029035.html
926 def test_ex5_from_c3_switch(self):
927 # Testing ex5 from C3 switch discussion...
928 class A(object): pass
929 class B(object): pass
930 class C(object): pass
931 class X(A): pass
932 class Y(A): pass
933 class Z(X,B,Y,C): pass
934 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935
Georg Brandl479a7e72008-02-05 18:13:15 +0000936 # see "A Monotonic Superclass Linearization for Dylan",
937 # by Kim Barrett et al. (OOPSLA 1996)
938 def test_monotonicity(self):
939 # Testing MRO monotonicity...
940 class Boat(object): pass
941 class DayBoat(Boat): pass
942 class WheelBoat(Boat): pass
943 class EngineLess(DayBoat): pass
944 class SmallMultihull(DayBoat): pass
945 class PedalWheelBoat(EngineLess,WheelBoat): pass
946 class SmallCatamaran(SmallMultihull): pass
947 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000948
Georg Brandl479a7e72008-02-05 18:13:15 +0000949 self.assertEqual(PedalWheelBoat.__mro__,
950 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
951 self.assertEqual(SmallCatamaran.__mro__,
952 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
953 self.assertEqual(Pedalo.__mro__,
954 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
955 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000956
Georg Brandl479a7e72008-02-05 18:13:15 +0000957 # see "A Monotonic Superclass Linearization for Dylan",
958 # by Kim Barrett et al. (OOPSLA 1996)
959 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200960 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000961 class Pane(object): pass
962 class ScrollingMixin(object): pass
963 class EditingMixin(object): pass
964 class ScrollablePane(Pane,ScrollingMixin): pass
965 class EditablePane(Pane,EditingMixin): pass
966 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000967
Georg Brandl479a7e72008-02-05 18:13:15 +0000968 self.assertEqual(EditableScrollablePane.__mro__,
969 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
970 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000971
Georg Brandl479a7e72008-02-05 18:13:15 +0000972 def test_mro_disagreement(self):
973 # Testing error messages for MRO disagreement...
974 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000975order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000976
Georg Brandl479a7e72008-02-05 18:13:15 +0000977 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000978 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000979 callable(*args)
980 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000981 # the exact msg is generally considered an impl detail
982 if support.check_impl_detail():
983 if not str(msg).startswith(expected):
984 self.fail("Message %r, expected %r" %
985 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000986 else:
987 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000988
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 class A(object): pass
990 class B(A): pass
991 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000992
Georg Brandl479a7e72008-02-05 18:13:15 +0000993 # Test some very simple errors
994 raises(TypeError, "duplicate base class A",
995 type, "X", (A, A), {})
996 raises(TypeError, mro_err_msg,
997 type, "X", (A, B), {})
998 raises(TypeError, mro_err_msg,
999 type, "X", (A, C, B), {})
1000 # Test a slightly more complex error
1001 class GridLayout(object): pass
1002 class HorizontalGrid(GridLayout): pass
1003 class VerticalGrid(GridLayout): pass
1004 class HVGrid(HorizontalGrid, VerticalGrid): pass
1005 class VHGrid(VerticalGrid, HorizontalGrid): pass
1006 raises(TypeError, mro_err_msg,
1007 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +00001008
Georg Brandl479a7e72008-02-05 18:13:15 +00001009 def test_object_class(self):
1010 # Testing object class...
1011 a = object()
1012 self.assertEqual(a.__class__, object)
1013 self.assertEqual(type(a), object)
1014 b = object()
1015 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001016 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001017 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 a.foo = 12
1019 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001020 pass
1021 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001022 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001023 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001024
Georg Brandl479a7e72008-02-05 18:13:15 +00001025 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001026 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001027 x = Cdict()
1028 self.assertEqual(x.__dict__, {})
1029 x.foo = 1
1030 self.assertEqual(x.foo, 1)
1031 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001033 def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1034 class SubType(types.ModuleType):
1035 a = 1
1036
1037 m = types.ModuleType("m")
1038 self.assertTrue(m.__class__ is types.ModuleType)
1039 self.assertFalse(hasattr(m, "a"))
1040
1041 m.__class__ = SubType
1042 self.assertTrue(m.__class__ is SubType)
1043 self.assertTrue(hasattr(m, "a"))
1044
1045 m.__class__ = types.ModuleType
1046 self.assertTrue(m.__class__ is types.ModuleType)
1047 self.assertFalse(hasattr(m, "a"))
1048
Guido van Rossum7d293ee2015-09-04 20:54:07 -07001049 # Make sure that builtin immutable objects don't support __class__
1050 # assignment, because the object instances may be interned.
1051 # We set __slots__ = () to ensure that the subclasses are
1052 # memory-layout compatible, and thus otherwise reasonable candidates
1053 # for __class__ assignment.
1054
1055 # The following types have immutable instances, but are not
1056 # subclassable and thus don't need to be checked:
1057 # NoneType, bool
1058
1059 class MyInt(int):
1060 __slots__ = ()
1061 with self.assertRaises(TypeError):
1062 (1).__class__ = MyInt
1063
1064 class MyFloat(float):
1065 __slots__ = ()
1066 with self.assertRaises(TypeError):
1067 (1.0).__class__ = MyFloat
1068
1069 class MyComplex(complex):
1070 __slots__ = ()
1071 with self.assertRaises(TypeError):
1072 (1 + 2j).__class__ = MyComplex
1073
1074 class MyStr(str):
1075 __slots__ = ()
1076 with self.assertRaises(TypeError):
1077 "a".__class__ = MyStr
1078
1079 class MyBytes(bytes):
1080 __slots__ = ()
1081 with self.assertRaises(TypeError):
1082 b"a".__class__ = MyBytes
1083
1084 class MyTuple(tuple):
1085 __slots__ = ()
1086 with self.assertRaises(TypeError):
1087 ().__class__ = MyTuple
1088
1089 class MyFrozenSet(frozenset):
1090 __slots__ = ()
1091 with self.assertRaises(TypeError):
1092 frozenset().__class__ = MyFrozenSet
1093
Georg Brandl479a7e72008-02-05 18:13:15 +00001094 def test_slots(self):
1095 # Testing __slots__...
1096 class C0(object):
1097 __slots__ = []
1098 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001099 self.assertNotHasAttr(x, "__dict__")
1100 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001101
1102 class C1(object):
1103 __slots__ = ['a']
1104 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001105 self.assertNotHasAttr(x, "__dict__")
1106 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001108 self.assertEqual(x.a, 1)
1109 x.a = None
1110 self.assertEqual(x.a, None)
1111 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001112 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001113
Georg Brandl479a7e72008-02-05 18:13:15 +00001114 class C3(object):
1115 __slots__ = ['a', 'b', 'c']
1116 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001117 self.assertNotHasAttr(x, "__dict__")
1118 self.assertNotHasAttr(x, 'a')
1119 self.assertNotHasAttr(x, 'b')
1120 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001121 x.a = 1
1122 x.b = 2
1123 x.c = 3
1124 self.assertEqual(x.a, 1)
1125 self.assertEqual(x.b, 2)
1126 self.assertEqual(x.c, 3)
1127
1128 class C4(object):
1129 """Validate name mangling"""
1130 __slots__ = ['__a']
1131 def __init__(self, value):
1132 self.__a = value
1133 def get(self):
1134 return self.__a
1135 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001136 self.assertNotHasAttr(x, '__dict__')
1137 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001138 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001139 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001140 x.__a = 6
1141 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001142 pass
1143 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001144 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001145
Georg Brandl479a7e72008-02-05 18:13:15 +00001146 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001147 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001148 class C(object):
1149 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001150 except TypeError:
1151 pass
1152 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001153 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001154 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001155 class C(object):
1156 __slots__ = ["foo bar"]
1157 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001158 pass
1159 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001160 self.fail("['foo bar'] slots not caught")
1161 try:
1162 class C(object):
1163 __slots__ = ["foo\0bar"]
1164 except TypeError:
1165 pass
1166 else:
1167 self.fail("['foo\\0bar'] slots not caught")
1168 try:
1169 class C(object):
1170 __slots__ = ["1"]
1171 except TypeError:
1172 pass
1173 else:
1174 self.fail("['1'] slots not caught")
1175 try:
1176 class C(object):
1177 __slots__ = [""]
1178 except TypeError:
1179 pass
1180 else:
1181 self.fail("[''] slots not caught")
1182 class C(object):
1183 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1184 # XXX(nnorwitz): was there supposed to be something tested
1185 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001186
Georg Brandl479a7e72008-02-05 18:13:15 +00001187 # Test a single string is not expanded as a sequence.
1188 class C(object):
1189 __slots__ = "abc"
1190 c = C()
1191 c.abc = 5
1192 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001193
Georg Brandl479a7e72008-02-05 18:13:15 +00001194 # Test unicode slot names
1195 # Test a single unicode string is not expanded as a sequence.
1196 class C(object):
1197 __slots__ = "abc"
1198 c = C()
1199 c.abc = 5
1200 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001201
Georg Brandl479a7e72008-02-05 18:13:15 +00001202 # _unicode_to_string used to modify slots in certain circumstances
1203 slots = ("foo", "bar")
1204 class C(object):
1205 __slots__ = slots
1206 x = C()
1207 x.foo = 5
1208 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001209 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001210 # this used to leak references
1211 try:
1212 class C(object):
1213 __slots__ = [chr(128)]
1214 except (TypeError, UnicodeEncodeError):
1215 pass
1216 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001217 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001218
Georg Brandl479a7e72008-02-05 18:13:15 +00001219 # Test leaks
1220 class Counted(object):
1221 counter = 0 # counts the number of instances alive
1222 def __init__(self):
1223 Counted.counter += 1
1224 def __del__(self):
1225 Counted.counter -= 1
1226 class C(object):
1227 __slots__ = ['a', 'b', 'c']
1228 x = C()
1229 x.a = Counted()
1230 x.b = Counted()
1231 x.c = Counted()
1232 self.assertEqual(Counted.counter, 3)
1233 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001234 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001235 self.assertEqual(Counted.counter, 0)
1236 class D(C):
1237 pass
1238 x = D()
1239 x.a = Counted()
1240 x.z = Counted()
1241 self.assertEqual(Counted.counter, 2)
1242 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001243 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001244 self.assertEqual(Counted.counter, 0)
1245 class E(D):
1246 __slots__ = ['e']
1247 x = E()
1248 x.a = Counted()
1249 x.z = Counted()
1250 x.e = Counted()
1251 self.assertEqual(Counted.counter, 3)
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)
Guido van Rossum3926a632001-09-25 16:25:58 +00001255
Georg Brandl479a7e72008-02-05 18:13:15 +00001256 # Test cyclical leaks [SF bug 519621]
1257 class F(object):
1258 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001259 s = F()
1260 s.a = [Counted(), s]
1261 self.assertEqual(Counted.counter, 1)
1262 s = None
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 lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001267 if hasattr(gc, 'get_objects'):
1268 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001269 def __eq__(self, other):
1270 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001271 g = G()
1272 orig_objects = len(gc.get_objects())
1273 for i in range(10):
1274 g==g
1275 new_objects = len(gc.get_objects())
1276 self.assertEqual(orig_objects, new_objects)
1277
Georg Brandl479a7e72008-02-05 18:13:15 +00001278 class H(object):
1279 __slots__ = ['a', 'b']
1280 def __init__(self):
1281 self.a = 1
1282 self.b = 2
1283 def __del__(self_):
1284 self.assertEqual(self_.a, 1)
1285 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001286 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001287 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001288 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001289 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001290
Benjamin Petersond12362a2009-12-30 19:44:54 +00001291 class X(object):
1292 __slots__ = "a"
1293 with self.assertRaises(AttributeError):
1294 del X().a
1295
Georg Brandl479a7e72008-02-05 18:13:15 +00001296 def test_slots_special(self):
1297 # Testing __dict__ and __weakref__ in __slots__...
1298 class D(object):
1299 __slots__ = ["__dict__"]
1300 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001301 self.assertHasAttr(a, "__dict__")
1302 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001303 a.foo = 42
1304 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001305
Georg Brandl479a7e72008-02-05 18:13:15 +00001306 class W(object):
1307 __slots__ = ["__weakref__"]
1308 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001309 self.assertHasAttr(a, "__weakref__")
1310 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001311 try:
1312 a.foo = 42
1313 except AttributeError:
1314 pass
1315 else:
1316 self.fail("shouldn't be allowed to set a.foo")
1317
1318 class C1(W, D):
1319 __slots__ = []
1320 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001321 self.assertHasAttr(a, "__dict__")
1322 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001323 a.foo = 42
1324 self.assertEqual(a.__dict__, {"foo": 42})
1325
1326 class C2(D, W):
1327 __slots__ = []
1328 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001329 self.assertHasAttr(a, "__dict__")
1330 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001331 a.foo = 42
1332 self.assertEqual(a.__dict__, {"foo": 42})
1333
Xiang Zhangc393ee82017-03-08 11:18:49 +08001334 def test_slots_special2(self):
1335 # Testing __qualname__ and __classcell__ in __slots__
1336 class Meta(type):
1337 def __new__(cls, name, bases, namespace, attr):
1338 self.assertIn(attr, namespace)
1339 return super().__new__(cls, name, bases, namespace)
1340
1341 class C1:
1342 def __init__(self):
1343 self.b = 42
1344 class C2(C1, metaclass=Meta, attr="__classcell__"):
1345 __slots__ = ["__classcell__"]
1346 def __init__(self):
1347 super().__init__()
1348 self.assertIsInstance(C2.__dict__["__classcell__"],
1349 types.MemberDescriptorType)
1350 c = C2()
1351 self.assertEqual(c.b, 42)
1352 self.assertNotHasAttr(c, "__classcell__")
1353 c.__classcell__ = 42
1354 self.assertEqual(c.__classcell__, 42)
1355 with self.assertRaises(TypeError):
1356 class C3:
1357 __classcell__ = 42
1358 __slots__ = ["__classcell__"]
1359
1360 class Q1(metaclass=Meta, attr="__qualname__"):
1361 __slots__ = ["__qualname__"]
1362 self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
1363 self.assertIsInstance(Q1.__dict__["__qualname__"],
1364 types.MemberDescriptorType)
1365 q = Q1()
1366 self.assertNotHasAttr(q, "__qualname__")
1367 q.__qualname__ = "q"
1368 self.assertEqual(q.__qualname__, "q")
1369 with self.assertRaises(TypeError):
1370 class Q2:
1371 __qualname__ = object()
1372 __slots__ = ["__qualname__"]
1373
Christian Heimesa156e092008-02-16 07:38:31 +00001374 def test_slots_descriptor(self):
1375 # Issue2115: slot descriptors did not correctly check
1376 # the type of the given object
1377 import abc
1378 class MyABC(metaclass=abc.ABCMeta):
1379 __slots__ = "a"
1380
1381 class Unrelated(object):
1382 pass
1383 MyABC.register(Unrelated)
1384
1385 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001386 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001387
1388 # This used to crash
1389 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1390
Georg Brandl479a7e72008-02-05 18:13:15 +00001391 def test_dynamics(self):
1392 # Testing class attribute propagation...
1393 class D(object):
1394 pass
1395 class E(D):
1396 pass
1397 class F(D):
1398 pass
1399 D.foo = 1
1400 self.assertEqual(D.foo, 1)
1401 # Test that dynamic attributes are inherited
1402 self.assertEqual(E.foo, 1)
1403 self.assertEqual(F.foo, 1)
1404 # Test dynamic instances
1405 class C(object):
1406 pass
1407 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001408 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001409 C.foobar = 2
1410 self.assertEqual(a.foobar, 2)
1411 C.method = lambda self: 42
1412 self.assertEqual(a.method(), 42)
1413 C.__repr__ = lambda self: "C()"
1414 self.assertEqual(repr(a), "C()")
1415 C.__int__ = lambda self: 100
1416 self.assertEqual(int(a), 100)
1417 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001418 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001419 def mygetattr(self, name):
1420 if name == "spam":
1421 return "spam"
1422 raise AttributeError
1423 C.__getattr__ = mygetattr
1424 self.assertEqual(a.spam, "spam")
1425 a.new = 12
1426 self.assertEqual(a.new, 12)
1427 def mysetattr(self, name, value):
1428 if name == "spam":
1429 raise AttributeError
1430 return object.__setattr__(self, name, value)
1431 C.__setattr__ = mysetattr
1432 try:
1433 a.spam = "not spam"
1434 except AttributeError:
1435 pass
1436 else:
1437 self.fail("expected AttributeError")
1438 self.assertEqual(a.spam, "spam")
1439 class D(C):
1440 pass
1441 d = D()
1442 d.foo = 1
1443 self.assertEqual(d.foo, 1)
1444
1445 # Test handling of int*seq and seq*int
1446 class I(int):
1447 pass
1448 self.assertEqual("a"*I(2), "aa")
1449 self.assertEqual(I(2)*"a", "aa")
1450 self.assertEqual(2*I(3), 6)
1451 self.assertEqual(I(3)*2, 6)
1452 self.assertEqual(I(3)*I(2), 6)
1453
Georg Brandl479a7e72008-02-05 18:13:15 +00001454 # Test comparison of classes with dynamic metaclasses
1455 class dynamicmetaclass(type):
1456 pass
1457 class someclass(metaclass=dynamicmetaclass):
1458 pass
1459 self.assertNotEqual(someclass, object)
1460
1461 def test_errors(self):
1462 # Testing errors...
1463 try:
1464 class C(list, dict):
1465 pass
1466 except TypeError:
1467 pass
1468 else:
1469 self.fail("inheritance from both list and dict should be illegal")
1470
1471 try:
1472 class C(object, None):
1473 pass
1474 except TypeError:
1475 pass
1476 else:
1477 self.fail("inheritance from non-type should be illegal")
1478 class Classic:
1479 pass
1480
1481 try:
1482 class C(type(len)):
1483 pass
1484 except TypeError:
1485 pass
1486 else:
1487 self.fail("inheritance from CFunction should be illegal")
1488
1489 try:
1490 class C(object):
1491 __slots__ = 1
1492 except TypeError:
1493 pass
1494 else:
1495 self.fail("__slots__ = 1 should be illegal")
1496
1497 try:
1498 class C(object):
1499 __slots__ = [1]
1500 except TypeError:
1501 pass
1502 else:
1503 self.fail("__slots__ = [1] should be illegal")
1504
1505 class M1(type):
1506 pass
1507 class M2(type):
1508 pass
1509 class A1(object, metaclass=M1):
1510 pass
1511 class A2(object, metaclass=M2):
1512 pass
1513 try:
1514 class B(A1, A2):
1515 pass
1516 except TypeError:
1517 pass
1518 else:
1519 self.fail("finding the most derived metaclass should have failed")
1520
1521 def test_classmethods(self):
1522 # Testing class methods...
1523 class C(object):
1524 def foo(*a): return a
1525 goo = classmethod(foo)
1526 c = C()
1527 self.assertEqual(C.goo(1), (C, 1))
1528 self.assertEqual(c.goo(1), (C, 1))
1529 self.assertEqual(c.foo(1), (c, 1))
1530 class D(C):
1531 pass
1532 d = D()
1533 self.assertEqual(D.goo(1), (D, 1))
1534 self.assertEqual(d.goo(1), (D, 1))
1535 self.assertEqual(d.foo(1), (d, 1))
1536 self.assertEqual(D.foo(d, 1), (d, 1))
1537 # Test for a specific crash (SF bug 528132)
1538 def f(cls, arg): return (cls, arg)
1539 ff = classmethod(f)
1540 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1541 self.assertEqual(ff.__get__(0)(42), (int, 42))
1542
1543 # Test super() with classmethods (SF bug 535444)
1544 self.assertEqual(C.goo.__self__, C)
1545 self.assertEqual(D.goo.__self__, D)
1546 self.assertEqual(super(D,D).goo.__self__, D)
1547 self.assertEqual(super(D,d).goo.__self__, D)
1548 self.assertEqual(super(D,D).goo(), (D,))
1549 self.assertEqual(super(D,d).goo(), (D,))
1550
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001551 # Verify that a non-callable will raise
1552 meth = classmethod(1).__get__(1)
1553 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001554
1555 # Verify that classmethod() doesn't allow keyword args
1556 try:
1557 classmethod(f, kw=1)
1558 except TypeError:
1559 pass
1560 else:
1561 self.fail("classmethod shouldn't accept keyword args")
1562
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001563 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001564 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001565 cm.x = 42
1566 self.assertEqual(cm.x, 42)
1567 self.assertEqual(cm.__dict__, {"x" : 42})
1568 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001569 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001570
Oren Milmand019bc82018-02-13 12:28:33 +02001571 @support.refcount_test
1572 def test_refleaks_in_classmethod___init__(self):
1573 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1574 cm = classmethod(None)
1575 refs_before = gettotalrefcount()
1576 for i in range(100):
1577 cm.__init__(None)
1578 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1579
Benjamin Petersone549ead2009-03-28 21:42:05 +00001580 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001581 def test_classmethods_in_c(self):
1582 # Testing C-based class methods...
1583 import xxsubtype as spam
1584 a = (1, 2, 3)
1585 d = {'abc': 123}
1586 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1587 self.assertEqual(x, spam.spamlist)
1588 self.assertEqual(a, a1)
1589 self.assertEqual(d, d1)
1590 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1591 self.assertEqual(x, spam.spamlist)
1592 self.assertEqual(a, a1)
1593 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001594 spam_cm = spam.spamlist.__dict__['classmeth']
1595 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1596 self.assertEqual(x2, spam.spamlist)
1597 self.assertEqual(a2, a1)
1598 self.assertEqual(d2, d1)
1599 class SubSpam(spam.spamlist): pass
1600 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1601 self.assertEqual(x2, SubSpam)
1602 self.assertEqual(a2, a1)
1603 self.assertEqual(d2, d1)
Inada Naoki871309c2019-03-26 18:26:33 +09001604
1605 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001606 spam_cm()
Inada Naoki871309c2019-03-26 18:26:33 +09001607 self.assertEqual(
1608 str(cm.exception),
1609 "descriptor 'classmeth' of 'xxsubtype.spamlist' "
1610 "object needs an argument")
1611
1612 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001613 spam_cm(spam.spamlist())
Inada Naoki871309c2019-03-26 18:26:33 +09001614 self.assertEqual(
1615 str(cm.exception),
Jeroen Demeyer3f345c32019-06-07 12:20:24 +02001616 "descriptor 'classmeth' for type 'xxsubtype.spamlist' "
1617 "needs a type, not a 'xxsubtype.spamlist' as arg 2")
Inada Naoki871309c2019-03-26 18:26:33 +09001618
1619 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001620 spam_cm(list)
Inada Naoki62f95882019-04-01 17:56:11 +09001621 expected_errmsg = (
Inada Naoki871309c2019-03-26 18:26:33 +09001622 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
1623 "but received 'list'")
Inada Naoki62f95882019-04-01 17:56:11 +09001624 self.assertEqual(str(cm.exception), expected_errmsg)
1625
1626 with self.assertRaises(TypeError) as cm:
1627 spam_cm.__get__(None, list)
1628 self.assertEqual(str(cm.exception), expected_errmsg)
Georg Brandl479a7e72008-02-05 18:13:15 +00001629
1630 def test_staticmethods(self):
1631 # Testing static methods...
1632 class C(object):
1633 def foo(*a): return a
1634 goo = staticmethod(foo)
1635 c = C()
1636 self.assertEqual(C.goo(1), (1,))
1637 self.assertEqual(c.goo(1), (1,))
1638 self.assertEqual(c.foo(1), (c, 1,))
1639 class D(C):
1640 pass
1641 d = D()
1642 self.assertEqual(D.goo(1), (1,))
1643 self.assertEqual(d.goo(1), (1,))
1644 self.assertEqual(d.foo(1), (d, 1))
1645 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001646 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001647 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001648 sm.x = 42
1649 self.assertEqual(sm.x, 42)
1650 self.assertEqual(sm.__dict__, {"x" : 42})
1651 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001652 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001653
Oren Milmand019bc82018-02-13 12:28:33 +02001654 @support.refcount_test
1655 def test_refleaks_in_staticmethod___init__(self):
1656 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1657 sm = staticmethod(None)
1658 refs_before = gettotalrefcount()
1659 for i in range(100):
1660 sm.__init__(None)
1661 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1662
Benjamin Petersone549ead2009-03-28 21:42:05 +00001663 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001664 def test_staticmethods_in_c(self):
1665 # Testing C-based static methods...
1666 import xxsubtype as spam
1667 a = (1, 2, 3)
1668 d = {"abc": 123}
1669 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1670 self.assertEqual(x, None)
1671 self.assertEqual(a, a1)
1672 self.assertEqual(d, d1)
1673 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1674 self.assertEqual(x, None)
1675 self.assertEqual(a, a1)
1676 self.assertEqual(d, d1)
1677
1678 def test_classic(self):
1679 # Testing classic classes...
1680 class C:
1681 def foo(*a): return a
1682 goo = classmethod(foo)
1683 c = C()
1684 self.assertEqual(C.goo(1), (C, 1))
1685 self.assertEqual(c.goo(1), (C, 1))
1686 self.assertEqual(c.foo(1), (c, 1))
1687 class D(C):
1688 pass
1689 d = D()
1690 self.assertEqual(D.goo(1), (D, 1))
1691 self.assertEqual(d.goo(1), (D, 1))
1692 self.assertEqual(d.foo(1), (d, 1))
1693 self.assertEqual(D.foo(d, 1), (d, 1))
1694 class E: # *not* subclassing from C
1695 foo = C.foo
1696 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001697 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001698
1699 def test_compattr(self):
1700 # Testing computed attributes...
1701 class C(object):
1702 class computed_attribute(object):
1703 def __init__(self, get, set=None, delete=None):
1704 self.__get = get
1705 self.__set = set
1706 self.__delete = delete
1707 def __get__(self, obj, type=None):
1708 return self.__get(obj)
1709 def __set__(self, obj, value):
1710 return self.__set(obj, value)
1711 def __delete__(self, obj):
1712 return self.__delete(obj)
1713 def __init__(self):
1714 self.__x = 0
1715 def __get_x(self):
1716 x = self.__x
1717 self.__x = x+1
1718 return x
1719 def __set_x(self, x):
1720 self.__x = x
1721 def __delete_x(self):
1722 del self.__x
1723 x = computed_attribute(__get_x, __set_x, __delete_x)
1724 a = C()
1725 self.assertEqual(a.x, 0)
1726 self.assertEqual(a.x, 1)
1727 a.x = 10
1728 self.assertEqual(a.x, 10)
1729 self.assertEqual(a.x, 11)
1730 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001731 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001732
1733 def test_newslots(self):
1734 # Testing __new__ slot override...
1735 class C(list):
1736 def __new__(cls):
1737 self = list.__new__(cls)
1738 self.foo = 1
1739 return self
1740 def __init__(self):
1741 self.foo = self.foo + 2
1742 a = C()
1743 self.assertEqual(a.foo, 3)
1744 self.assertEqual(a.__class__, C)
1745 class D(C):
1746 pass
1747 b = D()
1748 self.assertEqual(b.foo, 3)
1749 self.assertEqual(b.__class__, D)
1750
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001751 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001752 def test_bad_new(self):
1753 self.assertRaises(TypeError, object.__new__)
1754 self.assertRaises(TypeError, object.__new__, '')
1755 self.assertRaises(TypeError, list.__new__, object)
1756 self.assertRaises(TypeError, object.__new__, list)
1757 class C(object):
1758 __new__ = list.__new__
1759 self.assertRaises(TypeError, C)
1760 class C(list):
1761 __new__ = object.__new__
1762 self.assertRaises(TypeError, C)
1763
1764 def test_object_new(self):
1765 class A(object):
1766 pass
1767 object.__new__(A)
1768 self.assertRaises(TypeError, object.__new__, A, 5)
1769 object.__init__(A())
1770 self.assertRaises(TypeError, object.__init__, A(), 5)
1771
1772 class A(object):
1773 def __init__(self, foo):
1774 self.foo = foo
1775 object.__new__(A)
1776 object.__new__(A, 5)
1777 object.__init__(A(3))
1778 self.assertRaises(TypeError, object.__init__, A(3), 5)
1779
1780 class A(object):
1781 def __new__(cls, foo):
1782 return object.__new__(cls)
1783 object.__new__(A)
1784 self.assertRaises(TypeError, object.__new__, A, 5)
1785 object.__init__(A(3))
1786 object.__init__(A(3), 5)
1787
1788 class A(object):
1789 def __new__(cls, foo):
1790 return object.__new__(cls)
1791 def __init__(self, foo):
1792 self.foo = foo
1793 object.__new__(A)
1794 self.assertRaises(TypeError, object.__new__, A, 5)
1795 object.__init__(A(3))
1796 self.assertRaises(TypeError, object.__init__, A(3), 5)
1797
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001798 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001799 def test_restored_object_new(self):
1800 class A(object):
1801 def __new__(cls, *args, **kwargs):
1802 raise AssertionError
1803 self.assertRaises(AssertionError, A)
1804 class B(A):
1805 __new__ = object.__new__
1806 def __init__(self, foo):
1807 self.foo = foo
1808 with warnings.catch_warnings():
1809 warnings.simplefilter('error', DeprecationWarning)
1810 b = B(3)
1811 self.assertEqual(b.foo, 3)
1812 self.assertEqual(b.__class__, B)
1813 del B.__new__
1814 self.assertRaises(AssertionError, B)
1815 del A.__new__
1816 with warnings.catch_warnings():
1817 warnings.simplefilter('error', DeprecationWarning)
1818 b = B(3)
1819 self.assertEqual(b.foo, 3)
1820 self.assertEqual(b.__class__, B)
1821
Georg Brandl479a7e72008-02-05 18:13:15 +00001822 def test_altmro(self):
1823 # Testing mro() and overriding it...
1824 class A(object):
1825 def f(self): return "A"
1826 class B(A):
1827 pass
1828 class C(A):
1829 def f(self): return "C"
1830 class D(B, C):
1831 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001832 self.assertEqual(A.mro(), [A, object])
1833 self.assertEqual(A.__mro__, (A, object))
1834 self.assertEqual(B.mro(), [B, A, object])
1835 self.assertEqual(B.__mro__, (B, A, object))
1836 self.assertEqual(C.mro(), [C, A, object])
1837 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001838 self.assertEqual(D.mro(), [D, B, C, A, object])
1839 self.assertEqual(D.__mro__, (D, B, C, A, object))
1840 self.assertEqual(D().f(), "C")
1841
1842 class PerverseMetaType(type):
1843 def mro(cls):
1844 L = type.mro(cls)
1845 L.reverse()
1846 return L
1847 class X(D,B,C,A, metaclass=PerverseMetaType):
1848 pass
1849 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1850 self.assertEqual(X().f(), "A")
1851
1852 try:
1853 class _metaclass(type):
1854 def mro(self):
1855 return [self, dict, object]
1856 class X(object, metaclass=_metaclass):
1857 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001858 # In CPython, the class creation above already raises
1859 # TypeError, as a protection against the fact that
1860 # instances of X would segfault it. In other Python
1861 # implementations it would be ok to let the class X
1862 # be created, but instead get a clean TypeError on the
1863 # __setitem__ below.
1864 x = object.__new__(X)
1865 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001866 except TypeError:
1867 pass
1868 else:
1869 self.fail("devious mro() return not caught")
1870
1871 try:
1872 class _metaclass(type):
1873 def mro(self):
1874 return [1]
1875 class X(object, metaclass=_metaclass):
1876 pass
1877 except TypeError:
1878 pass
1879 else:
1880 self.fail("non-class mro() return not caught")
1881
1882 try:
1883 class _metaclass(type):
1884 def mro(self):
1885 return 1
1886 class X(object, metaclass=_metaclass):
1887 pass
1888 except TypeError:
1889 pass
1890 else:
1891 self.fail("non-sequence mro() return not caught")
1892
1893 def test_overloading(self):
1894 # Testing operator overloading...
1895
1896 class B(object):
1897 "Intermediate class because object doesn't have a __setattr__"
1898
1899 class C(B):
1900 def __getattr__(self, name):
1901 if name == "foo":
1902 return ("getattr", name)
1903 else:
1904 raise AttributeError
1905 def __setattr__(self, name, value):
1906 if name == "foo":
1907 self.setattr = (name, value)
1908 else:
1909 return B.__setattr__(self, name, value)
1910 def __delattr__(self, name):
1911 if name == "foo":
1912 self.delattr = name
1913 else:
1914 return B.__delattr__(self, name)
1915
1916 def __getitem__(self, key):
1917 return ("getitem", key)
1918 def __setitem__(self, key, value):
1919 self.setitem = (key, value)
1920 def __delitem__(self, key):
1921 self.delitem = key
1922
1923 a = C()
1924 self.assertEqual(a.foo, ("getattr", "foo"))
1925 a.foo = 12
1926 self.assertEqual(a.setattr, ("foo", 12))
1927 del a.foo
1928 self.assertEqual(a.delattr, "foo")
1929
1930 self.assertEqual(a[12], ("getitem", 12))
1931 a[12] = 21
1932 self.assertEqual(a.setitem, (12, 21))
1933 del a[12]
1934 self.assertEqual(a.delitem, 12)
1935
1936 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1937 a[0:10] = "foo"
1938 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1939 del a[0:10]
1940 self.assertEqual(a.delitem, (slice(0, 10)))
1941
1942 def test_methods(self):
1943 # Testing methods...
1944 class C(object):
1945 def __init__(self, x):
1946 self.x = x
1947 def foo(self):
1948 return self.x
1949 c1 = C(1)
1950 self.assertEqual(c1.foo(), 1)
1951 class D(C):
1952 boo = C.foo
1953 goo = c1.foo
1954 d2 = D(2)
1955 self.assertEqual(d2.foo(), 2)
1956 self.assertEqual(d2.boo(), 2)
1957 self.assertEqual(d2.goo(), 1)
1958 class E(object):
1959 foo = C.foo
1960 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001961 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001962
Inada Naoki62f95882019-04-01 17:56:11 +09001963 @support.impl_detail("testing error message from implementation")
1964 def test_methods_in_c(self):
1965 # This test checks error messages in builtin method descriptor.
1966 # It is allowed that other Python implementations use
1967 # different error messages.
1968 set_add = set.add
1969
1970 expected_errmsg = "descriptor 'add' of 'set' object needs an argument"
1971
1972 with self.assertRaises(TypeError) as cm:
1973 set_add()
1974 self.assertEqual(cm.exception.args[0], expected_errmsg)
1975
1976 expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"
1977
1978 with self.assertRaises(TypeError) as cm:
1979 set_add(0)
1980 self.assertEqual(cm.exception.args[0], expected_errmsg)
1981
1982 with self.assertRaises(TypeError) as cm:
1983 set_add.__get__(0)
1984 self.assertEqual(cm.exception.args[0], expected_errmsg)
1985
Benjamin Peterson224205f2009-05-08 03:25:19 +00001986 def test_special_method_lookup(self):
1987 # The lookup of special methods bypasses __getattr__ and
1988 # __getattribute__, but they still can be descriptors.
1989
1990 def run_context(manager):
1991 with manager:
1992 pass
1993 def iden(self):
1994 return self
1995 def hello(self):
1996 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001997 def empty_seq(self):
1998 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001999 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00002000 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00002001 def complex_num(self):
2002 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00002003 def stop(self):
2004 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002005 def return_true(self, thing=None):
2006 return True
2007 def do_isinstance(obj):
2008 return isinstance(int, obj)
2009 def do_issubclass(obj):
2010 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00002011 def do_dict_missing(checker):
2012 class DictSub(checker.__class__, dict):
2013 pass
2014 self.assertEqual(DictSub()["hi"], 4)
2015 def some_number(self_, key):
2016 self.assertEqual(key, "hi")
2017 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002018 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002019 def format_impl(self, spec):
2020 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00002021
2022 # It would be nice to have every special method tested here, but I'm
2023 # only listing the ones I can remember outside of typeobject.c, since it
2024 # does it right.
2025 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002026 ("__bytes__", bytes, hello, set(), {}),
2027 ("__reversed__", reversed, empty_seq, set(), {}),
2028 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00002029 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002030 ("__sizeof__", sys.getsizeof, zero, set(), {}),
2031 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00002032 ("__missing__", do_dict_missing, some_number,
2033 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002034 ("__subclasscheck__", do_issubclass, return_true,
2035 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002036 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
2037 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00002038 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002039 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002040 ("__floor__", math.floor, zero, set(), {}),
2041 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04002042 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00002043 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05002044 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002045 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00002046 ]
2047
2048 class Checker(object):
2049 def __getattr__(self, attr, test=self):
2050 test.fail("__getattr__ called with {0}".format(attr))
2051 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002052 if attr not in ok:
2053 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00002054 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002055 class SpecialDescr(object):
2056 def __init__(self, impl):
2057 self.impl = impl
2058 def __get__(self, obj, owner):
2059 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002060 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002061 class MyException(Exception):
2062 pass
2063 class ErrDescr(object):
2064 def __get__(self, obj, owner):
2065 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00002066
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002067 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00002068 class X(Checker):
2069 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002070 for attr, obj in env.items():
2071 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002072 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002073 runner(X())
2074
2075 record = []
2076 class X(Checker):
2077 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002078 for attr, obj in env.items():
2079 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002080 setattr(X, name, SpecialDescr(meth_impl))
2081 runner(X())
2082 self.assertEqual(record, [1], name)
2083
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002084 class X(Checker):
2085 pass
2086 for attr, obj in env.items():
2087 setattr(X, attr, obj)
2088 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002089 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002090
Georg Brandl479a7e72008-02-05 18:13:15 +00002091 def test_specials(self):
2092 # Testing special operators...
2093 # Test operators like __hash__ for which a built-in default exists
2094
2095 # Test the default behavior for static classes
2096 class C(object):
2097 def __getitem__(self, i):
2098 if 0 <= i < 10: return i
2099 raise IndexError
2100 c1 = C()
2101 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002102 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002103 self.assertNotEqual(id(c1), id(c2))
2104 hash(c1)
2105 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002106 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002107 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002108 self.assertFalse(c1 != c1)
2109 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002110 # Note that the module name appears in str/repr, and that varies
2111 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002112 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002113 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002114 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002115 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002116 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002117 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002118 # Test the default behavior for dynamic classes
2119 class D(object):
2120 def __getitem__(self, i):
2121 if 0 <= i < 10: return i
2122 raise IndexError
2123 d1 = D()
2124 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002125 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002126 self.assertNotEqual(id(d1), id(d2))
2127 hash(d1)
2128 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002129 self.assertEqual(d1, d1)
2130 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002131 self.assertFalse(d1 != d1)
2132 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002133 # Note that the module name appears in str/repr, and that varies
2134 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002135 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002136 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002137 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002138 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002139 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002140 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002141 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002142 class Proxy(object):
2143 def __init__(self, x):
2144 self.x = x
2145 def __bool__(self):
2146 return not not self.x
2147 def __hash__(self):
2148 return hash(self.x)
2149 def __eq__(self, other):
2150 return self.x == other
2151 def __ne__(self, other):
2152 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002153 def __ge__(self, other):
2154 return self.x >= other
2155 def __gt__(self, other):
2156 return self.x > other
2157 def __le__(self, other):
2158 return self.x <= other
2159 def __lt__(self, other):
2160 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002161 def __str__(self):
2162 return "Proxy:%s" % self.x
2163 def __repr__(self):
2164 return "Proxy(%r)" % self.x
2165 def __contains__(self, value):
2166 return value in self.x
2167 p0 = Proxy(0)
2168 p1 = Proxy(1)
2169 p_1 = Proxy(-1)
2170 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002171 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002172 self.assertEqual(hash(p0), hash(0))
2173 self.assertEqual(p0, p0)
2174 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002175 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002176 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002177 self.assertTrue(p0 < p1)
2178 self.assertTrue(p0 <= p1)
2179 self.assertTrue(p1 > p0)
2180 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002181 self.assertEqual(str(p0), "Proxy:0")
2182 self.assertEqual(repr(p0), "Proxy(0)")
2183 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002184 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002185 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002186 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002187 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002188
Georg Brandl479a7e72008-02-05 18:13:15 +00002189 def test_weakrefs(self):
2190 # Testing weak references...
2191 import weakref
2192 class C(object):
2193 pass
2194 c = C()
2195 r = weakref.ref(c)
2196 self.assertEqual(r(), c)
2197 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002198 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002199 self.assertEqual(r(), None)
2200 del r
2201 class NoWeak(object):
2202 __slots__ = ['foo']
2203 no = NoWeak()
2204 try:
2205 weakref.ref(no)
2206 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002207 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002208 else:
2209 self.fail("weakref.ref(no) should be illegal")
2210 class Weak(object):
2211 __slots__ = ['foo', '__weakref__']
2212 yes = Weak()
2213 r = weakref.ref(yes)
2214 self.assertEqual(r(), yes)
2215 del yes
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
2220 def test_properties(self):
2221 # Testing property...
2222 class C(object):
2223 def getx(self):
2224 return self.__x
2225 def setx(self, value):
2226 self.__x = value
2227 def delx(self):
2228 del self.__x
2229 x = property(getx, setx, delx, doc="I'm the x property.")
2230 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002231 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002232 a.x = 42
2233 self.assertEqual(a._C__x, 42)
2234 self.assertEqual(a.x, 42)
2235 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002236 self.assertNotHasAttr(a, "x")
2237 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002238 C.x.__set__(a, 100)
2239 self.assertEqual(C.x.__get__(a), 100)
2240 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002241 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002242
2243 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002244 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002245
2246 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002247 self.assertIn("__doc__", attrs)
2248 self.assertIn("fget", attrs)
2249 self.assertIn("fset", attrs)
2250 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002251
2252 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002253 self.assertIs(raw.fget, C.__dict__['getx'])
2254 self.assertIs(raw.fset, C.__dict__['setx'])
2255 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002256
Raymond Hettingereac503a2015-05-13 01:09:59 -07002257 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002258 try:
2259 setattr(raw, attr, 42)
2260 except AttributeError as msg:
2261 if str(msg).find('readonly') < 0:
2262 self.fail("when setting readonly attr %r on a property, "
2263 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2264 else:
2265 self.fail("expected AttributeError from trying to set readonly %r "
2266 "attr on a property" % attr)
2267
Raymond Hettingereac503a2015-05-13 01:09:59 -07002268 raw.__doc__ = 42
2269 self.assertEqual(raw.__doc__, 42)
2270
Georg Brandl479a7e72008-02-05 18:13:15 +00002271 class D(object):
2272 __getitem__ = property(lambda s: 1/0)
2273
2274 d = D()
2275 try:
2276 for i in d:
2277 str(i)
2278 except ZeroDivisionError:
2279 pass
2280 else:
2281 self.fail("expected ZeroDivisionError from bad property")
2282
R. David Murray378c0cf2010-02-24 01:46:21 +00002283 @unittest.skipIf(sys.flags.optimize >= 2,
2284 "Docstrings are omitted with -O2 and above")
2285 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002286 class E(object):
2287 def getter(self):
2288 "getter method"
2289 return 0
2290 def setter(self_, value):
2291 "setter method"
2292 pass
2293 prop = property(getter)
2294 self.assertEqual(prop.__doc__, "getter method")
2295 prop2 = property(fset=setter)
2296 self.assertEqual(prop2.__doc__, None)
2297
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002298 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002299 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002300 # this segfaulted in 2.5b2
2301 try:
2302 import _testcapi
2303 except ImportError:
2304 pass
2305 else:
2306 class X(object):
2307 p = property(_testcapi.test_with_docstring)
2308
2309 def test_properties_plus(self):
2310 class C(object):
2311 foo = property(doc="hello")
2312 @foo.getter
2313 def foo(self):
2314 return self._foo
2315 @foo.setter
2316 def foo(self, value):
2317 self._foo = abs(value)
2318 @foo.deleter
2319 def foo(self):
2320 del self._foo
2321 c = C()
2322 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002323 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002324 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002325 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002326 self.assertEqual(c._foo, 42)
2327 self.assertEqual(c.foo, 42)
2328 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002329 self.assertNotHasAttr(c, '_foo')
2330 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002331
2332 class D(C):
2333 @C.foo.deleter
2334 def foo(self):
2335 try:
2336 del self._foo
2337 except AttributeError:
2338 pass
2339 d = D()
2340 d.foo = 24
2341 self.assertEqual(d.foo, 24)
2342 del d.foo
2343 del d.foo
2344
2345 class E(object):
2346 @property
2347 def foo(self):
2348 return self._foo
2349 @foo.setter
2350 def foo(self, value):
2351 raise RuntimeError
2352 @foo.setter
2353 def foo(self, value):
2354 self._foo = abs(value)
2355 @foo.deleter
2356 def foo(self, value=None):
2357 del self._foo
2358
2359 e = E()
2360 e.foo = -42
2361 self.assertEqual(e.foo, 42)
2362 del e.foo
2363
2364 class F(E):
2365 @E.foo.deleter
2366 def foo(self):
2367 del self._foo
2368 @foo.setter
2369 def foo(self, value):
2370 self._foo = max(0, value)
2371 f = F()
2372 f.foo = -10
2373 self.assertEqual(f.foo, 0)
2374 del f.foo
2375
2376 def test_dict_constructors(self):
2377 # Testing dict constructor ...
2378 d = dict()
2379 self.assertEqual(d, {})
2380 d = dict({})
2381 self.assertEqual(d, {})
2382 d = dict({1: 2, 'a': 'b'})
2383 self.assertEqual(d, {1: 2, 'a': 'b'})
2384 self.assertEqual(d, dict(list(d.items())))
2385 self.assertEqual(d, dict(iter(d.items())))
2386 d = dict({'one':1, 'two':2})
2387 self.assertEqual(d, dict(one=1, two=2))
2388 self.assertEqual(d, dict(**d))
2389 self.assertEqual(d, dict({"one": 1}, two=2))
2390 self.assertEqual(d, dict([("two", 2)], one=1))
2391 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2392 self.assertEqual(d, dict(**d))
2393
2394 for badarg in 0, 0, 0j, "0", [0], (0,):
2395 try:
2396 dict(badarg)
2397 except TypeError:
2398 pass
2399 except ValueError:
2400 if badarg == "0":
2401 # It's a sequence, and its elements are also sequences (gotta
2402 # love strings <wink>), but they aren't of length 2, so this
2403 # one seemed better as a ValueError than a TypeError.
2404 pass
2405 else:
2406 self.fail("no TypeError from dict(%r)" % badarg)
2407 else:
2408 self.fail("no TypeError from dict(%r)" % badarg)
2409
2410 try:
2411 dict({}, {})
2412 except TypeError:
2413 pass
2414 else:
2415 self.fail("no TypeError from dict({}, {})")
2416
2417 class Mapping:
2418 # Lacks a .keys() method; will be added later.
2419 dict = {1:2, 3:4, 'a':1j}
2420
2421 try:
2422 dict(Mapping())
2423 except TypeError:
2424 pass
2425 else:
2426 self.fail("no TypeError from dict(incomplete mapping)")
2427
2428 Mapping.keys = lambda self: list(self.dict.keys())
2429 Mapping.__getitem__ = lambda self, i: self.dict[i]
2430 d = dict(Mapping())
2431 self.assertEqual(d, Mapping.dict)
2432
2433 # Init from sequence of iterable objects, each producing a 2-sequence.
2434 class AddressBookEntry:
2435 def __init__(self, first, last):
2436 self.first = first
2437 self.last = last
2438 def __iter__(self):
2439 return iter([self.first, self.last])
2440
2441 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2442 AddressBookEntry('Barry', 'Peters'),
2443 AddressBookEntry('Tim', 'Peters'),
2444 AddressBookEntry('Barry', 'Warsaw')])
2445 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2446
2447 d = dict(zip(range(4), range(1, 5)))
2448 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2449
2450 # Bad sequence lengths.
2451 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2452 try:
2453 dict(bad)
2454 except ValueError:
2455 pass
2456 else:
2457 self.fail("no ValueError from dict(%r)" % bad)
2458
2459 def test_dir(self):
2460 # Testing dir() ...
2461 junk = 12
2462 self.assertEqual(dir(), ['junk', 'self'])
2463 del junk
2464
2465 # Just make sure these don't blow up!
2466 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2467 dir(arg)
2468
2469 # Test dir on new-style classes. Since these have object as a
2470 # base class, a lot more gets sucked in.
2471 def interesting(strings):
2472 return [s for s in strings if not s.startswith('_')]
2473
2474 class C(object):
2475 Cdata = 1
2476 def Cmethod(self): pass
2477
2478 cstuff = ['Cdata', 'Cmethod']
2479 self.assertEqual(interesting(dir(C)), cstuff)
2480
2481 c = C()
2482 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002483 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002484
2485 c.cdata = 2
2486 c.cmethod = lambda self: 0
2487 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002488 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002489
2490 class A(C):
2491 Adata = 1
2492 def Amethod(self): pass
2493
2494 astuff = ['Adata', 'Amethod'] + cstuff
2495 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002496 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002497 a = A()
2498 self.assertEqual(interesting(dir(a)), astuff)
2499 a.adata = 42
2500 a.amethod = lambda self: 3
2501 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002502 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002503
2504 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002505 class M(type(sys)):
2506 pass
2507 minstance = M("m")
2508 minstance.b = 2
2509 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002510 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002511 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002512 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002513 self.assertEqual(names, ['a', 'b'])
2514
2515 class M2(M):
2516 def getdict(self):
2517 return "Not a dict!"
2518 __dict__ = property(getdict)
2519
2520 m2instance = M2("m2")
2521 m2instance.b = 2
2522 m2instance.a = 1
2523 self.assertEqual(m2instance.__dict__, "Not a dict!")
2524 try:
2525 dir(m2instance)
2526 except TypeError:
2527 pass
2528
2529 # Two essentially featureless objects, just inheriting stuff from
2530 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002531 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002532
2533 # Nasty test case for proxied objects
2534 class Wrapper(object):
2535 def __init__(self, obj):
2536 self.__obj = obj
2537 def __repr__(self):
2538 return "Wrapper(%s)" % repr(self.__obj)
2539 def __getitem__(self, key):
2540 return Wrapper(self.__obj[key])
2541 def __len__(self):
2542 return len(self.__obj)
2543 def __getattr__(self, name):
2544 return Wrapper(getattr(self.__obj, name))
2545
2546 class C(object):
2547 def __getclass(self):
2548 return Wrapper(type(self))
2549 __class__ = property(__getclass)
2550
2551 dir(C()) # This used to segfault
2552
2553 def test_supers(self):
2554 # Testing super...
2555
2556 class A(object):
2557 def meth(self, a):
2558 return "A(%r)" % a
2559
2560 self.assertEqual(A().meth(1), "A(1)")
2561
2562 class B(A):
2563 def __init__(self):
2564 self.__super = super(B, self)
2565 def meth(self, a):
2566 return "B(%r)" % a + self.__super.meth(a)
2567
2568 self.assertEqual(B().meth(2), "B(2)A(2)")
2569
2570 class C(A):
2571 def meth(self, a):
2572 return "C(%r)" % a + self.__super.meth(a)
2573 C._C__super = super(C)
2574
2575 self.assertEqual(C().meth(3), "C(3)A(3)")
2576
2577 class D(C, B):
2578 def meth(self, a):
2579 return "D(%r)" % a + super(D, self).meth(a)
2580
2581 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2582
2583 # Test for subclassing super
2584
2585 class mysuper(super):
2586 def __init__(self, *args):
2587 return super(mysuper, self).__init__(*args)
2588
2589 class E(D):
2590 def meth(self, a):
2591 return "E(%r)" % a + mysuper(E, self).meth(a)
2592
2593 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2594
2595 class F(E):
2596 def meth(self, a):
2597 s = self.__super # == mysuper(F, self)
2598 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2599 F._F__super = mysuper(F)
2600
2601 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2602
2603 # Make sure certain errors are raised
2604
2605 try:
2606 super(D, 42)
2607 except TypeError:
2608 pass
2609 else:
2610 self.fail("shouldn't allow super(D, 42)")
2611
2612 try:
2613 super(D, C())
2614 except TypeError:
2615 pass
2616 else:
2617 self.fail("shouldn't allow super(D, C())")
2618
2619 try:
2620 super(D).__get__(12)
2621 except TypeError:
2622 pass
2623 else:
2624 self.fail("shouldn't allow super(D).__get__(12)")
2625
2626 try:
2627 super(D).__get__(C())
2628 except TypeError:
2629 pass
2630 else:
2631 self.fail("shouldn't allow super(D).__get__(C())")
2632
2633 # Make sure data descriptors can be overridden and accessed via super
2634 # (new feature in Python 2.3)
2635
2636 class DDbase(object):
2637 def getx(self): return 42
2638 x = property(getx)
2639
2640 class DDsub(DDbase):
2641 def getx(self): return "hello"
2642 x = property(getx)
2643
2644 dd = DDsub()
2645 self.assertEqual(dd.x, "hello")
2646 self.assertEqual(super(DDsub, dd).x, 42)
2647
2648 # Ensure that super() lookup of descriptor from classmethod
2649 # works (SF ID# 743627)
2650
2651 class Base(object):
2652 aProp = property(lambda self: "foo")
2653
2654 class Sub(Base):
2655 @classmethod
2656 def test(klass):
2657 return super(Sub,klass).aProp
2658
2659 self.assertEqual(Sub.test(), Base.aProp)
2660
2661 # Verify that super() doesn't allow keyword args
2662 try:
2663 super(Base, kw=1)
2664 except TypeError:
2665 pass
2666 else:
2667 self.assertEqual("super shouldn't accept keyword args")
2668
2669 def test_basic_inheritance(self):
2670 # Testing inheritance from basic types...
2671
2672 class hexint(int):
2673 def __repr__(self):
2674 return hex(self)
2675 def __add__(self, other):
2676 return hexint(int.__add__(self, other))
2677 # (Note that overriding __radd__ doesn't work,
2678 # because the int type gets first dibs.)
2679 self.assertEqual(repr(hexint(7) + 9), "0x10")
2680 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2681 a = hexint(12345)
2682 self.assertEqual(a, 12345)
2683 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002684 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002685 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002686 self.assertIs((+a).__class__, int)
2687 self.assertIs((a >> 0).__class__, int)
2688 self.assertIs((a << 0).__class__, int)
2689 self.assertIs((hexint(0) << 12).__class__, int)
2690 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002691
2692 class octlong(int):
2693 __slots__ = []
2694 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002695 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002696 def __add__(self, other):
2697 return self.__class__(super(octlong, self).__add__(other))
2698 __radd__ = __add__
2699 self.assertEqual(str(octlong(3) + 5), "0o10")
2700 # (Note that overriding __radd__ here only seems to work
2701 # because the example uses a short int left argument.)
2702 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2703 a = octlong(12345)
2704 self.assertEqual(a, 12345)
2705 self.assertEqual(int(a), 12345)
2706 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002707 self.assertIs(int(a).__class__, int)
2708 self.assertIs((+a).__class__, int)
2709 self.assertIs((-a).__class__, int)
2710 self.assertIs((-octlong(0)).__class__, int)
2711 self.assertIs((a >> 0).__class__, int)
2712 self.assertIs((a << 0).__class__, int)
2713 self.assertIs((a - 0).__class__, int)
2714 self.assertIs((a * 1).__class__, int)
2715 self.assertIs((a ** 1).__class__, int)
2716 self.assertIs((a // 1).__class__, int)
2717 self.assertIs((1 * a).__class__, int)
2718 self.assertIs((a | 0).__class__, int)
2719 self.assertIs((a ^ 0).__class__, int)
2720 self.assertIs((a & -1).__class__, int)
2721 self.assertIs((octlong(0) << 12).__class__, int)
2722 self.assertIs((octlong(0) >> 12).__class__, int)
2723 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002724
2725 # Because octlong overrides __add__, we can't check the absence of +0
2726 # optimizations using octlong.
2727 class longclone(int):
2728 pass
2729 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002730 self.assertIs((a + 0).__class__, int)
2731 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002732
2733 # Check that negative clones don't segfault
2734 a = longclone(-1)
2735 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002736 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002737
2738 class precfloat(float):
2739 __slots__ = ['prec']
2740 def __init__(self, value=0.0, prec=12):
2741 self.prec = int(prec)
2742 def __repr__(self):
2743 return "%.*g" % (self.prec, self)
2744 self.assertEqual(repr(precfloat(1.1)), "1.1")
2745 a = precfloat(12345)
2746 self.assertEqual(a, 12345.0)
2747 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002748 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002749 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002750 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002751
2752 class madcomplex(complex):
2753 def __repr__(self):
2754 return "%.17gj%+.17g" % (self.imag, self.real)
2755 a = madcomplex(-3, 4)
2756 self.assertEqual(repr(a), "4j-3")
2757 base = complex(-3, 4)
2758 self.assertEqual(base.__class__, complex)
2759 self.assertEqual(a, base)
2760 self.assertEqual(complex(a), base)
2761 self.assertEqual(complex(a).__class__, complex)
2762 a = madcomplex(a) # just trying another form of the constructor
2763 self.assertEqual(repr(a), "4j-3")
2764 self.assertEqual(a, base)
2765 self.assertEqual(complex(a), base)
2766 self.assertEqual(complex(a).__class__, complex)
2767 self.assertEqual(hash(a), hash(base))
2768 self.assertEqual((+a).__class__, complex)
2769 self.assertEqual((a + 0).__class__, complex)
2770 self.assertEqual(a + 0, base)
2771 self.assertEqual((a - 0).__class__, complex)
2772 self.assertEqual(a - 0, base)
2773 self.assertEqual((a * 1).__class__, complex)
2774 self.assertEqual(a * 1, base)
2775 self.assertEqual((a / 1).__class__, complex)
2776 self.assertEqual(a / 1, base)
2777
2778 class madtuple(tuple):
2779 _rev = None
2780 def rev(self):
2781 if self._rev is not None:
2782 return self._rev
2783 L = list(self)
2784 L.reverse()
2785 self._rev = self.__class__(L)
2786 return self._rev
2787 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2788 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2789 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2790 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2791 for i in range(512):
2792 t = madtuple(range(i))
2793 u = t.rev()
2794 v = u.rev()
2795 self.assertEqual(v, t)
2796 a = madtuple((1,2,3,4,5))
2797 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002798 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002799 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002800 self.assertIs(a[:].__class__, tuple)
2801 self.assertIs((a * 1).__class__, tuple)
2802 self.assertIs((a * 0).__class__, tuple)
2803 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002804 a = madtuple(())
2805 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002806 self.assertIs(tuple(a).__class__, tuple)
2807 self.assertIs((a + a).__class__, tuple)
2808 self.assertIs((a * 0).__class__, tuple)
2809 self.assertIs((a * 1).__class__, tuple)
2810 self.assertIs((a * 2).__class__, tuple)
2811 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002812
2813 class madstring(str):
2814 _rev = None
2815 def rev(self):
2816 if self._rev is not None:
2817 return self._rev
2818 L = list(self)
2819 L.reverse()
2820 self._rev = self.__class__("".join(L))
2821 return self._rev
2822 s = madstring("abcdefghijklmnopqrstuvwxyz")
2823 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2824 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2825 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2826 for i in range(256):
2827 s = madstring("".join(map(chr, range(i))))
2828 t = s.rev()
2829 u = t.rev()
2830 self.assertEqual(u, s)
2831 s = madstring("12345")
2832 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002833 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002834
2835 base = "\x00" * 5
2836 s = madstring(base)
2837 self.assertEqual(s, base)
2838 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002839 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002840 self.assertEqual(hash(s), hash(base))
2841 self.assertEqual({s: 1}[base], 1)
2842 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002843 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002844 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002845 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002846 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002847 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002848 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002849 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002850 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002851 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002852 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002853 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002854 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002855 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002856 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002858 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002859 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002860 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002861 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002862 self.assertEqual(s.rstrip(), base)
2863 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002864 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002865 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002866 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002867 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002868 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002869 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002870 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002871 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002872 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002873 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002874 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002875 self.assertEqual(s.lower(), base)
2876
2877 class madunicode(str):
2878 _rev = None
2879 def rev(self):
2880 if self._rev is not None:
2881 return self._rev
2882 L = list(self)
2883 L.reverse()
2884 self._rev = self.__class__("".join(L))
2885 return self._rev
2886 u = madunicode("ABCDEF")
2887 self.assertEqual(u, "ABCDEF")
2888 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2889 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2890 base = "12345"
2891 u = madunicode(base)
2892 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002893 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002894 self.assertEqual(hash(u), hash(base))
2895 self.assertEqual({u: 1}[base], 1)
2896 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002897 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002898 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002899 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002900 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002901 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002902 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002903 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002904 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002905 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002906 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002907 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002909 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002910 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002911 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002912 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002913 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002915 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002916 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002917 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002918 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002919 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002920 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002921 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002922 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002923 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002924 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002925 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002926 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002927 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002928 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002929 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002930 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002931 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002932 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002933 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002934 self.assertEqual(u[0:0], "")
2935
2936 class sublist(list):
2937 pass
2938 a = sublist(range(5))
2939 self.assertEqual(a, list(range(5)))
2940 a.append("hello")
2941 self.assertEqual(a, list(range(5)) + ["hello"])
2942 a[5] = 5
2943 self.assertEqual(a, list(range(6)))
2944 a.extend(range(6, 20))
2945 self.assertEqual(a, list(range(20)))
2946 a[-5:] = []
2947 self.assertEqual(a, list(range(15)))
2948 del a[10:15]
2949 self.assertEqual(len(a), 10)
2950 self.assertEqual(a, list(range(10)))
2951 self.assertEqual(list(a), list(range(10)))
2952 self.assertEqual(a[0], 0)
2953 self.assertEqual(a[9], 9)
2954 self.assertEqual(a[-10], 0)
2955 self.assertEqual(a[-1], 9)
2956 self.assertEqual(a[:5], list(range(5)))
2957
2958 ## class CountedInput(file):
2959 ## """Counts lines read by self.readline().
2960 ##
2961 ## self.lineno is the 0-based ordinal of the last line read, up to
2962 ## a maximum of one greater than the number of lines in the file.
2963 ##
2964 ## self.ateof is true if and only if the final "" line has been read,
2965 ## at which point self.lineno stops incrementing, and further calls
2966 ## to readline() continue to return "".
2967 ## """
2968 ##
2969 ## lineno = 0
2970 ## ateof = 0
2971 ## def readline(self):
2972 ## if self.ateof:
2973 ## return ""
2974 ## s = file.readline(self)
2975 ## # Next line works too.
2976 ## # s = super(CountedInput, self).readline()
2977 ## self.lineno += 1
2978 ## if s == "":
2979 ## self.ateof = 1
2980 ## return s
2981 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002982 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002983 ## lines = ['a\n', 'b\n', 'c\n']
2984 ## try:
2985 ## f.writelines(lines)
2986 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002987 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002988 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2989 ## got = f.readline()
2990 ## self.assertEqual(expected, got)
2991 ## self.assertEqual(f.lineno, i)
2992 ## self.assertEqual(f.ateof, (i > len(lines)))
2993 ## f.close()
2994 ## finally:
2995 ## try:
2996 ## f.close()
2997 ## except:
2998 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002999 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00003000
3001 def test_keywords(self):
3002 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003003 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3004 int(x=1)
3005 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3006 float(x=2)
3007 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3008 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003009 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
3010 self.assertEqual(str(object=500), '500')
3011 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003012 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3013 tuple(sequence=range(3))
3014 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3015 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00003016 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
3017
3018 for constructor in (int, float, int, complex, str, str,
3019 tuple, list):
3020 try:
3021 constructor(bogus_keyword_arg=1)
3022 except TypeError:
3023 pass
3024 else:
3025 self.fail("expected TypeError from bogus keyword argument to %r"
3026 % constructor)
3027
3028 def test_str_subclass_as_dict_key(self):
3029 # Testing a str subclass used as dict key ..
3030
3031 class cistr(str):
3032 """Sublcass of str that computes __eq__ case-insensitively.
3033
3034 Also computes a hash code of the string in canonical form.
3035 """
3036
3037 def __init__(self, value):
3038 self.canonical = value.lower()
3039 self.hashcode = hash(self.canonical)
3040
3041 def __eq__(self, other):
3042 if not isinstance(other, cistr):
3043 other = cistr(other)
3044 return self.canonical == other.canonical
3045
3046 def __hash__(self):
3047 return self.hashcode
3048
3049 self.assertEqual(cistr('ABC'), 'abc')
3050 self.assertEqual('aBc', cistr('ABC'))
3051 self.assertEqual(str(cistr('ABC')), 'ABC')
3052
3053 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3054 self.assertEqual(d[cistr('one')], 1)
3055 self.assertEqual(d[cistr('tWo')], 2)
3056 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00003057 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003058 self.assertEqual(d.get(cistr('thrEE')), 3)
3059
3060 def test_classic_comparisons(self):
3061 # Testing classic comparisons...
3062 class classic:
3063 pass
3064
3065 for base in (classic, int, object):
3066 class C(base):
3067 def __init__(self, value):
3068 self.value = int(value)
3069 def __eq__(self, other):
3070 if isinstance(other, C):
3071 return self.value == other.value
3072 if isinstance(other, int) or isinstance(other, int):
3073 return self.value == other
3074 return NotImplemented
3075 def __ne__(self, other):
3076 if isinstance(other, C):
3077 return self.value != other.value
3078 if isinstance(other, int) or isinstance(other, int):
3079 return self.value != other
3080 return NotImplemented
3081 def __lt__(self, other):
3082 if isinstance(other, C):
3083 return self.value < other.value
3084 if isinstance(other, int) or isinstance(other, int):
3085 return self.value < other
3086 return NotImplemented
3087 def __le__(self, other):
3088 if isinstance(other, C):
3089 return self.value <= other.value
3090 if isinstance(other, int) or isinstance(other, int):
3091 return self.value <= other
3092 return NotImplemented
3093 def __gt__(self, other):
3094 if isinstance(other, C):
3095 return self.value > other.value
3096 if isinstance(other, int) or isinstance(other, int):
3097 return self.value > other
3098 return NotImplemented
3099 def __ge__(self, other):
3100 if isinstance(other, C):
3101 return self.value >= other.value
3102 if isinstance(other, int) or isinstance(other, int):
3103 return self.value >= other
3104 return NotImplemented
3105
3106 c1 = C(1)
3107 c2 = C(2)
3108 c3 = C(3)
3109 self.assertEqual(c1, 1)
3110 c = {1: c1, 2: c2, 3: c3}
3111 for x in 1, 2, 3:
3112 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003113 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003114 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003115 eval("x %s y" % op),
3116 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003117 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003118 eval("x %s y" % op),
3119 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003120 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003121 eval("x %s y" % op),
3122 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003123
3124 def test_rich_comparisons(self):
3125 # Testing rich comparisons...
3126 class Z(complex):
3127 pass
3128 z = Z(1)
3129 self.assertEqual(z, 1+0j)
3130 self.assertEqual(1+0j, z)
3131 class ZZ(complex):
3132 def __eq__(self, other):
3133 try:
3134 return abs(self - other) <= 1e-6
3135 except:
3136 return NotImplemented
3137 zz = ZZ(1.0000003)
3138 self.assertEqual(zz, 1+0j)
3139 self.assertEqual(1+0j, zz)
3140
3141 class classic:
3142 pass
3143 for base in (classic, int, object, list):
3144 class C(base):
3145 def __init__(self, value):
3146 self.value = int(value)
3147 def __cmp__(self_, other):
3148 self.fail("shouldn't call __cmp__")
3149 def __eq__(self, other):
3150 if isinstance(other, C):
3151 return self.value == other.value
3152 if isinstance(other, int) or isinstance(other, int):
3153 return self.value == other
3154 return NotImplemented
3155 def __ne__(self, other):
3156 if isinstance(other, C):
3157 return self.value != other.value
3158 if isinstance(other, int) or isinstance(other, int):
3159 return self.value != other
3160 return NotImplemented
3161 def __lt__(self, other):
3162 if isinstance(other, C):
3163 return self.value < other.value
3164 if isinstance(other, int) or isinstance(other, int):
3165 return self.value < other
3166 return NotImplemented
3167 def __le__(self, other):
3168 if isinstance(other, C):
3169 return self.value <= other.value
3170 if isinstance(other, int) or isinstance(other, int):
3171 return self.value <= other
3172 return NotImplemented
3173 def __gt__(self, other):
3174 if isinstance(other, C):
3175 return self.value > other.value
3176 if isinstance(other, int) or isinstance(other, int):
3177 return self.value > other
3178 return NotImplemented
3179 def __ge__(self, other):
3180 if isinstance(other, C):
3181 return self.value >= other.value
3182 if isinstance(other, int) or isinstance(other, int):
3183 return self.value >= other
3184 return NotImplemented
3185 c1 = C(1)
3186 c2 = C(2)
3187 c3 = C(3)
3188 self.assertEqual(c1, 1)
3189 c = {1: c1, 2: c2, 3: c3}
3190 for x in 1, 2, 3:
3191 for y in 1, 2, 3:
3192 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003193 self.assertEqual(eval("c[x] %s c[y]" % op),
3194 eval("x %s y" % op),
3195 "x=%d, y=%d" % (x, y))
3196 self.assertEqual(eval("c[x] %s y" % op),
3197 eval("x %s y" % op),
3198 "x=%d, y=%d" % (x, y))
3199 self.assertEqual(eval("x %s c[y]" % op),
3200 eval("x %s y" % op),
3201 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003202
3203 def test_descrdoc(self):
3204 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003205 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003206 def check(descr, what):
3207 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003208 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003209 check(complex.real, "the real part of a complex number") # member descriptor
3210
3211 def test_doc_descriptor(self):
3212 # Testing __doc__ descriptor...
3213 # SF bug 542984
3214 class DocDescr(object):
3215 def __get__(self, object, otype):
3216 if object:
3217 object = object.__class__.__name__ + ' instance'
3218 if otype:
3219 otype = otype.__name__
3220 return 'object=%s; type=%s' % (object, otype)
3221 class OldClass:
3222 __doc__ = DocDescr()
3223 class NewClass(object):
3224 __doc__ = DocDescr()
3225 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3226 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3227 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3228 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3229
3230 def test_set_class(self):
3231 # Testing __class__ assignment...
3232 class C(object): pass
3233 class D(object): pass
3234 class E(object): pass
3235 class F(D, E): pass
3236 for cls in C, D, E, F:
3237 for cls2 in C, D, E, F:
3238 x = cls()
3239 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003240 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003241 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003242 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003243 def cant(x, C):
3244 try:
3245 x.__class__ = C
3246 except TypeError:
3247 pass
3248 else:
3249 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3250 try:
3251 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003252 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003253 pass
3254 else:
3255 self.fail("shouldn't allow del %r.__class__" % x)
3256 cant(C(), list)
3257 cant(list(), C)
3258 cant(C(), 1)
3259 cant(C(), object)
3260 cant(object(), list)
3261 cant(list(), object)
3262 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003263 cant(True, int)
3264 cant(2, bool)
3265 o = object()
3266 cant(o, type(1))
3267 cant(o, type(None))
3268 del o
3269 class G(object):
3270 __slots__ = ["a", "b"]
3271 class H(object):
3272 __slots__ = ["b", "a"]
3273 class I(object):
3274 __slots__ = ["a", "b"]
3275 class J(object):
3276 __slots__ = ["c", "b"]
3277 class K(object):
3278 __slots__ = ["a", "b", "d"]
3279 class L(H):
3280 __slots__ = ["e"]
3281 class M(I):
3282 __slots__ = ["e"]
3283 class N(J):
3284 __slots__ = ["__weakref__"]
3285 class P(J):
3286 __slots__ = ["__dict__"]
3287 class Q(J):
3288 pass
3289 class R(J):
3290 __slots__ = ["__dict__", "__weakref__"]
3291
3292 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3293 x = cls()
3294 x.a = 1
3295 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003296 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003297 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3298 self.assertEqual(x.a, 1)
3299 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003300 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003301 "assigning %r as __class__ for %r silently failed" % (cls, x))
3302 self.assertEqual(x.a, 1)
3303 for cls in G, J, K, L, M, N, P, R, list, Int:
3304 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3305 if cls is cls2:
3306 continue
3307 cant(cls(), cls2)
3308
Benjamin Peterson193152c2009-04-25 01:08:45 +00003309 # Issue5283: when __class__ changes in __del__, the wrong
3310 # type gets DECREF'd.
3311 class O(object):
3312 pass
3313 class A(object):
3314 def __del__(self):
3315 self.__class__ = O
3316 l = [A() for x in range(100)]
3317 del l
3318
Georg Brandl479a7e72008-02-05 18:13:15 +00003319 def test_set_dict(self):
3320 # Testing __dict__ assignment...
3321 class C(object): pass
3322 a = C()
3323 a.__dict__ = {'b': 1}
3324 self.assertEqual(a.b, 1)
3325 def cant(x, dict):
3326 try:
3327 x.__dict__ = dict
3328 except (AttributeError, TypeError):
3329 pass
3330 else:
3331 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3332 cant(a, None)
3333 cant(a, [])
3334 cant(a, 1)
3335 del a.__dict__ # Deleting __dict__ is allowed
3336
3337 class Base(object):
3338 pass
3339 def verify_dict_readonly(x):
3340 """
3341 x has to be an instance of a class inheriting from Base.
3342 """
3343 cant(x, {})
3344 try:
3345 del x.__dict__
3346 except (AttributeError, TypeError):
3347 pass
3348 else:
3349 self.fail("shouldn't allow del %r.__dict__" % x)
3350 dict_descr = Base.__dict__["__dict__"]
3351 try:
3352 dict_descr.__set__(x, {})
3353 except (AttributeError, TypeError):
3354 pass
3355 else:
3356 self.fail("dict_descr allowed access to %r's dict" % x)
3357
3358 # Classes don't allow __dict__ assignment and have readonly dicts
3359 class Meta1(type, Base):
3360 pass
3361 class Meta2(Base, type):
3362 pass
3363 class D(object, metaclass=Meta1):
3364 pass
3365 class E(object, metaclass=Meta2):
3366 pass
3367 for cls in C, D, E:
3368 verify_dict_readonly(cls)
3369 class_dict = cls.__dict__
3370 try:
3371 class_dict["spam"] = "eggs"
3372 except TypeError:
3373 pass
3374 else:
3375 self.fail("%r's __dict__ can be modified" % cls)
3376
3377 # Modules also disallow __dict__ assignment
3378 class Module1(types.ModuleType, Base):
3379 pass
3380 class Module2(Base, types.ModuleType):
3381 pass
3382 for ModuleType in Module1, Module2:
3383 mod = ModuleType("spam")
3384 verify_dict_readonly(mod)
3385 mod.__dict__["spam"] = "eggs"
3386
3387 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003388 # (at least not any more than regular exception's __dict__ can
3389 # be deleted; on CPython it is not the case, whereas on PyPy they
3390 # can, just like any other new-style instance's __dict__.)
3391 def can_delete_dict(e):
3392 try:
3393 del e.__dict__
3394 except (TypeError, AttributeError):
3395 return False
3396 else:
3397 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003398 class Exception1(Exception, Base):
3399 pass
3400 class Exception2(Base, Exception):
3401 pass
3402 for ExceptionType in Exception, Exception1, Exception2:
3403 e = ExceptionType()
3404 e.__dict__ = {"a": 1}
3405 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003406 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003407
Georg Brandl479a7e72008-02-05 18:13:15 +00003408 def test_binary_operator_override(self):
3409 # Testing overrides of binary operations...
3410 class I(int):
3411 def __repr__(self):
3412 return "I(%r)" % int(self)
3413 def __add__(self, other):
3414 return I(int(self) + int(other))
3415 __radd__ = __add__
3416 def __pow__(self, other, mod=None):
3417 if mod is None:
3418 return I(pow(int(self), int(other)))
3419 else:
3420 return I(pow(int(self), int(other), int(mod)))
3421 def __rpow__(self, other, mod=None):
3422 if mod is None:
3423 return I(pow(int(other), int(self), mod))
3424 else:
3425 return I(pow(int(other), int(self), int(mod)))
3426
3427 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3428 self.assertEqual(repr(I(1) + 2), "I(3)")
3429 self.assertEqual(repr(1 + I(2)), "I(3)")
3430 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3431 self.assertEqual(repr(2 ** I(3)), "I(8)")
3432 self.assertEqual(repr(I(2) ** 3), "I(8)")
3433 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3434 class S(str):
3435 def __eq__(self, other):
3436 return self.lower() == other.lower()
3437
3438 def test_subclass_propagation(self):
3439 # Testing propagation of slot functions to subclasses...
3440 class A(object):
3441 pass
3442 class B(A):
3443 pass
3444 class C(A):
3445 pass
3446 class D(B, C):
3447 pass
3448 d = D()
3449 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3450 A.__hash__ = lambda self: 42
3451 self.assertEqual(hash(d), 42)
3452 C.__hash__ = lambda self: 314
3453 self.assertEqual(hash(d), 314)
3454 B.__hash__ = lambda self: 144
3455 self.assertEqual(hash(d), 144)
3456 D.__hash__ = lambda self: 100
3457 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003458 D.__hash__ = None
3459 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003460 del D.__hash__
3461 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003462 B.__hash__ = None
3463 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003464 del B.__hash__
3465 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003466 C.__hash__ = None
3467 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003468 del C.__hash__
3469 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003470 A.__hash__ = None
3471 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003472 del A.__hash__
3473 self.assertEqual(hash(d), orig_hash)
3474 d.foo = 42
3475 d.bar = 42
3476 self.assertEqual(d.foo, 42)
3477 self.assertEqual(d.bar, 42)
3478 def __getattribute__(self, name):
3479 if name == "foo":
3480 return 24
3481 return object.__getattribute__(self, name)
3482 A.__getattribute__ = __getattribute__
3483 self.assertEqual(d.foo, 24)
3484 self.assertEqual(d.bar, 42)
3485 def __getattr__(self, name):
3486 if name in ("spam", "foo", "bar"):
3487 return "hello"
3488 raise AttributeError(name)
3489 B.__getattr__ = __getattr__
3490 self.assertEqual(d.spam, "hello")
3491 self.assertEqual(d.foo, 24)
3492 self.assertEqual(d.bar, 42)
3493 del A.__getattribute__
3494 self.assertEqual(d.foo, 42)
3495 del d.foo
3496 self.assertEqual(d.foo, "hello")
3497 self.assertEqual(d.bar, 42)
3498 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003499 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003500 d.foo
3501 except AttributeError:
3502 pass
3503 else:
3504 self.fail("d.foo should be undefined now")
3505
3506 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003507 class A(object):
3508 pass
3509 class B(A):
3510 pass
3511 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003512 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003513 A.__setitem__ = lambda *a: None # crash
3514
3515 def test_buffer_inheritance(self):
3516 # Testing that buffer interface is inherited ...
3517
3518 import binascii
3519 # SF bug [#470040] ParseTuple t# vs subclasses.
3520
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003521 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003522 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003523 base = b'abc'
3524 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003525 # b2a_hex uses the buffer interface to get its argument's value, via
3526 # PyArg_ParseTuple 't#' code.
3527 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3528
Georg Brandl479a7e72008-02-05 18:13:15 +00003529 class MyInt(int):
3530 pass
3531 m = MyInt(42)
3532 try:
3533 binascii.b2a_hex(m)
3534 self.fail('subclass of int should not have a buffer interface')
3535 except TypeError:
3536 pass
3537
3538 def test_str_of_str_subclass(self):
3539 # Testing __str__ defined in subclass of str ...
3540 import binascii
3541 import io
3542
3543 class octetstring(str):
3544 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003545 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003546 def __repr__(self):
3547 return self + " repr"
3548
3549 o = octetstring('A')
3550 self.assertEqual(type(o), octetstring)
3551 self.assertEqual(type(str(o)), str)
3552 self.assertEqual(type(repr(o)), str)
3553 self.assertEqual(ord(o), 0x41)
3554 self.assertEqual(str(o), '41')
3555 self.assertEqual(repr(o), 'A repr')
3556 self.assertEqual(o.__str__(), '41')
3557 self.assertEqual(o.__repr__(), 'A repr')
3558
3559 capture = io.StringIO()
3560 # Calling str() or not exercises different internal paths.
3561 print(o, file=capture)
3562 print(str(o), file=capture)
3563 self.assertEqual(capture.getvalue(), '41\n41\n')
3564 capture.close()
3565
3566 def test_keyword_arguments(self):
3567 # Testing keyword arguments to __init__, __call__...
3568 def f(a): return a
3569 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003570 ba = bytearray()
3571 bytearray.__init__(ba, 'abc\xbd\u20ac',
3572 encoding='latin1', errors='replace')
3573 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003574
3575 def test_recursive_call(self):
3576 # Testing recursive __call__() by setting to instance of class...
3577 class A(object):
3578 pass
3579
3580 A.__call__ = A()
3581 try:
3582 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003583 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003584 pass
3585 else:
3586 self.fail("Recursion limit should have been reached for __call__()")
3587
3588 def test_delete_hook(self):
3589 # Testing __del__ hook...
3590 log = []
3591 class C(object):
3592 def __del__(self):
3593 log.append(1)
3594 c = C()
3595 self.assertEqual(log, [])
3596 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003597 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003598 self.assertEqual(log, [1])
3599
3600 class D(object): pass
3601 d = D()
3602 try: del d[0]
3603 except TypeError: pass
3604 else: self.fail("invalid del() didn't raise TypeError")
3605
3606 def test_hash_inheritance(self):
3607 # Testing hash of mutable subclasses...
3608
3609 class mydict(dict):
3610 pass
3611 d = mydict()
3612 try:
3613 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003614 except TypeError:
3615 pass
3616 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 self.fail("hash() of dict subclass should fail")
3618
3619 class mylist(list):
3620 pass
3621 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003622 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003623 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003624 except TypeError:
3625 pass
3626 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003627 self.fail("hash() of list subclass should fail")
3628
3629 def test_str_operations(self):
3630 try: 'a' + 5
3631 except TypeError: pass
3632 else: self.fail("'' + 5 doesn't raise TypeError")
3633
3634 try: ''.split('')
3635 except ValueError: pass
3636 else: self.fail("''.split('') doesn't raise ValueError")
3637
3638 try: ''.join([0])
3639 except TypeError: pass
3640 else: self.fail("''.join([0]) doesn't raise TypeError")
3641
3642 try: ''.rindex('5')
3643 except ValueError: pass
3644 else: self.fail("''.rindex('5') doesn't raise ValueError")
3645
3646 try: '%(n)s' % None
3647 except TypeError: pass
3648 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3649
3650 try: '%(n' % {}
3651 except ValueError: pass
3652 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3653
3654 try: '%*s' % ('abc')
3655 except TypeError: pass
3656 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3657
3658 try: '%*.*s' % ('abc', 5)
3659 except TypeError: pass
3660 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3661
3662 try: '%s' % (1, 2)
3663 except TypeError: pass
3664 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3665
3666 try: '%' % None
3667 except ValueError: pass
3668 else: self.fail("'%' % None doesn't raise ValueError")
3669
3670 self.assertEqual('534253'.isdigit(), 1)
3671 self.assertEqual('534253x'.isdigit(), 0)
3672 self.assertEqual('%c' % 5, '\x05')
3673 self.assertEqual('%c' % '5', '5')
3674
3675 def test_deepcopy_recursive(self):
3676 # Testing deepcopy of recursive objects...
3677 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003678 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003679 a = Node()
3680 b = Node()
3681 a.b = b
3682 b.a = a
3683 z = deepcopy(a) # This blew up before
3684
Martin Panterf05641642016-05-08 13:48:10 +00003685 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003686 # Testing uninitialized module objects...
3687 from types import ModuleType as M
3688 m = M.__new__(M)
3689 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003690 self.assertNotHasAttr(m, "__name__")
3691 self.assertNotHasAttr(m, "__file__")
3692 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003693 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003694 m.foo = 1
3695 self.assertEqual(m.__dict__, {"foo": 1})
3696
3697 def test_funny_new(self):
3698 # Testing __new__ returning something unexpected...
3699 class C(object):
3700 def __new__(cls, arg):
3701 if isinstance(arg, str): return [1, 2, 3]
3702 elif isinstance(arg, int): return object.__new__(D)
3703 else: return object.__new__(cls)
3704 class D(C):
3705 def __init__(self, arg):
3706 self.foo = arg
3707 self.assertEqual(C("1"), [1, 2, 3])
3708 self.assertEqual(D("1"), [1, 2, 3])
3709 d = D(None)
3710 self.assertEqual(d.foo, None)
3711 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003712 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003713 self.assertEqual(d.foo, 1)
3714 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003715 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003716 self.assertEqual(d.foo, 1)
3717
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003718 class C(object):
3719 @staticmethod
3720 def __new__(*args):
3721 return args
3722 self.assertEqual(C(1, 2), (C, 1, 2))
3723 class D(C):
3724 pass
3725 self.assertEqual(D(1, 2), (D, 1, 2))
3726
3727 class C(object):
3728 @classmethod
3729 def __new__(*args):
3730 return args
3731 self.assertEqual(C(1, 2), (C, C, 1, 2))
3732 class D(C):
3733 pass
3734 self.assertEqual(D(1, 2), (D, D, 1, 2))
3735
Georg Brandl479a7e72008-02-05 18:13:15 +00003736 def test_imul_bug(self):
3737 # Testing for __imul__ problems...
3738 # SF bug 544647
3739 class C(object):
3740 def __imul__(self, other):
3741 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003742 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003743 y = x
3744 y *= 1.0
3745 self.assertEqual(y, (x, 1.0))
3746 y = x
3747 y *= 2
3748 self.assertEqual(y, (x, 2))
3749 y = x
3750 y *= 3
3751 self.assertEqual(y, (x, 3))
3752 y = x
3753 y *= 1<<100
3754 self.assertEqual(y, (x, 1<<100))
3755 y = x
3756 y *= None
3757 self.assertEqual(y, (x, None))
3758 y = x
3759 y *= "foo"
3760 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003761
Georg Brandl479a7e72008-02-05 18:13:15 +00003762 def test_copy_setstate(self):
3763 # Testing that copy.*copy() correctly uses __setstate__...
3764 import copy
3765 class C(object):
3766 def __init__(self, foo=None):
3767 self.foo = foo
3768 self.__foo = foo
3769 def setfoo(self, foo=None):
3770 self.foo = foo
3771 def getfoo(self):
3772 return self.__foo
3773 def __getstate__(self):
3774 return [self.foo]
3775 def __setstate__(self_, lst):
3776 self.assertEqual(len(lst), 1)
3777 self_.__foo = self_.foo = lst[0]
3778 a = C(42)
3779 a.setfoo(24)
3780 self.assertEqual(a.foo, 24)
3781 self.assertEqual(a.getfoo(), 42)
3782 b = copy.copy(a)
3783 self.assertEqual(b.foo, 24)
3784 self.assertEqual(b.getfoo(), 24)
3785 b = copy.deepcopy(a)
3786 self.assertEqual(b.foo, 24)
3787 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003788
Georg Brandl479a7e72008-02-05 18:13:15 +00003789 def test_slices(self):
3790 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003791
Georg Brandl479a7e72008-02-05 18:13:15 +00003792 # Strings
3793 self.assertEqual("hello"[:4], "hell")
3794 self.assertEqual("hello"[slice(4)], "hell")
3795 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3796 class S(str):
3797 def __getitem__(self, x):
3798 return str.__getitem__(self, x)
3799 self.assertEqual(S("hello")[:4], "hell")
3800 self.assertEqual(S("hello")[slice(4)], "hell")
3801 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3802 # Tuples
3803 self.assertEqual((1,2,3)[:2], (1,2))
3804 self.assertEqual((1,2,3)[slice(2)], (1,2))
3805 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3806 class T(tuple):
3807 def __getitem__(self, x):
3808 return tuple.__getitem__(self, x)
3809 self.assertEqual(T((1,2,3))[:2], (1,2))
3810 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3811 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3812 # Lists
3813 self.assertEqual([1,2,3][:2], [1,2])
3814 self.assertEqual([1,2,3][slice(2)], [1,2])
3815 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3816 class L(list):
3817 def __getitem__(self, x):
3818 return list.__getitem__(self, x)
3819 self.assertEqual(L([1,2,3])[:2], [1,2])
3820 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3821 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3822 # Now do lists and __setitem__
3823 a = L([1,2,3])
3824 a[slice(1, 3)] = [3,2]
3825 self.assertEqual(a, [1,3,2])
3826 a[slice(0, 2, 1)] = [3,1]
3827 self.assertEqual(a, [3,1,2])
3828 a.__setitem__(slice(1, 3), [2,1])
3829 self.assertEqual(a, [3,2,1])
3830 a.__setitem__(slice(0, 2, 1), [2,3])
3831 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003832
Georg Brandl479a7e72008-02-05 18:13:15 +00003833 def test_subtype_resurrection(self):
3834 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003835
Georg Brandl479a7e72008-02-05 18:13:15 +00003836 class C(object):
3837 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003838
Georg Brandl479a7e72008-02-05 18:13:15 +00003839 def __del__(self):
3840 # resurrect the instance
3841 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003842
Georg Brandl479a7e72008-02-05 18:13:15 +00003843 c = C()
3844 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003845
Benjamin Petersone549ead2009-03-28 21:42:05 +00003846 # The most interesting thing here is whether this blows up, due to
3847 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3848 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003849 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003850
Benjamin Petersone549ead2009-03-28 21:42:05 +00003851 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003852 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003853
Georg Brandl479a7e72008-02-05 18:13:15 +00003854 # Make c mortal again, so that the test framework with -l doesn't report
3855 # it as a leak.
3856 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003857
Georg Brandl479a7e72008-02-05 18:13:15 +00003858 def test_slots_trash(self):
3859 # Testing slot trash...
3860 # Deallocating deeply nested slotted trash caused stack overflows
3861 class trash(object):
3862 __slots__ = ['x']
3863 def __init__(self, x):
3864 self.x = x
3865 o = None
3866 for i in range(50000):
3867 o = trash(o)
3868 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003869
Georg Brandl479a7e72008-02-05 18:13:15 +00003870 def test_slots_multiple_inheritance(self):
3871 # SF bug 575229, multiple inheritance w/ slots dumps core
3872 class A(object):
3873 __slots__=()
3874 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003875 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003876 class C(A,B) :
3877 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003878 if support.check_impl_detail():
3879 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003880 self.assertHasAttr(C, '__dict__')
3881 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003882 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003883
Georg Brandl479a7e72008-02-05 18:13:15 +00003884 def test_rmul(self):
3885 # Testing correct invocation of __rmul__...
3886 # SF patch 592646
3887 class C(object):
3888 def __mul__(self, other):
3889 return "mul"
3890 def __rmul__(self, other):
3891 return "rmul"
3892 a = C()
3893 self.assertEqual(a*2, "mul")
3894 self.assertEqual(a*2.2, "mul")
3895 self.assertEqual(2*a, "rmul")
3896 self.assertEqual(2.2*a, "rmul")
3897
3898 def test_ipow(self):
3899 # Testing correct invocation of __ipow__...
3900 # [SF bug 620179]
3901 class C(object):
3902 def __ipow__(self, other):
3903 pass
3904 a = C()
3905 a **= 2
3906
3907 def test_mutable_bases(self):
3908 # Testing mutable bases...
3909
3910 # stuff that should work:
3911 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003912 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003913 class C2(object):
3914 def __getattribute__(self, attr):
3915 if attr == 'a':
3916 return 2
3917 else:
3918 return super(C2, self).__getattribute__(attr)
3919 def meth(self):
3920 return 1
3921 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003922 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003923 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003924 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003925 d = D()
3926 e = E()
3927 D.__bases__ = (C,)
3928 D.__bases__ = (C2,)
3929 self.assertEqual(d.meth(), 1)
3930 self.assertEqual(e.meth(), 1)
3931 self.assertEqual(d.a, 2)
3932 self.assertEqual(e.a, 2)
3933 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003934
Georg Brandl479a7e72008-02-05 18:13:15 +00003935 try:
3936 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003937 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003938 pass
3939 else:
3940 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003941
Georg Brandl479a7e72008-02-05 18:13:15 +00003942 try:
3943 D.__bases__ = ()
3944 except TypeError as msg:
3945 if str(msg) == "a new-style class can't have only classic bases":
3946 self.fail("wrong error message for .__bases__ = ()")
3947 else:
3948 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003949
Georg Brandl479a7e72008-02-05 18:13:15 +00003950 try:
3951 D.__bases__ = (D,)
3952 except TypeError:
3953 pass
3954 else:
3955 # actually, we'll have crashed by here...
3956 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003957
Georg Brandl479a7e72008-02-05 18:13:15 +00003958 try:
3959 D.__bases__ = (C, C)
3960 except TypeError:
3961 pass
3962 else:
3963 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003964
Georg Brandl479a7e72008-02-05 18:13:15 +00003965 try:
3966 D.__bases__ = (E,)
3967 except TypeError:
3968 pass
3969 else:
3970 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003971
Benjamin Petersonae937c02009-04-18 20:54:08 +00003972 def test_builtin_bases(self):
3973 # Make sure all the builtin types can have their base queried without
3974 # segfaulting. See issue #5787.
3975 builtin_types = [tp for tp in builtins.__dict__.values()
3976 if isinstance(tp, type)]
3977 for tp in builtin_types:
3978 object.__getattribute__(tp, "__bases__")
3979 if tp is not object:
3980 self.assertEqual(len(tp.__bases__), 1, tp)
3981
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003982 class L(list):
3983 pass
3984
3985 class C(object):
3986 pass
3987
3988 class D(C):
3989 pass
3990
3991 try:
3992 L.__bases__ = (dict,)
3993 except TypeError:
3994 pass
3995 else:
3996 self.fail("shouldn't turn list subclass into dict subclass")
3997
3998 try:
3999 list.__bases__ = (dict,)
4000 except TypeError:
4001 pass
4002 else:
4003 self.fail("shouldn't be able to assign to list.__bases__")
4004
4005 try:
4006 D.__bases__ = (C, list)
4007 except TypeError:
4008 pass
4009 else:
4010 assert 0, "best_base calculation found wanting"
4011
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07004012 def test_unsubclassable_types(self):
4013 with self.assertRaises(TypeError):
4014 class X(type(None)):
4015 pass
4016 with self.assertRaises(TypeError):
4017 class X(object, type(None)):
4018 pass
4019 with self.assertRaises(TypeError):
4020 class X(type(None), object):
4021 pass
4022 class O(object):
4023 pass
4024 with self.assertRaises(TypeError):
4025 class X(O, type(None)):
4026 pass
4027 with self.assertRaises(TypeError):
4028 class X(type(None), O):
4029 pass
4030
4031 class X(object):
4032 pass
4033 with self.assertRaises(TypeError):
4034 X.__bases__ = type(None),
4035 with self.assertRaises(TypeError):
4036 X.__bases__ = object, type(None)
4037 with self.assertRaises(TypeError):
4038 X.__bases__ = type(None), object
4039 with self.assertRaises(TypeError):
4040 X.__bases__ = O, type(None)
4041 with self.assertRaises(TypeError):
4042 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00004043
Georg Brandl479a7e72008-02-05 18:13:15 +00004044 def test_mutable_bases_with_failing_mro(self):
4045 # Testing mutable bases with failing mro...
4046 class WorkOnce(type):
4047 def __new__(self, name, bases, ns):
4048 self.flag = 0
4049 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4050 def mro(self):
4051 if self.flag > 0:
4052 raise RuntimeError("bozo")
4053 else:
4054 self.flag += 1
4055 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004056
Georg Brandl479a7e72008-02-05 18:13:15 +00004057 class WorkAlways(type):
4058 def mro(self):
4059 # this is here to make sure that .mro()s aren't called
4060 # with an exception set (which was possible at one point).
4061 # An error message will be printed in a debug build.
4062 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004063 return type.mro(self)
4064
Georg Brandl479a7e72008-02-05 18:13:15 +00004065 class C(object):
4066 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004067
Georg Brandl479a7e72008-02-05 18:13:15 +00004068 class C2(object):
4069 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004070
Georg Brandl479a7e72008-02-05 18:13:15 +00004071 class D(C):
4072 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004073
Georg Brandl479a7e72008-02-05 18:13:15 +00004074 class E(D):
4075 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004076
Georg Brandl479a7e72008-02-05 18:13:15 +00004077 class F(D, metaclass=WorkOnce):
4078 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004079
Georg Brandl479a7e72008-02-05 18:13:15 +00004080 class G(D, metaclass=WorkAlways):
4081 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004082
Georg Brandl479a7e72008-02-05 18:13:15 +00004083 # Immediate subclasses have their mro's adjusted in alphabetical
4084 # order, so E's will get adjusted before adjusting F's fails. We
4085 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004086
Georg Brandl479a7e72008-02-05 18:13:15 +00004087 E_mro_before = E.__mro__
4088 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004089
Armin Rigofd163f92005-12-29 15:59:19 +00004090 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004091 D.__bases__ = (C2,)
4092 except RuntimeError:
4093 self.assertEqual(E.__mro__, E_mro_before)
4094 self.assertEqual(D.__mro__, D_mro_before)
4095 else:
4096 self.fail("exception not propagated")
4097
4098 def test_mutable_bases_catch_mro_conflict(self):
4099 # Testing mutable bases catch mro conflict...
4100 class A(object):
4101 pass
4102
4103 class B(object):
4104 pass
4105
4106 class C(A, B):
4107 pass
4108
4109 class D(A, B):
4110 pass
4111
4112 class E(C, D):
4113 pass
4114
4115 try:
4116 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004117 except TypeError:
4118 pass
4119 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004120 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004121
Georg Brandl479a7e72008-02-05 18:13:15 +00004122 def test_mutable_names(self):
4123 # Testing mutable names...
4124 class C(object):
4125 pass
4126
4127 # C.__module__ could be 'test_descr' or '__main__'
4128 mod = C.__module__
4129
4130 C.__name__ = 'D'
4131 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4132
4133 C.__name__ = 'D.E'
4134 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4135
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004136 def test_evil_type_name(self):
4137 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4138 # execution while the type structure was not in a sane state, and a
4139 # possible segmentation fault as a result. See bug #16447.
4140 class Nasty(str):
4141 def __del__(self):
4142 C.__name__ = "other"
4143
4144 class C:
4145 pass
4146
4147 C.__name__ = Nasty("abc")
4148 C.__name__ = "normal"
4149
Georg Brandl479a7e72008-02-05 18:13:15 +00004150 def test_subclass_right_op(self):
4151 # Testing correct dispatch of subclass overloading __r<op>__...
4152
4153 # This code tests various cases where right-dispatch of a subclass
4154 # should be preferred over left-dispatch of a base class.
4155
4156 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4157
4158 class B(int):
4159 def __floordiv__(self, other):
4160 return "B.__floordiv__"
4161 def __rfloordiv__(self, other):
4162 return "B.__rfloordiv__"
4163
4164 self.assertEqual(B(1) // 1, "B.__floordiv__")
4165 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4166
4167 # Case 2: subclass of object; this is just the baseline for case 3
4168
4169 class C(object):
4170 def __floordiv__(self, other):
4171 return "C.__floordiv__"
4172 def __rfloordiv__(self, other):
4173 return "C.__rfloordiv__"
4174
4175 self.assertEqual(C() // 1, "C.__floordiv__")
4176 self.assertEqual(1 // C(), "C.__rfloordiv__")
4177
4178 # Case 3: subclass of new-style class; here it gets interesting
4179
4180 class D(C):
4181 def __floordiv__(self, other):
4182 return "D.__floordiv__"
4183 def __rfloordiv__(self, other):
4184 return "D.__rfloordiv__"
4185
4186 self.assertEqual(D() // C(), "D.__floordiv__")
4187 self.assertEqual(C() // D(), "D.__rfloordiv__")
4188
4189 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4190
4191 class E(C):
4192 pass
4193
4194 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4195
4196 self.assertEqual(E() // 1, "C.__floordiv__")
4197 self.assertEqual(1 // E(), "C.__rfloordiv__")
4198 self.assertEqual(E() // C(), "C.__floordiv__")
4199 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4200
Benjamin Petersone549ead2009-03-28 21:42:05 +00004201 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004202 def test_meth_class_get(self):
4203 # Testing __get__ method of METH_CLASS C methods...
4204 # Full coverage of descrobject.c::classmethod_get()
4205
4206 # Baseline
4207 arg = [1, 2, 3]
4208 res = {1: None, 2: None, 3: None}
4209 self.assertEqual(dict.fromkeys(arg), res)
4210 self.assertEqual({}.fromkeys(arg), res)
4211
4212 # Now get the descriptor
4213 descr = dict.__dict__["fromkeys"]
4214
4215 # More baseline using the descriptor directly
4216 self.assertEqual(descr.__get__(None, dict)(arg), res)
4217 self.assertEqual(descr.__get__({})(arg), res)
4218
4219 # Now check various error cases
4220 try:
4221 descr.__get__(None, None)
4222 except TypeError:
4223 pass
4224 else:
4225 self.fail("shouldn't have allowed descr.__get__(None, None)")
4226 try:
4227 descr.__get__(42)
4228 except TypeError:
4229 pass
4230 else:
4231 self.fail("shouldn't have allowed descr.__get__(42)")
4232 try:
4233 descr.__get__(None, 42)
4234 except TypeError:
4235 pass
4236 else:
4237 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4238 try:
4239 descr.__get__(None, int)
4240 except TypeError:
4241 pass
4242 else:
4243 self.fail("shouldn't have allowed descr.__get__(None, int)")
4244
4245 def test_isinst_isclass(self):
4246 # Testing proxy isinstance() and isclass()...
4247 class Proxy(object):
4248 def __init__(self, obj):
4249 self.__obj = obj
4250 def __getattribute__(self, name):
4251 if name.startswith("_Proxy__"):
4252 return object.__getattribute__(self, name)
4253 else:
4254 return getattr(self.__obj, name)
4255 # Test with a classic class
4256 class C:
4257 pass
4258 a = C()
4259 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004260 self.assertIsInstance(a, C) # Baseline
4261 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004262 # Test with a classic subclass
4263 class D(C):
4264 pass
4265 a = D()
4266 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004267 self.assertIsInstance(a, C) # Baseline
4268 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004269 # Test with a new-style class
4270 class C(object):
4271 pass
4272 a = C()
4273 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004274 self.assertIsInstance(a, C) # Baseline
4275 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004276 # Test with a new-style subclass
4277 class D(C):
4278 pass
4279 a = D()
4280 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004281 self.assertIsInstance(a, C) # Baseline
4282 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004283
4284 def test_proxy_super(self):
4285 # Testing super() for a proxy object...
4286 class Proxy(object):
4287 def __init__(self, obj):
4288 self.__obj = obj
4289 def __getattribute__(self, name):
4290 if name.startswith("_Proxy__"):
4291 return object.__getattribute__(self, name)
4292 else:
4293 return getattr(self.__obj, name)
4294
4295 class B(object):
4296 def f(self):
4297 return "B.f"
4298
4299 class C(B):
4300 def f(self):
4301 return super(C, self).f() + "->C.f"
4302
4303 obj = C()
4304 p = Proxy(obj)
4305 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4306
4307 def test_carloverre(self):
4308 # Testing prohibition of Carlo Verre's hack...
4309 try:
4310 object.__setattr__(str, "foo", 42)
4311 except TypeError:
4312 pass
4313 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004314 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 try:
4316 object.__delattr__(str, "lower")
4317 except TypeError:
4318 pass
4319 else:
4320 self.fail("Carlo Verre __delattr__ succeeded!")
4321
4322 def test_weakref_segfault(self):
4323 # Testing weakref segfault...
4324 # SF 742911
4325 import weakref
4326
4327 class Provoker:
4328 def __init__(self, referrent):
4329 self.ref = weakref.ref(referrent)
4330
4331 def __del__(self):
4332 x = self.ref()
4333
4334 class Oops(object):
4335 pass
4336
4337 o = Oops()
4338 o.whatever = Provoker(o)
4339 del o
4340
4341 def test_wrapper_segfault(self):
4342 # SF 927248: deeply nested wrappers could cause stack overflow
4343 f = lambda:None
4344 for i in range(1000000):
4345 f = f.__call__
4346 f = None
4347
4348 def test_file_fault(self):
4349 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004350 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004351 class StdoutGuard:
4352 def __getattr__(self, attr):
4353 sys.stdout = sys.__stdout__
4354 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4355 sys.stdout = StdoutGuard()
4356 try:
4357 print("Oops!")
4358 except RuntimeError:
4359 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004360 finally:
4361 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004362
4363 def test_vicious_descriptor_nonsense(self):
4364 # Testing vicious_descriptor_nonsense...
4365
4366 # A potential segfault spotted by Thomas Wouters in mail to
4367 # python-dev 2003-04-17, turned into an example & fixed by Michael
4368 # Hudson just less than four months later...
4369
4370 class Evil(object):
4371 def __hash__(self):
4372 return hash('attr')
4373 def __eq__(self, other):
Serhiy Storchakaff3d39f2019-02-26 08:03:21 +02004374 try:
4375 del C.attr
4376 except AttributeError:
4377 # possible race condition
4378 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00004379 return 0
4380
4381 class Descr(object):
4382 def __get__(self, ob, type=None):
4383 return 1
4384
4385 class C(object):
4386 attr = Descr()
4387
4388 c = C()
4389 c.__dict__[Evil()] = 0
4390
4391 self.assertEqual(c.attr, 1)
4392 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004393 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004394 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004395
4396 def test_init(self):
4397 # SF 1155938
4398 class Foo(object):
4399 def __init__(self):
4400 return 10
4401 try:
4402 Foo()
4403 except TypeError:
4404 pass
4405 else:
4406 self.fail("did not test __init__() for None return")
4407
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004408 def assertNotOrderable(self, a, b):
4409 with self.assertRaises(TypeError):
4410 a < b
4411 with self.assertRaises(TypeError):
4412 a > b
4413 with self.assertRaises(TypeError):
4414 a <= b
4415 with self.assertRaises(TypeError):
4416 a >= b
4417
Georg Brandl479a7e72008-02-05 18:13:15 +00004418 def test_method_wrapper(self):
4419 # Testing method-wrapper objects...
4420 # <type 'method-wrapper'> did not support any reflection before 2.5
Georg Brandl479a7e72008-02-05 18:13:15 +00004421 l = []
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004422 self.assertTrue(l.__add__ == l.__add__)
4423 self.assertFalse(l.__add__ != l.__add__)
4424 self.assertFalse(l.__add__ == [].__add__)
4425 self.assertTrue(l.__add__ != [].__add__)
4426 self.assertFalse(l.__add__ == l.__mul__)
4427 self.assertTrue(l.__add__ != l.__mul__)
4428 self.assertNotOrderable(l.__add__, l.__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004429 self.assertEqual(l.__add__.__name__, '__add__')
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004430 self.assertIs(l.__add__.__self__, l)
4431 self.assertIs(l.__add__.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004432 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004433 # hash([].__add__) should not be based on hash([])
4434 hash(l.__add__)
Georg Brandl479a7e72008-02-05 18:13:15 +00004435
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004436 def test_builtin_function_or_method(self):
4437 # Not really belonging to test_descr, but introspection and
4438 # comparison on <type 'builtin_function_or_method'> seems not
4439 # to be tested elsewhere
4440 l = []
4441 self.assertTrue(l.append == l.append)
4442 self.assertFalse(l.append != l.append)
4443 self.assertFalse(l.append == [].append)
4444 self.assertTrue(l.append != [].append)
4445 self.assertFalse(l.append == l.pop)
4446 self.assertTrue(l.append != l.pop)
4447 self.assertNotOrderable(l.append, l.append)
4448 self.assertEqual(l.append.__name__, 'append')
4449 self.assertIs(l.append.__self__, l)
4450 # self.assertIs(l.append.__objclass__, list) --- could be added?
4451 self.assertEqual(l.append.__doc__, list.append.__doc__)
4452 # hash([].append) should not be based on hash([])
4453 hash(l.append)
4454
4455 def test_special_unbound_method_types(self):
4456 # Testing objects of <type 'wrapper_descriptor'>...
4457 self.assertTrue(list.__add__ == list.__add__)
4458 self.assertFalse(list.__add__ != list.__add__)
4459 self.assertFalse(list.__add__ == list.__mul__)
4460 self.assertTrue(list.__add__ != list.__mul__)
4461 self.assertNotOrderable(list.__add__, list.__add__)
4462 self.assertEqual(list.__add__.__name__, '__add__')
4463 self.assertIs(list.__add__.__objclass__, list)
4464
4465 # Testing objects of <type 'method_descriptor'>...
4466 self.assertTrue(list.append == list.append)
4467 self.assertFalse(list.append != list.append)
4468 self.assertFalse(list.append == list.pop)
4469 self.assertTrue(list.append != list.pop)
4470 self.assertNotOrderable(list.append, list.append)
4471 self.assertEqual(list.append.__name__, 'append')
4472 self.assertIs(list.append.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004473
4474 def test_not_implemented(self):
4475 # Testing NotImplemented...
4476 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004477 import operator
4478
4479 def specialmethod(self, other):
4480 return NotImplemented
4481
4482 def check(expr, x, y):
4483 try:
4484 exec(expr, {'x': x, 'y': y, 'operator': operator})
4485 except TypeError:
4486 pass
4487 else:
4488 self.fail("no TypeError from %r" % (expr,))
4489
4490 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4491 # TypeErrors
4492 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4493 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004494 for name, expr, iexpr in [
4495 ('__add__', 'x + y', 'x += y'),
4496 ('__sub__', 'x - y', 'x -= y'),
4497 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004498 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004499 ('__truediv__', 'x / y', 'x /= y'),
4500 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004501 ('__mod__', 'x % y', 'x %= y'),
4502 ('__divmod__', 'divmod(x, y)', None),
4503 ('__pow__', 'x ** y', 'x **= y'),
4504 ('__lshift__', 'x << y', 'x <<= y'),
4505 ('__rshift__', 'x >> y', 'x >>= y'),
4506 ('__and__', 'x & y', 'x &= y'),
4507 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004508 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004509 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004510 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004511 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004512 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004513 check(expr, a, N1)
4514 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004515 if iexpr:
4516 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004517 check(iexpr, a, N1)
4518 check(iexpr, a, N2)
4519 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004520 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004521 c = C()
4522 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004523 check(iexpr, c, N1)
4524 check(iexpr, c, N2)
4525
Georg Brandl479a7e72008-02-05 18:13:15 +00004526 def test_assign_slice(self):
4527 # ceval.c's assign_slice used to check for
4528 # tp->tp_as_sequence->sq_slice instead of
4529 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004530
Georg Brandl479a7e72008-02-05 18:13:15 +00004531 class C(object):
4532 def __setitem__(self, idx, value):
4533 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004534
Georg Brandl479a7e72008-02-05 18:13:15 +00004535 c = C()
4536 c[1:2] = 3
4537 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004538
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004539 def test_set_and_no_get(self):
4540 # See
4541 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4542 class Descr(object):
4543
4544 def __init__(self, name):
4545 self.name = name
4546
4547 def __set__(self, obj, value):
4548 obj.__dict__[self.name] = value
4549 descr = Descr("a")
4550
4551 class X(object):
4552 a = descr
4553
4554 x = X()
4555 self.assertIs(x.a, descr)
4556 x.a = 42
4557 self.assertEqual(x.a, 42)
4558
Benjamin Peterson21896a32010-03-21 22:03:03 +00004559 # Also check type_getattro for correctness.
4560 class Meta(type):
4561 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004562 class X(metaclass=Meta):
4563 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004564 X.a = 42
4565 Meta.a = Descr("a")
4566 self.assertEqual(X.a, 42)
4567
Benjamin Peterson9262b842008-11-17 22:45:50 +00004568 def test_getattr_hooks(self):
4569 # issue 4230
4570
4571 class Descriptor(object):
4572 counter = 0
4573 def __get__(self, obj, objtype=None):
4574 def getter(name):
4575 self.counter += 1
4576 raise AttributeError(name)
4577 return getter
4578
4579 descr = Descriptor()
4580 class A(object):
4581 __getattribute__ = descr
4582 class B(object):
4583 __getattr__ = descr
4584 class C(object):
4585 __getattribute__ = descr
4586 __getattr__ = descr
4587
4588 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004589 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004590 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004591 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004592 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004593 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004594
Benjamin Peterson9262b842008-11-17 22:45:50 +00004595 class EvilGetattribute(object):
4596 # This used to segfault
4597 def __getattr__(self, name):
4598 raise AttributeError(name)
4599 def __getattribute__(self, name):
4600 del EvilGetattribute.__getattr__
4601 for i in range(5):
4602 gc.collect()
4603 raise AttributeError(name)
4604
4605 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4606
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004607 def test_type___getattribute__(self):
4608 self.assertRaises(TypeError, type.__getattribute__, list, type)
4609
Benjamin Peterson477ba912011-01-12 15:34:01 +00004610 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004611 # type pretends not to have __abstractmethods__.
4612 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4613 class meta(type):
4614 pass
4615 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004616 class X(object):
4617 pass
4618 with self.assertRaises(AttributeError):
4619 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004620
Victor Stinner3249dec2011-05-01 23:19:15 +02004621 def test_proxy_call(self):
4622 class FakeStr:
4623 __class__ = str
4624
4625 fake_str = FakeStr()
4626 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004627 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004628
4629 # call a method descriptor
4630 with self.assertRaises(TypeError):
4631 str.split(fake_str)
4632
4633 # call a slot wrapper descriptor
4634 with self.assertRaises(TypeError):
4635 str.__add__(fake_str, "abc")
4636
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004637 def test_repr_as_str(self):
4638 # Issue #11603: crash or infinite loop when rebinding __str__ as
4639 # __repr__.
4640 class Foo:
4641 pass
4642 Foo.__repr__ = Foo.__str__
4643 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004644 self.assertRaises(RecursionError, str, foo)
4645 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004646
4647 def test_mixing_slot_wrappers(self):
4648 class X(dict):
4649 __setattr__ = dict.__setitem__
4650 x = X()
4651 x.y = 42
4652 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004653
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004654 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004655 with self.assertRaises(ValueError) as cm:
4656 class X:
4657 __slots__ = ["foo"]
4658 foo = None
4659 m = str(cm.exception)
4660 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4661
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004662 def test_set_doc(self):
4663 class X:
4664 "elephant"
4665 X.__doc__ = "banana"
4666 self.assertEqual(X.__doc__, "banana")
4667 with self.assertRaises(TypeError) as cm:
4668 type(list).__dict__["__doc__"].__set__(list, "blah")
4669 self.assertIn("can't set list.__doc__", str(cm.exception))
4670 with self.assertRaises(TypeError) as cm:
4671 type(X).__dict__["__doc__"].__delete__(X)
4672 self.assertIn("can't delete X.__doc__", str(cm.exception))
4673 self.assertEqual(X.__doc__, "banana")
4674
Antoine Pitrou9d574812011-12-12 13:47:25 +01004675 def test_qualname(self):
4676 descriptors = [str.lower, complex.real, float.real, int.__add__]
4677 types = ['method', 'member', 'getset', 'wrapper']
4678
4679 # make sure we have an example of each type of descriptor
4680 for d, n in zip(descriptors, types):
4681 self.assertEqual(type(d).__name__, n + '_descriptor')
4682
4683 for d in descriptors:
4684 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4685 self.assertEqual(d.__qualname__, qualname)
4686
4687 self.assertEqual(str.lower.__qualname__, 'str.lower')
4688 self.assertEqual(complex.real.__qualname__, 'complex.real')
4689 self.assertEqual(float.real.__qualname__, 'float.real')
4690 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4691
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004692 class X:
4693 pass
4694 with self.assertRaises(TypeError):
4695 del X.__qualname__
4696
4697 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4698 str, 'Oink')
4699
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004700 global Y
4701 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004702 class Inside:
4703 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004704 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004705 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004706
Victor Stinner6f738742012-02-25 01:22:36 +01004707 def test_qualname_dict(self):
4708 ns = {'__qualname__': 'some.name'}
4709 tp = type('Foo', (), ns)
4710 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004711 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004712 self.assertEqual(ns, {'__qualname__': 'some.name'})
4713
4714 ns = {'__qualname__': 1}
4715 self.assertRaises(TypeError, type, 'Foo', (), ns)
4716
Benjamin Peterson52c42432012-03-07 18:41:11 -06004717 def test_cycle_through_dict(self):
4718 # See bug #1469629
4719 class X(dict):
4720 def __init__(self):
4721 dict.__init__(self)
4722 self.__dict__ = self
4723 x = X()
4724 x.attr = 42
4725 wr = weakref.ref(x)
4726 del x
4727 support.gc_collect()
4728 self.assertIsNone(wr())
4729 for o in gc.get_objects():
4730 self.assertIsNot(type(o), X)
4731
Benjamin Peterson96384b92012-03-17 00:05:44 -05004732 def test_object_new_and_init_with_parameters(self):
4733 # See issue #1683368
4734 class OverrideNeither:
4735 pass
4736 self.assertRaises(TypeError, OverrideNeither, 1)
4737 self.assertRaises(TypeError, OverrideNeither, kw=1)
4738 class OverrideNew:
4739 def __new__(cls, foo, kw=0, *args, **kwds):
4740 return object.__new__(cls, *args, **kwds)
4741 class OverrideInit:
4742 def __init__(self, foo, kw=0, *args, **kwargs):
4743 return object.__init__(self, *args, **kwargs)
4744 class OverrideBoth(OverrideNew, OverrideInit):
4745 pass
4746 for case in OverrideNew, OverrideInit, OverrideBoth:
4747 case(1)
4748 case(1, kw=2)
4749 self.assertRaises(TypeError, case, 1, 2, 3)
4750 self.assertRaises(TypeError, case, 1, 2, foo=3)
4751
Benjamin Petersondf813792014-03-17 15:57:17 -05004752 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4753 class Base:
4754 pass
4755 class Sub(Base):
4756 pass
4757 self.assertIn("__dict__", Base.__dict__)
4758 self.assertNotIn("__dict__", Sub.__dict__)
4759
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004760 def test_bound_method_repr(self):
4761 class Foo:
4762 def method(self):
4763 pass
4764 self.assertRegex(repr(Foo().method),
4765 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4766
4767
4768 class Base:
4769 def method(self):
4770 pass
4771 class Derived1(Base):
4772 pass
4773 class Derived2(Base):
4774 def method(self):
4775 pass
4776 base = Base()
4777 derived1 = Derived1()
4778 derived2 = Derived2()
4779 super_d2 = super(Derived2, derived2)
4780 self.assertRegex(repr(base.method),
4781 r"<bound method .*Base\.method of <.*Base object at .*>>")
4782 self.assertRegex(repr(derived1.method),
4783 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4784 self.assertRegex(repr(derived2.method),
4785 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4786 self.assertRegex(repr(super_d2.method),
4787 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4788
4789 class Foo:
4790 @classmethod
4791 def method(cls):
4792 pass
4793 foo = Foo()
4794 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004795 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004796 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004797 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004798
4799
4800 class MyCallable:
4801 def __call__(self, arg):
4802 pass
4803 func = MyCallable() # func has no __name__ or __qualname__ attributes
4804 instance = object()
4805 method = types.MethodType(func, instance)
4806 self.assertRegex(repr(method),
4807 r"<bound method \? of <object object at .*>>")
4808 func.__name__ = "name"
4809 self.assertRegex(repr(method),
4810 r"<bound method name of <object object at .*>>")
4811 func.__qualname__ = "qualname"
4812 self.assertRegex(repr(method),
4813 r"<bound method qualname of <object object at .*>>")
4814
jdemeyer5a306202018-10-19 23:50:06 +02004815 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4816 def test_bpo25750(self):
4817 # bpo-25750: calling a descriptor (implemented as built-in
4818 # function with METH_FASTCALL) should not crash CPython if the
4819 # descriptor deletes itself from the class.
4820 class Descr:
4821 __get__ = _testcapi.bad_get
4822
4823 class X:
4824 descr = Descr()
4825 def __new__(cls):
4826 cls.descr = None
4827 # Create this large list to corrupt some unused memory
4828 cls.lst = [2**i for i in range(10000)]
4829 X.descr
4830
Antoine Pitrou9d574812011-12-12 13:47:25 +01004831
Georg Brandl479a7e72008-02-05 18:13:15 +00004832class DictProxyTests(unittest.TestCase):
4833 def setUp(self):
4834 class C(object):
4835 def meth(self):
4836 pass
4837 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004838
Brett Cannon7a540732011-02-22 03:04:06 +00004839 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4840 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004841 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004842 # Testing dict-proxy keys...
4843 it = self.C.__dict__.keys()
4844 self.assertNotIsInstance(it, list)
4845 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004846 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004847 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004848 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004849
Brett Cannon7a540732011-02-22 03:04:06 +00004850 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4851 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004852 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004853 # Testing dict-proxy values...
4854 it = self.C.__dict__.values()
4855 self.assertNotIsInstance(it, list)
4856 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004857 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004858
Brett Cannon7a540732011-02-22 03:04:06 +00004859 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4860 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004861 def test_iter_items(self):
4862 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004863 it = self.C.__dict__.items()
4864 self.assertNotIsInstance(it, list)
4865 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004866 keys.sort()
4867 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004868 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004869
Georg Brandl479a7e72008-02-05 18:13:15 +00004870 def test_dict_type_with_metaclass(self):
4871 # Testing type of __dict__ when metaclass set...
4872 class B(object):
4873 pass
4874 class M(type):
4875 pass
4876 class C(metaclass=M):
4877 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4878 pass
4879 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004880
Ezio Melottiac53ab62010-12-18 14:59:43 +00004881 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004882 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004883 # We can't blindly compare with the repr of another dict as ordering
4884 # of keys and values is arbitrary and may differ.
4885 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004886 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004887 self.assertTrue(r.endswith(')'), r)
4888 for k, v in self.C.__dict__.items():
4889 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004890
Christian Heimesbbffeb62008-01-24 09:42:52 +00004891
Georg Brandl479a7e72008-02-05 18:13:15 +00004892class PTypesLongInitTest(unittest.TestCase):
4893 # This is in its own TestCase so that it can be run before any other tests.
4894 def test_pytype_long_ready(self):
4895 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004896
Georg Brandl479a7e72008-02-05 18:13:15 +00004897 # This dumps core when SF bug 551412 isn't fixed --
4898 # but only when test_descr.py is run separately.
4899 # (That can't be helped -- as soon as PyType_Ready()
4900 # is called for PyLong_Type, the bug is gone.)
4901 class UserLong(object):
4902 def __pow__(self, *args):
4903 pass
4904 try:
4905 pow(0, UserLong(), 0)
4906 except:
4907 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004908
Georg Brandl479a7e72008-02-05 18:13:15 +00004909 # Another segfault only when run early
4910 # (before PyType_Ready(tuple) is called)
4911 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004912
4913
Victor Stinnerd74782b2012-03-09 00:39:08 +01004914class MiscTests(unittest.TestCase):
4915 def test_type_lookup_mro_reference(self):
4916 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4917 # the type MRO because it may be modified during the lookup, if
4918 # __bases__ is set during the lookup for example.
4919 class MyKey(object):
4920 def __hash__(self):
4921 return hash('mykey')
4922
4923 def __eq__(self, other):
4924 X.__bases__ = (Base2,)
4925
4926 class Base(object):
4927 mykey = 'from Base'
4928 mykey2 = 'from Base'
4929
4930 class Base2(object):
4931 mykey = 'from Base2'
4932 mykey2 = 'from Base2'
4933
4934 X = type('X', (Base,), {MyKey(): 5})
4935 # mykey is read from Base
4936 self.assertEqual(X.mykey, 'from Base')
4937 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4938 self.assertEqual(X.mykey2, 'from Base2')
4939
4940
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004941class PicklingTests(unittest.TestCase):
4942
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004943 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004944 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004945 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004946 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004947 if kwargs:
4948 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4949 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004950 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004951 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4952 self.assertEqual(reduce_value[1], (type(obj),) + args)
4953 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004954 if listitems is not None:
4955 self.assertListEqual(list(reduce_value[3]), listitems)
4956 else:
4957 self.assertIsNone(reduce_value[3])
4958 if dictitems is not None:
4959 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4960 else:
4961 self.assertIsNone(reduce_value[4])
4962 else:
4963 base_type = type(obj).__base__
4964 reduce_value = (copyreg._reconstructor,
4965 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004966 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004967 None if base_type is object else base_type(obj)))
4968 if state is not None:
4969 reduce_value += (state,)
4970 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4971 self.assertEqual(obj.__reduce__(), reduce_value)
4972
4973 def test_reduce(self):
4974 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4975 args = (-101, "spam")
4976 kwargs = {'bacon': -201, 'fish': -301}
4977 state = {'cheese': -401}
4978
4979 class C1:
4980 def __getnewargs__(self):
4981 return args
4982 obj = C1()
4983 for proto in protocols:
4984 self._check_reduce(proto, obj, args)
4985
4986 for name, value in state.items():
4987 setattr(obj, name, value)
4988 for proto in protocols:
4989 self._check_reduce(proto, obj, args, state=state)
4990
4991 class C2:
4992 def __getnewargs__(self):
4993 return "bad args"
4994 obj = C2()
4995 for proto in protocols:
4996 if proto >= 2:
4997 with self.assertRaises(TypeError):
4998 obj.__reduce_ex__(proto)
4999
5000 class C3:
5001 def __getnewargs_ex__(self):
5002 return (args, kwargs)
5003 obj = C3()
5004 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03005005 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005006 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005007
5008 class C4:
5009 def __getnewargs_ex__(self):
5010 return (args, "bad dict")
5011 class C5:
5012 def __getnewargs_ex__(self):
5013 return ("bad tuple", kwargs)
5014 class C6:
5015 def __getnewargs_ex__(self):
5016 return ()
5017 class C7:
5018 def __getnewargs_ex__(self):
5019 return "bad args"
5020 for proto in protocols:
5021 for cls in C4, C5, C6, C7:
5022 obj = cls()
5023 if proto >= 2:
5024 with self.assertRaises((TypeError, ValueError)):
5025 obj.__reduce_ex__(proto)
5026
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005027 class C9:
5028 def __getnewargs_ex__(self):
5029 return (args, {})
5030 obj = C9()
5031 for proto in protocols:
5032 self._check_reduce(proto, obj, args)
5033
5034 class C10:
5035 def __getnewargs_ex__(self):
5036 raise IndexError
5037 obj = C10()
5038 for proto in protocols:
5039 if proto >= 2:
5040 with self.assertRaises(IndexError):
5041 obj.__reduce_ex__(proto)
5042
5043 class C11:
5044 def __getstate__(self):
5045 return state
5046 obj = C11()
5047 for proto in protocols:
5048 self._check_reduce(proto, obj, state=state)
5049
5050 class C12:
5051 def __getstate__(self):
5052 return "not dict"
5053 obj = C12()
5054 for proto in protocols:
5055 self._check_reduce(proto, obj, state="not dict")
5056
5057 class C13:
5058 def __getstate__(self):
5059 raise IndexError
5060 obj = C13()
5061 for proto in protocols:
5062 with self.assertRaises(IndexError):
5063 obj.__reduce_ex__(proto)
5064 if proto < 2:
5065 with self.assertRaises(IndexError):
5066 obj.__reduce__()
5067
5068 class C14:
5069 __slots__ = tuple(state)
5070 def __init__(self):
5071 for name, value in state.items():
5072 setattr(self, name, value)
5073
5074 obj = C14()
5075 for proto in protocols:
5076 if proto >= 2:
5077 self._check_reduce(proto, obj, state=(None, state))
5078 else:
5079 with self.assertRaises(TypeError):
5080 obj.__reduce_ex__(proto)
5081 with self.assertRaises(TypeError):
5082 obj.__reduce__()
5083
5084 class C15(dict):
5085 pass
5086 obj = C15({"quebec": -601})
5087 for proto in protocols:
5088 self._check_reduce(proto, obj, dictitems=dict(obj))
5089
5090 class C16(list):
5091 pass
5092 obj = C16(["yukon"])
5093 for proto in protocols:
5094 self._check_reduce(proto, obj, listitems=list(obj))
5095
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005096 def test_special_method_lookup(self):
5097 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5098 class Picky:
5099 def __getstate__(self):
5100 return {}
5101
5102 def __getattr__(self, attr):
5103 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5104 raise AssertionError(attr)
5105 return None
5106 for protocol in protocols:
5107 state = {} if protocol >= 2 else None
5108 self._check_reduce(protocol, Picky(), state=state)
5109
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005110 def _assert_is_copy(self, obj, objcopy, msg=None):
5111 """Utility method to verify if two objects are copies of each others.
5112 """
5113 if msg is None:
5114 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5115 if type(obj).__repr__ is object.__repr__:
5116 # We have this limitation for now because we use the object's repr
5117 # to help us verify that the two objects are copies. This allows
5118 # us to delegate the non-generic verification logic to the objects
5119 # themselves.
5120 raise ValueError("object passed to _assert_is_copy must " +
5121 "override the __repr__ method.")
5122 self.assertIsNot(obj, objcopy, msg=msg)
5123 self.assertIs(type(obj), type(objcopy), msg=msg)
5124 if hasattr(obj, '__dict__'):
5125 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5126 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5127 if hasattr(obj, '__slots__'):
5128 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5129 for slot in obj.__slots__:
5130 self.assertEqual(
5131 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5132 self.assertEqual(getattr(obj, slot, None),
5133 getattr(objcopy, slot, None), msg=msg)
5134 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5135
5136 @staticmethod
5137 def _generate_pickle_copiers():
5138 """Utility method to generate the many possible pickle configurations.
5139 """
5140 class PickleCopier:
5141 "This class copies object using pickle."
5142 def __init__(self, proto, dumps, loads):
5143 self.proto = proto
5144 self.dumps = dumps
5145 self.loads = loads
5146 def copy(self, obj):
5147 return self.loads(self.dumps(obj, self.proto))
5148 def __repr__(self):
5149 # We try to be as descriptive as possible here since this is
5150 # the string which we will allow us to tell the pickle
5151 # configuration we are using during debugging.
5152 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5153 .format(self.proto,
5154 self.dumps.__module__, self.dumps.__qualname__,
5155 self.loads.__module__, self.loads.__qualname__))
5156 return (PickleCopier(*args) for args in
5157 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5158 {pickle.dumps, pickle._dumps},
5159 {pickle.loads, pickle._loads}))
5160
5161 def test_pickle_slots(self):
5162 # Tests pickling of classes with __slots__.
5163
5164 # Pickling of classes with __slots__ but without __getstate__ should
5165 # fail (if using protocol 0 or 1)
5166 global C
5167 class C:
5168 __slots__ = ['a']
5169 with self.assertRaises(TypeError):
5170 pickle.dumps(C(), 0)
5171
5172 global D
5173 class D(C):
5174 pass
5175 with self.assertRaises(TypeError):
5176 pickle.dumps(D(), 0)
5177
5178 class C:
5179 "A class with __getstate__ and __setstate__ implemented."
5180 __slots__ = ['a']
5181 def __getstate__(self):
5182 state = getattr(self, '__dict__', {}).copy()
5183 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005184 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005185 try:
5186 state[slot] = getattr(self, slot)
5187 except AttributeError:
5188 pass
5189 return state
5190 def __setstate__(self, state):
5191 for k, v in state.items():
5192 setattr(self, k, v)
5193 def __repr__(self):
5194 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5195
5196 class D(C):
5197 "A subclass of a class with slots."
5198 pass
5199
5200 global E
5201 class E(C):
5202 "A subclass with an extra slot."
5203 __slots__ = ['b']
5204
5205 # Now it should work
5206 for pickle_copier in self._generate_pickle_copiers():
5207 with self.subTest(pickle_copier=pickle_copier):
5208 x = C()
5209 y = pickle_copier.copy(x)
5210 self._assert_is_copy(x, y)
5211
5212 x.a = 42
5213 y = pickle_copier.copy(x)
5214 self._assert_is_copy(x, y)
5215
5216 x = D()
5217 x.a = 42
5218 x.b = 100
5219 y = pickle_copier.copy(x)
5220 self._assert_is_copy(x, y)
5221
5222 x = E()
5223 x.a = 42
5224 x.b = "foo"
5225 y = pickle_copier.copy(x)
5226 self._assert_is_copy(x, y)
5227
5228 def test_reduce_copying(self):
5229 # Tests pickling and copying new-style classes and objects.
5230 global C1
5231 class C1:
5232 "The state of this class is copyable via its instance dict."
5233 ARGS = (1, 2)
5234 NEED_DICT_COPYING = True
5235 def __init__(self, a, b):
5236 super().__init__()
5237 self.a = a
5238 self.b = b
5239 def __repr__(self):
5240 return "C1(%r, %r)" % (self.a, self.b)
5241
5242 global C2
5243 class C2(list):
5244 "A list subclass copyable via __getnewargs__."
5245 ARGS = (1, 2)
5246 NEED_DICT_COPYING = False
5247 def __new__(cls, a, b):
5248 self = super().__new__(cls)
5249 self.a = a
5250 self.b = b
5251 return self
5252 def __init__(self, *args):
5253 super().__init__()
5254 # This helps testing that __init__ is not called during the
5255 # unpickling process, which would cause extra appends.
5256 self.append("cheese")
5257 @classmethod
5258 def __getnewargs__(cls):
5259 return cls.ARGS
5260 def __repr__(self):
5261 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5262
5263 global C3
5264 class C3(list):
5265 "A list subclass copyable via __getstate__."
5266 ARGS = (1, 2)
5267 NEED_DICT_COPYING = False
5268 def __init__(self, a, b):
5269 self.a = a
5270 self.b = b
5271 # This helps testing that __init__ is not called during the
5272 # unpickling process, which would cause extra appends.
5273 self.append("cheese")
5274 @classmethod
5275 def __getstate__(cls):
5276 return cls.ARGS
5277 def __setstate__(self, state):
5278 a, b = state
5279 self.a = a
5280 self.b = b
5281 def __repr__(self):
5282 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5283
5284 global C4
5285 class C4(int):
5286 "An int subclass copyable via __getnewargs__."
5287 ARGS = ("hello", "world", 1)
5288 NEED_DICT_COPYING = False
5289 def __new__(cls, a, b, value):
5290 self = super().__new__(cls, value)
5291 self.a = a
5292 self.b = b
5293 return self
5294 @classmethod
5295 def __getnewargs__(cls):
5296 return cls.ARGS
5297 def __repr__(self):
5298 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5299
5300 global C5
5301 class C5(int):
5302 "An int subclass copyable via __getnewargs_ex__."
5303 ARGS = (1, 2)
5304 KWARGS = {'value': 3}
5305 NEED_DICT_COPYING = False
5306 def __new__(cls, a, b, *, value=0):
5307 self = super().__new__(cls, value)
5308 self.a = a
5309 self.b = b
5310 return self
5311 @classmethod
5312 def __getnewargs_ex__(cls):
5313 return (cls.ARGS, cls.KWARGS)
5314 def __repr__(self):
5315 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5316
5317 test_classes = (C1, C2, C3, C4, C5)
5318 # Testing copying through pickle
5319 pickle_copiers = self._generate_pickle_copiers()
5320 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5321 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5322 kwargs = getattr(cls, 'KWARGS', {})
5323 obj = cls(*cls.ARGS, **kwargs)
5324 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005325 objcopy = pickle_copier.copy(obj)
5326 self._assert_is_copy(obj, objcopy)
5327 # For test classes that supports this, make sure we didn't go
5328 # around the reduce protocol by simply copying the attribute
5329 # dictionary. We clear attributes using the previous copy to
5330 # not mutate the original argument.
5331 if proto >= 2 and not cls.NEED_DICT_COPYING:
5332 objcopy.__dict__.clear()
5333 objcopy2 = pickle_copier.copy(objcopy)
5334 self._assert_is_copy(obj, objcopy2)
5335
5336 # Testing copying through copy.deepcopy()
5337 for cls in test_classes:
5338 with self.subTest(cls=cls):
5339 kwargs = getattr(cls, 'KWARGS', {})
5340 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005341 objcopy = deepcopy(obj)
5342 self._assert_is_copy(obj, objcopy)
5343 # For test classes that supports this, make sure we didn't go
5344 # around the reduce protocol by simply copying the attribute
5345 # dictionary. We clear attributes using the previous copy to
5346 # not mutate the original argument.
5347 if not cls.NEED_DICT_COPYING:
5348 objcopy.__dict__.clear()
5349 objcopy2 = deepcopy(objcopy)
5350 self._assert_is_copy(obj, objcopy2)
5351
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005352 def test_issue24097(self):
5353 # Slot name is freed inside __getattr__ and is later used.
5354 class S(str): # Not interned
5355 pass
5356 class A:
5357 __slotnames__ = [S('spam')]
5358 def __getattr__(self, attr):
5359 if attr == 'spam':
5360 A.__slotnames__[:] = [S('spam')]
5361 return 42
5362 else:
5363 raise AttributeError
5364
5365 import copyreg
5366 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005367 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5368
5369 def test_object_reduce(self):
5370 # Issue #29914
5371 # __reduce__() takes no arguments
5372 object().__reduce__()
5373 with self.assertRaises(TypeError):
5374 object().__reduce__(0)
5375 # __reduce_ex__() takes one integer argument
5376 object().__reduce_ex__(0)
5377 with self.assertRaises(TypeError):
5378 object().__reduce_ex__()
5379 with self.assertRaises(TypeError):
5380 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005381
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005382
Benjamin Peterson2a605342014-03-17 16:20:12 -05005383class SharedKeyTests(unittest.TestCase):
5384
5385 @support.cpython_only
5386 def test_subclasses(self):
5387 # Verify that subclasses can share keys (per PEP 412)
5388 class A:
5389 pass
5390 class B(A):
5391 pass
5392
5393 a, b = A(), B()
5394 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
Inada Naokif2a18672019-03-12 17:25:44 +09005395 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005396 # Initial hash table can contain at most 5 elements.
5397 # Set 6 attributes to cause internal resizing.
5398 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005399 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5400 a2 = A()
5401 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
Inada Naokif2a18672019-03-12 17:25:44 +09005402 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005403 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Inada Naokif2a18672019-03-12 17:25:44 +09005404 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
Benjamin Peterson2a605342014-03-17 16:20:12 -05005405
5406
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005407class DebugHelperMeta(type):
5408 """
5409 Sets default __doc__ and simplifies repr() output.
5410 """
5411 def __new__(mcls, name, bases, attrs):
5412 if attrs.get('__doc__') is None:
5413 attrs['__doc__'] = name # helps when debugging with gdb
5414 return type.__new__(mcls, name, bases, attrs)
5415 def __repr__(cls):
5416 return repr(cls.__name__)
5417
5418
5419class MroTest(unittest.TestCase):
5420 """
5421 Regressions for some bugs revealed through
5422 mcsl.mro() customization (typeobject.c: mro_internal()) and
5423 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5424 """
5425
5426 def setUp(self):
5427 self.step = 0
5428 self.ready = False
5429
5430 def step_until(self, limit):
5431 ret = (self.step < limit)
5432 if ret:
5433 self.step += 1
5434 return ret
5435
5436 def test_incomplete_set_bases_on_self(self):
5437 """
5438 type_set_bases must be aware that type->tp_mro can be NULL.
5439 """
5440 class M(DebugHelperMeta):
5441 def mro(cls):
5442 if self.step_until(1):
5443 assert cls.__mro__ is None
5444 cls.__bases__ += ()
5445
5446 return type.mro(cls)
5447
5448 class A(metaclass=M):
5449 pass
5450
5451 def test_reent_set_bases_on_base(self):
5452 """
5453 Deep reentrancy must not over-decref old_mro.
5454 """
5455 class M(DebugHelperMeta):
5456 def mro(cls):
5457 if cls.__mro__ is not None and cls.__name__ == 'B':
5458 # 4-5 steps are usually enough to make it crash somewhere
5459 if self.step_until(10):
5460 A.__bases__ += ()
5461
5462 return type.mro(cls)
5463
5464 class A(metaclass=M):
5465 pass
5466 class B(A):
5467 pass
5468 B.__bases__ += ()
5469
5470 def test_reent_set_bases_on_direct_base(self):
5471 """
5472 Similar to test_reent_set_bases_on_base, but may crash differently.
5473 """
5474 class M(DebugHelperMeta):
5475 def mro(cls):
5476 base = cls.__bases__[0]
5477 if base is not object:
5478 if self.step_until(5):
5479 base.__bases__ += ()
5480
5481 return type.mro(cls)
5482
5483 class A(metaclass=M):
5484 pass
5485 class B(A):
5486 pass
5487 class C(B):
5488 pass
5489
5490 def test_reent_set_bases_tp_base_cycle(self):
5491 """
5492 type_set_bases must check for an inheritance cycle not only through
5493 MRO of the type, which may be not yet updated in case of reentrance,
5494 but also through tp_base chain, which is assigned before diving into
5495 inner calls to mro().
5496
5497 Otherwise, the following snippet can loop forever:
5498 do {
5499 // ...
5500 type = type->tp_base;
5501 } while (type != NULL);
5502
5503 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5504 would not be happy in that case, causing a stack overflow.
5505 """
5506 class M(DebugHelperMeta):
5507 def mro(cls):
5508 if self.ready:
5509 if cls.__name__ == 'B1':
5510 B2.__bases__ = (B1,)
5511 if cls.__name__ == 'B2':
5512 B1.__bases__ = (B2,)
5513 return type.mro(cls)
5514
5515 class A(metaclass=M):
5516 pass
5517 class B1(A):
5518 pass
5519 class B2(A):
5520 pass
5521
5522 self.ready = True
5523 with self.assertRaises(TypeError):
5524 B1.__bases__ += ()
5525
5526 def test_tp_subclasses_cycle_in_update_slots(self):
5527 """
5528 type_set_bases must check for reentrancy upon finishing its job
5529 by updating tp_subclasses of old/new bases of the type.
5530 Otherwise, an implicit inheritance cycle through tp_subclasses
5531 can break functions that recurse on elements of that field
5532 (like recurse_down_subclasses and mro_hierarchy) eventually
5533 leading to a stack overflow.
5534 """
5535 class M(DebugHelperMeta):
5536 def mro(cls):
5537 if self.ready and cls.__name__ == 'C':
5538 self.ready = False
5539 C.__bases__ = (B2,)
5540 return type.mro(cls)
5541
5542 class A(metaclass=M):
5543 pass
5544 class B1(A):
5545 pass
5546 class B2(A):
5547 pass
5548 class C(A):
5549 pass
5550
5551 self.ready = True
5552 C.__bases__ = (B1,)
5553 B1.__bases__ = (C,)
5554
5555 self.assertEqual(C.__bases__, (B2,))
5556 self.assertEqual(B2.__subclasses__(), [C])
5557 self.assertEqual(B1.__subclasses__(), [])
5558
5559 self.assertEqual(B1.__bases__, (C,))
5560 self.assertEqual(C.__subclasses__(), [B1])
5561
5562 def test_tp_subclasses_cycle_error_return_path(self):
5563 """
5564 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5565 a code path executed on error (goto bail).
5566 """
5567 class E(Exception):
5568 pass
5569 class M(DebugHelperMeta):
5570 def mro(cls):
5571 if self.ready and cls.__name__ == 'C':
5572 if C.__bases__ == (B2,):
5573 self.ready = False
5574 else:
5575 C.__bases__ = (B2,)
5576 raise E
5577 return type.mro(cls)
5578
5579 class A(metaclass=M):
5580 pass
5581 class B1(A):
5582 pass
5583 class B2(A):
5584 pass
5585 class C(A):
5586 pass
5587
5588 self.ready = True
5589 with self.assertRaises(E):
5590 C.__bases__ = (B1,)
5591 B1.__bases__ = (C,)
5592
5593 self.assertEqual(C.__bases__, (B2,))
5594 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5595
5596 def test_incomplete_extend(self):
5597 """
5598 Extending an unitialized type with type->tp_mro == NULL must
5599 throw a reasonable TypeError exception, instead of failing
5600 with PyErr_BadInternalCall.
5601 """
5602 class M(DebugHelperMeta):
5603 def mro(cls):
5604 if cls.__mro__ is None and cls.__name__ != 'X':
5605 with self.assertRaises(TypeError):
5606 class X(cls):
5607 pass
5608
5609 return type.mro(cls)
5610
5611 class A(metaclass=M):
5612 pass
5613
5614 def test_incomplete_super(self):
5615 """
5616 Attrubute lookup on a super object must be aware that
5617 its target type can be uninitialized (type->tp_mro == NULL).
5618 """
5619 class M(DebugHelperMeta):
5620 def mro(cls):
5621 if cls.__mro__ is None:
5622 with self.assertRaises(AttributeError):
5623 super(cls, cls).xxx
5624
5625 return type.mro(cls)
5626
5627 class A(metaclass=M):
5628 pass
5629
5630
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005631def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005632 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005633 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005634 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005635 MiscTests, PicklingTests, SharedKeyTests,
5636 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005637
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005638if __name__ == "__main__":
5639 test_main()