blob: e37a98417f505cb257e9abcf0d1e6df92306e055 [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
392class ClassPropertiesAndMethods(unittest.TestCase):
393
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200394 def assertHasAttr(self, obj, name):
395 self.assertTrue(hasattr(obj, name),
396 '%r has no attribute %r' % (obj, name))
397
398 def assertNotHasAttr(self, obj, name):
399 self.assertFalse(hasattr(obj, name),
400 '%r has unexpected attribute %r' % (obj, name))
401
Georg Brandl479a7e72008-02-05 18:13:15 +0000402 def test_python_dicts(self):
403 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000404 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000405 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000406 d = dict()
407 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200408 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000409 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000410 class C(dict):
411 state = -1
412 def __init__(self_local, *a, **kw):
413 if a:
414 self.assertEqual(len(a), 1)
415 self_local.state = a[0]
416 if kw:
417 for k, v in list(kw.items()):
418 self_local[v] = k
419 def __getitem__(self, key):
420 return self.get(key, 0)
421 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000422 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000423 dict.__setitem__(self_local, key, value)
424 def setstate(self, state):
425 self.state = state
426 def getstate(self):
427 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000428 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000429 a1 = C(12)
430 self.assertEqual(a1.state, 12)
431 a2 = C(foo=1, bar=2)
432 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
433 a = C()
434 self.assertEqual(a.state, -1)
435 self.assertEqual(a.getstate(), -1)
436 a.setstate(0)
437 self.assertEqual(a.state, 0)
438 self.assertEqual(a.getstate(), 0)
439 a.setstate(10)
440 self.assertEqual(a.state, 10)
441 self.assertEqual(a.getstate(), 10)
442 self.assertEqual(a[42], 0)
443 a[42] = 24
444 self.assertEqual(a[42], 24)
445 N = 50
446 for i in range(N):
447 a[i] = C()
448 for j in range(N):
449 a[i][j] = i*j
450 for i in range(N):
451 for j in range(N):
452 self.assertEqual(a[i][j], i*j)
453
454 def test_python_lists(self):
455 # Testing Python subclass of list...
456 class C(list):
457 def __getitem__(self, i):
458 if isinstance(i, slice):
459 return i.start, i.stop
460 return list.__getitem__(self, i) + 100
461 a = C()
462 a.extend([0,1,2])
463 self.assertEqual(a[0], 100)
464 self.assertEqual(a[1], 101)
465 self.assertEqual(a[2], 102)
466 self.assertEqual(a[100:200], (100,200))
467
468 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000469 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000470 class C(metaclass=type):
471 def __init__(self):
472 self.__state = 0
473 def getstate(self):
474 return self.__state
475 def setstate(self, state):
476 self.__state = state
477 a = C()
478 self.assertEqual(a.getstate(), 0)
479 a.setstate(10)
480 self.assertEqual(a.getstate(), 10)
481 class _metaclass(type):
482 def myself(cls): return cls
483 class D(metaclass=_metaclass):
484 pass
485 self.assertEqual(D.myself(), D)
486 d = D()
487 self.assertEqual(d.__class__, D)
488 class M1(type):
489 def __new__(cls, name, bases, dict):
490 dict['__spam__'] = 1
491 return type.__new__(cls, name, bases, dict)
492 class C(metaclass=M1):
493 pass
494 self.assertEqual(C.__spam__, 1)
495 c = C()
496 self.assertEqual(c.__spam__, 1)
497
498 class _instance(object):
499 pass
500 class M2(object):
501 @staticmethod
502 def __new__(cls, name, bases, dict):
503 self = object.__new__(cls)
504 self.name = name
505 self.bases = bases
506 self.dict = dict
507 return self
508 def __call__(self):
509 it = _instance()
510 # Early binding of methods
511 for key in self.dict:
512 if key.startswith("__"):
513 continue
514 setattr(it, key, self.dict[key].__get__(it, self))
515 return it
516 class C(metaclass=M2):
517 def spam(self):
518 return 42
519 self.assertEqual(C.name, 'C')
520 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000521 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000522 c = C()
523 self.assertEqual(c.spam(), 42)
524
525 # More metaclass examples
526
527 class autosuper(type):
528 # Automatically add __super to the class
529 # This trick only works for dynamic classes
530 def __new__(metaclass, name, bases, dict):
531 cls = super(autosuper, metaclass).__new__(metaclass,
532 name, bases, dict)
533 # Name mangling for __super removes leading underscores
534 while name[:1] == "_":
535 name = name[1:]
536 if name:
537 name = "_%s__super" % name
538 else:
539 name = "__super"
540 setattr(cls, name, super(cls))
541 return cls
542 class A(metaclass=autosuper):
543 def meth(self):
544 return "A"
545 class B(A):
546 def meth(self):
547 return "B" + self.__super.meth()
548 class C(A):
549 def meth(self):
550 return "C" + self.__super.meth()
551 class D(C, B):
552 def meth(self):
553 return "D" + self.__super.meth()
554 self.assertEqual(D().meth(), "DCBA")
555 class E(B, C):
556 def meth(self):
557 return "E" + self.__super.meth()
558 self.assertEqual(E().meth(), "EBCA")
559
560 class autoproperty(type):
561 # Automatically create property attributes when methods
562 # named _get_x and/or _set_x are found
563 def __new__(metaclass, name, bases, dict):
564 hits = {}
565 for key, val in dict.items():
566 if key.startswith("_get_"):
567 key = key[5:]
568 get, set = hits.get(key, (None, None))
569 get = val
570 hits[key] = get, set
571 elif key.startswith("_set_"):
572 key = key[5:]
573 get, set = hits.get(key, (None, None))
574 set = val
575 hits[key] = get, set
576 for key, (get, set) in hits.items():
577 dict[key] = property(get, set)
578 return super(autoproperty, metaclass).__new__(metaclass,
579 name, bases, dict)
580 class A(metaclass=autoproperty):
581 def _get_x(self):
582 return -self.__x
583 def _set_x(self, x):
584 self.__x = -x
585 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200586 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000587 a.x = 12
588 self.assertEqual(a.x, 12)
589 self.assertEqual(a._A__x, -12)
590
591 class multimetaclass(autoproperty, autosuper):
592 # Merge of multiple cooperating metaclasses
593 pass
594 class A(metaclass=multimetaclass):
595 def _get_x(self):
596 return "A"
597 class B(A):
598 def _get_x(self):
599 return "B" + self.__super._get_x()
600 class C(A):
601 def _get_x(self):
602 return "C" + self.__super._get_x()
603 class D(C, B):
604 def _get_x(self):
605 return "D" + self.__super._get_x()
606 self.assertEqual(D().x, "DCBA")
607
608 # Make sure type(x) doesn't call x.__class__.__init__
609 class T(type):
610 counter = 0
611 def __init__(self, *args):
612 T.counter += 1
613 class C(metaclass=T):
614 pass
615 self.assertEqual(T.counter, 1)
616 a = C()
617 self.assertEqual(type(a), C)
618 self.assertEqual(T.counter, 1)
619
620 class C(object): pass
621 c = C()
622 try: c()
623 except TypeError: pass
624 else: self.fail("calling object w/o call method should raise "
625 "TypeError")
626
627 # Testing code to find most derived baseclass
628 class A(type):
629 def __new__(*args, **kwargs):
630 return type.__new__(*args, **kwargs)
631
632 class B(object):
633 pass
634
635 class C(object, metaclass=A):
636 pass
637
638 # The most derived metaclass of D is A rather than type.
639 class D(B, C):
640 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000641 self.assertIs(A, type(D))
642
643 # issue1294232: correct metaclass calculation
644 new_calls = [] # to check the order of __new__ calls
645 class AMeta(type):
646 @staticmethod
647 def __new__(mcls, name, bases, ns):
648 new_calls.append('AMeta')
649 return super().__new__(mcls, name, bases, ns)
650 @classmethod
651 def __prepare__(mcls, name, bases):
652 return {}
653
654 class BMeta(AMeta):
655 @staticmethod
656 def __new__(mcls, name, bases, ns):
657 new_calls.append('BMeta')
658 return super().__new__(mcls, name, bases, ns)
659 @classmethod
660 def __prepare__(mcls, name, bases):
661 ns = super().__prepare__(name, bases)
662 ns['BMeta_was_here'] = True
663 return ns
664
665 class A(metaclass=AMeta):
666 pass
667 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000668 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000669
670 class B(metaclass=BMeta):
671 pass
672 # BMeta.__new__ calls AMeta.__new__ with super:
673 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000674 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000675
676 class C(A, B):
677 pass
678 # The most derived metaclass is BMeta:
679 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000680 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000681 # BMeta.__prepare__ should've been called:
682 self.assertIn('BMeta_was_here', C.__dict__)
683
684 # The order of the bases shouldn't matter:
685 class C2(B, A):
686 pass
687 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000688 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000689 self.assertIn('BMeta_was_here', C2.__dict__)
690
691 # Check correct metaclass calculation when a metaclass is declared:
692 class D(C, metaclass=type):
693 pass
694 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000695 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000696 self.assertIn('BMeta_was_here', D.__dict__)
697
698 class E(C, metaclass=AMeta):
699 pass
700 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000701 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000702 self.assertIn('BMeta_was_here', E.__dict__)
703
704 # Special case: the given metaclass isn't a class,
705 # so there is no metaclass calculation.
706 marker = object()
707 def func(*args, **kwargs):
708 return marker
709 class X(metaclass=func):
710 pass
711 class Y(object, metaclass=func):
712 pass
713 class Z(D, metaclass=func):
714 pass
715 self.assertIs(marker, X)
716 self.assertIs(marker, Y)
717 self.assertIs(marker, Z)
718
719 # The given metaclass is a class,
720 # but not a descendant of type.
721 prepare_calls = [] # to track __prepare__ calls
722 class ANotMeta:
723 def __new__(mcls, *args, **kwargs):
724 new_calls.append('ANotMeta')
725 return super().__new__(mcls)
726 @classmethod
727 def __prepare__(mcls, name, bases):
728 prepare_calls.append('ANotMeta')
729 return {}
730 class BNotMeta(ANotMeta):
731 def __new__(mcls, *args, **kwargs):
732 new_calls.append('BNotMeta')
733 return super().__new__(mcls)
734 @classmethod
735 def __prepare__(mcls, name, bases):
736 prepare_calls.append('BNotMeta')
737 return super().__prepare__(name, bases)
738
739 class A(metaclass=ANotMeta):
740 pass
741 self.assertIs(ANotMeta, type(A))
742 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000743 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000744 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000745 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000746
747 class B(metaclass=BNotMeta):
748 pass
749 self.assertIs(BNotMeta, type(B))
750 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000751 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000752 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000753 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000754
755 class C(A, B):
756 pass
757 self.assertIs(BNotMeta, type(C))
758 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000759 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000760 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000761 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000762
763 class C2(B, A):
764 pass
765 self.assertIs(BNotMeta, type(C2))
766 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000767 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000768 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000769 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000770
771 # This is a TypeError, because of a metaclass conflict:
772 # BNotMeta is neither a subclass, nor a superclass of type
773 with self.assertRaises(TypeError):
774 class D(C, metaclass=type):
775 pass
776
777 class E(C, metaclass=ANotMeta):
778 pass
779 self.assertIs(BNotMeta, type(E))
780 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000781 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000782 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000783 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000784
785 class F(object(), C):
786 pass
787 self.assertIs(BNotMeta, type(F))
788 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000789 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000790 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000791 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000792
793 class F2(C, object()):
794 pass
795 self.assertIs(BNotMeta, type(F2))
796 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000797 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000798 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000799 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000800
801 # TypeError: BNotMeta is neither a
802 # subclass, nor a superclass of int
803 with self.assertRaises(TypeError):
804 class X(C, int()):
805 pass
806 with self.assertRaises(TypeError):
807 class X(int(), C):
808 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000809
810 def test_module_subclasses(self):
811 # Testing Python subclass of module...
812 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000813 MT = type(sys)
814 class MM(MT):
815 def __init__(self, name):
816 MT.__init__(self, name)
817 def __getattribute__(self, name):
818 log.append(("getattr", name))
819 return MT.__getattribute__(self, name)
820 def __setattr__(self, name, value):
821 log.append(("setattr", name, value))
822 MT.__setattr__(self, name, value)
823 def __delattr__(self, name):
824 log.append(("delattr", name))
825 MT.__delattr__(self, name)
826 a = MM("a")
827 a.foo = 12
828 x = a.foo
829 del a.foo
830 self.assertEqual(log, [("setattr", "foo", 12),
831 ("getattr", "foo"),
832 ("delattr", "foo")])
833
834 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000835 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000836 class Module(types.ModuleType, str):
837 pass
838 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000839 pass
840 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000841 self.fail("inheriting from ModuleType and str at the same time "
842 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000843
Georg Brandl479a7e72008-02-05 18:13:15 +0000844 def test_multiple_inheritance(self):
845 # Testing multiple inheritance...
846 class C(object):
847 def __init__(self):
848 self.__state = 0
849 def getstate(self):
850 return self.__state
851 def setstate(self, state):
852 self.__state = state
853 a = C()
854 self.assertEqual(a.getstate(), 0)
855 a.setstate(10)
856 self.assertEqual(a.getstate(), 10)
857 class D(dict, C):
858 def __init__(self):
859 type({}).__init__(self)
860 C.__init__(self)
861 d = D()
862 self.assertEqual(list(d.keys()), [])
863 d["hello"] = "world"
864 self.assertEqual(list(d.items()), [("hello", "world")])
865 self.assertEqual(d["hello"], "world")
866 self.assertEqual(d.getstate(), 0)
867 d.setstate(10)
868 self.assertEqual(d.getstate(), 10)
869 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000870
Georg Brandl479a7e72008-02-05 18:13:15 +0000871 # SF bug #442833
872 class Node(object):
873 def __int__(self):
874 return int(self.foo())
875 def foo(self):
876 return "23"
877 class Frag(Node, list):
878 def foo(self):
879 return "42"
880 self.assertEqual(Node().__int__(), 23)
881 self.assertEqual(int(Node()), 23)
882 self.assertEqual(Frag().__int__(), 42)
883 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000884
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700885 def test_diamond_inheritance(self):
Georg Brandl479a7e72008-02-05 18:13:15 +0000886 # Testing multiple inheritance special cases...
887 class A(object):
888 def spam(self): return "A"
889 self.assertEqual(A().spam(), "A")
890 class B(A):
891 def boo(self): return "B"
892 def spam(self): return "B"
893 self.assertEqual(B().spam(), "B")
894 self.assertEqual(B().boo(), "B")
895 class C(A):
896 def boo(self): return "C"
897 self.assertEqual(C().spam(), "A")
898 self.assertEqual(C().boo(), "C")
899 class D(B, C): pass
900 self.assertEqual(D().spam(), "B")
901 self.assertEqual(D().boo(), "B")
902 self.assertEqual(D.__mro__, (D, B, C, A, object))
903 class E(C, B): pass
904 self.assertEqual(E().spam(), "B")
905 self.assertEqual(E().boo(), "C")
906 self.assertEqual(E.__mro__, (E, C, B, A, object))
907 # MRO order disagreement
908 try:
909 class F(D, E): pass
910 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000911 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000912 else:
913 self.fail("expected MRO order disagreement (F)")
914 try:
915 class G(E, D): pass
916 except TypeError:
917 pass
918 else:
919 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000920
Georg Brandl479a7e72008-02-05 18:13:15 +0000921 # see thread python-dev/2002-October/029035.html
922 def test_ex5_from_c3_switch(self):
923 # Testing ex5 from C3 switch discussion...
924 class A(object): pass
925 class B(object): pass
926 class C(object): pass
927 class X(A): pass
928 class Y(A): pass
929 class Z(X,B,Y,C): pass
930 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931
Georg Brandl479a7e72008-02-05 18:13:15 +0000932 # see "A Monotonic Superclass Linearization for Dylan",
933 # by Kim Barrett et al. (OOPSLA 1996)
934 def test_monotonicity(self):
935 # Testing MRO monotonicity...
936 class Boat(object): pass
937 class DayBoat(Boat): pass
938 class WheelBoat(Boat): pass
939 class EngineLess(DayBoat): pass
940 class SmallMultihull(DayBoat): pass
941 class PedalWheelBoat(EngineLess,WheelBoat): pass
942 class SmallCatamaran(SmallMultihull): pass
943 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000944
Georg Brandl479a7e72008-02-05 18:13:15 +0000945 self.assertEqual(PedalWheelBoat.__mro__,
946 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
947 self.assertEqual(SmallCatamaran.__mro__,
948 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
949 self.assertEqual(Pedalo.__mro__,
950 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
951 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000952
Georg Brandl479a7e72008-02-05 18:13:15 +0000953 # see "A Monotonic Superclass Linearization for Dylan",
954 # by Kim Barrett et al. (OOPSLA 1996)
955 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200956 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000957 class Pane(object): pass
958 class ScrollingMixin(object): pass
959 class EditingMixin(object): pass
960 class ScrollablePane(Pane,ScrollingMixin): pass
961 class EditablePane(Pane,EditingMixin): pass
962 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000963
Georg Brandl479a7e72008-02-05 18:13:15 +0000964 self.assertEqual(EditableScrollablePane.__mro__,
965 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
966 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000967
Georg Brandl479a7e72008-02-05 18:13:15 +0000968 def test_mro_disagreement(self):
969 # Testing error messages for MRO disagreement...
970 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000971order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000972
Georg Brandl479a7e72008-02-05 18:13:15 +0000973 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000974 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000975 callable(*args)
976 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000977 # the exact msg is generally considered an impl detail
978 if support.check_impl_detail():
979 if not str(msg).startswith(expected):
980 self.fail("Message %r, expected %r" %
981 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000982 else:
983 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000984
Georg Brandl479a7e72008-02-05 18:13:15 +0000985 class A(object): pass
986 class B(A): pass
987 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000988
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 # Test some very simple errors
990 raises(TypeError, "duplicate base class A",
991 type, "X", (A, A), {})
992 raises(TypeError, mro_err_msg,
993 type, "X", (A, B), {})
994 raises(TypeError, mro_err_msg,
995 type, "X", (A, C, B), {})
996 # Test a slightly more complex error
997 class GridLayout(object): pass
998 class HorizontalGrid(GridLayout): pass
999 class VerticalGrid(GridLayout): pass
1000 class HVGrid(HorizontalGrid, VerticalGrid): pass
1001 class VHGrid(VerticalGrid, HorizontalGrid): pass
1002 raises(TypeError, mro_err_msg,
1003 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +00001004
Georg Brandl479a7e72008-02-05 18:13:15 +00001005 def test_object_class(self):
1006 # Testing object class...
1007 a = object()
1008 self.assertEqual(a.__class__, object)
1009 self.assertEqual(type(a), object)
1010 b = object()
1011 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001012 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001013 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001014 a.foo = 12
1015 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001016 pass
1017 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001019 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001020
Georg Brandl479a7e72008-02-05 18:13:15 +00001021 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001022 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001023 x = Cdict()
1024 self.assertEqual(x.__dict__, {})
1025 x.foo = 1
1026 self.assertEqual(x.foo, 1)
1027 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001029 def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1030 class SubType(types.ModuleType):
1031 a = 1
1032
1033 m = types.ModuleType("m")
1034 self.assertTrue(m.__class__ is types.ModuleType)
1035 self.assertFalse(hasattr(m, "a"))
1036
1037 m.__class__ = SubType
1038 self.assertTrue(m.__class__ is SubType)
1039 self.assertTrue(hasattr(m, "a"))
1040
1041 m.__class__ = types.ModuleType
1042 self.assertTrue(m.__class__ is types.ModuleType)
1043 self.assertFalse(hasattr(m, "a"))
1044
Guido van Rossum7d293ee2015-09-04 20:54:07 -07001045 # Make sure that builtin immutable objects don't support __class__
1046 # assignment, because the object instances may be interned.
1047 # We set __slots__ = () to ensure that the subclasses are
1048 # memory-layout compatible, and thus otherwise reasonable candidates
1049 # for __class__ assignment.
1050
1051 # The following types have immutable instances, but are not
1052 # subclassable and thus don't need to be checked:
1053 # NoneType, bool
1054
1055 class MyInt(int):
1056 __slots__ = ()
1057 with self.assertRaises(TypeError):
1058 (1).__class__ = MyInt
1059
1060 class MyFloat(float):
1061 __slots__ = ()
1062 with self.assertRaises(TypeError):
1063 (1.0).__class__ = MyFloat
1064
1065 class MyComplex(complex):
1066 __slots__ = ()
1067 with self.assertRaises(TypeError):
1068 (1 + 2j).__class__ = MyComplex
1069
1070 class MyStr(str):
1071 __slots__ = ()
1072 with self.assertRaises(TypeError):
1073 "a".__class__ = MyStr
1074
1075 class MyBytes(bytes):
1076 __slots__ = ()
1077 with self.assertRaises(TypeError):
1078 b"a".__class__ = MyBytes
1079
1080 class MyTuple(tuple):
1081 __slots__ = ()
1082 with self.assertRaises(TypeError):
1083 ().__class__ = MyTuple
1084
1085 class MyFrozenSet(frozenset):
1086 __slots__ = ()
1087 with self.assertRaises(TypeError):
1088 frozenset().__class__ = MyFrozenSet
1089
Georg Brandl479a7e72008-02-05 18:13:15 +00001090 def test_slots(self):
1091 # Testing __slots__...
1092 class C0(object):
1093 __slots__ = []
1094 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001095 self.assertNotHasAttr(x, "__dict__")
1096 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001097
1098 class C1(object):
1099 __slots__ = ['a']
1100 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001101 self.assertNotHasAttr(x, "__dict__")
1102 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001103 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001104 self.assertEqual(x.a, 1)
1105 x.a = None
1106 self.assertEqual(x.a, None)
1107 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001108 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001109
Georg Brandl479a7e72008-02-05 18:13:15 +00001110 class C3(object):
1111 __slots__ = ['a', 'b', 'c']
1112 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001113 self.assertNotHasAttr(x, "__dict__")
1114 self.assertNotHasAttr(x, 'a')
1115 self.assertNotHasAttr(x, 'b')
1116 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001117 x.a = 1
1118 x.b = 2
1119 x.c = 3
1120 self.assertEqual(x.a, 1)
1121 self.assertEqual(x.b, 2)
1122 self.assertEqual(x.c, 3)
1123
1124 class C4(object):
1125 """Validate name mangling"""
1126 __slots__ = ['__a']
1127 def __init__(self, value):
1128 self.__a = value
1129 def get(self):
1130 return self.__a
1131 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001132 self.assertNotHasAttr(x, '__dict__')
1133 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001134 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001135 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001136 x.__a = 6
1137 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001138 pass
1139 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001140 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001141
Georg Brandl479a7e72008-02-05 18:13:15 +00001142 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001143 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001144 class C(object):
1145 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001146 except TypeError:
1147 pass
1148 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001149 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001150 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001151 class C(object):
1152 __slots__ = ["foo bar"]
1153 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001154 pass
1155 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001156 self.fail("['foo bar'] slots not caught")
1157 try:
1158 class C(object):
1159 __slots__ = ["foo\0bar"]
1160 except TypeError:
1161 pass
1162 else:
1163 self.fail("['foo\\0bar'] slots not caught")
1164 try:
1165 class C(object):
1166 __slots__ = ["1"]
1167 except TypeError:
1168 pass
1169 else:
1170 self.fail("['1'] slots not caught")
1171 try:
1172 class C(object):
1173 __slots__ = [""]
1174 except TypeError:
1175 pass
1176 else:
1177 self.fail("[''] slots not caught")
1178 class C(object):
1179 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1180 # XXX(nnorwitz): was there supposed to be something tested
1181 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001182
Georg Brandl479a7e72008-02-05 18:13:15 +00001183 # Test a single string is not expanded as a sequence.
1184 class C(object):
1185 __slots__ = "abc"
1186 c = C()
1187 c.abc = 5
1188 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001189
Georg Brandl479a7e72008-02-05 18:13:15 +00001190 # Test unicode slot names
1191 # Test a single unicode string is not expanded as a sequence.
1192 class C(object):
1193 __slots__ = "abc"
1194 c = C()
1195 c.abc = 5
1196 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001197
Georg Brandl479a7e72008-02-05 18:13:15 +00001198 # _unicode_to_string used to modify slots in certain circumstances
1199 slots = ("foo", "bar")
1200 class C(object):
1201 __slots__ = slots
1202 x = C()
1203 x.foo = 5
1204 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001205 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001206 # this used to leak references
1207 try:
1208 class C(object):
1209 __slots__ = [chr(128)]
1210 except (TypeError, UnicodeEncodeError):
1211 pass
1212 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001213 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001214
Georg Brandl479a7e72008-02-05 18:13:15 +00001215 # Test leaks
1216 class Counted(object):
1217 counter = 0 # counts the number of instances alive
1218 def __init__(self):
1219 Counted.counter += 1
1220 def __del__(self):
1221 Counted.counter -= 1
1222 class C(object):
1223 __slots__ = ['a', 'b', 'c']
1224 x = C()
1225 x.a = Counted()
1226 x.b = Counted()
1227 x.c = Counted()
1228 self.assertEqual(Counted.counter, 3)
1229 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001230 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001231 self.assertEqual(Counted.counter, 0)
1232 class D(C):
1233 pass
1234 x = D()
1235 x.a = Counted()
1236 x.z = Counted()
1237 self.assertEqual(Counted.counter, 2)
1238 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001239 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001240 self.assertEqual(Counted.counter, 0)
1241 class E(D):
1242 __slots__ = ['e']
1243 x = E()
1244 x.a = Counted()
1245 x.z = Counted()
1246 x.e = Counted()
1247 self.assertEqual(Counted.counter, 3)
1248 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001249 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001250 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001251
Georg Brandl479a7e72008-02-05 18:13:15 +00001252 # Test cyclical leaks [SF bug 519621]
1253 class F(object):
1254 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001255 s = F()
1256 s.a = [Counted(), s]
1257 self.assertEqual(Counted.counter, 1)
1258 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001259 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001260 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001261
Georg Brandl479a7e72008-02-05 18:13:15 +00001262 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001263 if hasattr(gc, 'get_objects'):
1264 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001265 def __eq__(self, other):
1266 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001267 g = G()
1268 orig_objects = len(gc.get_objects())
1269 for i in range(10):
1270 g==g
1271 new_objects = len(gc.get_objects())
1272 self.assertEqual(orig_objects, new_objects)
1273
Georg Brandl479a7e72008-02-05 18:13:15 +00001274 class H(object):
1275 __slots__ = ['a', 'b']
1276 def __init__(self):
1277 self.a = 1
1278 self.b = 2
1279 def __del__(self_):
1280 self.assertEqual(self_.a, 1)
1281 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001282 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001283 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001284 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001285 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001286
Benjamin Petersond12362a2009-12-30 19:44:54 +00001287 class X(object):
1288 __slots__ = "a"
1289 with self.assertRaises(AttributeError):
1290 del X().a
1291
Georg Brandl479a7e72008-02-05 18:13:15 +00001292 def test_slots_special(self):
1293 # Testing __dict__ and __weakref__ in __slots__...
1294 class D(object):
1295 __slots__ = ["__dict__"]
1296 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001297 self.assertHasAttr(a, "__dict__")
1298 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001299 a.foo = 42
1300 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001301
Georg Brandl479a7e72008-02-05 18:13:15 +00001302 class W(object):
1303 __slots__ = ["__weakref__"]
1304 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001305 self.assertHasAttr(a, "__weakref__")
1306 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001307 try:
1308 a.foo = 42
1309 except AttributeError:
1310 pass
1311 else:
1312 self.fail("shouldn't be allowed to set a.foo")
1313
1314 class C1(W, D):
1315 __slots__ = []
1316 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001317 self.assertHasAttr(a, "__dict__")
1318 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001319 a.foo = 42
1320 self.assertEqual(a.__dict__, {"foo": 42})
1321
1322 class C2(D, W):
1323 __slots__ = []
1324 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001325 self.assertHasAttr(a, "__dict__")
1326 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001327 a.foo = 42
1328 self.assertEqual(a.__dict__, {"foo": 42})
1329
Xiang Zhangc393ee82017-03-08 11:18:49 +08001330 def test_slots_special2(self):
1331 # Testing __qualname__ and __classcell__ in __slots__
1332 class Meta(type):
1333 def __new__(cls, name, bases, namespace, attr):
1334 self.assertIn(attr, namespace)
1335 return super().__new__(cls, name, bases, namespace)
1336
1337 class C1:
1338 def __init__(self):
1339 self.b = 42
1340 class C2(C1, metaclass=Meta, attr="__classcell__"):
1341 __slots__ = ["__classcell__"]
1342 def __init__(self):
1343 super().__init__()
1344 self.assertIsInstance(C2.__dict__["__classcell__"],
1345 types.MemberDescriptorType)
1346 c = C2()
1347 self.assertEqual(c.b, 42)
1348 self.assertNotHasAttr(c, "__classcell__")
1349 c.__classcell__ = 42
1350 self.assertEqual(c.__classcell__, 42)
1351 with self.assertRaises(TypeError):
1352 class C3:
1353 __classcell__ = 42
1354 __slots__ = ["__classcell__"]
1355
1356 class Q1(metaclass=Meta, attr="__qualname__"):
1357 __slots__ = ["__qualname__"]
1358 self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
1359 self.assertIsInstance(Q1.__dict__["__qualname__"],
1360 types.MemberDescriptorType)
1361 q = Q1()
1362 self.assertNotHasAttr(q, "__qualname__")
1363 q.__qualname__ = "q"
1364 self.assertEqual(q.__qualname__, "q")
1365 with self.assertRaises(TypeError):
1366 class Q2:
1367 __qualname__ = object()
1368 __slots__ = ["__qualname__"]
1369
Christian Heimesa156e092008-02-16 07:38:31 +00001370 def test_slots_descriptor(self):
1371 # Issue2115: slot descriptors did not correctly check
1372 # the type of the given object
1373 import abc
1374 class MyABC(metaclass=abc.ABCMeta):
1375 __slots__ = "a"
1376
1377 class Unrelated(object):
1378 pass
1379 MyABC.register(Unrelated)
1380
1381 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001382 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001383
1384 # This used to crash
1385 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1386
Georg Brandl479a7e72008-02-05 18:13:15 +00001387 def test_dynamics(self):
1388 # Testing class attribute propagation...
1389 class D(object):
1390 pass
1391 class E(D):
1392 pass
1393 class F(D):
1394 pass
1395 D.foo = 1
1396 self.assertEqual(D.foo, 1)
1397 # Test that dynamic attributes are inherited
1398 self.assertEqual(E.foo, 1)
1399 self.assertEqual(F.foo, 1)
1400 # Test dynamic instances
1401 class C(object):
1402 pass
1403 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001404 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001405 C.foobar = 2
1406 self.assertEqual(a.foobar, 2)
1407 C.method = lambda self: 42
1408 self.assertEqual(a.method(), 42)
1409 C.__repr__ = lambda self: "C()"
1410 self.assertEqual(repr(a), "C()")
1411 C.__int__ = lambda self: 100
1412 self.assertEqual(int(a), 100)
1413 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001414 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001415 def mygetattr(self, name):
1416 if name == "spam":
1417 return "spam"
1418 raise AttributeError
1419 C.__getattr__ = mygetattr
1420 self.assertEqual(a.spam, "spam")
1421 a.new = 12
1422 self.assertEqual(a.new, 12)
1423 def mysetattr(self, name, value):
1424 if name == "spam":
1425 raise AttributeError
1426 return object.__setattr__(self, name, value)
1427 C.__setattr__ = mysetattr
1428 try:
1429 a.spam = "not spam"
1430 except AttributeError:
1431 pass
1432 else:
1433 self.fail("expected AttributeError")
1434 self.assertEqual(a.spam, "spam")
1435 class D(C):
1436 pass
1437 d = D()
1438 d.foo = 1
1439 self.assertEqual(d.foo, 1)
1440
1441 # Test handling of int*seq and seq*int
1442 class I(int):
1443 pass
1444 self.assertEqual("a"*I(2), "aa")
1445 self.assertEqual(I(2)*"a", "aa")
1446 self.assertEqual(2*I(3), 6)
1447 self.assertEqual(I(3)*2, 6)
1448 self.assertEqual(I(3)*I(2), 6)
1449
Georg Brandl479a7e72008-02-05 18:13:15 +00001450 # Test comparison of classes with dynamic metaclasses
1451 class dynamicmetaclass(type):
1452 pass
1453 class someclass(metaclass=dynamicmetaclass):
1454 pass
1455 self.assertNotEqual(someclass, object)
1456
1457 def test_errors(self):
1458 # Testing errors...
1459 try:
1460 class C(list, dict):
1461 pass
1462 except TypeError:
1463 pass
1464 else:
1465 self.fail("inheritance from both list and dict should be illegal")
1466
1467 try:
1468 class C(object, None):
1469 pass
1470 except TypeError:
1471 pass
1472 else:
1473 self.fail("inheritance from non-type should be illegal")
1474 class Classic:
1475 pass
1476
1477 try:
1478 class C(type(len)):
1479 pass
1480 except TypeError:
1481 pass
1482 else:
1483 self.fail("inheritance from CFunction should be illegal")
1484
1485 try:
1486 class C(object):
1487 __slots__ = 1
1488 except TypeError:
1489 pass
1490 else:
1491 self.fail("__slots__ = 1 should be illegal")
1492
1493 try:
1494 class C(object):
1495 __slots__ = [1]
1496 except TypeError:
1497 pass
1498 else:
1499 self.fail("__slots__ = [1] should be illegal")
1500
1501 class M1(type):
1502 pass
1503 class M2(type):
1504 pass
1505 class A1(object, metaclass=M1):
1506 pass
1507 class A2(object, metaclass=M2):
1508 pass
1509 try:
1510 class B(A1, A2):
1511 pass
1512 except TypeError:
1513 pass
1514 else:
1515 self.fail("finding the most derived metaclass should have failed")
1516
1517 def test_classmethods(self):
1518 # Testing class methods...
1519 class C(object):
1520 def foo(*a): return a
1521 goo = classmethod(foo)
1522 c = C()
1523 self.assertEqual(C.goo(1), (C, 1))
1524 self.assertEqual(c.goo(1), (C, 1))
1525 self.assertEqual(c.foo(1), (c, 1))
1526 class D(C):
1527 pass
1528 d = D()
1529 self.assertEqual(D.goo(1), (D, 1))
1530 self.assertEqual(d.goo(1), (D, 1))
1531 self.assertEqual(d.foo(1), (d, 1))
1532 self.assertEqual(D.foo(d, 1), (d, 1))
1533 # Test for a specific crash (SF bug 528132)
1534 def f(cls, arg): return (cls, arg)
1535 ff = classmethod(f)
1536 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1537 self.assertEqual(ff.__get__(0)(42), (int, 42))
1538
1539 # Test super() with classmethods (SF bug 535444)
1540 self.assertEqual(C.goo.__self__, C)
1541 self.assertEqual(D.goo.__self__, D)
1542 self.assertEqual(super(D,D).goo.__self__, D)
1543 self.assertEqual(super(D,d).goo.__self__, D)
1544 self.assertEqual(super(D,D).goo(), (D,))
1545 self.assertEqual(super(D,d).goo(), (D,))
1546
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001547 # Verify that a non-callable will raise
1548 meth = classmethod(1).__get__(1)
1549 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001550
1551 # Verify that classmethod() doesn't allow keyword args
1552 try:
1553 classmethod(f, kw=1)
1554 except TypeError:
1555 pass
1556 else:
1557 self.fail("classmethod shouldn't accept keyword args")
1558
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001559 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001560 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001561 cm.x = 42
1562 self.assertEqual(cm.x, 42)
1563 self.assertEqual(cm.__dict__, {"x" : 42})
1564 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001565 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001566
Oren Milmand019bc82018-02-13 12:28:33 +02001567 @support.refcount_test
1568 def test_refleaks_in_classmethod___init__(self):
1569 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1570 cm = classmethod(None)
1571 refs_before = gettotalrefcount()
1572 for i in range(100):
1573 cm.__init__(None)
1574 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1575
Benjamin Petersone549ead2009-03-28 21:42:05 +00001576 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001577 def test_classmethods_in_c(self):
1578 # Testing C-based class methods...
1579 import xxsubtype as spam
1580 a = (1, 2, 3)
1581 d = {'abc': 123}
1582 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1583 self.assertEqual(x, spam.spamlist)
1584 self.assertEqual(a, a1)
1585 self.assertEqual(d, d1)
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)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001590 spam_cm = spam.spamlist.__dict__['classmeth']
1591 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1592 self.assertEqual(x2, spam.spamlist)
1593 self.assertEqual(a2, a1)
1594 self.assertEqual(d2, d1)
1595 class SubSpam(spam.spamlist): pass
1596 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1597 self.assertEqual(x2, SubSpam)
1598 self.assertEqual(a2, a1)
1599 self.assertEqual(d2, d1)
Inada Naoki871309c2019-03-26 18:26:33 +09001600
1601 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001602 spam_cm()
Inada Naoki871309c2019-03-26 18:26:33 +09001603 self.assertEqual(
1604 str(cm.exception),
1605 "descriptor 'classmeth' of 'xxsubtype.spamlist' "
1606 "object needs an argument")
1607
1608 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001609 spam_cm(spam.spamlist())
Inada Naoki871309c2019-03-26 18:26:33 +09001610 self.assertEqual(
1611 str(cm.exception),
1612 "descriptor 'classmeth' requires a type "
1613 "but received a 'xxsubtype.spamlist' instance")
1614
1615 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001616 spam_cm(list)
Inada Naoki62f95882019-04-01 17:56:11 +09001617 expected_errmsg = (
Inada Naoki871309c2019-03-26 18:26:33 +09001618 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
1619 "but received 'list'")
Inada Naoki62f95882019-04-01 17:56:11 +09001620 self.assertEqual(str(cm.exception), expected_errmsg)
1621
1622 with self.assertRaises(TypeError) as cm:
1623 spam_cm.__get__(None, list)
1624 self.assertEqual(str(cm.exception), expected_errmsg)
Georg Brandl479a7e72008-02-05 18:13:15 +00001625
1626 def test_staticmethods(self):
1627 # Testing static methods...
1628 class C(object):
1629 def foo(*a): return a
1630 goo = staticmethod(foo)
1631 c = C()
1632 self.assertEqual(C.goo(1), (1,))
1633 self.assertEqual(c.goo(1), (1,))
1634 self.assertEqual(c.foo(1), (c, 1,))
1635 class D(C):
1636 pass
1637 d = D()
1638 self.assertEqual(D.goo(1), (1,))
1639 self.assertEqual(d.goo(1), (1,))
1640 self.assertEqual(d.foo(1), (d, 1))
1641 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001642 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001643 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001644 sm.x = 42
1645 self.assertEqual(sm.x, 42)
1646 self.assertEqual(sm.__dict__, {"x" : 42})
1647 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001648 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001649
Oren Milmand019bc82018-02-13 12:28:33 +02001650 @support.refcount_test
1651 def test_refleaks_in_staticmethod___init__(self):
1652 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1653 sm = staticmethod(None)
1654 refs_before = gettotalrefcount()
1655 for i in range(100):
1656 sm.__init__(None)
1657 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1658
Benjamin Petersone549ead2009-03-28 21:42:05 +00001659 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001660 def test_staticmethods_in_c(self):
1661 # Testing C-based static methods...
1662 import xxsubtype as spam
1663 a = (1, 2, 3)
1664 d = {"abc": 123}
1665 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1666 self.assertEqual(x, None)
1667 self.assertEqual(a, a1)
1668 self.assertEqual(d, d1)
1669 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1670 self.assertEqual(x, None)
1671 self.assertEqual(a, a1)
1672 self.assertEqual(d, d1)
1673
1674 def test_classic(self):
1675 # Testing classic classes...
1676 class C:
1677 def foo(*a): return a
1678 goo = classmethod(foo)
1679 c = C()
1680 self.assertEqual(C.goo(1), (C, 1))
1681 self.assertEqual(c.goo(1), (C, 1))
1682 self.assertEqual(c.foo(1), (c, 1))
1683 class D(C):
1684 pass
1685 d = D()
1686 self.assertEqual(D.goo(1), (D, 1))
1687 self.assertEqual(d.goo(1), (D, 1))
1688 self.assertEqual(d.foo(1), (d, 1))
1689 self.assertEqual(D.foo(d, 1), (d, 1))
1690 class E: # *not* subclassing from C
1691 foo = C.foo
1692 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001693 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001694
1695 def test_compattr(self):
1696 # Testing computed attributes...
1697 class C(object):
1698 class computed_attribute(object):
1699 def __init__(self, get, set=None, delete=None):
1700 self.__get = get
1701 self.__set = set
1702 self.__delete = delete
1703 def __get__(self, obj, type=None):
1704 return self.__get(obj)
1705 def __set__(self, obj, value):
1706 return self.__set(obj, value)
1707 def __delete__(self, obj):
1708 return self.__delete(obj)
1709 def __init__(self):
1710 self.__x = 0
1711 def __get_x(self):
1712 x = self.__x
1713 self.__x = x+1
1714 return x
1715 def __set_x(self, x):
1716 self.__x = x
1717 def __delete_x(self):
1718 del self.__x
1719 x = computed_attribute(__get_x, __set_x, __delete_x)
1720 a = C()
1721 self.assertEqual(a.x, 0)
1722 self.assertEqual(a.x, 1)
1723 a.x = 10
1724 self.assertEqual(a.x, 10)
1725 self.assertEqual(a.x, 11)
1726 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001727 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001728
1729 def test_newslots(self):
1730 # Testing __new__ slot override...
1731 class C(list):
1732 def __new__(cls):
1733 self = list.__new__(cls)
1734 self.foo = 1
1735 return self
1736 def __init__(self):
1737 self.foo = self.foo + 2
1738 a = C()
1739 self.assertEqual(a.foo, 3)
1740 self.assertEqual(a.__class__, C)
1741 class D(C):
1742 pass
1743 b = D()
1744 self.assertEqual(b.foo, 3)
1745 self.assertEqual(b.__class__, D)
1746
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001747 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001748 def test_bad_new(self):
1749 self.assertRaises(TypeError, object.__new__)
1750 self.assertRaises(TypeError, object.__new__, '')
1751 self.assertRaises(TypeError, list.__new__, object)
1752 self.assertRaises(TypeError, object.__new__, list)
1753 class C(object):
1754 __new__ = list.__new__
1755 self.assertRaises(TypeError, C)
1756 class C(list):
1757 __new__ = object.__new__
1758 self.assertRaises(TypeError, C)
1759
1760 def test_object_new(self):
1761 class A(object):
1762 pass
1763 object.__new__(A)
1764 self.assertRaises(TypeError, object.__new__, A, 5)
1765 object.__init__(A())
1766 self.assertRaises(TypeError, object.__init__, A(), 5)
1767
1768 class A(object):
1769 def __init__(self, foo):
1770 self.foo = foo
1771 object.__new__(A)
1772 object.__new__(A, 5)
1773 object.__init__(A(3))
1774 self.assertRaises(TypeError, object.__init__, A(3), 5)
1775
1776 class A(object):
1777 def __new__(cls, foo):
1778 return object.__new__(cls)
1779 object.__new__(A)
1780 self.assertRaises(TypeError, object.__new__, A, 5)
1781 object.__init__(A(3))
1782 object.__init__(A(3), 5)
1783
1784 class A(object):
1785 def __new__(cls, foo):
1786 return object.__new__(cls)
1787 def __init__(self, foo):
1788 self.foo = foo
1789 object.__new__(A)
1790 self.assertRaises(TypeError, object.__new__, A, 5)
1791 object.__init__(A(3))
1792 self.assertRaises(TypeError, object.__init__, A(3), 5)
1793
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001794 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001795 def test_restored_object_new(self):
1796 class A(object):
1797 def __new__(cls, *args, **kwargs):
1798 raise AssertionError
1799 self.assertRaises(AssertionError, A)
1800 class B(A):
1801 __new__ = object.__new__
1802 def __init__(self, foo):
1803 self.foo = foo
1804 with warnings.catch_warnings():
1805 warnings.simplefilter('error', DeprecationWarning)
1806 b = B(3)
1807 self.assertEqual(b.foo, 3)
1808 self.assertEqual(b.__class__, B)
1809 del B.__new__
1810 self.assertRaises(AssertionError, B)
1811 del A.__new__
1812 with warnings.catch_warnings():
1813 warnings.simplefilter('error', DeprecationWarning)
1814 b = B(3)
1815 self.assertEqual(b.foo, 3)
1816 self.assertEqual(b.__class__, B)
1817
Georg Brandl479a7e72008-02-05 18:13:15 +00001818 def test_altmro(self):
1819 # Testing mro() and overriding it...
1820 class A(object):
1821 def f(self): return "A"
1822 class B(A):
1823 pass
1824 class C(A):
1825 def f(self): return "C"
1826 class D(B, C):
1827 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001828 self.assertEqual(A.mro(), [A, object])
1829 self.assertEqual(A.__mro__, (A, object))
1830 self.assertEqual(B.mro(), [B, A, object])
1831 self.assertEqual(B.__mro__, (B, A, object))
1832 self.assertEqual(C.mro(), [C, A, object])
1833 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001834 self.assertEqual(D.mro(), [D, B, C, A, object])
1835 self.assertEqual(D.__mro__, (D, B, C, A, object))
1836 self.assertEqual(D().f(), "C")
1837
1838 class PerverseMetaType(type):
1839 def mro(cls):
1840 L = type.mro(cls)
1841 L.reverse()
1842 return L
1843 class X(D,B,C,A, metaclass=PerverseMetaType):
1844 pass
1845 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1846 self.assertEqual(X().f(), "A")
1847
1848 try:
1849 class _metaclass(type):
1850 def mro(self):
1851 return [self, dict, object]
1852 class X(object, metaclass=_metaclass):
1853 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001854 # In CPython, the class creation above already raises
1855 # TypeError, as a protection against the fact that
1856 # instances of X would segfault it. In other Python
1857 # implementations it would be ok to let the class X
1858 # be created, but instead get a clean TypeError on the
1859 # __setitem__ below.
1860 x = object.__new__(X)
1861 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001862 except TypeError:
1863 pass
1864 else:
1865 self.fail("devious mro() return not caught")
1866
1867 try:
1868 class _metaclass(type):
1869 def mro(self):
1870 return [1]
1871 class X(object, metaclass=_metaclass):
1872 pass
1873 except TypeError:
1874 pass
1875 else:
1876 self.fail("non-class mro() return not caught")
1877
1878 try:
1879 class _metaclass(type):
1880 def mro(self):
1881 return 1
1882 class X(object, metaclass=_metaclass):
1883 pass
1884 except TypeError:
1885 pass
1886 else:
1887 self.fail("non-sequence mro() return not caught")
1888
1889 def test_overloading(self):
1890 # Testing operator overloading...
1891
1892 class B(object):
1893 "Intermediate class because object doesn't have a __setattr__"
1894
1895 class C(B):
1896 def __getattr__(self, name):
1897 if name == "foo":
1898 return ("getattr", name)
1899 else:
1900 raise AttributeError
1901 def __setattr__(self, name, value):
1902 if name == "foo":
1903 self.setattr = (name, value)
1904 else:
1905 return B.__setattr__(self, name, value)
1906 def __delattr__(self, name):
1907 if name == "foo":
1908 self.delattr = name
1909 else:
1910 return B.__delattr__(self, name)
1911
1912 def __getitem__(self, key):
1913 return ("getitem", key)
1914 def __setitem__(self, key, value):
1915 self.setitem = (key, value)
1916 def __delitem__(self, key):
1917 self.delitem = key
1918
1919 a = C()
1920 self.assertEqual(a.foo, ("getattr", "foo"))
1921 a.foo = 12
1922 self.assertEqual(a.setattr, ("foo", 12))
1923 del a.foo
1924 self.assertEqual(a.delattr, "foo")
1925
1926 self.assertEqual(a[12], ("getitem", 12))
1927 a[12] = 21
1928 self.assertEqual(a.setitem, (12, 21))
1929 del a[12]
1930 self.assertEqual(a.delitem, 12)
1931
1932 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1933 a[0:10] = "foo"
1934 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1935 del a[0:10]
1936 self.assertEqual(a.delitem, (slice(0, 10)))
1937
1938 def test_methods(self):
1939 # Testing methods...
1940 class C(object):
1941 def __init__(self, x):
1942 self.x = x
1943 def foo(self):
1944 return self.x
1945 c1 = C(1)
1946 self.assertEqual(c1.foo(), 1)
1947 class D(C):
1948 boo = C.foo
1949 goo = c1.foo
1950 d2 = D(2)
1951 self.assertEqual(d2.foo(), 2)
1952 self.assertEqual(d2.boo(), 2)
1953 self.assertEqual(d2.goo(), 1)
1954 class E(object):
1955 foo = C.foo
1956 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001957 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001958
Inada Naoki62f95882019-04-01 17:56:11 +09001959 @support.impl_detail("testing error message from implementation")
1960 def test_methods_in_c(self):
1961 # This test checks error messages in builtin method descriptor.
1962 # It is allowed that other Python implementations use
1963 # different error messages.
1964 set_add = set.add
1965
1966 expected_errmsg = "descriptor 'add' of 'set' object needs an argument"
1967
1968 with self.assertRaises(TypeError) as cm:
1969 set_add()
1970 self.assertEqual(cm.exception.args[0], expected_errmsg)
1971
1972 expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"
1973
1974 with self.assertRaises(TypeError) as cm:
1975 set_add(0)
1976 self.assertEqual(cm.exception.args[0], expected_errmsg)
1977
1978 with self.assertRaises(TypeError) as cm:
1979 set_add.__get__(0)
1980 self.assertEqual(cm.exception.args[0], expected_errmsg)
1981
Benjamin Peterson224205f2009-05-08 03:25:19 +00001982 def test_special_method_lookup(self):
1983 # The lookup of special methods bypasses __getattr__ and
1984 # __getattribute__, but they still can be descriptors.
1985
1986 def run_context(manager):
1987 with manager:
1988 pass
1989 def iden(self):
1990 return self
1991 def hello(self):
1992 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001993 def empty_seq(self):
1994 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001995 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001996 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001997 def complex_num(self):
1998 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001999 def stop(self):
2000 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002001 def return_true(self, thing=None):
2002 return True
2003 def do_isinstance(obj):
2004 return isinstance(int, obj)
2005 def do_issubclass(obj):
2006 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00002007 def do_dict_missing(checker):
2008 class DictSub(checker.__class__, dict):
2009 pass
2010 self.assertEqual(DictSub()["hi"], 4)
2011 def some_number(self_, key):
2012 self.assertEqual(key, "hi")
2013 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002014 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002015 def format_impl(self, spec):
2016 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00002017
2018 # It would be nice to have every special method tested here, but I'm
2019 # only listing the ones I can remember outside of typeobject.c, since it
2020 # does it right.
2021 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002022 ("__bytes__", bytes, hello, set(), {}),
2023 ("__reversed__", reversed, empty_seq, set(), {}),
2024 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00002025 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002026 ("__sizeof__", sys.getsizeof, zero, set(), {}),
2027 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00002028 ("__missing__", do_dict_missing, some_number,
2029 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002030 ("__subclasscheck__", do_issubclass, return_true,
2031 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002032 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
2033 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00002034 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002035 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002036 ("__floor__", math.floor, zero, set(), {}),
2037 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04002038 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00002039 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05002040 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002041 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00002042 ]
2043
2044 class Checker(object):
2045 def __getattr__(self, attr, test=self):
2046 test.fail("__getattr__ called with {0}".format(attr))
2047 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002048 if attr not in ok:
2049 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00002050 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002051 class SpecialDescr(object):
2052 def __init__(self, impl):
2053 self.impl = impl
2054 def __get__(self, obj, owner):
2055 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002056 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002057 class MyException(Exception):
2058 pass
2059 class ErrDescr(object):
2060 def __get__(self, obj, owner):
2061 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00002062
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002063 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00002064 class X(Checker):
2065 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002066 for attr, obj in env.items():
2067 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002068 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002069 runner(X())
2070
2071 record = []
2072 class X(Checker):
2073 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002074 for attr, obj in env.items():
2075 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002076 setattr(X, name, SpecialDescr(meth_impl))
2077 runner(X())
2078 self.assertEqual(record, [1], name)
2079
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002080 class X(Checker):
2081 pass
2082 for attr, obj in env.items():
2083 setattr(X, attr, obj)
2084 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002085 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002086
Georg Brandl479a7e72008-02-05 18:13:15 +00002087 def test_specials(self):
2088 # Testing special operators...
2089 # Test operators like __hash__ for which a built-in default exists
2090
2091 # Test the default behavior for static classes
2092 class C(object):
2093 def __getitem__(self, i):
2094 if 0 <= i < 10: return i
2095 raise IndexError
2096 c1 = C()
2097 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002098 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002099 self.assertNotEqual(id(c1), id(c2))
2100 hash(c1)
2101 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002102 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002103 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002104 self.assertFalse(c1 != c1)
2105 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002106 # Note that the module name appears in str/repr, and that varies
2107 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002108 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002109 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002110 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002111 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002112 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002113 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002114 # Test the default behavior for dynamic classes
2115 class D(object):
2116 def __getitem__(self, i):
2117 if 0 <= i < 10: return i
2118 raise IndexError
2119 d1 = D()
2120 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002121 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002122 self.assertNotEqual(id(d1), id(d2))
2123 hash(d1)
2124 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002125 self.assertEqual(d1, d1)
2126 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002127 self.assertFalse(d1 != d1)
2128 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002129 # Note that the module name appears in str/repr, and that varies
2130 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002131 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002132 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002133 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002134 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002135 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002136 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002137 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002138 class Proxy(object):
2139 def __init__(self, x):
2140 self.x = x
2141 def __bool__(self):
2142 return not not self.x
2143 def __hash__(self):
2144 return hash(self.x)
2145 def __eq__(self, other):
2146 return self.x == other
2147 def __ne__(self, other):
2148 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002149 def __ge__(self, other):
2150 return self.x >= other
2151 def __gt__(self, other):
2152 return self.x > other
2153 def __le__(self, other):
2154 return self.x <= other
2155 def __lt__(self, other):
2156 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002157 def __str__(self):
2158 return "Proxy:%s" % self.x
2159 def __repr__(self):
2160 return "Proxy(%r)" % self.x
2161 def __contains__(self, value):
2162 return value in self.x
2163 p0 = Proxy(0)
2164 p1 = Proxy(1)
2165 p_1 = Proxy(-1)
2166 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002167 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002168 self.assertEqual(hash(p0), hash(0))
2169 self.assertEqual(p0, p0)
2170 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002171 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002172 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002173 self.assertTrue(p0 < p1)
2174 self.assertTrue(p0 <= p1)
2175 self.assertTrue(p1 > p0)
2176 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002177 self.assertEqual(str(p0), "Proxy:0")
2178 self.assertEqual(repr(p0), "Proxy(0)")
2179 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002180 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002181 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002182 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002183 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002184
Georg Brandl479a7e72008-02-05 18:13:15 +00002185 def test_weakrefs(self):
2186 # Testing weak references...
2187 import weakref
2188 class C(object):
2189 pass
2190 c = C()
2191 r = weakref.ref(c)
2192 self.assertEqual(r(), c)
2193 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002194 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002195 self.assertEqual(r(), None)
2196 del r
2197 class NoWeak(object):
2198 __slots__ = ['foo']
2199 no = NoWeak()
2200 try:
2201 weakref.ref(no)
2202 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002203 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002204 else:
2205 self.fail("weakref.ref(no) should be illegal")
2206 class Weak(object):
2207 __slots__ = ['foo', '__weakref__']
2208 yes = Weak()
2209 r = weakref.ref(yes)
2210 self.assertEqual(r(), yes)
2211 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002212 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002213 self.assertEqual(r(), None)
2214 del r
2215
2216 def test_properties(self):
2217 # Testing property...
2218 class C(object):
2219 def getx(self):
2220 return self.__x
2221 def setx(self, value):
2222 self.__x = value
2223 def delx(self):
2224 del self.__x
2225 x = property(getx, setx, delx, doc="I'm the x property.")
2226 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002227 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002228 a.x = 42
2229 self.assertEqual(a._C__x, 42)
2230 self.assertEqual(a.x, 42)
2231 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002232 self.assertNotHasAttr(a, "x")
2233 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002234 C.x.__set__(a, 100)
2235 self.assertEqual(C.x.__get__(a), 100)
2236 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002237 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002238
2239 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002240 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002241
2242 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002243 self.assertIn("__doc__", attrs)
2244 self.assertIn("fget", attrs)
2245 self.assertIn("fset", attrs)
2246 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002247
2248 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002249 self.assertIs(raw.fget, C.__dict__['getx'])
2250 self.assertIs(raw.fset, C.__dict__['setx'])
2251 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002252
Raymond Hettingereac503a2015-05-13 01:09:59 -07002253 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002254 try:
2255 setattr(raw, attr, 42)
2256 except AttributeError as msg:
2257 if str(msg).find('readonly') < 0:
2258 self.fail("when setting readonly attr %r on a property, "
2259 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2260 else:
2261 self.fail("expected AttributeError from trying to set readonly %r "
2262 "attr on a property" % attr)
2263
Raymond Hettingereac503a2015-05-13 01:09:59 -07002264 raw.__doc__ = 42
2265 self.assertEqual(raw.__doc__, 42)
2266
Georg Brandl479a7e72008-02-05 18:13:15 +00002267 class D(object):
2268 __getitem__ = property(lambda s: 1/0)
2269
2270 d = D()
2271 try:
2272 for i in d:
2273 str(i)
2274 except ZeroDivisionError:
2275 pass
2276 else:
2277 self.fail("expected ZeroDivisionError from bad property")
2278
R. David Murray378c0cf2010-02-24 01:46:21 +00002279 @unittest.skipIf(sys.flags.optimize >= 2,
2280 "Docstrings are omitted with -O2 and above")
2281 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002282 class E(object):
2283 def getter(self):
2284 "getter method"
2285 return 0
2286 def setter(self_, value):
2287 "setter method"
2288 pass
2289 prop = property(getter)
2290 self.assertEqual(prop.__doc__, "getter method")
2291 prop2 = property(fset=setter)
2292 self.assertEqual(prop2.__doc__, None)
2293
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002294 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002295 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002296 # this segfaulted in 2.5b2
2297 try:
2298 import _testcapi
2299 except ImportError:
2300 pass
2301 else:
2302 class X(object):
2303 p = property(_testcapi.test_with_docstring)
2304
2305 def test_properties_plus(self):
2306 class C(object):
2307 foo = property(doc="hello")
2308 @foo.getter
2309 def foo(self):
2310 return self._foo
2311 @foo.setter
2312 def foo(self, value):
2313 self._foo = abs(value)
2314 @foo.deleter
2315 def foo(self):
2316 del self._foo
2317 c = C()
2318 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002319 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002320 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002321 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002322 self.assertEqual(c._foo, 42)
2323 self.assertEqual(c.foo, 42)
2324 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002325 self.assertNotHasAttr(c, '_foo')
2326 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002327
2328 class D(C):
2329 @C.foo.deleter
2330 def foo(self):
2331 try:
2332 del self._foo
2333 except AttributeError:
2334 pass
2335 d = D()
2336 d.foo = 24
2337 self.assertEqual(d.foo, 24)
2338 del d.foo
2339 del d.foo
2340
2341 class E(object):
2342 @property
2343 def foo(self):
2344 return self._foo
2345 @foo.setter
2346 def foo(self, value):
2347 raise RuntimeError
2348 @foo.setter
2349 def foo(self, value):
2350 self._foo = abs(value)
2351 @foo.deleter
2352 def foo(self, value=None):
2353 del self._foo
2354
2355 e = E()
2356 e.foo = -42
2357 self.assertEqual(e.foo, 42)
2358 del e.foo
2359
2360 class F(E):
2361 @E.foo.deleter
2362 def foo(self):
2363 del self._foo
2364 @foo.setter
2365 def foo(self, value):
2366 self._foo = max(0, value)
2367 f = F()
2368 f.foo = -10
2369 self.assertEqual(f.foo, 0)
2370 del f.foo
2371
2372 def test_dict_constructors(self):
2373 # Testing dict constructor ...
2374 d = dict()
2375 self.assertEqual(d, {})
2376 d = dict({})
2377 self.assertEqual(d, {})
2378 d = dict({1: 2, 'a': 'b'})
2379 self.assertEqual(d, {1: 2, 'a': 'b'})
2380 self.assertEqual(d, dict(list(d.items())))
2381 self.assertEqual(d, dict(iter(d.items())))
2382 d = dict({'one':1, 'two':2})
2383 self.assertEqual(d, dict(one=1, two=2))
2384 self.assertEqual(d, dict(**d))
2385 self.assertEqual(d, dict({"one": 1}, two=2))
2386 self.assertEqual(d, dict([("two", 2)], one=1))
2387 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2388 self.assertEqual(d, dict(**d))
2389
2390 for badarg in 0, 0, 0j, "0", [0], (0,):
2391 try:
2392 dict(badarg)
2393 except TypeError:
2394 pass
2395 except ValueError:
2396 if badarg == "0":
2397 # It's a sequence, and its elements are also sequences (gotta
2398 # love strings <wink>), but they aren't of length 2, so this
2399 # one seemed better as a ValueError than a TypeError.
2400 pass
2401 else:
2402 self.fail("no TypeError from dict(%r)" % badarg)
2403 else:
2404 self.fail("no TypeError from dict(%r)" % badarg)
2405
2406 try:
2407 dict({}, {})
2408 except TypeError:
2409 pass
2410 else:
2411 self.fail("no TypeError from dict({}, {})")
2412
2413 class Mapping:
2414 # Lacks a .keys() method; will be added later.
2415 dict = {1:2, 3:4, 'a':1j}
2416
2417 try:
2418 dict(Mapping())
2419 except TypeError:
2420 pass
2421 else:
2422 self.fail("no TypeError from dict(incomplete mapping)")
2423
2424 Mapping.keys = lambda self: list(self.dict.keys())
2425 Mapping.__getitem__ = lambda self, i: self.dict[i]
2426 d = dict(Mapping())
2427 self.assertEqual(d, Mapping.dict)
2428
2429 # Init from sequence of iterable objects, each producing a 2-sequence.
2430 class AddressBookEntry:
2431 def __init__(self, first, last):
2432 self.first = first
2433 self.last = last
2434 def __iter__(self):
2435 return iter([self.first, self.last])
2436
2437 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2438 AddressBookEntry('Barry', 'Peters'),
2439 AddressBookEntry('Tim', 'Peters'),
2440 AddressBookEntry('Barry', 'Warsaw')])
2441 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2442
2443 d = dict(zip(range(4), range(1, 5)))
2444 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2445
2446 # Bad sequence lengths.
2447 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2448 try:
2449 dict(bad)
2450 except ValueError:
2451 pass
2452 else:
2453 self.fail("no ValueError from dict(%r)" % bad)
2454
2455 def test_dir(self):
2456 # Testing dir() ...
2457 junk = 12
2458 self.assertEqual(dir(), ['junk', 'self'])
2459 del junk
2460
2461 # Just make sure these don't blow up!
2462 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2463 dir(arg)
2464
2465 # Test dir on new-style classes. Since these have object as a
2466 # base class, a lot more gets sucked in.
2467 def interesting(strings):
2468 return [s for s in strings if not s.startswith('_')]
2469
2470 class C(object):
2471 Cdata = 1
2472 def Cmethod(self): pass
2473
2474 cstuff = ['Cdata', 'Cmethod']
2475 self.assertEqual(interesting(dir(C)), cstuff)
2476
2477 c = C()
2478 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002479 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002480
2481 c.cdata = 2
2482 c.cmethod = lambda self: 0
2483 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002484 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002485
2486 class A(C):
2487 Adata = 1
2488 def Amethod(self): pass
2489
2490 astuff = ['Adata', 'Amethod'] + cstuff
2491 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002492 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002493 a = A()
2494 self.assertEqual(interesting(dir(a)), astuff)
2495 a.adata = 42
2496 a.amethod = lambda self: 3
2497 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002498 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002499
2500 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002501 class M(type(sys)):
2502 pass
2503 minstance = M("m")
2504 minstance.b = 2
2505 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002506 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002507 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002508 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002509 self.assertEqual(names, ['a', 'b'])
2510
2511 class M2(M):
2512 def getdict(self):
2513 return "Not a dict!"
2514 __dict__ = property(getdict)
2515
2516 m2instance = M2("m2")
2517 m2instance.b = 2
2518 m2instance.a = 1
2519 self.assertEqual(m2instance.__dict__, "Not a dict!")
2520 try:
2521 dir(m2instance)
2522 except TypeError:
2523 pass
2524
2525 # Two essentially featureless objects, just inheriting stuff from
2526 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002527 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002528
2529 # Nasty test case for proxied objects
2530 class Wrapper(object):
2531 def __init__(self, obj):
2532 self.__obj = obj
2533 def __repr__(self):
2534 return "Wrapper(%s)" % repr(self.__obj)
2535 def __getitem__(self, key):
2536 return Wrapper(self.__obj[key])
2537 def __len__(self):
2538 return len(self.__obj)
2539 def __getattr__(self, name):
2540 return Wrapper(getattr(self.__obj, name))
2541
2542 class C(object):
2543 def __getclass(self):
2544 return Wrapper(type(self))
2545 __class__ = property(__getclass)
2546
2547 dir(C()) # This used to segfault
2548
2549 def test_supers(self):
2550 # Testing super...
2551
2552 class A(object):
2553 def meth(self, a):
2554 return "A(%r)" % a
2555
2556 self.assertEqual(A().meth(1), "A(1)")
2557
2558 class B(A):
2559 def __init__(self):
2560 self.__super = super(B, self)
2561 def meth(self, a):
2562 return "B(%r)" % a + self.__super.meth(a)
2563
2564 self.assertEqual(B().meth(2), "B(2)A(2)")
2565
2566 class C(A):
2567 def meth(self, a):
2568 return "C(%r)" % a + self.__super.meth(a)
2569 C._C__super = super(C)
2570
2571 self.assertEqual(C().meth(3), "C(3)A(3)")
2572
2573 class D(C, B):
2574 def meth(self, a):
2575 return "D(%r)" % a + super(D, self).meth(a)
2576
2577 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2578
2579 # Test for subclassing super
2580
2581 class mysuper(super):
2582 def __init__(self, *args):
2583 return super(mysuper, self).__init__(*args)
2584
2585 class E(D):
2586 def meth(self, a):
2587 return "E(%r)" % a + mysuper(E, self).meth(a)
2588
2589 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2590
2591 class F(E):
2592 def meth(self, a):
2593 s = self.__super # == mysuper(F, self)
2594 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2595 F._F__super = mysuper(F)
2596
2597 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2598
2599 # Make sure certain errors are raised
2600
2601 try:
2602 super(D, 42)
2603 except TypeError:
2604 pass
2605 else:
2606 self.fail("shouldn't allow super(D, 42)")
2607
2608 try:
2609 super(D, C())
2610 except TypeError:
2611 pass
2612 else:
2613 self.fail("shouldn't allow super(D, C())")
2614
2615 try:
2616 super(D).__get__(12)
2617 except TypeError:
2618 pass
2619 else:
2620 self.fail("shouldn't allow super(D).__get__(12)")
2621
2622 try:
2623 super(D).__get__(C())
2624 except TypeError:
2625 pass
2626 else:
2627 self.fail("shouldn't allow super(D).__get__(C())")
2628
2629 # Make sure data descriptors can be overridden and accessed via super
2630 # (new feature in Python 2.3)
2631
2632 class DDbase(object):
2633 def getx(self): return 42
2634 x = property(getx)
2635
2636 class DDsub(DDbase):
2637 def getx(self): return "hello"
2638 x = property(getx)
2639
2640 dd = DDsub()
2641 self.assertEqual(dd.x, "hello")
2642 self.assertEqual(super(DDsub, dd).x, 42)
2643
2644 # Ensure that super() lookup of descriptor from classmethod
2645 # works (SF ID# 743627)
2646
2647 class Base(object):
2648 aProp = property(lambda self: "foo")
2649
2650 class Sub(Base):
2651 @classmethod
2652 def test(klass):
2653 return super(Sub,klass).aProp
2654
2655 self.assertEqual(Sub.test(), Base.aProp)
2656
2657 # Verify that super() doesn't allow keyword args
2658 try:
2659 super(Base, kw=1)
2660 except TypeError:
2661 pass
2662 else:
2663 self.assertEqual("super shouldn't accept keyword args")
2664
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):
3028 """Sublcass of str that computes __eq__ case-insensitively.
3029
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__
4646 x = X()
4647 x.y = 42
4648 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004649
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004650 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004651 with self.assertRaises(ValueError) as cm:
4652 class X:
4653 __slots__ = ["foo"]
4654 foo = None
4655 m = str(cm.exception)
4656 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4657
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004658 def test_set_doc(self):
4659 class X:
4660 "elephant"
4661 X.__doc__ = "banana"
4662 self.assertEqual(X.__doc__, "banana")
4663 with self.assertRaises(TypeError) as cm:
4664 type(list).__dict__["__doc__"].__set__(list, "blah")
4665 self.assertIn("can't set list.__doc__", str(cm.exception))
4666 with self.assertRaises(TypeError) as cm:
4667 type(X).__dict__["__doc__"].__delete__(X)
4668 self.assertIn("can't delete X.__doc__", str(cm.exception))
4669 self.assertEqual(X.__doc__, "banana")
4670
Antoine Pitrou9d574812011-12-12 13:47:25 +01004671 def test_qualname(self):
4672 descriptors = [str.lower, complex.real, float.real, int.__add__]
4673 types = ['method', 'member', 'getset', 'wrapper']
4674
4675 # make sure we have an example of each type of descriptor
4676 for d, n in zip(descriptors, types):
4677 self.assertEqual(type(d).__name__, n + '_descriptor')
4678
4679 for d in descriptors:
4680 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4681 self.assertEqual(d.__qualname__, qualname)
4682
4683 self.assertEqual(str.lower.__qualname__, 'str.lower')
4684 self.assertEqual(complex.real.__qualname__, 'complex.real')
4685 self.assertEqual(float.real.__qualname__, 'float.real')
4686 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4687
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004688 class X:
4689 pass
4690 with self.assertRaises(TypeError):
4691 del X.__qualname__
4692
4693 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4694 str, 'Oink')
4695
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004696 global Y
4697 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004698 class Inside:
4699 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004700 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004701 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004702
Victor Stinner6f738742012-02-25 01:22:36 +01004703 def test_qualname_dict(self):
4704 ns = {'__qualname__': 'some.name'}
4705 tp = type('Foo', (), ns)
4706 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004707 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004708 self.assertEqual(ns, {'__qualname__': 'some.name'})
4709
4710 ns = {'__qualname__': 1}
4711 self.assertRaises(TypeError, type, 'Foo', (), ns)
4712
Benjamin Peterson52c42432012-03-07 18:41:11 -06004713 def test_cycle_through_dict(self):
4714 # See bug #1469629
4715 class X(dict):
4716 def __init__(self):
4717 dict.__init__(self)
4718 self.__dict__ = self
4719 x = X()
4720 x.attr = 42
4721 wr = weakref.ref(x)
4722 del x
4723 support.gc_collect()
4724 self.assertIsNone(wr())
4725 for o in gc.get_objects():
4726 self.assertIsNot(type(o), X)
4727
Benjamin Peterson96384b92012-03-17 00:05:44 -05004728 def test_object_new_and_init_with_parameters(self):
4729 # See issue #1683368
4730 class OverrideNeither:
4731 pass
4732 self.assertRaises(TypeError, OverrideNeither, 1)
4733 self.assertRaises(TypeError, OverrideNeither, kw=1)
4734 class OverrideNew:
4735 def __new__(cls, foo, kw=0, *args, **kwds):
4736 return object.__new__(cls, *args, **kwds)
4737 class OverrideInit:
4738 def __init__(self, foo, kw=0, *args, **kwargs):
4739 return object.__init__(self, *args, **kwargs)
4740 class OverrideBoth(OverrideNew, OverrideInit):
4741 pass
4742 for case in OverrideNew, OverrideInit, OverrideBoth:
4743 case(1)
4744 case(1, kw=2)
4745 self.assertRaises(TypeError, case, 1, 2, 3)
4746 self.assertRaises(TypeError, case, 1, 2, foo=3)
4747
Benjamin Petersondf813792014-03-17 15:57:17 -05004748 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4749 class Base:
4750 pass
4751 class Sub(Base):
4752 pass
4753 self.assertIn("__dict__", Base.__dict__)
4754 self.assertNotIn("__dict__", Sub.__dict__)
4755
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004756 def test_bound_method_repr(self):
4757 class Foo:
4758 def method(self):
4759 pass
4760 self.assertRegex(repr(Foo().method),
4761 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4762
4763
4764 class Base:
4765 def method(self):
4766 pass
4767 class Derived1(Base):
4768 pass
4769 class Derived2(Base):
4770 def method(self):
4771 pass
4772 base = Base()
4773 derived1 = Derived1()
4774 derived2 = Derived2()
4775 super_d2 = super(Derived2, derived2)
4776 self.assertRegex(repr(base.method),
4777 r"<bound method .*Base\.method of <.*Base object at .*>>")
4778 self.assertRegex(repr(derived1.method),
4779 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4780 self.assertRegex(repr(derived2.method),
4781 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4782 self.assertRegex(repr(super_d2.method),
4783 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4784
4785 class Foo:
4786 @classmethod
4787 def method(cls):
4788 pass
4789 foo = Foo()
4790 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004791 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004792 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004793 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004794
4795
4796 class MyCallable:
4797 def __call__(self, arg):
4798 pass
4799 func = MyCallable() # func has no __name__ or __qualname__ attributes
4800 instance = object()
4801 method = types.MethodType(func, instance)
4802 self.assertRegex(repr(method),
4803 r"<bound method \? of <object object at .*>>")
4804 func.__name__ = "name"
4805 self.assertRegex(repr(method),
4806 r"<bound method name of <object object at .*>>")
4807 func.__qualname__ = "qualname"
4808 self.assertRegex(repr(method),
4809 r"<bound method qualname of <object object at .*>>")
4810
jdemeyer5a306202018-10-19 23:50:06 +02004811 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4812 def test_bpo25750(self):
4813 # bpo-25750: calling a descriptor (implemented as built-in
4814 # function with METH_FASTCALL) should not crash CPython if the
4815 # descriptor deletes itself from the class.
4816 class Descr:
4817 __get__ = _testcapi.bad_get
4818
4819 class X:
4820 descr = Descr()
4821 def __new__(cls):
4822 cls.descr = None
4823 # Create this large list to corrupt some unused memory
4824 cls.lst = [2**i for i in range(10000)]
4825 X.descr
4826
Antoine Pitrou9d574812011-12-12 13:47:25 +01004827
Georg Brandl479a7e72008-02-05 18:13:15 +00004828class DictProxyTests(unittest.TestCase):
4829 def setUp(self):
4830 class C(object):
4831 def meth(self):
4832 pass
4833 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004834
Brett Cannon7a540732011-02-22 03:04:06 +00004835 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4836 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004837 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004838 # Testing dict-proxy keys...
4839 it = self.C.__dict__.keys()
4840 self.assertNotIsInstance(it, list)
4841 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004842 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004843 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004844 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004845
Brett Cannon7a540732011-02-22 03:04:06 +00004846 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4847 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004848 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004849 # Testing dict-proxy values...
4850 it = self.C.__dict__.values()
4851 self.assertNotIsInstance(it, list)
4852 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004853 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004854
Brett Cannon7a540732011-02-22 03:04:06 +00004855 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4856 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004857 def test_iter_items(self):
4858 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004859 it = self.C.__dict__.items()
4860 self.assertNotIsInstance(it, list)
4861 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004862 keys.sort()
4863 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004864 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004865
Georg Brandl479a7e72008-02-05 18:13:15 +00004866 def test_dict_type_with_metaclass(self):
4867 # Testing type of __dict__ when metaclass set...
4868 class B(object):
4869 pass
4870 class M(type):
4871 pass
4872 class C(metaclass=M):
4873 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4874 pass
4875 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004876
Ezio Melottiac53ab62010-12-18 14:59:43 +00004877 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004878 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004879 # We can't blindly compare with the repr of another dict as ordering
4880 # of keys and values is arbitrary and may differ.
4881 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004882 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004883 self.assertTrue(r.endswith(')'), r)
4884 for k, v in self.C.__dict__.items():
4885 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004886
Christian Heimesbbffeb62008-01-24 09:42:52 +00004887
Georg Brandl479a7e72008-02-05 18:13:15 +00004888class PTypesLongInitTest(unittest.TestCase):
4889 # This is in its own TestCase so that it can be run before any other tests.
4890 def test_pytype_long_ready(self):
4891 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004892
Georg Brandl479a7e72008-02-05 18:13:15 +00004893 # This dumps core when SF bug 551412 isn't fixed --
4894 # but only when test_descr.py is run separately.
4895 # (That can't be helped -- as soon as PyType_Ready()
4896 # is called for PyLong_Type, the bug is gone.)
4897 class UserLong(object):
4898 def __pow__(self, *args):
4899 pass
4900 try:
4901 pow(0, UserLong(), 0)
4902 except:
4903 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004904
Georg Brandl479a7e72008-02-05 18:13:15 +00004905 # Another segfault only when run early
4906 # (before PyType_Ready(tuple) is called)
4907 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004908
4909
Victor Stinnerd74782b2012-03-09 00:39:08 +01004910class MiscTests(unittest.TestCase):
4911 def test_type_lookup_mro_reference(self):
4912 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4913 # the type MRO because it may be modified during the lookup, if
4914 # __bases__ is set during the lookup for example.
4915 class MyKey(object):
4916 def __hash__(self):
4917 return hash('mykey')
4918
4919 def __eq__(self, other):
4920 X.__bases__ = (Base2,)
4921
4922 class Base(object):
4923 mykey = 'from Base'
4924 mykey2 = 'from Base'
4925
4926 class Base2(object):
4927 mykey = 'from Base2'
4928 mykey2 = 'from Base2'
4929
4930 X = type('X', (Base,), {MyKey(): 5})
4931 # mykey is read from Base
4932 self.assertEqual(X.mykey, 'from Base')
4933 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4934 self.assertEqual(X.mykey2, 'from Base2')
4935
4936
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004937class PicklingTests(unittest.TestCase):
4938
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004939 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004940 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004941 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004942 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004943 if kwargs:
4944 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4945 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004946 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004947 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4948 self.assertEqual(reduce_value[1], (type(obj),) + args)
4949 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004950 if listitems is not None:
4951 self.assertListEqual(list(reduce_value[3]), listitems)
4952 else:
4953 self.assertIsNone(reduce_value[3])
4954 if dictitems is not None:
4955 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4956 else:
4957 self.assertIsNone(reduce_value[4])
4958 else:
4959 base_type = type(obj).__base__
4960 reduce_value = (copyreg._reconstructor,
4961 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004962 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004963 None if base_type is object else base_type(obj)))
4964 if state is not None:
4965 reduce_value += (state,)
4966 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4967 self.assertEqual(obj.__reduce__(), reduce_value)
4968
4969 def test_reduce(self):
4970 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4971 args = (-101, "spam")
4972 kwargs = {'bacon': -201, 'fish': -301}
4973 state = {'cheese': -401}
4974
4975 class C1:
4976 def __getnewargs__(self):
4977 return args
4978 obj = C1()
4979 for proto in protocols:
4980 self._check_reduce(proto, obj, args)
4981
4982 for name, value in state.items():
4983 setattr(obj, name, value)
4984 for proto in protocols:
4985 self._check_reduce(proto, obj, args, state=state)
4986
4987 class C2:
4988 def __getnewargs__(self):
4989 return "bad args"
4990 obj = C2()
4991 for proto in protocols:
4992 if proto >= 2:
4993 with self.assertRaises(TypeError):
4994 obj.__reduce_ex__(proto)
4995
4996 class C3:
4997 def __getnewargs_ex__(self):
4998 return (args, kwargs)
4999 obj = C3()
5000 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03005001 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005002 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005003
5004 class C4:
5005 def __getnewargs_ex__(self):
5006 return (args, "bad dict")
5007 class C5:
5008 def __getnewargs_ex__(self):
5009 return ("bad tuple", kwargs)
5010 class C6:
5011 def __getnewargs_ex__(self):
5012 return ()
5013 class C7:
5014 def __getnewargs_ex__(self):
5015 return "bad args"
5016 for proto in protocols:
5017 for cls in C4, C5, C6, C7:
5018 obj = cls()
5019 if proto >= 2:
5020 with self.assertRaises((TypeError, ValueError)):
5021 obj.__reduce_ex__(proto)
5022
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005023 class C9:
5024 def __getnewargs_ex__(self):
5025 return (args, {})
5026 obj = C9()
5027 for proto in protocols:
5028 self._check_reduce(proto, obj, args)
5029
5030 class C10:
5031 def __getnewargs_ex__(self):
5032 raise IndexError
5033 obj = C10()
5034 for proto in protocols:
5035 if proto >= 2:
5036 with self.assertRaises(IndexError):
5037 obj.__reduce_ex__(proto)
5038
5039 class C11:
5040 def __getstate__(self):
5041 return state
5042 obj = C11()
5043 for proto in protocols:
5044 self._check_reduce(proto, obj, state=state)
5045
5046 class C12:
5047 def __getstate__(self):
5048 return "not dict"
5049 obj = C12()
5050 for proto in protocols:
5051 self._check_reduce(proto, obj, state="not dict")
5052
5053 class C13:
5054 def __getstate__(self):
5055 raise IndexError
5056 obj = C13()
5057 for proto in protocols:
5058 with self.assertRaises(IndexError):
5059 obj.__reduce_ex__(proto)
5060 if proto < 2:
5061 with self.assertRaises(IndexError):
5062 obj.__reduce__()
5063
5064 class C14:
5065 __slots__ = tuple(state)
5066 def __init__(self):
5067 for name, value in state.items():
5068 setattr(self, name, value)
5069
5070 obj = C14()
5071 for proto in protocols:
5072 if proto >= 2:
5073 self._check_reduce(proto, obj, state=(None, state))
5074 else:
5075 with self.assertRaises(TypeError):
5076 obj.__reduce_ex__(proto)
5077 with self.assertRaises(TypeError):
5078 obj.__reduce__()
5079
5080 class C15(dict):
5081 pass
5082 obj = C15({"quebec": -601})
5083 for proto in protocols:
5084 self._check_reduce(proto, obj, dictitems=dict(obj))
5085
5086 class C16(list):
5087 pass
5088 obj = C16(["yukon"])
5089 for proto in protocols:
5090 self._check_reduce(proto, obj, listitems=list(obj))
5091
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005092 def test_special_method_lookup(self):
5093 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5094 class Picky:
5095 def __getstate__(self):
5096 return {}
5097
5098 def __getattr__(self, attr):
5099 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5100 raise AssertionError(attr)
5101 return None
5102 for protocol in protocols:
5103 state = {} if protocol >= 2 else None
5104 self._check_reduce(protocol, Picky(), state=state)
5105
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005106 def _assert_is_copy(self, obj, objcopy, msg=None):
5107 """Utility method to verify if two objects are copies of each others.
5108 """
5109 if msg is None:
5110 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5111 if type(obj).__repr__ is object.__repr__:
5112 # We have this limitation for now because we use the object's repr
5113 # to help us verify that the two objects are copies. This allows
5114 # us to delegate the non-generic verification logic to the objects
5115 # themselves.
5116 raise ValueError("object passed to _assert_is_copy must " +
5117 "override the __repr__ method.")
5118 self.assertIsNot(obj, objcopy, msg=msg)
5119 self.assertIs(type(obj), type(objcopy), msg=msg)
5120 if hasattr(obj, '__dict__'):
5121 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5122 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5123 if hasattr(obj, '__slots__'):
5124 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5125 for slot in obj.__slots__:
5126 self.assertEqual(
5127 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5128 self.assertEqual(getattr(obj, slot, None),
5129 getattr(objcopy, slot, None), msg=msg)
5130 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5131
5132 @staticmethod
5133 def _generate_pickle_copiers():
5134 """Utility method to generate the many possible pickle configurations.
5135 """
5136 class PickleCopier:
5137 "This class copies object using pickle."
5138 def __init__(self, proto, dumps, loads):
5139 self.proto = proto
5140 self.dumps = dumps
5141 self.loads = loads
5142 def copy(self, obj):
5143 return self.loads(self.dumps(obj, self.proto))
5144 def __repr__(self):
5145 # We try to be as descriptive as possible here since this is
5146 # the string which we will allow us to tell the pickle
5147 # configuration we are using during debugging.
5148 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5149 .format(self.proto,
5150 self.dumps.__module__, self.dumps.__qualname__,
5151 self.loads.__module__, self.loads.__qualname__))
5152 return (PickleCopier(*args) for args in
5153 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5154 {pickle.dumps, pickle._dumps},
5155 {pickle.loads, pickle._loads}))
5156
5157 def test_pickle_slots(self):
5158 # Tests pickling of classes with __slots__.
5159
5160 # Pickling of classes with __slots__ but without __getstate__ should
5161 # fail (if using protocol 0 or 1)
5162 global C
5163 class C:
5164 __slots__ = ['a']
5165 with self.assertRaises(TypeError):
5166 pickle.dumps(C(), 0)
5167
5168 global D
5169 class D(C):
5170 pass
5171 with self.assertRaises(TypeError):
5172 pickle.dumps(D(), 0)
5173
5174 class C:
5175 "A class with __getstate__ and __setstate__ implemented."
5176 __slots__ = ['a']
5177 def __getstate__(self):
5178 state = getattr(self, '__dict__', {}).copy()
5179 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005180 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005181 try:
5182 state[slot] = getattr(self, slot)
5183 except AttributeError:
5184 pass
5185 return state
5186 def __setstate__(self, state):
5187 for k, v in state.items():
5188 setattr(self, k, v)
5189 def __repr__(self):
5190 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5191
5192 class D(C):
5193 "A subclass of a class with slots."
5194 pass
5195
5196 global E
5197 class E(C):
5198 "A subclass with an extra slot."
5199 __slots__ = ['b']
5200
5201 # Now it should work
5202 for pickle_copier in self._generate_pickle_copiers():
5203 with self.subTest(pickle_copier=pickle_copier):
5204 x = C()
5205 y = pickle_copier.copy(x)
5206 self._assert_is_copy(x, y)
5207
5208 x.a = 42
5209 y = pickle_copier.copy(x)
5210 self._assert_is_copy(x, y)
5211
5212 x = D()
5213 x.a = 42
5214 x.b = 100
5215 y = pickle_copier.copy(x)
5216 self._assert_is_copy(x, y)
5217
5218 x = E()
5219 x.a = 42
5220 x.b = "foo"
5221 y = pickle_copier.copy(x)
5222 self._assert_is_copy(x, y)
5223
5224 def test_reduce_copying(self):
5225 # Tests pickling and copying new-style classes and objects.
5226 global C1
5227 class C1:
5228 "The state of this class is copyable via its instance dict."
5229 ARGS = (1, 2)
5230 NEED_DICT_COPYING = True
5231 def __init__(self, a, b):
5232 super().__init__()
5233 self.a = a
5234 self.b = b
5235 def __repr__(self):
5236 return "C1(%r, %r)" % (self.a, self.b)
5237
5238 global C2
5239 class C2(list):
5240 "A list subclass copyable via __getnewargs__."
5241 ARGS = (1, 2)
5242 NEED_DICT_COPYING = False
5243 def __new__(cls, a, b):
5244 self = super().__new__(cls)
5245 self.a = a
5246 self.b = b
5247 return self
5248 def __init__(self, *args):
5249 super().__init__()
5250 # This helps testing that __init__ is not called during the
5251 # unpickling process, which would cause extra appends.
5252 self.append("cheese")
5253 @classmethod
5254 def __getnewargs__(cls):
5255 return cls.ARGS
5256 def __repr__(self):
5257 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5258
5259 global C3
5260 class C3(list):
5261 "A list subclass copyable via __getstate__."
5262 ARGS = (1, 2)
5263 NEED_DICT_COPYING = False
5264 def __init__(self, a, b):
5265 self.a = a
5266 self.b = b
5267 # This helps testing that __init__ is not called during the
5268 # unpickling process, which would cause extra appends.
5269 self.append("cheese")
5270 @classmethod
5271 def __getstate__(cls):
5272 return cls.ARGS
5273 def __setstate__(self, state):
5274 a, b = state
5275 self.a = a
5276 self.b = b
5277 def __repr__(self):
5278 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5279
5280 global C4
5281 class C4(int):
5282 "An int subclass copyable via __getnewargs__."
5283 ARGS = ("hello", "world", 1)
5284 NEED_DICT_COPYING = False
5285 def __new__(cls, a, b, value):
5286 self = super().__new__(cls, value)
5287 self.a = a
5288 self.b = b
5289 return self
5290 @classmethod
5291 def __getnewargs__(cls):
5292 return cls.ARGS
5293 def __repr__(self):
5294 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5295
5296 global C5
5297 class C5(int):
5298 "An int subclass copyable via __getnewargs_ex__."
5299 ARGS = (1, 2)
5300 KWARGS = {'value': 3}
5301 NEED_DICT_COPYING = False
5302 def __new__(cls, a, b, *, value=0):
5303 self = super().__new__(cls, value)
5304 self.a = a
5305 self.b = b
5306 return self
5307 @classmethod
5308 def __getnewargs_ex__(cls):
5309 return (cls.ARGS, cls.KWARGS)
5310 def __repr__(self):
5311 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5312
5313 test_classes = (C1, C2, C3, C4, C5)
5314 # Testing copying through pickle
5315 pickle_copiers = self._generate_pickle_copiers()
5316 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5317 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5318 kwargs = getattr(cls, 'KWARGS', {})
5319 obj = cls(*cls.ARGS, **kwargs)
5320 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005321 objcopy = pickle_copier.copy(obj)
5322 self._assert_is_copy(obj, objcopy)
5323 # For test classes that supports this, make sure we didn't go
5324 # around the reduce protocol by simply copying the attribute
5325 # dictionary. We clear attributes using the previous copy to
5326 # not mutate the original argument.
5327 if proto >= 2 and not cls.NEED_DICT_COPYING:
5328 objcopy.__dict__.clear()
5329 objcopy2 = pickle_copier.copy(objcopy)
5330 self._assert_is_copy(obj, objcopy2)
5331
5332 # Testing copying through copy.deepcopy()
5333 for cls in test_classes:
5334 with self.subTest(cls=cls):
5335 kwargs = getattr(cls, 'KWARGS', {})
5336 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005337 objcopy = deepcopy(obj)
5338 self._assert_is_copy(obj, objcopy)
5339 # For test classes that supports this, make sure we didn't go
5340 # around the reduce protocol by simply copying the attribute
5341 # dictionary. We clear attributes using the previous copy to
5342 # not mutate the original argument.
5343 if not cls.NEED_DICT_COPYING:
5344 objcopy.__dict__.clear()
5345 objcopy2 = deepcopy(objcopy)
5346 self._assert_is_copy(obj, objcopy2)
5347
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005348 def test_issue24097(self):
5349 # Slot name is freed inside __getattr__ and is later used.
5350 class S(str): # Not interned
5351 pass
5352 class A:
5353 __slotnames__ = [S('spam')]
5354 def __getattr__(self, attr):
5355 if attr == 'spam':
5356 A.__slotnames__[:] = [S('spam')]
5357 return 42
5358 else:
5359 raise AttributeError
5360
5361 import copyreg
5362 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005363 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5364
5365 def test_object_reduce(self):
5366 # Issue #29914
5367 # __reduce__() takes no arguments
5368 object().__reduce__()
5369 with self.assertRaises(TypeError):
5370 object().__reduce__(0)
5371 # __reduce_ex__() takes one integer argument
5372 object().__reduce_ex__(0)
5373 with self.assertRaises(TypeError):
5374 object().__reduce_ex__()
5375 with self.assertRaises(TypeError):
5376 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005377
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005378
Benjamin Peterson2a605342014-03-17 16:20:12 -05005379class SharedKeyTests(unittest.TestCase):
5380
5381 @support.cpython_only
5382 def test_subclasses(self):
5383 # Verify that subclasses can share keys (per PEP 412)
5384 class A:
5385 pass
5386 class B(A):
5387 pass
5388
5389 a, b = A(), B()
5390 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
Inada Naokif2a18672019-03-12 17:25:44 +09005391 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005392 # Initial hash table can contain at most 5 elements.
5393 # Set 6 attributes to cause internal resizing.
5394 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005395 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5396 a2 = A()
5397 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
Inada Naokif2a18672019-03-12 17:25:44 +09005398 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
Victor Stinner742da042016-09-07 17:40:12 -07005399 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Inada Naokif2a18672019-03-12 17:25:44 +09005400 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
Benjamin Peterson2a605342014-03-17 16:20:12 -05005401
5402
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005403class DebugHelperMeta(type):
5404 """
5405 Sets default __doc__ and simplifies repr() output.
5406 """
5407 def __new__(mcls, name, bases, attrs):
5408 if attrs.get('__doc__') is None:
5409 attrs['__doc__'] = name # helps when debugging with gdb
5410 return type.__new__(mcls, name, bases, attrs)
5411 def __repr__(cls):
5412 return repr(cls.__name__)
5413
5414
5415class MroTest(unittest.TestCase):
5416 """
5417 Regressions for some bugs revealed through
5418 mcsl.mro() customization (typeobject.c: mro_internal()) and
5419 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5420 """
5421
5422 def setUp(self):
5423 self.step = 0
5424 self.ready = False
5425
5426 def step_until(self, limit):
5427 ret = (self.step < limit)
5428 if ret:
5429 self.step += 1
5430 return ret
5431
5432 def test_incomplete_set_bases_on_self(self):
5433 """
5434 type_set_bases must be aware that type->tp_mro can be NULL.
5435 """
5436 class M(DebugHelperMeta):
5437 def mro(cls):
5438 if self.step_until(1):
5439 assert cls.__mro__ is None
5440 cls.__bases__ += ()
5441
5442 return type.mro(cls)
5443
5444 class A(metaclass=M):
5445 pass
5446
5447 def test_reent_set_bases_on_base(self):
5448 """
5449 Deep reentrancy must not over-decref old_mro.
5450 """
5451 class M(DebugHelperMeta):
5452 def mro(cls):
5453 if cls.__mro__ is not None and cls.__name__ == 'B':
5454 # 4-5 steps are usually enough to make it crash somewhere
5455 if self.step_until(10):
5456 A.__bases__ += ()
5457
5458 return type.mro(cls)
5459
5460 class A(metaclass=M):
5461 pass
5462 class B(A):
5463 pass
5464 B.__bases__ += ()
5465
5466 def test_reent_set_bases_on_direct_base(self):
5467 """
5468 Similar to test_reent_set_bases_on_base, but may crash differently.
5469 """
5470 class M(DebugHelperMeta):
5471 def mro(cls):
5472 base = cls.__bases__[0]
5473 if base is not object:
5474 if self.step_until(5):
5475 base.__bases__ += ()
5476
5477 return type.mro(cls)
5478
5479 class A(metaclass=M):
5480 pass
5481 class B(A):
5482 pass
5483 class C(B):
5484 pass
5485
5486 def test_reent_set_bases_tp_base_cycle(self):
5487 """
5488 type_set_bases must check for an inheritance cycle not only through
5489 MRO of the type, which may be not yet updated in case of reentrance,
5490 but also through tp_base chain, which is assigned before diving into
5491 inner calls to mro().
5492
5493 Otherwise, the following snippet can loop forever:
5494 do {
5495 // ...
5496 type = type->tp_base;
5497 } while (type != NULL);
5498
5499 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5500 would not be happy in that case, causing a stack overflow.
5501 """
5502 class M(DebugHelperMeta):
5503 def mro(cls):
5504 if self.ready:
5505 if cls.__name__ == 'B1':
5506 B2.__bases__ = (B1,)
5507 if cls.__name__ == 'B2':
5508 B1.__bases__ = (B2,)
5509 return type.mro(cls)
5510
5511 class A(metaclass=M):
5512 pass
5513 class B1(A):
5514 pass
5515 class B2(A):
5516 pass
5517
5518 self.ready = True
5519 with self.assertRaises(TypeError):
5520 B1.__bases__ += ()
5521
5522 def test_tp_subclasses_cycle_in_update_slots(self):
5523 """
5524 type_set_bases must check for reentrancy upon finishing its job
5525 by updating tp_subclasses of old/new bases of the type.
5526 Otherwise, an implicit inheritance cycle through tp_subclasses
5527 can break functions that recurse on elements of that field
5528 (like recurse_down_subclasses and mro_hierarchy) eventually
5529 leading to a stack overflow.
5530 """
5531 class M(DebugHelperMeta):
5532 def mro(cls):
5533 if self.ready and cls.__name__ == 'C':
5534 self.ready = False
5535 C.__bases__ = (B2,)
5536 return type.mro(cls)
5537
5538 class A(metaclass=M):
5539 pass
5540 class B1(A):
5541 pass
5542 class B2(A):
5543 pass
5544 class C(A):
5545 pass
5546
5547 self.ready = True
5548 C.__bases__ = (B1,)
5549 B1.__bases__ = (C,)
5550
5551 self.assertEqual(C.__bases__, (B2,))
5552 self.assertEqual(B2.__subclasses__(), [C])
5553 self.assertEqual(B1.__subclasses__(), [])
5554
5555 self.assertEqual(B1.__bases__, (C,))
5556 self.assertEqual(C.__subclasses__(), [B1])
5557
5558 def test_tp_subclasses_cycle_error_return_path(self):
5559 """
5560 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5561 a code path executed on error (goto bail).
5562 """
5563 class E(Exception):
5564 pass
5565 class M(DebugHelperMeta):
5566 def mro(cls):
5567 if self.ready and cls.__name__ == 'C':
5568 if C.__bases__ == (B2,):
5569 self.ready = False
5570 else:
5571 C.__bases__ = (B2,)
5572 raise E
5573 return type.mro(cls)
5574
5575 class A(metaclass=M):
5576 pass
5577 class B1(A):
5578 pass
5579 class B2(A):
5580 pass
5581 class C(A):
5582 pass
5583
5584 self.ready = True
5585 with self.assertRaises(E):
5586 C.__bases__ = (B1,)
5587 B1.__bases__ = (C,)
5588
5589 self.assertEqual(C.__bases__, (B2,))
5590 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5591
5592 def test_incomplete_extend(self):
5593 """
5594 Extending an unitialized type with type->tp_mro == NULL must
5595 throw a reasonable TypeError exception, instead of failing
5596 with PyErr_BadInternalCall.
5597 """
5598 class M(DebugHelperMeta):
5599 def mro(cls):
5600 if cls.__mro__ is None and cls.__name__ != 'X':
5601 with self.assertRaises(TypeError):
5602 class X(cls):
5603 pass
5604
5605 return type.mro(cls)
5606
5607 class A(metaclass=M):
5608 pass
5609
5610 def test_incomplete_super(self):
5611 """
5612 Attrubute lookup on a super object must be aware that
5613 its target type can be uninitialized (type->tp_mro == NULL).
5614 """
5615 class M(DebugHelperMeta):
5616 def mro(cls):
5617 if cls.__mro__ is None:
5618 with self.assertRaises(AttributeError):
5619 super(cls, cls).xxx
5620
5621 return type.mro(cls)
5622
5623 class A(metaclass=M):
5624 pass
5625
5626
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005627def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005628 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005629 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005630 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005631 MiscTests, PicklingTests, SharedKeyTests,
5632 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005633
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005634if __name__ == "__main__":
5635 test_main()