blob: c4d900a8c1bcb918f76a16a79b46236163b849d0 [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),
1616 "descriptor 'classmeth' requires a type "
1617 "but received a 'xxsubtype.spamlist' instance")
1618
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
Miss Islington (bot)c75f0e52019-08-26 16:02:21 -07002662 with self.assertRaises(TypeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002663 super(Base, kw=1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002664
2665 def test_basic_inheritance(self):
2666 # Testing inheritance from basic types...
2667
2668 class hexint(int):
2669 def __repr__(self):
2670 return hex(self)
2671 def __add__(self, other):
2672 return hexint(int.__add__(self, other))
2673 # (Note that overriding __radd__ doesn't work,
2674 # because the int type gets first dibs.)
2675 self.assertEqual(repr(hexint(7) + 9), "0x10")
2676 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2677 a = hexint(12345)
2678 self.assertEqual(a, 12345)
2679 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002680 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002681 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002682 self.assertIs((+a).__class__, int)
2683 self.assertIs((a >> 0).__class__, int)
2684 self.assertIs((a << 0).__class__, int)
2685 self.assertIs((hexint(0) << 12).__class__, int)
2686 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002687
2688 class octlong(int):
2689 __slots__ = []
2690 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002691 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002692 def __add__(self, other):
2693 return self.__class__(super(octlong, self).__add__(other))
2694 __radd__ = __add__
2695 self.assertEqual(str(octlong(3) + 5), "0o10")
2696 # (Note that overriding __radd__ here only seems to work
2697 # because the example uses a short int left argument.)
2698 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2699 a = octlong(12345)
2700 self.assertEqual(a, 12345)
2701 self.assertEqual(int(a), 12345)
2702 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002703 self.assertIs(int(a).__class__, int)
2704 self.assertIs((+a).__class__, int)
2705 self.assertIs((-a).__class__, int)
2706 self.assertIs((-octlong(0)).__class__, int)
2707 self.assertIs((a >> 0).__class__, int)
2708 self.assertIs((a << 0).__class__, int)
2709 self.assertIs((a - 0).__class__, int)
2710 self.assertIs((a * 1).__class__, int)
2711 self.assertIs((a ** 1).__class__, int)
2712 self.assertIs((a // 1).__class__, int)
2713 self.assertIs((1 * a).__class__, int)
2714 self.assertIs((a | 0).__class__, int)
2715 self.assertIs((a ^ 0).__class__, int)
2716 self.assertIs((a & -1).__class__, int)
2717 self.assertIs((octlong(0) << 12).__class__, int)
2718 self.assertIs((octlong(0) >> 12).__class__, int)
2719 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002720
2721 # Because octlong overrides __add__, we can't check the absence of +0
2722 # optimizations using octlong.
2723 class longclone(int):
2724 pass
2725 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002726 self.assertIs((a + 0).__class__, int)
2727 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002728
2729 # Check that negative clones don't segfault
2730 a = longclone(-1)
2731 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002732 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002733
2734 class precfloat(float):
2735 __slots__ = ['prec']
2736 def __init__(self, value=0.0, prec=12):
2737 self.prec = int(prec)
2738 def __repr__(self):
2739 return "%.*g" % (self.prec, self)
2740 self.assertEqual(repr(precfloat(1.1)), "1.1")
2741 a = precfloat(12345)
2742 self.assertEqual(a, 12345.0)
2743 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002744 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002745 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002746 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002747
2748 class madcomplex(complex):
2749 def __repr__(self):
2750 return "%.17gj%+.17g" % (self.imag, self.real)
2751 a = madcomplex(-3, 4)
2752 self.assertEqual(repr(a), "4j-3")
2753 base = complex(-3, 4)
2754 self.assertEqual(base.__class__, complex)
2755 self.assertEqual(a, base)
2756 self.assertEqual(complex(a), base)
2757 self.assertEqual(complex(a).__class__, complex)
2758 a = madcomplex(a) # just trying another form of the constructor
2759 self.assertEqual(repr(a), "4j-3")
2760 self.assertEqual(a, base)
2761 self.assertEqual(complex(a), base)
2762 self.assertEqual(complex(a).__class__, complex)
2763 self.assertEqual(hash(a), hash(base))
2764 self.assertEqual((+a).__class__, complex)
2765 self.assertEqual((a + 0).__class__, complex)
2766 self.assertEqual(a + 0, base)
2767 self.assertEqual((a - 0).__class__, complex)
2768 self.assertEqual(a - 0, base)
2769 self.assertEqual((a * 1).__class__, complex)
2770 self.assertEqual(a * 1, base)
2771 self.assertEqual((a / 1).__class__, complex)
2772 self.assertEqual(a / 1, base)
2773
2774 class madtuple(tuple):
2775 _rev = None
2776 def rev(self):
2777 if self._rev is not None:
2778 return self._rev
2779 L = list(self)
2780 L.reverse()
2781 self._rev = self.__class__(L)
2782 return self._rev
2783 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2784 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2785 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2786 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2787 for i in range(512):
2788 t = madtuple(range(i))
2789 u = t.rev()
2790 v = u.rev()
2791 self.assertEqual(v, t)
2792 a = madtuple((1,2,3,4,5))
2793 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002794 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002795 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002796 self.assertIs(a[:].__class__, tuple)
2797 self.assertIs((a * 1).__class__, tuple)
2798 self.assertIs((a * 0).__class__, tuple)
2799 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002800 a = madtuple(())
2801 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002802 self.assertIs(tuple(a).__class__, tuple)
2803 self.assertIs((a + a).__class__, tuple)
2804 self.assertIs((a * 0).__class__, tuple)
2805 self.assertIs((a * 1).__class__, tuple)
2806 self.assertIs((a * 2).__class__, tuple)
2807 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002808
2809 class madstring(str):
2810 _rev = None
2811 def rev(self):
2812 if self._rev is not None:
2813 return self._rev
2814 L = list(self)
2815 L.reverse()
2816 self._rev = self.__class__("".join(L))
2817 return self._rev
2818 s = madstring("abcdefghijklmnopqrstuvwxyz")
2819 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2820 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2821 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2822 for i in range(256):
2823 s = madstring("".join(map(chr, range(i))))
2824 t = s.rev()
2825 u = t.rev()
2826 self.assertEqual(u, s)
2827 s = madstring("12345")
2828 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002829 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002830
2831 base = "\x00" * 5
2832 s = madstring(base)
2833 self.assertEqual(s, base)
2834 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002835 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002836 self.assertEqual(hash(s), hash(base))
2837 self.assertEqual({s: 1}[base], 1)
2838 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002839 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002840 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002841 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002842 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002843 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002844 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002845 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002846 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002847 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002848 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002849 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002850 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002851 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002852 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002853 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002854 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002855 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002856 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002858 self.assertEqual(s.rstrip(), base)
2859 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002860 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002861 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002862 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002863 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002864 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002865 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002866 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002867 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002868 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002869 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002870 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002871 self.assertEqual(s.lower(), base)
2872
2873 class madunicode(str):
2874 _rev = None
2875 def rev(self):
2876 if self._rev is not None:
2877 return self._rev
2878 L = list(self)
2879 L.reverse()
2880 self._rev = self.__class__("".join(L))
2881 return self._rev
2882 u = madunicode("ABCDEF")
2883 self.assertEqual(u, "ABCDEF")
2884 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2885 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2886 base = "12345"
2887 u = madunicode(base)
2888 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002889 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002890 self.assertEqual(hash(u), hash(base))
2891 self.assertEqual({u: 1}[base], 1)
2892 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002893 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002894 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002895 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002896 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002897 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002898 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002899 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002900 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002901 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002902 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002903 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002904 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002905 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002906 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002907 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002909 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002910 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002911 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002912 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002913 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002915 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002916 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002917 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002918 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002919 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002920 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002921 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002922 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002923 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002924 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002925 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002926 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002927 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002928 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002929 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002930 self.assertEqual(u[0:0], "")
2931
2932 class sublist(list):
2933 pass
2934 a = sublist(range(5))
2935 self.assertEqual(a, list(range(5)))
2936 a.append("hello")
2937 self.assertEqual(a, list(range(5)) + ["hello"])
2938 a[5] = 5
2939 self.assertEqual(a, list(range(6)))
2940 a.extend(range(6, 20))
2941 self.assertEqual(a, list(range(20)))
2942 a[-5:] = []
2943 self.assertEqual(a, list(range(15)))
2944 del a[10:15]
2945 self.assertEqual(len(a), 10)
2946 self.assertEqual(a, list(range(10)))
2947 self.assertEqual(list(a), list(range(10)))
2948 self.assertEqual(a[0], 0)
2949 self.assertEqual(a[9], 9)
2950 self.assertEqual(a[-10], 0)
2951 self.assertEqual(a[-1], 9)
2952 self.assertEqual(a[:5], list(range(5)))
2953
2954 ## class CountedInput(file):
2955 ## """Counts lines read by self.readline().
2956 ##
2957 ## self.lineno is the 0-based ordinal of the last line read, up to
2958 ## a maximum of one greater than the number of lines in the file.
2959 ##
2960 ## self.ateof is true if and only if the final "" line has been read,
2961 ## at which point self.lineno stops incrementing, and further calls
2962 ## to readline() continue to return "".
2963 ## """
2964 ##
2965 ## lineno = 0
2966 ## ateof = 0
2967 ## def readline(self):
2968 ## if self.ateof:
2969 ## return ""
2970 ## s = file.readline(self)
2971 ## # Next line works too.
2972 ## # s = super(CountedInput, self).readline()
2973 ## self.lineno += 1
2974 ## if s == "":
2975 ## self.ateof = 1
2976 ## return s
2977 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002978 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002979 ## lines = ['a\n', 'b\n', 'c\n']
2980 ## try:
2981 ## f.writelines(lines)
2982 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002983 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002984 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2985 ## got = f.readline()
2986 ## self.assertEqual(expected, got)
2987 ## self.assertEqual(f.lineno, i)
2988 ## self.assertEqual(f.ateof, (i > len(lines)))
2989 ## f.close()
2990 ## finally:
2991 ## try:
2992 ## f.close()
2993 ## except:
2994 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002995 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002996
2997 def test_keywords(self):
2998 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002999 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3000 int(x=1)
3001 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3002 float(x=2)
3003 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3004 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003005 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
3006 self.assertEqual(str(object=500), '500')
3007 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003008 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3009 tuple(sequence=range(3))
3010 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3011 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00003012 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
3013
3014 for constructor in (int, float, int, complex, str, str,
3015 tuple, list):
3016 try:
3017 constructor(bogus_keyword_arg=1)
3018 except TypeError:
3019 pass
3020 else:
3021 self.fail("expected TypeError from bogus keyword argument to %r"
3022 % constructor)
3023
3024 def test_str_subclass_as_dict_key(self):
3025 # Testing a str subclass used as dict key ..
3026
3027 class cistr(str):
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -07003028 """Subclass of str that computes __eq__ case-insensitively.
Georg Brandl479a7e72008-02-05 18:13:15 +00003029
3030 Also computes a hash code of the string in canonical form.
3031 """
3032
3033 def __init__(self, value):
3034 self.canonical = value.lower()
3035 self.hashcode = hash(self.canonical)
3036
3037 def __eq__(self, other):
3038 if not isinstance(other, cistr):
3039 other = cistr(other)
3040 return self.canonical == other.canonical
3041
3042 def __hash__(self):
3043 return self.hashcode
3044
3045 self.assertEqual(cistr('ABC'), 'abc')
3046 self.assertEqual('aBc', cistr('ABC'))
3047 self.assertEqual(str(cistr('ABC')), 'ABC')
3048
3049 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3050 self.assertEqual(d[cistr('one')], 1)
3051 self.assertEqual(d[cistr('tWo')], 2)
3052 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00003053 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003054 self.assertEqual(d.get(cistr('thrEE')), 3)
3055
3056 def test_classic_comparisons(self):
3057 # Testing classic comparisons...
3058 class classic:
3059 pass
3060
3061 for base in (classic, int, object):
3062 class C(base):
3063 def __init__(self, value):
3064 self.value = int(value)
3065 def __eq__(self, other):
3066 if isinstance(other, C):
3067 return self.value == other.value
3068 if isinstance(other, int) or isinstance(other, int):
3069 return self.value == other
3070 return NotImplemented
3071 def __ne__(self, other):
3072 if isinstance(other, C):
3073 return self.value != other.value
3074 if isinstance(other, int) or isinstance(other, int):
3075 return self.value != other
3076 return NotImplemented
3077 def __lt__(self, other):
3078 if isinstance(other, C):
3079 return self.value < other.value
3080 if isinstance(other, int) or isinstance(other, int):
3081 return self.value < other
3082 return NotImplemented
3083 def __le__(self, other):
3084 if isinstance(other, C):
3085 return self.value <= other.value
3086 if isinstance(other, int) or isinstance(other, int):
3087 return self.value <= other
3088 return NotImplemented
3089 def __gt__(self, other):
3090 if isinstance(other, C):
3091 return self.value > other.value
3092 if isinstance(other, int) or isinstance(other, int):
3093 return self.value > other
3094 return NotImplemented
3095 def __ge__(self, other):
3096 if isinstance(other, C):
3097 return self.value >= other.value
3098 if isinstance(other, int) or isinstance(other, int):
3099 return self.value >= other
3100 return NotImplemented
3101
3102 c1 = C(1)
3103 c2 = C(2)
3104 c3 = C(3)
3105 self.assertEqual(c1, 1)
3106 c = {1: c1, 2: c2, 3: c3}
3107 for x in 1, 2, 3:
3108 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003109 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003110 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003111 eval("x %s y" % op),
3112 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003113 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003114 eval("x %s y" % op),
3115 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003116 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003117 eval("x %s y" % op),
3118 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003119
3120 def test_rich_comparisons(self):
3121 # Testing rich comparisons...
3122 class Z(complex):
3123 pass
3124 z = Z(1)
3125 self.assertEqual(z, 1+0j)
3126 self.assertEqual(1+0j, z)
3127 class ZZ(complex):
3128 def __eq__(self, other):
3129 try:
3130 return abs(self - other) <= 1e-6
3131 except:
3132 return NotImplemented
3133 zz = ZZ(1.0000003)
3134 self.assertEqual(zz, 1+0j)
3135 self.assertEqual(1+0j, zz)
3136
3137 class classic:
3138 pass
3139 for base in (classic, int, object, list):
3140 class C(base):
3141 def __init__(self, value):
3142 self.value = int(value)
3143 def __cmp__(self_, other):
3144 self.fail("shouldn't call __cmp__")
3145 def __eq__(self, other):
3146 if isinstance(other, C):
3147 return self.value == other.value
3148 if isinstance(other, int) or isinstance(other, int):
3149 return self.value == other
3150 return NotImplemented
3151 def __ne__(self, other):
3152 if isinstance(other, C):
3153 return self.value != other.value
3154 if isinstance(other, int) or isinstance(other, int):
3155 return self.value != other
3156 return NotImplemented
3157 def __lt__(self, other):
3158 if isinstance(other, C):
3159 return self.value < other.value
3160 if isinstance(other, int) or isinstance(other, int):
3161 return self.value < other
3162 return NotImplemented
3163 def __le__(self, other):
3164 if isinstance(other, C):
3165 return self.value <= other.value
3166 if isinstance(other, int) or isinstance(other, int):
3167 return self.value <= other
3168 return NotImplemented
3169 def __gt__(self, other):
3170 if isinstance(other, C):
3171 return self.value > other.value
3172 if isinstance(other, int) or isinstance(other, int):
3173 return self.value > other
3174 return NotImplemented
3175 def __ge__(self, other):
3176 if isinstance(other, C):
3177 return self.value >= other.value
3178 if isinstance(other, int) or isinstance(other, int):
3179 return self.value >= other
3180 return NotImplemented
3181 c1 = C(1)
3182 c2 = C(2)
3183 c3 = C(3)
3184 self.assertEqual(c1, 1)
3185 c = {1: c1, 2: c2, 3: c3}
3186 for x in 1, 2, 3:
3187 for y in 1, 2, 3:
3188 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003189 self.assertEqual(eval("c[x] %s c[y]" % op),
3190 eval("x %s y" % op),
3191 "x=%d, y=%d" % (x, y))
3192 self.assertEqual(eval("c[x] %s y" % op),
3193 eval("x %s y" % op),
3194 "x=%d, y=%d" % (x, y))
3195 self.assertEqual(eval("x %s c[y]" % op),
3196 eval("x %s y" % op),
3197 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003198
3199 def test_descrdoc(self):
3200 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003201 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003202 def check(descr, what):
3203 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003204 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003205 check(complex.real, "the real part of a complex number") # member descriptor
3206
3207 def test_doc_descriptor(self):
3208 # Testing __doc__ descriptor...
3209 # SF bug 542984
3210 class DocDescr(object):
3211 def __get__(self, object, otype):
3212 if object:
3213 object = object.__class__.__name__ + ' instance'
3214 if otype:
3215 otype = otype.__name__
3216 return 'object=%s; type=%s' % (object, otype)
3217 class OldClass:
3218 __doc__ = DocDescr()
3219 class NewClass(object):
3220 __doc__ = DocDescr()
3221 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3222 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3223 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3224 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3225
3226 def test_set_class(self):
3227 # Testing __class__ assignment...
3228 class C(object): pass
3229 class D(object): pass
3230 class E(object): pass
3231 class F(D, E): pass
3232 for cls in C, D, E, F:
3233 for cls2 in C, D, E, F:
3234 x = cls()
3235 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003236 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003237 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003238 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003239 def cant(x, C):
3240 try:
3241 x.__class__ = C
3242 except TypeError:
3243 pass
3244 else:
3245 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3246 try:
3247 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003248 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003249 pass
3250 else:
3251 self.fail("shouldn't allow del %r.__class__" % x)
3252 cant(C(), list)
3253 cant(list(), C)
3254 cant(C(), 1)
3255 cant(C(), object)
3256 cant(object(), list)
3257 cant(list(), object)
3258 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003259 cant(True, int)
3260 cant(2, bool)
3261 o = object()
3262 cant(o, type(1))
3263 cant(o, type(None))
3264 del o
3265 class G(object):
3266 __slots__ = ["a", "b"]
3267 class H(object):
3268 __slots__ = ["b", "a"]
3269 class I(object):
3270 __slots__ = ["a", "b"]
3271 class J(object):
3272 __slots__ = ["c", "b"]
3273 class K(object):
3274 __slots__ = ["a", "b", "d"]
3275 class L(H):
3276 __slots__ = ["e"]
3277 class M(I):
3278 __slots__ = ["e"]
3279 class N(J):
3280 __slots__ = ["__weakref__"]
3281 class P(J):
3282 __slots__ = ["__dict__"]
3283 class Q(J):
3284 pass
3285 class R(J):
3286 __slots__ = ["__dict__", "__weakref__"]
3287
3288 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3289 x = cls()
3290 x.a = 1
3291 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003292 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003293 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3294 self.assertEqual(x.a, 1)
3295 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003296 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003297 "assigning %r as __class__ for %r silently failed" % (cls, x))
3298 self.assertEqual(x.a, 1)
3299 for cls in G, J, K, L, M, N, P, R, list, Int:
3300 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3301 if cls is cls2:
3302 continue
3303 cant(cls(), cls2)
3304
Benjamin Peterson193152c2009-04-25 01:08:45 +00003305 # Issue5283: when __class__ changes in __del__, the wrong
3306 # type gets DECREF'd.
3307 class O(object):
3308 pass
3309 class A(object):
3310 def __del__(self):
3311 self.__class__ = O
3312 l = [A() for x in range(100)]
3313 del l
3314
Georg Brandl479a7e72008-02-05 18:13:15 +00003315 def test_set_dict(self):
3316 # Testing __dict__ assignment...
3317 class C(object): pass
3318 a = C()
3319 a.__dict__ = {'b': 1}
3320 self.assertEqual(a.b, 1)
3321 def cant(x, dict):
3322 try:
3323 x.__dict__ = dict
3324 except (AttributeError, TypeError):
3325 pass
3326 else:
3327 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3328 cant(a, None)
3329 cant(a, [])
3330 cant(a, 1)
3331 del a.__dict__ # Deleting __dict__ is allowed
3332
3333 class Base(object):
3334 pass
3335 def verify_dict_readonly(x):
3336 """
3337 x has to be an instance of a class inheriting from Base.
3338 """
3339 cant(x, {})
3340 try:
3341 del x.__dict__
3342 except (AttributeError, TypeError):
3343 pass
3344 else:
3345 self.fail("shouldn't allow del %r.__dict__" % x)
3346 dict_descr = Base.__dict__["__dict__"]
3347 try:
3348 dict_descr.__set__(x, {})
3349 except (AttributeError, TypeError):
3350 pass
3351 else:
3352 self.fail("dict_descr allowed access to %r's dict" % x)
3353
3354 # Classes don't allow __dict__ assignment and have readonly dicts
3355 class Meta1(type, Base):
3356 pass
3357 class Meta2(Base, type):
3358 pass
3359 class D(object, metaclass=Meta1):
3360 pass
3361 class E(object, metaclass=Meta2):
3362 pass
3363 for cls in C, D, E:
3364 verify_dict_readonly(cls)
3365 class_dict = cls.__dict__
3366 try:
3367 class_dict["spam"] = "eggs"
3368 except TypeError:
3369 pass
3370 else:
3371 self.fail("%r's __dict__ can be modified" % cls)
3372
3373 # Modules also disallow __dict__ assignment
3374 class Module1(types.ModuleType, Base):
3375 pass
3376 class Module2(Base, types.ModuleType):
3377 pass
3378 for ModuleType in Module1, Module2:
3379 mod = ModuleType("spam")
3380 verify_dict_readonly(mod)
3381 mod.__dict__["spam"] = "eggs"
3382
3383 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003384 # (at least not any more than regular exception's __dict__ can
3385 # be deleted; on CPython it is not the case, whereas on PyPy they
3386 # can, just like any other new-style instance's __dict__.)
3387 def can_delete_dict(e):
3388 try:
3389 del e.__dict__
3390 except (TypeError, AttributeError):
3391 return False
3392 else:
3393 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003394 class Exception1(Exception, Base):
3395 pass
3396 class Exception2(Base, Exception):
3397 pass
3398 for ExceptionType in Exception, Exception1, Exception2:
3399 e = ExceptionType()
3400 e.__dict__ = {"a": 1}
3401 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003402 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003403
Georg Brandl479a7e72008-02-05 18:13:15 +00003404 def test_binary_operator_override(self):
3405 # Testing overrides of binary operations...
3406 class I(int):
3407 def __repr__(self):
3408 return "I(%r)" % int(self)
3409 def __add__(self, other):
3410 return I(int(self) + int(other))
3411 __radd__ = __add__
3412 def __pow__(self, other, mod=None):
3413 if mod is None:
3414 return I(pow(int(self), int(other)))
3415 else:
3416 return I(pow(int(self), int(other), int(mod)))
3417 def __rpow__(self, other, mod=None):
3418 if mod is None:
3419 return I(pow(int(other), int(self), mod))
3420 else:
3421 return I(pow(int(other), int(self), int(mod)))
3422
3423 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3424 self.assertEqual(repr(I(1) + 2), "I(3)")
3425 self.assertEqual(repr(1 + I(2)), "I(3)")
3426 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3427 self.assertEqual(repr(2 ** I(3)), "I(8)")
3428 self.assertEqual(repr(I(2) ** 3), "I(8)")
3429 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3430 class S(str):
3431 def __eq__(self, other):
3432 return self.lower() == other.lower()
3433
3434 def test_subclass_propagation(self):
3435 # Testing propagation of slot functions to subclasses...
3436 class A(object):
3437 pass
3438 class B(A):
3439 pass
3440 class C(A):
3441 pass
3442 class D(B, C):
3443 pass
3444 d = D()
3445 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3446 A.__hash__ = lambda self: 42
3447 self.assertEqual(hash(d), 42)
3448 C.__hash__ = lambda self: 314
3449 self.assertEqual(hash(d), 314)
3450 B.__hash__ = lambda self: 144
3451 self.assertEqual(hash(d), 144)
3452 D.__hash__ = lambda self: 100
3453 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003454 D.__hash__ = None
3455 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003456 del D.__hash__
3457 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003458 B.__hash__ = None
3459 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003460 del B.__hash__
3461 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003462 C.__hash__ = None
3463 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003464 del C.__hash__
3465 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003466 A.__hash__ = None
3467 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003468 del A.__hash__
3469 self.assertEqual(hash(d), orig_hash)
3470 d.foo = 42
3471 d.bar = 42
3472 self.assertEqual(d.foo, 42)
3473 self.assertEqual(d.bar, 42)
3474 def __getattribute__(self, name):
3475 if name == "foo":
3476 return 24
3477 return object.__getattribute__(self, name)
3478 A.__getattribute__ = __getattribute__
3479 self.assertEqual(d.foo, 24)
3480 self.assertEqual(d.bar, 42)
3481 def __getattr__(self, name):
3482 if name in ("spam", "foo", "bar"):
3483 return "hello"
3484 raise AttributeError(name)
3485 B.__getattr__ = __getattr__
3486 self.assertEqual(d.spam, "hello")
3487 self.assertEqual(d.foo, 24)
3488 self.assertEqual(d.bar, 42)
3489 del A.__getattribute__
3490 self.assertEqual(d.foo, 42)
3491 del d.foo
3492 self.assertEqual(d.foo, "hello")
3493 self.assertEqual(d.bar, 42)
3494 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003495 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003496 d.foo
3497 except AttributeError:
3498 pass
3499 else:
3500 self.fail("d.foo should be undefined now")
3501
3502 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003503 class A(object):
3504 pass
3505 class B(A):
3506 pass
3507 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003508 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003509 A.__setitem__ = lambda *a: None # crash
3510
3511 def test_buffer_inheritance(self):
3512 # Testing that buffer interface is inherited ...
3513
3514 import binascii
3515 # SF bug [#470040] ParseTuple t# vs subclasses.
3516
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003517 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003518 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003519 base = b'abc'
3520 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003521 # b2a_hex uses the buffer interface to get its argument's value, via
3522 # PyArg_ParseTuple 't#' code.
3523 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3524
Georg Brandl479a7e72008-02-05 18:13:15 +00003525 class MyInt(int):
3526 pass
3527 m = MyInt(42)
3528 try:
3529 binascii.b2a_hex(m)
3530 self.fail('subclass of int should not have a buffer interface')
3531 except TypeError:
3532 pass
3533
3534 def test_str_of_str_subclass(self):
3535 # Testing __str__ defined in subclass of str ...
3536 import binascii
3537 import io
3538
3539 class octetstring(str):
3540 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003541 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003542 def __repr__(self):
3543 return self + " repr"
3544
3545 o = octetstring('A')
3546 self.assertEqual(type(o), octetstring)
3547 self.assertEqual(type(str(o)), str)
3548 self.assertEqual(type(repr(o)), str)
3549 self.assertEqual(ord(o), 0x41)
3550 self.assertEqual(str(o), '41')
3551 self.assertEqual(repr(o), 'A repr')
3552 self.assertEqual(o.__str__(), '41')
3553 self.assertEqual(o.__repr__(), 'A repr')
3554
3555 capture = io.StringIO()
3556 # Calling str() or not exercises different internal paths.
3557 print(o, file=capture)
3558 print(str(o), file=capture)
3559 self.assertEqual(capture.getvalue(), '41\n41\n')
3560 capture.close()
3561
3562 def test_keyword_arguments(self):
3563 # Testing keyword arguments to __init__, __call__...
3564 def f(a): return a
3565 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003566 ba = bytearray()
3567 bytearray.__init__(ba, 'abc\xbd\u20ac',
3568 encoding='latin1', errors='replace')
3569 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003570
3571 def test_recursive_call(self):
3572 # Testing recursive __call__() by setting to instance of class...
3573 class A(object):
3574 pass
3575
3576 A.__call__ = A()
3577 try:
3578 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003579 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 pass
3581 else:
3582 self.fail("Recursion limit should have been reached for __call__()")
3583
3584 def test_delete_hook(self):
3585 # Testing __del__ hook...
3586 log = []
3587 class C(object):
3588 def __del__(self):
3589 log.append(1)
3590 c = C()
3591 self.assertEqual(log, [])
3592 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003593 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003594 self.assertEqual(log, [1])
3595
3596 class D(object): pass
3597 d = D()
3598 try: del d[0]
3599 except TypeError: pass
3600 else: self.fail("invalid del() didn't raise TypeError")
3601
3602 def test_hash_inheritance(self):
3603 # Testing hash of mutable subclasses...
3604
3605 class mydict(dict):
3606 pass
3607 d = mydict()
3608 try:
3609 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003610 except TypeError:
3611 pass
3612 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003613 self.fail("hash() of dict subclass should fail")
3614
3615 class mylist(list):
3616 pass
3617 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003618 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003619 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003620 except TypeError:
3621 pass
3622 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003623 self.fail("hash() of list subclass should fail")
3624
3625 def test_str_operations(self):
3626 try: 'a' + 5
3627 except TypeError: pass
3628 else: self.fail("'' + 5 doesn't raise TypeError")
3629
3630 try: ''.split('')
3631 except ValueError: pass
3632 else: self.fail("''.split('') doesn't raise ValueError")
3633
3634 try: ''.join([0])
3635 except TypeError: pass
3636 else: self.fail("''.join([0]) doesn't raise TypeError")
3637
3638 try: ''.rindex('5')
3639 except ValueError: pass
3640 else: self.fail("''.rindex('5') doesn't raise ValueError")
3641
3642 try: '%(n)s' % None
3643 except TypeError: pass
3644 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3645
3646 try: '%(n' % {}
3647 except ValueError: pass
3648 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3649
3650 try: '%*s' % ('abc')
3651 except TypeError: pass
3652 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3653
3654 try: '%*.*s' % ('abc', 5)
3655 except TypeError: pass
3656 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3657
3658 try: '%s' % (1, 2)
3659 except TypeError: pass
3660 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3661
3662 try: '%' % None
3663 except ValueError: pass
3664 else: self.fail("'%' % None doesn't raise ValueError")
3665
3666 self.assertEqual('534253'.isdigit(), 1)
3667 self.assertEqual('534253x'.isdigit(), 0)
3668 self.assertEqual('%c' % 5, '\x05')
3669 self.assertEqual('%c' % '5', '5')
3670
3671 def test_deepcopy_recursive(self):
3672 # Testing deepcopy of recursive objects...
3673 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003674 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003675 a = Node()
3676 b = Node()
3677 a.b = b
3678 b.a = a
3679 z = deepcopy(a) # This blew up before
3680
Martin Panterf05641642016-05-08 13:48:10 +00003681 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003682 # Testing uninitialized module objects...
3683 from types import ModuleType as M
3684 m = M.__new__(M)
3685 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003686 self.assertNotHasAttr(m, "__name__")
3687 self.assertNotHasAttr(m, "__file__")
3688 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003689 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003690 m.foo = 1
3691 self.assertEqual(m.__dict__, {"foo": 1})
3692
3693 def test_funny_new(self):
3694 # Testing __new__ returning something unexpected...
3695 class C(object):
3696 def __new__(cls, arg):
3697 if isinstance(arg, str): return [1, 2, 3]
3698 elif isinstance(arg, int): return object.__new__(D)
3699 else: return object.__new__(cls)
3700 class D(C):
3701 def __init__(self, arg):
3702 self.foo = arg
3703 self.assertEqual(C("1"), [1, 2, 3])
3704 self.assertEqual(D("1"), [1, 2, 3])
3705 d = D(None)
3706 self.assertEqual(d.foo, None)
3707 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003708 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003709 self.assertEqual(d.foo, 1)
3710 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003711 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003712 self.assertEqual(d.foo, 1)
3713
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003714 class C(object):
3715 @staticmethod
3716 def __new__(*args):
3717 return args
3718 self.assertEqual(C(1, 2), (C, 1, 2))
3719 class D(C):
3720 pass
3721 self.assertEqual(D(1, 2), (D, 1, 2))
3722
3723 class C(object):
3724 @classmethod
3725 def __new__(*args):
3726 return args
3727 self.assertEqual(C(1, 2), (C, C, 1, 2))
3728 class D(C):
3729 pass
3730 self.assertEqual(D(1, 2), (D, D, 1, 2))
3731
Georg Brandl479a7e72008-02-05 18:13:15 +00003732 def test_imul_bug(self):
3733 # Testing for __imul__ problems...
3734 # SF bug 544647
3735 class C(object):
3736 def __imul__(self, other):
3737 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003738 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003739 y = x
3740 y *= 1.0
3741 self.assertEqual(y, (x, 1.0))
3742 y = x
3743 y *= 2
3744 self.assertEqual(y, (x, 2))
3745 y = x
3746 y *= 3
3747 self.assertEqual(y, (x, 3))
3748 y = x
3749 y *= 1<<100
3750 self.assertEqual(y, (x, 1<<100))
3751 y = x
3752 y *= None
3753 self.assertEqual(y, (x, None))
3754 y = x
3755 y *= "foo"
3756 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003757
Georg Brandl479a7e72008-02-05 18:13:15 +00003758 def test_copy_setstate(self):
3759 # Testing that copy.*copy() correctly uses __setstate__...
3760 import copy
3761 class C(object):
3762 def __init__(self, foo=None):
3763 self.foo = foo
3764 self.__foo = foo
3765 def setfoo(self, foo=None):
3766 self.foo = foo
3767 def getfoo(self):
3768 return self.__foo
3769 def __getstate__(self):
3770 return [self.foo]
3771 def __setstate__(self_, lst):
3772 self.assertEqual(len(lst), 1)
3773 self_.__foo = self_.foo = lst[0]
3774 a = C(42)
3775 a.setfoo(24)
3776 self.assertEqual(a.foo, 24)
3777 self.assertEqual(a.getfoo(), 42)
3778 b = copy.copy(a)
3779 self.assertEqual(b.foo, 24)
3780 self.assertEqual(b.getfoo(), 24)
3781 b = copy.deepcopy(a)
3782 self.assertEqual(b.foo, 24)
3783 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003784
Georg Brandl479a7e72008-02-05 18:13:15 +00003785 def test_slices(self):
3786 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003787
Georg Brandl479a7e72008-02-05 18:13:15 +00003788 # Strings
3789 self.assertEqual("hello"[:4], "hell")
3790 self.assertEqual("hello"[slice(4)], "hell")
3791 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3792 class S(str):
3793 def __getitem__(self, x):
3794 return str.__getitem__(self, x)
3795 self.assertEqual(S("hello")[:4], "hell")
3796 self.assertEqual(S("hello")[slice(4)], "hell")
3797 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3798 # Tuples
3799 self.assertEqual((1,2,3)[:2], (1,2))
3800 self.assertEqual((1,2,3)[slice(2)], (1,2))
3801 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3802 class T(tuple):
3803 def __getitem__(self, x):
3804 return tuple.__getitem__(self, x)
3805 self.assertEqual(T((1,2,3))[:2], (1,2))
3806 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3807 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3808 # Lists
3809 self.assertEqual([1,2,3][:2], [1,2])
3810 self.assertEqual([1,2,3][slice(2)], [1,2])
3811 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3812 class L(list):
3813 def __getitem__(self, x):
3814 return list.__getitem__(self, x)
3815 self.assertEqual(L([1,2,3])[:2], [1,2])
3816 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3817 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3818 # Now do lists and __setitem__
3819 a = L([1,2,3])
3820 a[slice(1, 3)] = [3,2]
3821 self.assertEqual(a, [1,3,2])
3822 a[slice(0, 2, 1)] = [3,1]
3823 self.assertEqual(a, [3,1,2])
3824 a.__setitem__(slice(1, 3), [2,1])
3825 self.assertEqual(a, [3,2,1])
3826 a.__setitem__(slice(0, 2, 1), [2,3])
3827 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003828
Georg Brandl479a7e72008-02-05 18:13:15 +00003829 def test_subtype_resurrection(self):
3830 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003831
Georg Brandl479a7e72008-02-05 18:13:15 +00003832 class C(object):
3833 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003834
Georg Brandl479a7e72008-02-05 18:13:15 +00003835 def __del__(self):
3836 # resurrect the instance
3837 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003838
Georg Brandl479a7e72008-02-05 18:13:15 +00003839 c = C()
3840 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003841
Benjamin Petersone549ead2009-03-28 21:42:05 +00003842 # The most interesting thing here is whether this blows up, due to
3843 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3844 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003845 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003846
Benjamin Petersone549ead2009-03-28 21:42:05 +00003847 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003848 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003849
Georg Brandl479a7e72008-02-05 18:13:15 +00003850 # Make c mortal again, so that the test framework with -l doesn't report
3851 # it as a leak.
3852 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003853
Georg Brandl479a7e72008-02-05 18:13:15 +00003854 def test_slots_trash(self):
3855 # Testing slot trash...
3856 # Deallocating deeply nested slotted trash caused stack overflows
3857 class trash(object):
3858 __slots__ = ['x']
3859 def __init__(self, x):
3860 self.x = x
3861 o = None
3862 for i in range(50000):
3863 o = trash(o)
3864 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003865
Georg Brandl479a7e72008-02-05 18:13:15 +00003866 def test_slots_multiple_inheritance(self):
3867 # SF bug 575229, multiple inheritance w/ slots dumps core
3868 class A(object):
3869 __slots__=()
3870 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003871 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003872 class C(A,B) :
3873 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003874 if support.check_impl_detail():
3875 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003876 self.assertHasAttr(C, '__dict__')
3877 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003878 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003879
Georg Brandl479a7e72008-02-05 18:13:15 +00003880 def test_rmul(self):
3881 # Testing correct invocation of __rmul__...
3882 # SF patch 592646
3883 class C(object):
3884 def __mul__(self, other):
3885 return "mul"
3886 def __rmul__(self, other):
3887 return "rmul"
3888 a = C()
3889 self.assertEqual(a*2, "mul")
3890 self.assertEqual(a*2.2, "mul")
3891 self.assertEqual(2*a, "rmul")
3892 self.assertEqual(2.2*a, "rmul")
3893
3894 def test_ipow(self):
3895 # Testing correct invocation of __ipow__...
3896 # [SF bug 620179]
3897 class C(object):
3898 def __ipow__(self, other):
3899 pass
3900 a = C()
3901 a **= 2
3902
3903 def test_mutable_bases(self):
3904 # Testing mutable bases...
3905
3906 # stuff that should work:
3907 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003908 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003909 class C2(object):
3910 def __getattribute__(self, attr):
3911 if attr == 'a':
3912 return 2
3913 else:
3914 return super(C2, self).__getattribute__(attr)
3915 def meth(self):
3916 return 1
3917 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003918 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003919 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003920 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003921 d = D()
3922 e = E()
3923 D.__bases__ = (C,)
3924 D.__bases__ = (C2,)
3925 self.assertEqual(d.meth(), 1)
3926 self.assertEqual(e.meth(), 1)
3927 self.assertEqual(d.a, 2)
3928 self.assertEqual(e.a, 2)
3929 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003930
Georg Brandl479a7e72008-02-05 18:13:15 +00003931 try:
3932 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003933 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003934 pass
3935 else:
3936 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003937
Georg Brandl479a7e72008-02-05 18:13:15 +00003938 try:
3939 D.__bases__ = ()
3940 except TypeError as msg:
3941 if str(msg) == "a new-style class can't have only classic bases":
3942 self.fail("wrong error message for .__bases__ = ()")
3943 else:
3944 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003945
Georg Brandl479a7e72008-02-05 18:13:15 +00003946 try:
3947 D.__bases__ = (D,)
3948 except TypeError:
3949 pass
3950 else:
3951 # actually, we'll have crashed by here...
3952 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003953
Georg Brandl479a7e72008-02-05 18:13:15 +00003954 try:
3955 D.__bases__ = (C, C)
3956 except TypeError:
3957 pass
3958 else:
3959 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003960
Georg Brandl479a7e72008-02-05 18:13:15 +00003961 try:
3962 D.__bases__ = (E,)
3963 except TypeError:
3964 pass
3965 else:
3966 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003967
Benjamin Petersonae937c02009-04-18 20:54:08 +00003968 def test_builtin_bases(self):
3969 # Make sure all the builtin types can have their base queried without
3970 # segfaulting. See issue #5787.
3971 builtin_types = [tp for tp in builtins.__dict__.values()
3972 if isinstance(tp, type)]
3973 for tp in builtin_types:
3974 object.__getattribute__(tp, "__bases__")
3975 if tp is not object:
3976 self.assertEqual(len(tp.__bases__), 1, tp)
3977
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003978 class L(list):
3979 pass
3980
3981 class C(object):
3982 pass
3983
3984 class D(C):
3985 pass
3986
3987 try:
3988 L.__bases__ = (dict,)
3989 except TypeError:
3990 pass
3991 else:
3992 self.fail("shouldn't turn list subclass into dict subclass")
3993
3994 try:
3995 list.__bases__ = (dict,)
3996 except TypeError:
3997 pass
3998 else:
3999 self.fail("shouldn't be able to assign to list.__bases__")
4000
4001 try:
4002 D.__bases__ = (C, list)
4003 except TypeError:
4004 pass
4005 else:
4006 assert 0, "best_base calculation found wanting"
4007
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07004008 def test_unsubclassable_types(self):
4009 with self.assertRaises(TypeError):
4010 class X(type(None)):
4011 pass
4012 with self.assertRaises(TypeError):
4013 class X(object, type(None)):
4014 pass
4015 with self.assertRaises(TypeError):
4016 class X(type(None), object):
4017 pass
4018 class O(object):
4019 pass
4020 with self.assertRaises(TypeError):
4021 class X(O, type(None)):
4022 pass
4023 with self.assertRaises(TypeError):
4024 class X(type(None), O):
4025 pass
4026
4027 class X(object):
4028 pass
4029 with self.assertRaises(TypeError):
4030 X.__bases__ = type(None),
4031 with self.assertRaises(TypeError):
4032 X.__bases__ = object, type(None)
4033 with self.assertRaises(TypeError):
4034 X.__bases__ = type(None), object
4035 with self.assertRaises(TypeError):
4036 X.__bases__ = O, type(None)
4037 with self.assertRaises(TypeError):
4038 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00004039
Georg Brandl479a7e72008-02-05 18:13:15 +00004040 def test_mutable_bases_with_failing_mro(self):
4041 # Testing mutable bases with failing mro...
4042 class WorkOnce(type):
4043 def __new__(self, name, bases, ns):
4044 self.flag = 0
4045 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4046 def mro(self):
4047 if self.flag > 0:
4048 raise RuntimeError("bozo")
4049 else:
4050 self.flag += 1
4051 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004052
Georg Brandl479a7e72008-02-05 18:13:15 +00004053 class WorkAlways(type):
4054 def mro(self):
4055 # this is here to make sure that .mro()s aren't called
4056 # with an exception set (which was possible at one point).
4057 # An error message will be printed in a debug build.
4058 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004059 return type.mro(self)
4060
Georg Brandl479a7e72008-02-05 18:13:15 +00004061 class C(object):
4062 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004063
Georg Brandl479a7e72008-02-05 18:13:15 +00004064 class C2(object):
4065 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004066
Georg Brandl479a7e72008-02-05 18:13:15 +00004067 class D(C):
4068 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004069
Georg Brandl479a7e72008-02-05 18:13:15 +00004070 class E(D):
4071 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004072
Georg Brandl479a7e72008-02-05 18:13:15 +00004073 class F(D, metaclass=WorkOnce):
4074 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004075
Georg Brandl479a7e72008-02-05 18:13:15 +00004076 class G(D, metaclass=WorkAlways):
4077 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004078
Georg Brandl479a7e72008-02-05 18:13:15 +00004079 # Immediate subclasses have their mro's adjusted in alphabetical
4080 # order, so E's will get adjusted before adjusting F's fails. We
4081 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004082
Georg Brandl479a7e72008-02-05 18:13:15 +00004083 E_mro_before = E.__mro__
4084 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004085
Armin Rigofd163f92005-12-29 15:59:19 +00004086 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004087 D.__bases__ = (C2,)
4088 except RuntimeError:
4089 self.assertEqual(E.__mro__, E_mro_before)
4090 self.assertEqual(D.__mro__, D_mro_before)
4091 else:
4092 self.fail("exception not propagated")
4093
4094 def test_mutable_bases_catch_mro_conflict(self):
4095 # Testing mutable bases catch mro conflict...
4096 class A(object):
4097 pass
4098
4099 class B(object):
4100 pass
4101
4102 class C(A, B):
4103 pass
4104
4105 class D(A, B):
4106 pass
4107
4108 class E(C, D):
4109 pass
4110
4111 try:
4112 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004113 except TypeError:
4114 pass
4115 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004116 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004117
Georg Brandl479a7e72008-02-05 18:13:15 +00004118 def test_mutable_names(self):
4119 # Testing mutable names...
4120 class C(object):
4121 pass
4122
4123 # C.__module__ could be 'test_descr' or '__main__'
4124 mod = C.__module__
4125
4126 C.__name__ = 'D'
4127 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4128
4129 C.__name__ = 'D.E'
4130 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4131
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004132 def test_evil_type_name(self):
4133 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4134 # execution while the type structure was not in a sane state, and a
4135 # possible segmentation fault as a result. See bug #16447.
4136 class Nasty(str):
4137 def __del__(self):
4138 C.__name__ = "other"
4139
4140 class C:
4141 pass
4142
4143 C.__name__ = Nasty("abc")
4144 C.__name__ = "normal"
4145
Georg Brandl479a7e72008-02-05 18:13:15 +00004146 def test_subclass_right_op(self):
4147 # Testing correct dispatch of subclass overloading __r<op>__...
4148
4149 # This code tests various cases where right-dispatch of a subclass
4150 # should be preferred over left-dispatch of a base class.
4151
4152 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4153
4154 class B(int):
4155 def __floordiv__(self, other):
4156 return "B.__floordiv__"
4157 def __rfloordiv__(self, other):
4158 return "B.__rfloordiv__"
4159
4160 self.assertEqual(B(1) // 1, "B.__floordiv__")
4161 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4162
4163 # Case 2: subclass of object; this is just the baseline for case 3
4164
4165 class C(object):
4166 def __floordiv__(self, other):
4167 return "C.__floordiv__"
4168 def __rfloordiv__(self, other):
4169 return "C.__rfloordiv__"
4170
4171 self.assertEqual(C() // 1, "C.__floordiv__")
4172 self.assertEqual(1 // C(), "C.__rfloordiv__")
4173
4174 # Case 3: subclass of new-style class; here it gets interesting
4175
4176 class D(C):
4177 def __floordiv__(self, other):
4178 return "D.__floordiv__"
4179 def __rfloordiv__(self, other):
4180 return "D.__rfloordiv__"
4181
4182 self.assertEqual(D() // C(), "D.__floordiv__")
4183 self.assertEqual(C() // D(), "D.__rfloordiv__")
4184
4185 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4186
4187 class E(C):
4188 pass
4189
4190 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4191
4192 self.assertEqual(E() // 1, "C.__floordiv__")
4193 self.assertEqual(1 // E(), "C.__rfloordiv__")
4194 self.assertEqual(E() // C(), "C.__floordiv__")
4195 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4196
Benjamin Petersone549ead2009-03-28 21:42:05 +00004197 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004198 def test_meth_class_get(self):
4199 # Testing __get__ method of METH_CLASS C methods...
4200 # Full coverage of descrobject.c::classmethod_get()
4201
4202 # Baseline
4203 arg = [1, 2, 3]
4204 res = {1: None, 2: None, 3: None}
4205 self.assertEqual(dict.fromkeys(arg), res)
4206 self.assertEqual({}.fromkeys(arg), res)
4207
4208 # Now get the descriptor
4209 descr = dict.__dict__["fromkeys"]
4210
4211 # More baseline using the descriptor directly
4212 self.assertEqual(descr.__get__(None, dict)(arg), res)
4213 self.assertEqual(descr.__get__({})(arg), res)
4214
4215 # Now check various error cases
4216 try:
4217 descr.__get__(None, None)
4218 except TypeError:
4219 pass
4220 else:
4221 self.fail("shouldn't have allowed descr.__get__(None, None)")
4222 try:
4223 descr.__get__(42)
4224 except TypeError:
4225 pass
4226 else:
4227 self.fail("shouldn't have allowed descr.__get__(42)")
4228 try:
4229 descr.__get__(None, 42)
4230 except TypeError:
4231 pass
4232 else:
4233 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4234 try:
4235 descr.__get__(None, int)
4236 except TypeError:
4237 pass
4238 else:
4239 self.fail("shouldn't have allowed descr.__get__(None, int)")
4240
4241 def test_isinst_isclass(self):
4242 # Testing proxy isinstance() and isclass()...
4243 class Proxy(object):
4244 def __init__(self, obj):
4245 self.__obj = obj
4246 def __getattribute__(self, name):
4247 if name.startswith("_Proxy__"):
4248 return object.__getattribute__(self, name)
4249 else:
4250 return getattr(self.__obj, name)
4251 # Test with a classic class
4252 class C:
4253 pass
4254 a = C()
4255 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004256 self.assertIsInstance(a, C) # Baseline
4257 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004258 # Test with a classic subclass
4259 class D(C):
4260 pass
4261 a = D()
4262 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004263 self.assertIsInstance(a, C) # Baseline
4264 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004265 # Test with a new-style class
4266 class C(object):
4267 pass
4268 a = C()
4269 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004270 self.assertIsInstance(a, C) # Baseline
4271 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004272 # Test with a new-style subclass
4273 class D(C):
4274 pass
4275 a = D()
4276 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004277 self.assertIsInstance(a, C) # Baseline
4278 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004279
4280 def test_proxy_super(self):
4281 # Testing super() for a proxy object...
4282 class Proxy(object):
4283 def __init__(self, obj):
4284 self.__obj = obj
4285 def __getattribute__(self, name):
4286 if name.startswith("_Proxy__"):
4287 return object.__getattribute__(self, name)
4288 else:
4289 return getattr(self.__obj, name)
4290
4291 class B(object):
4292 def f(self):
4293 return "B.f"
4294
4295 class C(B):
4296 def f(self):
4297 return super(C, self).f() + "->C.f"
4298
4299 obj = C()
4300 p = Proxy(obj)
4301 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4302
4303 def test_carloverre(self):
4304 # Testing prohibition of Carlo Verre's hack...
4305 try:
4306 object.__setattr__(str, "foo", 42)
4307 except TypeError:
4308 pass
4309 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004310 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004311 try:
4312 object.__delattr__(str, "lower")
4313 except TypeError:
4314 pass
4315 else:
4316 self.fail("Carlo Verre __delattr__ succeeded!")
4317
4318 def test_weakref_segfault(self):
4319 # Testing weakref segfault...
4320 # SF 742911
4321 import weakref
4322
4323 class Provoker:
4324 def __init__(self, referrent):
4325 self.ref = weakref.ref(referrent)
4326
4327 def __del__(self):
4328 x = self.ref()
4329
4330 class Oops(object):
4331 pass
4332
4333 o = Oops()
4334 o.whatever = Provoker(o)
4335 del o
4336
4337 def test_wrapper_segfault(self):
4338 # SF 927248: deeply nested wrappers could cause stack overflow
4339 f = lambda:None
4340 for i in range(1000000):
4341 f = f.__call__
4342 f = None
4343
4344 def test_file_fault(self):
4345 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004346 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004347 class StdoutGuard:
4348 def __getattr__(self, attr):
4349 sys.stdout = sys.__stdout__
4350 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4351 sys.stdout = StdoutGuard()
4352 try:
4353 print("Oops!")
4354 except RuntimeError:
4355 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004356 finally:
4357 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004358
4359 def test_vicious_descriptor_nonsense(self):
4360 # Testing vicious_descriptor_nonsense...
4361
4362 # A potential segfault spotted by Thomas Wouters in mail to
4363 # python-dev 2003-04-17, turned into an example & fixed by Michael
4364 # Hudson just less than four months later...
4365
4366 class Evil(object):
4367 def __hash__(self):
4368 return hash('attr')
4369 def __eq__(self, other):
Serhiy Storchakaff3d39f2019-02-26 08:03:21 +02004370 try:
4371 del C.attr
4372 except AttributeError:
4373 # possible race condition
4374 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00004375 return 0
4376
4377 class Descr(object):
4378 def __get__(self, ob, type=None):
4379 return 1
4380
4381 class C(object):
4382 attr = Descr()
4383
4384 c = C()
4385 c.__dict__[Evil()] = 0
4386
4387 self.assertEqual(c.attr, 1)
4388 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004389 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004390 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004391
4392 def test_init(self):
4393 # SF 1155938
4394 class Foo(object):
4395 def __init__(self):
4396 return 10
4397 try:
4398 Foo()
4399 except TypeError:
4400 pass
4401 else:
4402 self.fail("did not test __init__() for None return")
4403
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004404 def assertNotOrderable(self, a, b):
4405 with self.assertRaises(TypeError):
4406 a < b
4407 with self.assertRaises(TypeError):
4408 a > b
4409 with self.assertRaises(TypeError):
4410 a <= b
4411 with self.assertRaises(TypeError):
4412 a >= b
4413
Georg Brandl479a7e72008-02-05 18:13:15 +00004414 def test_method_wrapper(self):
4415 # Testing method-wrapper objects...
4416 # <type 'method-wrapper'> did not support any reflection before 2.5
Georg Brandl479a7e72008-02-05 18:13:15 +00004417 l = []
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004418 self.assertTrue(l.__add__ == l.__add__)
4419 self.assertFalse(l.__add__ != l.__add__)
4420 self.assertFalse(l.__add__ == [].__add__)
4421 self.assertTrue(l.__add__ != [].__add__)
4422 self.assertFalse(l.__add__ == l.__mul__)
4423 self.assertTrue(l.__add__ != l.__mul__)
4424 self.assertNotOrderable(l.__add__, l.__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004425 self.assertEqual(l.__add__.__name__, '__add__')
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004426 self.assertIs(l.__add__.__self__, l)
4427 self.assertIs(l.__add__.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004428 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004429 # hash([].__add__) should not be based on hash([])
4430 hash(l.__add__)
Georg Brandl479a7e72008-02-05 18:13:15 +00004431
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004432 def test_builtin_function_or_method(self):
4433 # Not really belonging to test_descr, but introspection and
4434 # comparison on <type 'builtin_function_or_method'> seems not
4435 # to be tested elsewhere
4436 l = []
4437 self.assertTrue(l.append == l.append)
4438 self.assertFalse(l.append != l.append)
4439 self.assertFalse(l.append == [].append)
4440 self.assertTrue(l.append != [].append)
4441 self.assertFalse(l.append == l.pop)
4442 self.assertTrue(l.append != l.pop)
4443 self.assertNotOrderable(l.append, l.append)
4444 self.assertEqual(l.append.__name__, 'append')
4445 self.assertIs(l.append.__self__, l)
4446 # self.assertIs(l.append.__objclass__, list) --- could be added?
4447 self.assertEqual(l.append.__doc__, list.append.__doc__)
4448 # hash([].append) should not be based on hash([])
4449 hash(l.append)
4450
4451 def test_special_unbound_method_types(self):
4452 # Testing objects of <type 'wrapper_descriptor'>...
4453 self.assertTrue(list.__add__ == list.__add__)
4454 self.assertFalse(list.__add__ != list.__add__)
4455 self.assertFalse(list.__add__ == list.__mul__)
4456 self.assertTrue(list.__add__ != list.__mul__)
4457 self.assertNotOrderable(list.__add__, list.__add__)
4458 self.assertEqual(list.__add__.__name__, '__add__')
4459 self.assertIs(list.__add__.__objclass__, list)
4460
4461 # Testing objects of <type 'method_descriptor'>...
4462 self.assertTrue(list.append == list.append)
4463 self.assertFalse(list.append != list.append)
4464 self.assertFalse(list.append == list.pop)
4465 self.assertTrue(list.append != list.pop)
4466 self.assertNotOrderable(list.append, list.append)
4467 self.assertEqual(list.append.__name__, 'append')
4468 self.assertIs(list.append.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004469
4470 def test_not_implemented(self):
4471 # Testing NotImplemented...
4472 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004473 import operator
4474
4475 def specialmethod(self, other):
4476 return NotImplemented
4477
4478 def check(expr, x, y):
4479 try:
4480 exec(expr, {'x': x, 'y': y, 'operator': operator})
4481 except TypeError:
4482 pass
4483 else:
4484 self.fail("no TypeError from %r" % (expr,))
4485
4486 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4487 # TypeErrors
4488 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4489 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004490 for name, expr, iexpr in [
4491 ('__add__', 'x + y', 'x += y'),
4492 ('__sub__', 'x - y', 'x -= y'),
4493 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004494 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004495 ('__truediv__', 'x / y', 'x /= y'),
4496 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004497 ('__mod__', 'x % y', 'x %= y'),
4498 ('__divmod__', 'divmod(x, y)', None),
4499 ('__pow__', 'x ** y', 'x **= y'),
4500 ('__lshift__', 'x << y', 'x <<= y'),
4501 ('__rshift__', 'x >> y', 'x >>= y'),
4502 ('__and__', 'x & y', 'x &= y'),
4503 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004504 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004505 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004506 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004507 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004508 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004509 check(expr, a, N1)
4510 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004511 if iexpr:
4512 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004513 check(iexpr, a, N1)
4514 check(iexpr, a, N2)
4515 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004516 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004517 c = C()
4518 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004519 check(iexpr, c, N1)
4520 check(iexpr, c, N2)
4521
Georg Brandl479a7e72008-02-05 18:13:15 +00004522 def test_assign_slice(self):
4523 # ceval.c's assign_slice used to check for
4524 # tp->tp_as_sequence->sq_slice instead of
4525 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004526
Georg Brandl479a7e72008-02-05 18:13:15 +00004527 class C(object):
4528 def __setitem__(self, idx, value):
4529 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004530
Georg Brandl479a7e72008-02-05 18:13:15 +00004531 c = C()
4532 c[1:2] = 3
4533 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004534
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004535 def test_set_and_no_get(self):
4536 # See
4537 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4538 class Descr(object):
4539
4540 def __init__(self, name):
4541 self.name = name
4542
4543 def __set__(self, obj, value):
4544 obj.__dict__[self.name] = value
4545 descr = Descr("a")
4546
4547 class X(object):
4548 a = descr
4549
4550 x = X()
4551 self.assertIs(x.a, descr)
4552 x.a = 42
4553 self.assertEqual(x.a, 42)
4554
Benjamin Peterson21896a32010-03-21 22:03:03 +00004555 # Also check type_getattro for correctness.
4556 class Meta(type):
4557 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004558 class X(metaclass=Meta):
4559 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004560 X.a = 42
4561 Meta.a = Descr("a")
4562 self.assertEqual(X.a, 42)
4563
Benjamin Peterson9262b842008-11-17 22:45:50 +00004564 def test_getattr_hooks(self):
4565 # issue 4230
4566
4567 class Descriptor(object):
4568 counter = 0
4569 def __get__(self, obj, objtype=None):
4570 def getter(name):
4571 self.counter += 1
4572 raise AttributeError(name)
4573 return getter
4574
4575 descr = Descriptor()
4576 class A(object):
4577 __getattribute__ = descr
4578 class B(object):
4579 __getattr__ = descr
4580 class C(object):
4581 __getattribute__ = descr
4582 __getattr__ = descr
4583
4584 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004585 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004586 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004587 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004588 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004589 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004590
Benjamin Peterson9262b842008-11-17 22:45:50 +00004591 class EvilGetattribute(object):
4592 # This used to segfault
4593 def __getattr__(self, name):
4594 raise AttributeError(name)
4595 def __getattribute__(self, name):
4596 del EvilGetattribute.__getattr__
4597 for i in range(5):
4598 gc.collect()
4599 raise AttributeError(name)
4600
4601 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4602
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004603 def test_type___getattribute__(self):
4604 self.assertRaises(TypeError, type.__getattribute__, list, type)
4605
Benjamin Peterson477ba912011-01-12 15:34:01 +00004606 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004607 # type pretends not to have __abstractmethods__.
4608 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4609 class meta(type):
4610 pass
4611 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004612 class X(object):
4613 pass
4614 with self.assertRaises(AttributeError):
4615 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004616
Victor Stinner3249dec2011-05-01 23:19:15 +02004617 def test_proxy_call(self):
4618 class FakeStr:
4619 __class__ = str
4620
4621 fake_str = FakeStr()
4622 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004623 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004624
4625 # call a method descriptor
4626 with self.assertRaises(TypeError):
4627 str.split(fake_str)
4628
4629 # call a slot wrapper descriptor
4630 with self.assertRaises(TypeError):
4631 str.__add__(fake_str, "abc")
4632
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004633 def test_repr_as_str(self):
4634 # Issue #11603: crash or infinite loop when rebinding __str__ as
4635 # __repr__.
4636 class Foo:
4637 pass
4638 Foo.__repr__ = Foo.__str__
4639 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004640 self.assertRaises(RecursionError, str, foo)
4641 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004642
4643 def test_mixing_slot_wrappers(self):
4644 class X(dict):
4645 __setattr__ = dict.__setitem__
Miss Islington (bot)988fff52019-06-17 05:12:42 -07004646 __neg__ = dict.copy
Benjamin Peterson7b166872012-04-24 11:06:25 -04004647 x = X()
4648 x.y = 42
4649 self.assertEqual(x["y"], 42)
Miss Islington (bot)988fff52019-06-17 05:12:42 -07004650 self.assertEqual(x, -x)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004651
Miss Islington (bot)eb1bc482019-09-10 05:55:12 -07004652 def test_wrong_class_slot_wrapper(self):
4653 # Check bpo-37619: a wrapper descriptor taken from the wrong class
4654 # should raise an exception instead of silently being ignored
4655 class A(int):
4656 __eq__ = str.__eq__
4657 __add__ = str.__add__
4658 a = A()
4659 with self.assertRaises(TypeError):
4660 a == a
4661 with self.assertRaises(TypeError):
4662 a + a
4663
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004664 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004665 with self.assertRaises(ValueError) as cm:
4666 class X:
4667 __slots__ = ["foo"]
4668 foo = None
4669 m = str(cm.exception)
4670 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4671
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004672 def test_set_doc(self):
4673 class X:
4674 "elephant"
4675 X.__doc__ = "banana"
4676 self.assertEqual(X.__doc__, "banana")
4677 with self.assertRaises(TypeError) as cm:
4678 type(list).__dict__["__doc__"].__set__(list, "blah")
4679 self.assertIn("can't set list.__doc__", str(cm.exception))
4680 with self.assertRaises(TypeError) as cm:
4681 type(X).__dict__["__doc__"].__delete__(X)
4682 self.assertIn("can't delete X.__doc__", str(cm.exception))
4683 self.assertEqual(X.__doc__, "banana")
4684
Antoine Pitrou9d574812011-12-12 13:47:25 +01004685 def test_qualname(self):
4686 descriptors = [str.lower, complex.real, float.real, int.__add__]
4687 types = ['method', 'member', 'getset', 'wrapper']
4688
4689 # make sure we have an example of each type of descriptor
4690 for d, n in zip(descriptors, types):
4691 self.assertEqual(type(d).__name__, n + '_descriptor')
4692
4693 for d in descriptors:
4694 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4695 self.assertEqual(d.__qualname__, qualname)
4696
4697 self.assertEqual(str.lower.__qualname__, 'str.lower')
4698 self.assertEqual(complex.real.__qualname__, 'complex.real')
4699 self.assertEqual(float.real.__qualname__, 'float.real')
4700 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4701
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004702 class X:
4703 pass
4704 with self.assertRaises(TypeError):
4705 del X.__qualname__
4706
4707 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4708 str, 'Oink')
4709
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004710 global Y
4711 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004712 class Inside:
4713 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004714 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004715 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004716
Victor Stinner6f738742012-02-25 01:22:36 +01004717 def test_qualname_dict(self):
4718 ns = {'__qualname__': 'some.name'}
4719 tp = type('Foo', (), ns)
4720 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004721 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004722 self.assertEqual(ns, {'__qualname__': 'some.name'})
4723
4724 ns = {'__qualname__': 1}
4725 self.assertRaises(TypeError, type, 'Foo', (), ns)
4726
Benjamin Peterson52c42432012-03-07 18:41:11 -06004727 def test_cycle_through_dict(self):
4728 # See bug #1469629
4729 class X(dict):
4730 def __init__(self):
4731 dict.__init__(self)
4732 self.__dict__ = self
4733 x = X()
4734 x.attr = 42
4735 wr = weakref.ref(x)
4736 del x
4737 support.gc_collect()
4738 self.assertIsNone(wr())
4739 for o in gc.get_objects():
4740 self.assertIsNot(type(o), X)
4741
Benjamin Peterson96384b92012-03-17 00:05:44 -05004742 def test_object_new_and_init_with_parameters(self):
4743 # See issue #1683368
4744 class OverrideNeither:
4745 pass
4746 self.assertRaises(TypeError, OverrideNeither, 1)
4747 self.assertRaises(TypeError, OverrideNeither, kw=1)
4748 class OverrideNew:
4749 def __new__(cls, foo, kw=0, *args, **kwds):
4750 return object.__new__(cls, *args, **kwds)
4751 class OverrideInit:
4752 def __init__(self, foo, kw=0, *args, **kwargs):
4753 return object.__init__(self, *args, **kwargs)
4754 class OverrideBoth(OverrideNew, OverrideInit):
4755 pass
4756 for case in OverrideNew, OverrideInit, OverrideBoth:
4757 case(1)
4758 case(1, kw=2)
4759 self.assertRaises(TypeError, case, 1, 2, 3)
4760 self.assertRaises(TypeError, case, 1, 2, foo=3)
4761
Benjamin Petersondf813792014-03-17 15:57:17 -05004762 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4763 class Base:
4764 pass
4765 class Sub(Base):
4766 pass
4767 self.assertIn("__dict__", Base.__dict__)
4768 self.assertNotIn("__dict__", Sub.__dict__)
4769
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004770 def test_bound_method_repr(self):
4771 class Foo:
4772 def method(self):
4773 pass
4774 self.assertRegex(repr(Foo().method),
4775 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4776
4777
4778 class Base:
4779 def method(self):
4780 pass
4781 class Derived1(Base):
4782 pass
4783 class Derived2(Base):
4784 def method(self):
4785 pass
4786 base = Base()
4787 derived1 = Derived1()
4788 derived2 = Derived2()
4789 super_d2 = super(Derived2, derived2)
4790 self.assertRegex(repr(base.method),
4791 r"<bound method .*Base\.method of <.*Base object at .*>>")
4792 self.assertRegex(repr(derived1.method),
4793 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4794 self.assertRegex(repr(derived2.method),
4795 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4796 self.assertRegex(repr(super_d2.method),
4797 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4798
4799 class Foo:
4800 @classmethod
4801 def method(cls):
4802 pass
4803 foo = Foo()
4804 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004805 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004806 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004807 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004808
4809
4810 class MyCallable:
4811 def __call__(self, arg):
4812 pass
4813 func = MyCallable() # func has no __name__ or __qualname__ attributes
4814 instance = object()
4815 method = types.MethodType(func, instance)
4816 self.assertRegex(repr(method),
4817 r"<bound method \? of <object object at .*>>")
4818 func.__name__ = "name"
4819 self.assertRegex(repr(method),
4820 r"<bound method name of <object object at .*>>")
4821 func.__qualname__ = "qualname"
4822 self.assertRegex(repr(method),
4823 r"<bound method qualname of <object object at .*>>")
4824
jdemeyer5a306202018-10-19 23:50:06 +02004825 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4826 def test_bpo25750(self):
4827 # bpo-25750: calling a descriptor (implemented as built-in
4828 # function with METH_FASTCALL) should not crash CPython if the
4829 # descriptor deletes itself from the class.
4830 class Descr:
4831 __get__ = _testcapi.bad_get
4832
4833 class X:
4834 descr = Descr()
4835 def __new__(cls):
4836 cls.descr = None
4837 # Create this large list to corrupt some unused memory
4838 cls.lst = [2**i for i in range(10000)]
4839 X.descr
4840
Antoine Pitrou9d574812011-12-12 13:47:25 +01004841
Georg Brandl479a7e72008-02-05 18:13:15 +00004842class DictProxyTests(unittest.TestCase):
4843 def setUp(self):
4844 class C(object):
4845 def meth(self):
4846 pass
4847 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004848
Brett Cannon7a540732011-02-22 03:04:06 +00004849 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4850 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004851 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004852 # Testing dict-proxy keys...
4853 it = self.C.__dict__.keys()
4854 self.assertNotIsInstance(it, list)
4855 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004856 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004857 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004858 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004859
Brett Cannon7a540732011-02-22 03:04:06 +00004860 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4861 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004862 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004863 # Testing dict-proxy values...
4864 it = self.C.__dict__.values()
4865 self.assertNotIsInstance(it, list)
4866 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004867 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004868
Brett Cannon7a540732011-02-22 03:04:06 +00004869 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4870 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004871 def test_iter_items(self):
4872 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004873 it = self.C.__dict__.items()
4874 self.assertNotIsInstance(it, list)
4875 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004876 keys.sort()
4877 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004878 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004879
Georg Brandl479a7e72008-02-05 18:13:15 +00004880 def test_dict_type_with_metaclass(self):
4881 # Testing type of __dict__ when metaclass set...
4882 class B(object):
4883 pass
4884 class M(type):
4885 pass
4886 class C(metaclass=M):
4887 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4888 pass
4889 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004890
Ezio Melottiac53ab62010-12-18 14:59:43 +00004891 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004892 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004893 # We can't blindly compare with the repr of another dict as ordering
4894 # of keys and values is arbitrary and may differ.
4895 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004896 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004897 self.assertTrue(r.endswith(')'), r)
4898 for k, v in self.C.__dict__.items():
4899 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004900
Christian Heimesbbffeb62008-01-24 09:42:52 +00004901
Georg Brandl479a7e72008-02-05 18:13:15 +00004902class PTypesLongInitTest(unittest.TestCase):
4903 # This is in its own TestCase so that it can be run before any other tests.
4904 def test_pytype_long_ready(self):
4905 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004906
Georg Brandl479a7e72008-02-05 18:13:15 +00004907 # This dumps core when SF bug 551412 isn't fixed --
4908 # but only when test_descr.py is run separately.
4909 # (That can't be helped -- as soon as PyType_Ready()
4910 # is called for PyLong_Type, the bug is gone.)
4911 class UserLong(object):
4912 def __pow__(self, *args):
4913 pass
4914 try:
4915 pow(0, UserLong(), 0)
4916 except:
4917 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004918
Georg Brandl479a7e72008-02-05 18:13:15 +00004919 # Another segfault only when run early
4920 # (before PyType_Ready(tuple) is called)
4921 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004922
4923
Victor Stinnerd74782b2012-03-09 00:39:08 +01004924class MiscTests(unittest.TestCase):
4925 def test_type_lookup_mro_reference(self):
4926 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4927 # the type MRO because it may be modified during the lookup, if
4928 # __bases__ is set during the lookup for example.
4929 class MyKey(object):
4930 def __hash__(self):
4931 return hash('mykey')
4932
4933 def __eq__(self, other):
4934 X.__bases__ = (Base2,)
4935
4936 class Base(object):
4937 mykey = 'from Base'
4938 mykey2 = 'from Base'
4939
4940 class Base2(object):
4941 mykey = 'from Base2'
4942 mykey2 = 'from Base2'
4943
4944 X = type('X', (Base,), {MyKey(): 5})
4945 # mykey is read from Base
4946 self.assertEqual(X.mykey, 'from Base')
4947 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4948 self.assertEqual(X.mykey2, 'from Base2')
4949
4950
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004951class PicklingTests(unittest.TestCase):
4952
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004953 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004954 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004955 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004956 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004957 if kwargs:
4958 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4959 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004960 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004961 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4962 self.assertEqual(reduce_value[1], (type(obj),) + args)
4963 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004964 if listitems is not None:
4965 self.assertListEqual(list(reduce_value[3]), listitems)
4966 else:
4967 self.assertIsNone(reduce_value[3])
4968 if dictitems is not None:
4969 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4970 else:
4971 self.assertIsNone(reduce_value[4])
4972 else:
4973 base_type = type(obj).__base__
4974 reduce_value = (copyreg._reconstructor,
4975 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004976 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004977 None if base_type is object else base_type(obj)))
4978 if state is not None:
4979 reduce_value += (state,)
4980 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4981 self.assertEqual(obj.__reduce__(), reduce_value)
4982
4983 def test_reduce(self):
4984 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4985 args = (-101, "spam")
4986 kwargs = {'bacon': -201, 'fish': -301}
4987 state = {'cheese': -401}
4988
4989 class C1:
4990 def __getnewargs__(self):
4991 return args
4992 obj = C1()
4993 for proto in protocols:
4994 self._check_reduce(proto, obj, args)
4995
4996 for name, value in state.items():
4997 setattr(obj, name, value)
4998 for proto in protocols:
4999 self._check_reduce(proto, obj, args, state=state)
5000
5001 class C2:
5002 def __getnewargs__(self):
5003 return "bad args"
5004 obj = C2()
5005 for proto in protocols:
5006 if proto >= 2:
5007 with self.assertRaises(TypeError):
5008 obj.__reduce_ex__(proto)
5009
5010 class C3:
5011 def __getnewargs_ex__(self):
5012 return (args, kwargs)
5013 obj = C3()
5014 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03005015 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005016 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005017
5018 class C4:
5019 def __getnewargs_ex__(self):
5020 return (args, "bad dict")
5021 class C5:
5022 def __getnewargs_ex__(self):
5023 return ("bad tuple", kwargs)
5024 class C6:
5025 def __getnewargs_ex__(self):
5026 return ()
5027 class C7:
5028 def __getnewargs_ex__(self):
5029 return "bad args"
5030 for proto in protocols:
5031 for cls in C4, C5, C6, C7:
5032 obj = cls()
5033 if proto >= 2:
5034 with self.assertRaises((TypeError, ValueError)):
5035 obj.__reduce_ex__(proto)
5036
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005037 class C9:
5038 def __getnewargs_ex__(self):
5039 return (args, {})
5040 obj = C9()
5041 for proto in protocols:
5042 self._check_reduce(proto, obj, args)
5043
5044 class C10:
5045 def __getnewargs_ex__(self):
5046 raise IndexError
5047 obj = C10()
5048 for proto in protocols:
5049 if proto >= 2:
5050 with self.assertRaises(IndexError):
5051 obj.__reduce_ex__(proto)
5052
5053 class C11:
5054 def __getstate__(self):
5055 return state
5056 obj = C11()
5057 for proto in protocols:
5058 self._check_reduce(proto, obj, state=state)
5059
5060 class C12:
5061 def __getstate__(self):
5062 return "not dict"
5063 obj = C12()
5064 for proto in protocols:
5065 self._check_reduce(proto, obj, state="not dict")
5066
5067 class C13:
5068 def __getstate__(self):
5069 raise IndexError
5070 obj = C13()
5071 for proto in protocols:
5072 with self.assertRaises(IndexError):
5073 obj.__reduce_ex__(proto)
5074 if proto < 2:
5075 with self.assertRaises(IndexError):
5076 obj.__reduce__()
5077
5078 class C14:
5079 __slots__ = tuple(state)
5080 def __init__(self):
5081 for name, value in state.items():
5082 setattr(self, name, value)
5083
5084 obj = C14()
5085 for proto in protocols:
5086 if proto >= 2:
5087 self._check_reduce(proto, obj, state=(None, state))
5088 else:
5089 with self.assertRaises(TypeError):
5090 obj.__reduce_ex__(proto)
5091 with self.assertRaises(TypeError):
5092 obj.__reduce__()
5093
5094 class C15(dict):
5095 pass
5096 obj = C15({"quebec": -601})
5097 for proto in protocols:
5098 self._check_reduce(proto, obj, dictitems=dict(obj))
5099
5100 class C16(list):
5101 pass
5102 obj = C16(["yukon"])
5103 for proto in protocols:
5104 self._check_reduce(proto, obj, listitems=list(obj))
5105
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005106 def test_special_method_lookup(self):
5107 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5108 class Picky:
5109 def __getstate__(self):
5110 return {}
5111
5112 def __getattr__(self, attr):
5113 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5114 raise AssertionError(attr)
5115 return None
5116 for protocol in protocols:
5117 state = {} if protocol >= 2 else None
5118 self._check_reduce(protocol, Picky(), state=state)
5119
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005120 def _assert_is_copy(self, obj, objcopy, msg=None):
5121 """Utility method to verify if two objects are copies of each others.
5122 """
5123 if msg is None:
5124 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5125 if type(obj).__repr__ is object.__repr__:
5126 # We have this limitation for now because we use the object's repr
5127 # to help us verify that the two objects are copies. This allows
5128 # us to delegate the non-generic verification logic to the objects
5129 # themselves.
5130 raise ValueError("object passed to _assert_is_copy must " +
5131 "override the __repr__ method.")
5132 self.assertIsNot(obj, objcopy, msg=msg)
5133 self.assertIs(type(obj), type(objcopy), msg=msg)
5134 if hasattr(obj, '__dict__'):
5135 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5136 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5137 if hasattr(obj, '__slots__'):
5138 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5139 for slot in obj.__slots__:
5140 self.assertEqual(
5141 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5142 self.assertEqual(getattr(obj, slot, None),
5143 getattr(objcopy, slot, None), msg=msg)
5144 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5145
5146 @staticmethod
5147 def _generate_pickle_copiers():
5148 """Utility method to generate the many possible pickle configurations.
5149 """
5150 class PickleCopier:
5151 "This class copies object using pickle."
5152 def __init__(self, proto, dumps, loads):
5153 self.proto = proto
5154 self.dumps = dumps
5155 self.loads = loads
5156 def copy(self, obj):
5157 return self.loads(self.dumps(obj, self.proto))
5158 def __repr__(self):
5159 # We try to be as descriptive as possible here since this is
5160 # the string which we will allow us to tell the pickle
5161 # configuration we are using during debugging.
5162 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5163 .format(self.proto,
5164 self.dumps.__module__, self.dumps.__qualname__,
5165 self.loads.__module__, self.loads.__qualname__))
5166 return (PickleCopier(*args) for args in
5167 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5168 {pickle.dumps, pickle._dumps},
5169 {pickle.loads, pickle._loads}))
5170
5171 def test_pickle_slots(self):
5172 # Tests pickling of classes with __slots__.
5173
5174 # Pickling of classes with __slots__ but without __getstate__ should
5175 # fail (if using protocol 0 or 1)
5176 global C
5177 class C:
5178 __slots__ = ['a']
5179 with self.assertRaises(TypeError):
5180 pickle.dumps(C(), 0)
5181
5182 global D
5183 class D(C):
5184 pass
5185 with self.assertRaises(TypeError):
5186 pickle.dumps(D(), 0)
5187
5188 class C:
5189 "A class with __getstate__ and __setstate__ implemented."
5190 __slots__ = ['a']
5191 def __getstate__(self):
5192 state = getattr(self, '__dict__', {}).copy()
5193 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005194 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005195 try:
5196 state[slot] = getattr(self, slot)
5197 except AttributeError:
5198 pass
5199 return state
5200 def __setstate__(self, state):
5201 for k, v in state.items():
5202 setattr(self, k, v)
5203 def __repr__(self):
5204 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5205
5206 class D(C):
5207 "A subclass of a class with slots."
5208 pass
5209
5210 global E
5211 class E(C):
5212 "A subclass with an extra slot."
5213 __slots__ = ['b']
5214
5215 # Now it should work
5216 for pickle_copier in self._generate_pickle_copiers():
5217 with self.subTest(pickle_copier=pickle_copier):
5218 x = C()
5219 y = pickle_copier.copy(x)
5220 self._assert_is_copy(x, y)
5221
5222 x.a = 42
5223 y = pickle_copier.copy(x)
5224 self._assert_is_copy(x, y)
5225
5226 x = D()
5227 x.a = 42
5228 x.b = 100
5229 y = pickle_copier.copy(x)
5230 self._assert_is_copy(x, y)
5231
5232 x = E()
5233 x.a = 42
5234 x.b = "foo"
5235 y = pickle_copier.copy(x)
5236 self._assert_is_copy(x, y)
5237
5238 def test_reduce_copying(self):
5239 # Tests pickling and copying new-style classes and objects.
5240 global C1
5241 class C1:
5242 "The state of this class is copyable via its instance dict."
5243 ARGS = (1, 2)
5244 NEED_DICT_COPYING = True
5245 def __init__(self, a, b):
5246 super().__init__()
5247 self.a = a
5248 self.b = b
5249 def __repr__(self):
5250 return "C1(%r, %r)" % (self.a, self.b)
5251
5252 global C2
5253 class C2(list):
5254 "A list subclass copyable via __getnewargs__."
5255 ARGS = (1, 2)
5256 NEED_DICT_COPYING = False
5257 def __new__(cls, a, b):
5258 self = super().__new__(cls)
5259 self.a = a
5260 self.b = b
5261 return self
5262 def __init__(self, *args):
5263 super().__init__()
5264 # This helps testing that __init__ is not called during the
5265 # unpickling process, which would cause extra appends.
5266 self.append("cheese")
5267 @classmethod
5268 def __getnewargs__(cls):
5269 return cls.ARGS
5270 def __repr__(self):
5271 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5272
5273 global C3
5274 class C3(list):
5275 "A list subclass copyable via __getstate__."
5276 ARGS = (1, 2)
5277 NEED_DICT_COPYING = False
5278 def __init__(self, a, b):
5279 self.a = a
5280 self.b = b
5281 # This helps testing that __init__ is not called during the
5282 # unpickling process, which would cause extra appends.
5283 self.append("cheese")
5284 @classmethod
5285 def __getstate__(cls):
5286 return cls.ARGS
5287 def __setstate__(self, state):
5288 a, b = state
5289 self.a = a
5290 self.b = b
5291 def __repr__(self):
5292 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5293
5294 global C4
5295 class C4(int):
5296 "An int subclass copyable via __getnewargs__."
5297 ARGS = ("hello", "world", 1)
5298 NEED_DICT_COPYING = False
5299 def __new__(cls, a, b, value):
5300 self = super().__new__(cls, value)
5301 self.a = a
5302 self.b = b
5303 return self
5304 @classmethod
5305 def __getnewargs__(cls):
5306 return cls.ARGS
5307 def __repr__(self):
5308 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5309
5310 global C5
5311 class C5(int):
5312 "An int subclass copyable via __getnewargs_ex__."
5313 ARGS = (1, 2)
5314 KWARGS = {'value': 3}
5315 NEED_DICT_COPYING = False
5316 def __new__(cls, a, b, *, value=0):
5317 self = super().__new__(cls, value)
5318 self.a = a
5319 self.b = b
5320 return self
5321 @classmethod
5322 def __getnewargs_ex__(cls):
5323 return (cls.ARGS, cls.KWARGS)
5324 def __repr__(self):
5325 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5326
5327 test_classes = (C1, C2, C3, C4, C5)
5328 # Testing copying through pickle
5329 pickle_copiers = self._generate_pickle_copiers()
5330 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5331 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5332 kwargs = getattr(cls, 'KWARGS', {})
5333 obj = cls(*cls.ARGS, **kwargs)
5334 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005335 objcopy = pickle_copier.copy(obj)
5336 self._assert_is_copy(obj, objcopy)
5337 # For test classes that supports this, make sure we didn't go
5338 # around the reduce protocol by simply copying the attribute
5339 # dictionary. We clear attributes using the previous copy to
5340 # not mutate the original argument.
5341 if proto >= 2 and not cls.NEED_DICT_COPYING:
5342 objcopy.__dict__.clear()
5343 objcopy2 = pickle_copier.copy(objcopy)
5344 self._assert_is_copy(obj, objcopy2)
5345
5346 # Testing copying through copy.deepcopy()
5347 for cls in test_classes:
5348 with self.subTest(cls=cls):
5349 kwargs = getattr(cls, 'KWARGS', {})
5350 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005351 objcopy = deepcopy(obj)
5352 self._assert_is_copy(obj, objcopy)
5353 # For test classes that supports this, make sure we didn't go
5354 # around the reduce protocol by simply copying the attribute
5355 # dictionary. We clear attributes using the previous copy to
5356 # not mutate the original argument.
5357 if not cls.NEED_DICT_COPYING:
5358 objcopy.__dict__.clear()
5359 objcopy2 = deepcopy(objcopy)
5360 self._assert_is_copy(obj, objcopy2)
5361
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005362 def test_issue24097(self):
5363 # Slot name is freed inside __getattr__ and is later used.
5364 class S(str): # Not interned
5365 pass
5366 class A:
5367 __slotnames__ = [S('spam')]
5368 def __getattr__(self, attr):
5369 if attr == 'spam':
5370 A.__slotnames__[:] = [S('spam')]
5371 return 42
5372 else:
5373 raise AttributeError
5374
5375 import copyreg
5376 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005377 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5378
5379 def test_object_reduce(self):
5380 # Issue #29914
5381 # __reduce__() takes no arguments
5382 object().__reduce__()
5383 with self.assertRaises(TypeError):
5384 object().__reduce__(0)
5385 # __reduce_ex__() takes one integer argument
5386 object().__reduce_ex__(0)
5387 with self.assertRaises(TypeError):
5388 object().__reduce_ex__()
5389 with self.assertRaises(TypeError):
5390 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005391
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005392
Benjamin Peterson2a605342014-03-17 16:20:12 -05005393class SharedKeyTests(unittest.TestCase):
5394
5395 @support.cpython_only
5396 def test_subclasses(self):
5397 # Verify that subclasses can share keys (per PEP 412)
5398 class A:
5399 pass
5400 class B(A):
5401 pass
5402
5403 a, b = A(), B()
5404 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
Inada Naokif2a18672019-03-12 17:25:44 +09005405 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005406 # Initial hash table can contain at most 5 elements.
5407 # Set 6 attributes to cause internal resizing.
5408 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005409 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5410 a2 = A()
5411 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
Inada Naokif2a18672019-03-12 17:25:44 +09005412 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005413 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Inada Naokif2a18672019-03-12 17:25:44 +09005414 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
Benjamin Peterson2a605342014-03-17 16:20:12 -05005415
5416
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005417class DebugHelperMeta(type):
5418 """
5419 Sets default __doc__ and simplifies repr() output.
5420 """
5421 def __new__(mcls, name, bases, attrs):
5422 if attrs.get('__doc__') is None:
5423 attrs['__doc__'] = name # helps when debugging with gdb
5424 return type.__new__(mcls, name, bases, attrs)
5425 def __repr__(cls):
5426 return repr(cls.__name__)
5427
5428
5429class MroTest(unittest.TestCase):
5430 """
5431 Regressions for some bugs revealed through
5432 mcsl.mro() customization (typeobject.c: mro_internal()) and
5433 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5434 """
5435
5436 def setUp(self):
5437 self.step = 0
5438 self.ready = False
5439
5440 def step_until(self, limit):
5441 ret = (self.step < limit)
5442 if ret:
5443 self.step += 1
5444 return ret
5445
5446 def test_incomplete_set_bases_on_self(self):
5447 """
5448 type_set_bases must be aware that type->tp_mro can be NULL.
5449 """
5450 class M(DebugHelperMeta):
5451 def mro(cls):
5452 if self.step_until(1):
5453 assert cls.__mro__ is None
5454 cls.__bases__ += ()
5455
5456 return type.mro(cls)
5457
5458 class A(metaclass=M):
5459 pass
5460
5461 def test_reent_set_bases_on_base(self):
5462 """
5463 Deep reentrancy must not over-decref old_mro.
5464 """
5465 class M(DebugHelperMeta):
5466 def mro(cls):
5467 if cls.__mro__ is not None and cls.__name__ == 'B':
5468 # 4-5 steps are usually enough to make it crash somewhere
5469 if self.step_until(10):
5470 A.__bases__ += ()
5471
5472 return type.mro(cls)
5473
5474 class A(metaclass=M):
5475 pass
5476 class B(A):
5477 pass
5478 B.__bases__ += ()
5479
5480 def test_reent_set_bases_on_direct_base(self):
5481 """
5482 Similar to test_reent_set_bases_on_base, but may crash differently.
5483 """
5484 class M(DebugHelperMeta):
5485 def mro(cls):
5486 base = cls.__bases__[0]
5487 if base is not object:
5488 if self.step_until(5):
5489 base.__bases__ += ()
5490
5491 return type.mro(cls)
5492
5493 class A(metaclass=M):
5494 pass
5495 class B(A):
5496 pass
5497 class C(B):
5498 pass
5499
5500 def test_reent_set_bases_tp_base_cycle(self):
5501 """
5502 type_set_bases must check for an inheritance cycle not only through
5503 MRO of the type, which may be not yet updated in case of reentrance,
5504 but also through tp_base chain, which is assigned before diving into
5505 inner calls to mro().
5506
5507 Otherwise, the following snippet can loop forever:
5508 do {
5509 // ...
5510 type = type->tp_base;
5511 } while (type != NULL);
5512
5513 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5514 would not be happy in that case, causing a stack overflow.
5515 """
5516 class M(DebugHelperMeta):
5517 def mro(cls):
5518 if self.ready:
5519 if cls.__name__ == 'B1':
5520 B2.__bases__ = (B1,)
5521 if cls.__name__ == 'B2':
5522 B1.__bases__ = (B2,)
5523 return type.mro(cls)
5524
5525 class A(metaclass=M):
5526 pass
5527 class B1(A):
5528 pass
5529 class B2(A):
5530 pass
5531
5532 self.ready = True
5533 with self.assertRaises(TypeError):
5534 B1.__bases__ += ()
5535
5536 def test_tp_subclasses_cycle_in_update_slots(self):
5537 """
5538 type_set_bases must check for reentrancy upon finishing its job
5539 by updating tp_subclasses of old/new bases of the type.
5540 Otherwise, an implicit inheritance cycle through tp_subclasses
5541 can break functions that recurse on elements of that field
5542 (like recurse_down_subclasses and mro_hierarchy) eventually
5543 leading to a stack overflow.
5544 """
5545 class M(DebugHelperMeta):
5546 def mro(cls):
5547 if self.ready and cls.__name__ == 'C':
5548 self.ready = False
5549 C.__bases__ = (B2,)
5550 return type.mro(cls)
5551
5552 class A(metaclass=M):
5553 pass
5554 class B1(A):
5555 pass
5556 class B2(A):
5557 pass
5558 class C(A):
5559 pass
5560
5561 self.ready = True
5562 C.__bases__ = (B1,)
5563 B1.__bases__ = (C,)
5564
5565 self.assertEqual(C.__bases__, (B2,))
5566 self.assertEqual(B2.__subclasses__(), [C])
5567 self.assertEqual(B1.__subclasses__(), [])
5568
5569 self.assertEqual(B1.__bases__, (C,))
5570 self.assertEqual(C.__subclasses__(), [B1])
5571
5572 def test_tp_subclasses_cycle_error_return_path(self):
5573 """
5574 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5575 a code path executed on error (goto bail).
5576 """
5577 class E(Exception):
5578 pass
5579 class M(DebugHelperMeta):
5580 def mro(cls):
5581 if self.ready and cls.__name__ == 'C':
5582 if C.__bases__ == (B2,):
5583 self.ready = False
5584 else:
5585 C.__bases__ = (B2,)
5586 raise E
5587 return type.mro(cls)
5588
5589 class A(metaclass=M):
5590 pass
5591 class B1(A):
5592 pass
5593 class B2(A):
5594 pass
5595 class C(A):
5596 pass
5597
5598 self.ready = True
5599 with self.assertRaises(E):
5600 C.__bases__ = (B1,)
5601 B1.__bases__ = (C,)
5602
5603 self.assertEqual(C.__bases__, (B2,))
5604 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5605
5606 def test_incomplete_extend(self):
5607 """
5608 Extending an unitialized type with type->tp_mro == NULL must
5609 throw a reasonable TypeError exception, instead of failing
5610 with PyErr_BadInternalCall.
5611 """
5612 class M(DebugHelperMeta):
5613 def mro(cls):
5614 if cls.__mro__ is None and cls.__name__ != 'X':
5615 with self.assertRaises(TypeError):
5616 class X(cls):
5617 pass
5618
5619 return type.mro(cls)
5620
5621 class A(metaclass=M):
5622 pass
5623
5624 def test_incomplete_super(self):
5625 """
5626 Attrubute lookup on a super object must be aware that
5627 its target type can be uninitialized (type->tp_mro == NULL).
5628 """
5629 class M(DebugHelperMeta):
5630 def mro(cls):
5631 if cls.__mro__ is None:
5632 with self.assertRaises(AttributeError):
5633 super(cls, cls).xxx
5634
5635 return type.mro(cls)
5636
5637 class A(metaclass=M):
5638 pass
5639
5640
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005641def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005642 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005643 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005644 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005645 MiscTests, PicklingTests, SharedKeyTests,
5646 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005647
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005648if __name__ == "__main__":
5649 test_main()