blob: b38cb765cdc010987909eb17c0b798db8649ce2f [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)
1600 with self.assertRaises(TypeError):
1601 spam_cm()
1602 with self.assertRaises(TypeError):
1603 spam_cm(spam.spamlist())
1604 with self.assertRaises(TypeError):
1605 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001606
1607 def test_staticmethods(self):
1608 # Testing static methods...
1609 class C(object):
1610 def foo(*a): return a
1611 goo = staticmethod(foo)
1612 c = C()
1613 self.assertEqual(C.goo(1), (1,))
1614 self.assertEqual(c.goo(1), (1,))
1615 self.assertEqual(c.foo(1), (c, 1,))
1616 class D(C):
1617 pass
1618 d = D()
1619 self.assertEqual(D.goo(1), (1,))
1620 self.assertEqual(d.goo(1), (1,))
1621 self.assertEqual(d.foo(1), (d, 1))
1622 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001623 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001624 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001625 sm.x = 42
1626 self.assertEqual(sm.x, 42)
1627 self.assertEqual(sm.__dict__, {"x" : 42})
1628 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001629 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001630
Oren Milmand019bc82018-02-13 12:28:33 +02001631 @support.refcount_test
1632 def test_refleaks_in_staticmethod___init__(self):
1633 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1634 sm = staticmethod(None)
1635 refs_before = gettotalrefcount()
1636 for i in range(100):
1637 sm.__init__(None)
1638 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1639
Benjamin Petersone549ead2009-03-28 21:42:05 +00001640 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001641 def test_staticmethods_in_c(self):
1642 # Testing C-based static methods...
1643 import xxsubtype as spam
1644 a = (1, 2, 3)
1645 d = {"abc": 123}
1646 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1647 self.assertEqual(x, None)
1648 self.assertEqual(a, a1)
1649 self.assertEqual(d, d1)
1650 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1651 self.assertEqual(x, None)
1652 self.assertEqual(a, a1)
1653 self.assertEqual(d, d1)
1654
1655 def test_classic(self):
1656 # Testing classic classes...
1657 class C:
1658 def foo(*a): return a
1659 goo = classmethod(foo)
1660 c = C()
1661 self.assertEqual(C.goo(1), (C, 1))
1662 self.assertEqual(c.goo(1), (C, 1))
1663 self.assertEqual(c.foo(1), (c, 1))
1664 class D(C):
1665 pass
1666 d = D()
1667 self.assertEqual(D.goo(1), (D, 1))
1668 self.assertEqual(d.goo(1), (D, 1))
1669 self.assertEqual(d.foo(1), (d, 1))
1670 self.assertEqual(D.foo(d, 1), (d, 1))
1671 class E: # *not* subclassing from C
1672 foo = C.foo
1673 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001674 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001675
1676 def test_compattr(self):
1677 # Testing computed attributes...
1678 class C(object):
1679 class computed_attribute(object):
1680 def __init__(self, get, set=None, delete=None):
1681 self.__get = get
1682 self.__set = set
1683 self.__delete = delete
1684 def __get__(self, obj, type=None):
1685 return self.__get(obj)
1686 def __set__(self, obj, value):
1687 return self.__set(obj, value)
1688 def __delete__(self, obj):
1689 return self.__delete(obj)
1690 def __init__(self):
1691 self.__x = 0
1692 def __get_x(self):
1693 x = self.__x
1694 self.__x = x+1
1695 return x
1696 def __set_x(self, x):
1697 self.__x = x
1698 def __delete_x(self):
1699 del self.__x
1700 x = computed_attribute(__get_x, __set_x, __delete_x)
1701 a = C()
1702 self.assertEqual(a.x, 0)
1703 self.assertEqual(a.x, 1)
1704 a.x = 10
1705 self.assertEqual(a.x, 10)
1706 self.assertEqual(a.x, 11)
1707 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001708 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001709
1710 def test_newslots(self):
1711 # Testing __new__ slot override...
1712 class C(list):
1713 def __new__(cls):
1714 self = list.__new__(cls)
1715 self.foo = 1
1716 return self
1717 def __init__(self):
1718 self.foo = self.foo + 2
1719 a = C()
1720 self.assertEqual(a.foo, 3)
1721 self.assertEqual(a.__class__, C)
1722 class D(C):
1723 pass
1724 b = D()
1725 self.assertEqual(b.foo, 3)
1726 self.assertEqual(b.__class__, D)
1727
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001728 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001729 def test_bad_new(self):
1730 self.assertRaises(TypeError, object.__new__)
1731 self.assertRaises(TypeError, object.__new__, '')
1732 self.assertRaises(TypeError, list.__new__, object)
1733 self.assertRaises(TypeError, object.__new__, list)
1734 class C(object):
1735 __new__ = list.__new__
1736 self.assertRaises(TypeError, C)
1737 class C(list):
1738 __new__ = object.__new__
1739 self.assertRaises(TypeError, C)
1740
1741 def test_object_new(self):
1742 class A(object):
1743 pass
1744 object.__new__(A)
1745 self.assertRaises(TypeError, object.__new__, A, 5)
1746 object.__init__(A())
1747 self.assertRaises(TypeError, object.__init__, A(), 5)
1748
1749 class A(object):
1750 def __init__(self, foo):
1751 self.foo = foo
1752 object.__new__(A)
1753 object.__new__(A, 5)
1754 object.__init__(A(3))
1755 self.assertRaises(TypeError, object.__init__, A(3), 5)
1756
1757 class A(object):
1758 def __new__(cls, foo):
1759 return object.__new__(cls)
1760 object.__new__(A)
1761 self.assertRaises(TypeError, object.__new__, A, 5)
1762 object.__init__(A(3))
1763 object.__init__(A(3), 5)
1764
1765 class A(object):
1766 def __new__(cls, foo):
1767 return object.__new__(cls)
1768 def __init__(self, foo):
1769 self.foo = foo
1770 object.__new__(A)
1771 self.assertRaises(TypeError, object.__new__, A, 5)
1772 object.__init__(A(3))
1773 self.assertRaises(TypeError, object.__init__, A(3), 5)
1774
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001775 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001776 def test_restored_object_new(self):
1777 class A(object):
1778 def __new__(cls, *args, **kwargs):
1779 raise AssertionError
1780 self.assertRaises(AssertionError, A)
1781 class B(A):
1782 __new__ = object.__new__
1783 def __init__(self, foo):
1784 self.foo = foo
1785 with warnings.catch_warnings():
1786 warnings.simplefilter('error', DeprecationWarning)
1787 b = B(3)
1788 self.assertEqual(b.foo, 3)
1789 self.assertEqual(b.__class__, B)
1790 del B.__new__
1791 self.assertRaises(AssertionError, B)
1792 del A.__new__
1793 with warnings.catch_warnings():
1794 warnings.simplefilter('error', DeprecationWarning)
1795 b = B(3)
1796 self.assertEqual(b.foo, 3)
1797 self.assertEqual(b.__class__, B)
1798
Georg Brandl479a7e72008-02-05 18:13:15 +00001799 def test_altmro(self):
1800 # Testing mro() and overriding it...
1801 class A(object):
1802 def f(self): return "A"
1803 class B(A):
1804 pass
1805 class C(A):
1806 def f(self): return "C"
1807 class D(B, C):
1808 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001809 self.assertEqual(A.mro(), [A, object])
1810 self.assertEqual(A.__mro__, (A, object))
1811 self.assertEqual(B.mro(), [B, A, object])
1812 self.assertEqual(B.__mro__, (B, A, object))
1813 self.assertEqual(C.mro(), [C, A, object])
1814 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001815 self.assertEqual(D.mro(), [D, B, C, A, object])
1816 self.assertEqual(D.__mro__, (D, B, C, A, object))
1817 self.assertEqual(D().f(), "C")
1818
1819 class PerverseMetaType(type):
1820 def mro(cls):
1821 L = type.mro(cls)
1822 L.reverse()
1823 return L
1824 class X(D,B,C,A, metaclass=PerverseMetaType):
1825 pass
1826 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1827 self.assertEqual(X().f(), "A")
1828
1829 try:
1830 class _metaclass(type):
1831 def mro(self):
1832 return [self, dict, object]
1833 class X(object, metaclass=_metaclass):
1834 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001835 # In CPython, the class creation above already raises
1836 # TypeError, as a protection against the fact that
1837 # instances of X would segfault it. In other Python
1838 # implementations it would be ok to let the class X
1839 # be created, but instead get a clean TypeError on the
1840 # __setitem__ below.
1841 x = object.__new__(X)
1842 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001843 except TypeError:
1844 pass
1845 else:
1846 self.fail("devious mro() return not caught")
1847
1848 try:
1849 class _metaclass(type):
1850 def mro(self):
1851 return [1]
1852 class X(object, metaclass=_metaclass):
1853 pass
1854 except TypeError:
1855 pass
1856 else:
1857 self.fail("non-class mro() return not caught")
1858
1859 try:
1860 class _metaclass(type):
1861 def mro(self):
1862 return 1
1863 class X(object, metaclass=_metaclass):
1864 pass
1865 except TypeError:
1866 pass
1867 else:
1868 self.fail("non-sequence mro() return not caught")
1869
1870 def test_overloading(self):
1871 # Testing operator overloading...
1872
1873 class B(object):
1874 "Intermediate class because object doesn't have a __setattr__"
1875
1876 class C(B):
1877 def __getattr__(self, name):
1878 if name == "foo":
1879 return ("getattr", name)
1880 else:
1881 raise AttributeError
1882 def __setattr__(self, name, value):
1883 if name == "foo":
1884 self.setattr = (name, value)
1885 else:
1886 return B.__setattr__(self, name, value)
1887 def __delattr__(self, name):
1888 if name == "foo":
1889 self.delattr = name
1890 else:
1891 return B.__delattr__(self, name)
1892
1893 def __getitem__(self, key):
1894 return ("getitem", key)
1895 def __setitem__(self, key, value):
1896 self.setitem = (key, value)
1897 def __delitem__(self, key):
1898 self.delitem = key
1899
1900 a = C()
1901 self.assertEqual(a.foo, ("getattr", "foo"))
1902 a.foo = 12
1903 self.assertEqual(a.setattr, ("foo", 12))
1904 del a.foo
1905 self.assertEqual(a.delattr, "foo")
1906
1907 self.assertEqual(a[12], ("getitem", 12))
1908 a[12] = 21
1909 self.assertEqual(a.setitem, (12, 21))
1910 del a[12]
1911 self.assertEqual(a.delitem, 12)
1912
1913 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1914 a[0:10] = "foo"
1915 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1916 del a[0:10]
1917 self.assertEqual(a.delitem, (slice(0, 10)))
1918
1919 def test_methods(self):
1920 # Testing methods...
1921 class C(object):
1922 def __init__(self, x):
1923 self.x = x
1924 def foo(self):
1925 return self.x
1926 c1 = C(1)
1927 self.assertEqual(c1.foo(), 1)
1928 class D(C):
1929 boo = C.foo
1930 goo = c1.foo
1931 d2 = D(2)
1932 self.assertEqual(d2.foo(), 2)
1933 self.assertEqual(d2.boo(), 2)
1934 self.assertEqual(d2.goo(), 1)
1935 class E(object):
1936 foo = C.foo
1937 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001938 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001939
Benjamin Peterson224205f2009-05-08 03:25:19 +00001940 def test_special_method_lookup(self):
1941 # The lookup of special methods bypasses __getattr__ and
1942 # __getattribute__, but they still can be descriptors.
1943
1944 def run_context(manager):
1945 with manager:
1946 pass
1947 def iden(self):
1948 return self
1949 def hello(self):
1950 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001951 def empty_seq(self):
1952 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001953 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001954 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001955 def complex_num(self):
1956 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001957 def stop(self):
1958 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001959 def return_true(self, thing=None):
1960 return True
1961 def do_isinstance(obj):
1962 return isinstance(int, obj)
1963 def do_issubclass(obj):
1964 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001965 def do_dict_missing(checker):
1966 class DictSub(checker.__class__, dict):
1967 pass
1968 self.assertEqual(DictSub()["hi"], 4)
1969 def some_number(self_, key):
1970 self.assertEqual(key, "hi")
1971 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001972 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001973 def format_impl(self, spec):
1974 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001975
1976 # It would be nice to have every special method tested here, but I'm
1977 # only listing the ones I can remember outside of typeobject.c, since it
1978 # does it right.
1979 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001980 ("__bytes__", bytes, hello, set(), {}),
1981 ("__reversed__", reversed, empty_seq, set(), {}),
1982 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001983 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001984 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1985 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001986 ("__missing__", do_dict_missing, some_number,
1987 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001988 ("__subclasscheck__", do_issubclass, return_true,
1989 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001990 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1991 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001992 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001993 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001994 ("__floor__", math.floor, zero, set(), {}),
1995 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001996 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001997 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001998 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001999 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00002000 ]
2001
2002 class Checker(object):
2003 def __getattr__(self, attr, test=self):
2004 test.fail("__getattr__ called with {0}".format(attr))
2005 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002006 if attr not in ok:
2007 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00002008 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002009 class SpecialDescr(object):
2010 def __init__(self, impl):
2011 self.impl = impl
2012 def __get__(self, obj, owner):
2013 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002014 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002015 class MyException(Exception):
2016 pass
2017 class ErrDescr(object):
2018 def __get__(self, obj, owner):
2019 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00002020
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002021 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00002022 class X(Checker):
2023 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002024 for attr, obj in env.items():
2025 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002026 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002027 runner(X())
2028
2029 record = []
2030 class X(Checker):
2031 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002032 for attr, obj in env.items():
2033 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002034 setattr(X, name, SpecialDescr(meth_impl))
2035 runner(X())
2036 self.assertEqual(record, [1], name)
2037
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002038 class X(Checker):
2039 pass
2040 for attr, obj in env.items():
2041 setattr(X, attr, obj)
2042 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002043 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002044
Georg Brandl479a7e72008-02-05 18:13:15 +00002045 def test_specials(self):
2046 # Testing special operators...
2047 # Test operators like __hash__ for which a built-in default exists
2048
2049 # Test the default behavior for static classes
2050 class C(object):
2051 def __getitem__(self, i):
2052 if 0 <= i < 10: return i
2053 raise IndexError
2054 c1 = C()
2055 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002056 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002057 self.assertNotEqual(id(c1), id(c2))
2058 hash(c1)
2059 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002060 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002061 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002062 self.assertFalse(c1 != c1)
2063 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002064 # Note that the module name appears in str/repr, and that varies
2065 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002066 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002067 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002068 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002069 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002070 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002071 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002072 # Test the default behavior for dynamic classes
2073 class D(object):
2074 def __getitem__(self, i):
2075 if 0 <= i < 10: return i
2076 raise IndexError
2077 d1 = D()
2078 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002079 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002080 self.assertNotEqual(id(d1), id(d2))
2081 hash(d1)
2082 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002083 self.assertEqual(d1, d1)
2084 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002085 self.assertFalse(d1 != d1)
2086 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002087 # Note that the module name appears in str/repr, and that varies
2088 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002089 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002090 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002091 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002092 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002093 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002094 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002095 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002096 class Proxy(object):
2097 def __init__(self, x):
2098 self.x = x
2099 def __bool__(self):
2100 return not not self.x
2101 def __hash__(self):
2102 return hash(self.x)
2103 def __eq__(self, other):
2104 return self.x == other
2105 def __ne__(self, other):
2106 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002107 def __ge__(self, other):
2108 return self.x >= other
2109 def __gt__(self, other):
2110 return self.x > other
2111 def __le__(self, other):
2112 return self.x <= other
2113 def __lt__(self, other):
2114 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002115 def __str__(self):
2116 return "Proxy:%s" % self.x
2117 def __repr__(self):
2118 return "Proxy(%r)" % self.x
2119 def __contains__(self, value):
2120 return value in self.x
2121 p0 = Proxy(0)
2122 p1 = Proxy(1)
2123 p_1 = Proxy(-1)
2124 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002125 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002126 self.assertEqual(hash(p0), hash(0))
2127 self.assertEqual(p0, p0)
2128 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002129 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002130 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002131 self.assertTrue(p0 < p1)
2132 self.assertTrue(p0 <= p1)
2133 self.assertTrue(p1 > p0)
2134 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002135 self.assertEqual(str(p0), "Proxy:0")
2136 self.assertEqual(repr(p0), "Proxy(0)")
2137 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002138 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002139 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002140 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002141 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002142
Georg Brandl479a7e72008-02-05 18:13:15 +00002143 def test_weakrefs(self):
2144 # Testing weak references...
2145 import weakref
2146 class C(object):
2147 pass
2148 c = C()
2149 r = weakref.ref(c)
2150 self.assertEqual(r(), c)
2151 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002152 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002153 self.assertEqual(r(), None)
2154 del r
2155 class NoWeak(object):
2156 __slots__ = ['foo']
2157 no = NoWeak()
2158 try:
2159 weakref.ref(no)
2160 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002161 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002162 else:
2163 self.fail("weakref.ref(no) should be illegal")
2164 class Weak(object):
2165 __slots__ = ['foo', '__weakref__']
2166 yes = Weak()
2167 r = weakref.ref(yes)
2168 self.assertEqual(r(), yes)
2169 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002170 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002171 self.assertEqual(r(), None)
2172 del r
2173
2174 def test_properties(self):
2175 # Testing property...
2176 class C(object):
2177 def getx(self):
2178 return self.__x
2179 def setx(self, value):
2180 self.__x = value
2181 def delx(self):
2182 del self.__x
2183 x = property(getx, setx, delx, doc="I'm the x property.")
2184 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002185 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002186 a.x = 42
2187 self.assertEqual(a._C__x, 42)
2188 self.assertEqual(a.x, 42)
2189 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002190 self.assertNotHasAttr(a, "x")
2191 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002192 C.x.__set__(a, 100)
2193 self.assertEqual(C.x.__get__(a), 100)
2194 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002195 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002196
2197 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002198 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002199
2200 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002201 self.assertIn("__doc__", attrs)
2202 self.assertIn("fget", attrs)
2203 self.assertIn("fset", attrs)
2204 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002205
2206 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002207 self.assertIs(raw.fget, C.__dict__['getx'])
2208 self.assertIs(raw.fset, C.__dict__['setx'])
2209 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002210
Raymond Hettingereac503a2015-05-13 01:09:59 -07002211 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002212 try:
2213 setattr(raw, attr, 42)
2214 except AttributeError as msg:
2215 if str(msg).find('readonly') < 0:
2216 self.fail("when setting readonly attr %r on a property, "
2217 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2218 else:
2219 self.fail("expected AttributeError from trying to set readonly %r "
2220 "attr on a property" % attr)
2221
Raymond Hettingereac503a2015-05-13 01:09:59 -07002222 raw.__doc__ = 42
2223 self.assertEqual(raw.__doc__, 42)
2224
Georg Brandl479a7e72008-02-05 18:13:15 +00002225 class D(object):
2226 __getitem__ = property(lambda s: 1/0)
2227
2228 d = D()
2229 try:
2230 for i in d:
2231 str(i)
2232 except ZeroDivisionError:
2233 pass
2234 else:
2235 self.fail("expected ZeroDivisionError from bad property")
2236
R. David Murray378c0cf2010-02-24 01:46:21 +00002237 @unittest.skipIf(sys.flags.optimize >= 2,
2238 "Docstrings are omitted with -O2 and above")
2239 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002240 class E(object):
2241 def getter(self):
2242 "getter method"
2243 return 0
2244 def setter(self_, value):
2245 "setter method"
2246 pass
2247 prop = property(getter)
2248 self.assertEqual(prop.__doc__, "getter method")
2249 prop2 = property(fset=setter)
2250 self.assertEqual(prop2.__doc__, None)
2251
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002252 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002253 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002254 # this segfaulted in 2.5b2
2255 try:
2256 import _testcapi
2257 except ImportError:
2258 pass
2259 else:
2260 class X(object):
2261 p = property(_testcapi.test_with_docstring)
2262
2263 def test_properties_plus(self):
2264 class C(object):
2265 foo = property(doc="hello")
2266 @foo.getter
2267 def foo(self):
2268 return self._foo
2269 @foo.setter
2270 def foo(self, value):
2271 self._foo = abs(value)
2272 @foo.deleter
2273 def foo(self):
2274 del self._foo
2275 c = C()
2276 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002277 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002278 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002279 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002280 self.assertEqual(c._foo, 42)
2281 self.assertEqual(c.foo, 42)
2282 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002283 self.assertNotHasAttr(c, '_foo')
2284 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002285
2286 class D(C):
2287 @C.foo.deleter
2288 def foo(self):
2289 try:
2290 del self._foo
2291 except AttributeError:
2292 pass
2293 d = D()
2294 d.foo = 24
2295 self.assertEqual(d.foo, 24)
2296 del d.foo
2297 del d.foo
2298
2299 class E(object):
2300 @property
2301 def foo(self):
2302 return self._foo
2303 @foo.setter
2304 def foo(self, value):
2305 raise RuntimeError
2306 @foo.setter
2307 def foo(self, value):
2308 self._foo = abs(value)
2309 @foo.deleter
2310 def foo(self, value=None):
2311 del self._foo
2312
2313 e = E()
2314 e.foo = -42
2315 self.assertEqual(e.foo, 42)
2316 del e.foo
2317
2318 class F(E):
2319 @E.foo.deleter
2320 def foo(self):
2321 del self._foo
2322 @foo.setter
2323 def foo(self, value):
2324 self._foo = max(0, value)
2325 f = F()
2326 f.foo = -10
2327 self.assertEqual(f.foo, 0)
2328 del f.foo
2329
2330 def test_dict_constructors(self):
2331 # Testing dict constructor ...
2332 d = dict()
2333 self.assertEqual(d, {})
2334 d = dict({})
2335 self.assertEqual(d, {})
2336 d = dict({1: 2, 'a': 'b'})
2337 self.assertEqual(d, {1: 2, 'a': 'b'})
2338 self.assertEqual(d, dict(list(d.items())))
2339 self.assertEqual(d, dict(iter(d.items())))
2340 d = dict({'one':1, 'two':2})
2341 self.assertEqual(d, dict(one=1, two=2))
2342 self.assertEqual(d, dict(**d))
2343 self.assertEqual(d, dict({"one": 1}, two=2))
2344 self.assertEqual(d, dict([("two", 2)], one=1))
2345 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2346 self.assertEqual(d, dict(**d))
2347
2348 for badarg in 0, 0, 0j, "0", [0], (0,):
2349 try:
2350 dict(badarg)
2351 except TypeError:
2352 pass
2353 except ValueError:
2354 if badarg == "0":
2355 # It's a sequence, and its elements are also sequences (gotta
2356 # love strings <wink>), but they aren't of length 2, so this
2357 # one seemed better as a ValueError than a TypeError.
2358 pass
2359 else:
2360 self.fail("no TypeError from dict(%r)" % badarg)
2361 else:
2362 self.fail("no TypeError from dict(%r)" % badarg)
2363
2364 try:
2365 dict({}, {})
2366 except TypeError:
2367 pass
2368 else:
2369 self.fail("no TypeError from dict({}, {})")
2370
2371 class Mapping:
2372 # Lacks a .keys() method; will be added later.
2373 dict = {1:2, 3:4, 'a':1j}
2374
2375 try:
2376 dict(Mapping())
2377 except TypeError:
2378 pass
2379 else:
2380 self.fail("no TypeError from dict(incomplete mapping)")
2381
2382 Mapping.keys = lambda self: list(self.dict.keys())
2383 Mapping.__getitem__ = lambda self, i: self.dict[i]
2384 d = dict(Mapping())
2385 self.assertEqual(d, Mapping.dict)
2386
2387 # Init from sequence of iterable objects, each producing a 2-sequence.
2388 class AddressBookEntry:
2389 def __init__(self, first, last):
2390 self.first = first
2391 self.last = last
2392 def __iter__(self):
2393 return iter([self.first, self.last])
2394
2395 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2396 AddressBookEntry('Barry', 'Peters'),
2397 AddressBookEntry('Tim', 'Peters'),
2398 AddressBookEntry('Barry', 'Warsaw')])
2399 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2400
2401 d = dict(zip(range(4), range(1, 5)))
2402 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2403
2404 # Bad sequence lengths.
2405 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2406 try:
2407 dict(bad)
2408 except ValueError:
2409 pass
2410 else:
2411 self.fail("no ValueError from dict(%r)" % bad)
2412
2413 def test_dir(self):
2414 # Testing dir() ...
2415 junk = 12
2416 self.assertEqual(dir(), ['junk', 'self'])
2417 del junk
2418
2419 # Just make sure these don't blow up!
2420 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2421 dir(arg)
2422
2423 # Test dir on new-style classes. Since these have object as a
2424 # base class, a lot more gets sucked in.
2425 def interesting(strings):
2426 return [s for s in strings if not s.startswith('_')]
2427
2428 class C(object):
2429 Cdata = 1
2430 def Cmethod(self): pass
2431
2432 cstuff = ['Cdata', 'Cmethod']
2433 self.assertEqual(interesting(dir(C)), cstuff)
2434
2435 c = C()
2436 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002437 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002438
2439 c.cdata = 2
2440 c.cmethod = lambda self: 0
2441 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002442 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002443
2444 class A(C):
2445 Adata = 1
2446 def Amethod(self): pass
2447
2448 astuff = ['Adata', 'Amethod'] + cstuff
2449 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002450 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002451 a = A()
2452 self.assertEqual(interesting(dir(a)), astuff)
2453 a.adata = 42
2454 a.amethod = lambda self: 3
2455 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002456 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002457
2458 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002459 class M(type(sys)):
2460 pass
2461 minstance = M("m")
2462 minstance.b = 2
2463 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002464 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002465 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002466 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002467 self.assertEqual(names, ['a', 'b'])
2468
2469 class M2(M):
2470 def getdict(self):
2471 return "Not a dict!"
2472 __dict__ = property(getdict)
2473
2474 m2instance = M2("m2")
2475 m2instance.b = 2
2476 m2instance.a = 1
2477 self.assertEqual(m2instance.__dict__, "Not a dict!")
2478 try:
2479 dir(m2instance)
2480 except TypeError:
2481 pass
2482
2483 # Two essentially featureless objects, just inheriting stuff from
2484 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002485 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002486
2487 # Nasty test case for proxied objects
2488 class Wrapper(object):
2489 def __init__(self, obj):
2490 self.__obj = obj
2491 def __repr__(self):
2492 return "Wrapper(%s)" % repr(self.__obj)
2493 def __getitem__(self, key):
2494 return Wrapper(self.__obj[key])
2495 def __len__(self):
2496 return len(self.__obj)
2497 def __getattr__(self, name):
2498 return Wrapper(getattr(self.__obj, name))
2499
2500 class C(object):
2501 def __getclass(self):
2502 return Wrapper(type(self))
2503 __class__ = property(__getclass)
2504
2505 dir(C()) # This used to segfault
2506
2507 def test_supers(self):
2508 # Testing super...
2509
2510 class A(object):
2511 def meth(self, a):
2512 return "A(%r)" % a
2513
2514 self.assertEqual(A().meth(1), "A(1)")
2515
2516 class B(A):
2517 def __init__(self):
2518 self.__super = super(B, self)
2519 def meth(self, a):
2520 return "B(%r)" % a + self.__super.meth(a)
2521
2522 self.assertEqual(B().meth(2), "B(2)A(2)")
2523
2524 class C(A):
2525 def meth(self, a):
2526 return "C(%r)" % a + self.__super.meth(a)
2527 C._C__super = super(C)
2528
2529 self.assertEqual(C().meth(3), "C(3)A(3)")
2530
2531 class D(C, B):
2532 def meth(self, a):
2533 return "D(%r)" % a + super(D, self).meth(a)
2534
2535 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2536
2537 # Test for subclassing super
2538
2539 class mysuper(super):
2540 def __init__(self, *args):
2541 return super(mysuper, self).__init__(*args)
2542
2543 class E(D):
2544 def meth(self, a):
2545 return "E(%r)" % a + mysuper(E, self).meth(a)
2546
2547 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2548
2549 class F(E):
2550 def meth(self, a):
2551 s = self.__super # == mysuper(F, self)
2552 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2553 F._F__super = mysuper(F)
2554
2555 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2556
2557 # Make sure certain errors are raised
2558
2559 try:
2560 super(D, 42)
2561 except TypeError:
2562 pass
2563 else:
2564 self.fail("shouldn't allow super(D, 42)")
2565
2566 try:
2567 super(D, C())
2568 except TypeError:
2569 pass
2570 else:
2571 self.fail("shouldn't allow super(D, C())")
2572
2573 try:
2574 super(D).__get__(12)
2575 except TypeError:
2576 pass
2577 else:
2578 self.fail("shouldn't allow super(D).__get__(12)")
2579
2580 try:
2581 super(D).__get__(C())
2582 except TypeError:
2583 pass
2584 else:
2585 self.fail("shouldn't allow super(D).__get__(C())")
2586
2587 # Make sure data descriptors can be overridden and accessed via super
2588 # (new feature in Python 2.3)
2589
2590 class DDbase(object):
2591 def getx(self): return 42
2592 x = property(getx)
2593
2594 class DDsub(DDbase):
2595 def getx(self): return "hello"
2596 x = property(getx)
2597
2598 dd = DDsub()
2599 self.assertEqual(dd.x, "hello")
2600 self.assertEqual(super(DDsub, dd).x, 42)
2601
2602 # Ensure that super() lookup of descriptor from classmethod
2603 # works (SF ID# 743627)
2604
2605 class Base(object):
2606 aProp = property(lambda self: "foo")
2607
2608 class Sub(Base):
2609 @classmethod
2610 def test(klass):
2611 return super(Sub,klass).aProp
2612
2613 self.assertEqual(Sub.test(), Base.aProp)
2614
2615 # Verify that super() doesn't allow keyword args
2616 try:
2617 super(Base, kw=1)
2618 except TypeError:
2619 pass
2620 else:
2621 self.assertEqual("super shouldn't accept keyword args")
2622
2623 def test_basic_inheritance(self):
2624 # Testing inheritance from basic types...
2625
2626 class hexint(int):
2627 def __repr__(self):
2628 return hex(self)
2629 def __add__(self, other):
2630 return hexint(int.__add__(self, other))
2631 # (Note that overriding __radd__ doesn't work,
2632 # because the int type gets first dibs.)
2633 self.assertEqual(repr(hexint(7) + 9), "0x10")
2634 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2635 a = hexint(12345)
2636 self.assertEqual(a, 12345)
2637 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002638 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002639 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002640 self.assertIs((+a).__class__, int)
2641 self.assertIs((a >> 0).__class__, int)
2642 self.assertIs((a << 0).__class__, int)
2643 self.assertIs((hexint(0) << 12).__class__, int)
2644 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002645
2646 class octlong(int):
2647 __slots__ = []
2648 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002649 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 def __add__(self, other):
2651 return self.__class__(super(octlong, self).__add__(other))
2652 __radd__ = __add__
2653 self.assertEqual(str(octlong(3) + 5), "0o10")
2654 # (Note that overriding __radd__ here only seems to work
2655 # because the example uses a short int left argument.)
2656 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2657 a = octlong(12345)
2658 self.assertEqual(a, 12345)
2659 self.assertEqual(int(a), 12345)
2660 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002661 self.assertIs(int(a).__class__, int)
2662 self.assertIs((+a).__class__, int)
2663 self.assertIs((-a).__class__, int)
2664 self.assertIs((-octlong(0)).__class__, int)
2665 self.assertIs((a >> 0).__class__, int)
2666 self.assertIs((a << 0).__class__, int)
2667 self.assertIs((a - 0).__class__, int)
2668 self.assertIs((a * 1).__class__, int)
2669 self.assertIs((a ** 1).__class__, int)
2670 self.assertIs((a // 1).__class__, int)
2671 self.assertIs((1 * a).__class__, int)
2672 self.assertIs((a | 0).__class__, int)
2673 self.assertIs((a ^ 0).__class__, int)
2674 self.assertIs((a & -1).__class__, int)
2675 self.assertIs((octlong(0) << 12).__class__, int)
2676 self.assertIs((octlong(0) >> 12).__class__, int)
2677 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002678
2679 # Because octlong overrides __add__, we can't check the absence of +0
2680 # optimizations using octlong.
2681 class longclone(int):
2682 pass
2683 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002684 self.assertIs((a + 0).__class__, int)
2685 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002686
2687 # Check that negative clones don't segfault
2688 a = longclone(-1)
2689 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002690 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002691
2692 class precfloat(float):
2693 __slots__ = ['prec']
2694 def __init__(self, value=0.0, prec=12):
2695 self.prec = int(prec)
2696 def __repr__(self):
2697 return "%.*g" % (self.prec, self)
2698 self.assertEqual(repr(precfloat(1.1)), "1.1")
2699 a = precfloat(12345)
2700 self.assertEqual(a, 12345.0)
2701 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002702 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002703 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002704 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002705
2706 class madcomplex(complex):
2707 def __repr__(self):
2708 return "%.17gj%+.17g" % (self.imag, self.real)
2709 a = madcomplex(-3, 4)
2710 self.assertEqual(repr(a), "4j-3")
2711 base = complex(-3, 4)
2712 self.assertEqual(base.__class__, complex)
2713 self.assertEqual(a, base)
2714 self.assertEqual(complex(a), base)
2715 self.assertEqual(complex(a).__class__, complex)
2716 a = madcomplex(a) # just trying another form of the constructor
2717 self.assertEqual(repr(a), "4j-3")
2718 self.assertEqual(a, base)
2719 self.assertEqual(complex(a), base)
2720 self.assertEqual(complex(a).__class__, complex)
2721 self.assertEqual(hash(a), hash(base))
2722 self.assertEqual((+a).__class__, complex)
2723 self.assertEqual((a + 0).__class__, complex)
2724 self.assertEqual(a + 0, base)
2725 self.assertEqual((a - 0).__class__, complex)
2726 self.assertEqual(a - 0, base)
2727 self.assertEqual((a * 1).__class__, complex)
2728 self.assertEqual(a * 1, base)
2729 self.assertEqual((a / 1).__class__, complex)
2730 self.assertEqual(a / 1, base)
2731
2732 class madtuple(tuple):
2733 _rev = None
2734 def rev(self):
2735 if self._rev is not None:
2736 return self._rev
2737 L = list(self)
2738 L.reverse()
2739 self._rev = self.__class__(L)
2740 return self._rev
2741 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2742 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2743 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2744 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2745 for i in range(512):
2746 t = madtuple(range(i))
2747 u = t.rev()
2748 v = u.rev()
2749 self.assertEqual(v, t)
2750 a = madtuple((1,2,3,4,5))
2751 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002752 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002753 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002754 self.assertIs(a[:].__class__, tuple)
2755 self.assertIs((a * 1).__class__, tuple)
2756 self.assertIs((a * 0).__class__, tuple)
2757 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002758 a = madtuple(())
2759 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002760 self.assertIs(tuple(a).__class__, tuple)
2761 self.assertIs((a + a).__class__, tuple)
2762 self.assertIs((a * 0).__class__, tuple)
2763 self.assertIs((a * 1).__class__, tuple)
2764 self.assertIs((a * 2).__class__, tuple)
2765 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002766
2767 class madstring(str):
2768 _rev = None
2769 def rev(self):
2770 if self._rev is not None:
2771 return self._rev
2772 L = list(self)
2773 L.reverse()
2774 self._rev = self.__class__("".join(L))
2775 return self._rev
2776 s = madstring("abcdefghijklmnopqrstuvwxyz")
2777 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2778 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2779 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2780 for i in range(256):
2781 s = madstring("".join(map(chr, range(i))))
2782 t = s.rev()
2783 u = t.rev()
2784 self.assertEqual(u, s)
2785 s = madstring("12345")
2786 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002787 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002788
2789 base = "\x00" * 5
2790 s = madstring(base)
2791 self.assertEqual(s, base)
2792 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002793 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002794 self.assertEqual(hash(s), hash(base))
2795 self.assertEqual({s: 1}[base], 1)
2796 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002797 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002798 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002799 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002800 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002801 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002802 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002803 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002804 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002805 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002806 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002807 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002808 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002809 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002810 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002811 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002812 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002813 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002814 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002815 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002816 self.assertEqual(s.rstrip(), base)
2817 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002818 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002819 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002820 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002821 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002822 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002823 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002824 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002825 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002826 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002827 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002828 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002829 self.assertEqual(s.lower(), base)
2830
2831 class madunicode(str):
2832 _rev = None
2833 def rev(self):
2834 if self._rev is not None:
2835 return self._rev
2836 L = list(self)
2837 L.reverse()
2838 self._rev = self.__class__("".join(L))
2839 return self._rev
2840 u = madunicode("ABCDEF")
2841 self.assertEqual(u, "ABCDEF")
2842 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2843 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2844 base = "12345"
2845 u = madunicode(base)
2846 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002847 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002848 self.assertEqual(hash(u), hash(base))
2849 self.assertEqual({u: 1}[base], 1)
2850 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002851 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002852 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002853 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002854 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002855 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002856 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002858 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002859 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002860 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002861 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002862 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002864 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002865 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002866 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002867 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002868 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002869 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002870 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002871 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002872 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002873 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002874 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002875 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002876 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002877 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002878 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002879 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002880 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002881 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002882 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002883 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002884 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002885 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002886 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002887 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002888 self.assertEqual(u[0:0], "")
2889
2890 class sublist(list):
2891 pass
2892 a = sublist(range(5))
2893 self.assertEqual(a, list(range(5)))
2894 a.append("hello")
2895 self.assertEqual(a, list(range(5)) + ["hello"])
2896 a[5] = 5
2897 self.assertEqual(a, list(range(6)))
2898 a.extend(range(6, 20))
2899 self.assertEqual(a, list(range(20)))
2900 a[-5:] = []
2901 self.assertEqual(a, list(range(15)))
2902 del a[10:15]
2903 self.assertEqual(len(a), 10)
2904 self.assertEqual(a, list(range(10)))
2905 self.assertEqual(list(a), list(range(10)))
2906 self.assertEqual(a[0], 0)
2907 self.assertEqual(a[9], 9)
2908 self.assertEqual(a[-10], 0)
2909 self.assertEqual(a[-1], 9)
2910 self.assertEqual(a[:5], list(range(5)))
2911
2912 ## class CountedInput(file):
2913 ## """Counts lines read by self.readline().
2914 ##
2915 ## self.lineno is the 0-based ordinal of the last line read, up to
2916 ## a maximum of one greater than the number of lines in the file.
2917 ##
2918 ## self.ateof is true if and only if the final "" line has been read,
2919 ## at which point self.lineno stops incrementing, and further calls
2920 ## to readline() continue to return "".
2921 ## """
2922 ##
2923 ## lineno = 0
2924 ## ateof = 0
2925 ## def readline(self):
2926 ## if self.ateof:
2927 ## return ""
2928 ## s = file.readline(self)
2929 ## # Next line works too.
2930 ## # s = super(CountedInput, self).readline()
2931 ## self.lineno += 1
2932 ## if s == "":
2933 ## self.ateof = 1
2934 ## return s
2935 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002936 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002937 ## lines = ['a\n', 'b\n', 'c\n']
2938 ## try:
2939 ## f.writelines(lines)
2940 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002941 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002942 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2943 ## got = f.readline()
2944 ## self.assertEqual(expected, got)
2945 ## self.assertEqual(f.lineno, i)
2946 ## self.assertEqual(f.ateof, (i > len(lines)))
2947 ## f.close()
2948 ## finally:
2949 ## try:
2950 ## f.close()
2951 ## except:
2952 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002953 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002954
2955 def test_keywords(self):
2956 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002957 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2958 int(x=1)
2959 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2960 float(x=2)
2961 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2962 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002963 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2964 self.assertEqual(str(object=500), '500')
2965 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002966 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2967 tuple(sequence=range(3))
2968 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2969 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00002970 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2971
2972 for constructor in (int, float, int, complex, str, str,
2973 tuple, list):
2974 try:
2975 constructor(bogus_keyword_arg=1)
2976 except TypeError:
2977 pass
2978 else:
2979 self.fail("expected TypeError from bogus keyword argument to %r"
2980 % constructor)
2981
2982 def test_str_subclass_as_dict_key(self):
2983 # Testing a str subclass used as dict key ..
2984
2985 class cistr(str):
2986 """Sublcass of str that computes __eq__ case-insensitively.
2987
2988 Also computes a hash code of the string in canonical form.
2989 """
2990
2991 def __init__(self, value):
2992 self.canonical = value.lower()
2993 self.hashcode = hash(self.canonical)
2994
2995 def __eq__(self, other):
2996 if not isinstance(other, cistr):
2997 other = cistr(other)
2998 return self.canonical == other.canonical
2999
3000 def __hash__(self):
3001 return self.hashcode
3002
3003 self.assertEqual(cistr('ABC'), 'abc')
3004 self.assertEqual('aBc', cistr('ABC'))
3005 self.assertEqual(str(cistr('ABC')), 'ABC')
3006
3007 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3008 self.assertEqual(d[cistr('one')], 1)
3009 self.assertEqual(d[cistr('tWo')], 2)
3010 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00003011 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003012 self.assertEqual(d.get(cistr('thrEE')), 3)
3013
3014 def test_classic_comparisons(self):
3015 # Testing classic comparisons...
3016 class classic:
3017 pass
3018
3019 for base in (classic, int, object):
3020 class C(base):
3021 def __init__(self, value):
3022 self.value = int(value)
3023 def __eq__(self, other):
3024 if isinstance(other, C):
3025 return self.value == other.value
3026 if isinstance(other, int) or isinstance(other, int):
3027 return self.value == other
3028 return NotImplemented
3029 def __ne__(self, other):
3030 if isinstance(other, C):
3031 return self.value != other.value
3032 if isinstance(other, int) or isinstance(other, int):
3033 return self.value != other
3034 return NotImplemented
3035 def __lt__(self, other):
3036 if isinstance(other, C):
3037 return self.value < other.value
3038 if isinstance(other, int) or isinstance(other, int):
3039 return self.value < other
3040 return NotImplemented
3041 def __le__(self, other):
3042 if isinstance(other, C):
3043 return self.value <= other.value
3044 if isinstance(other, int) or isinstance(other, int):
3045 return self.value <= other
3046 return NotImplemented
3047 def __gt__(self, other):
3048 if isinstance(other, C):
3049 return self.value > other.value
3050 if isinstance(other, int) or isinstance(other, int):
3051 return self.value > other
3052 return NotImplemented
3053 def __ge__(self, other):
3054 if isinstance(other, C):
3055 return self.value >= other.value
3056 if isinstance(other, int) or isinstance(other, int):
3057 return self.value >= other
3058 return NotImplemented
3059
3060 c1 = C(1)
3061 c2 = C(2)
3062 c3 = C(3)
3063 self.assertEqual(c1, 1)
3064 c = {1: c1, 2: c2, 3: c3}
3065 for x in 1, 2, 3:
3066 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003067 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003068 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003069 eval("x %s y" % op),
3070 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003071 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003072 eval("x %s y" % op),
3073 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003074 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003075 eval("x %s y" % op),
3076 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003077
3078 def test_rich_comparisons(self):
3079 # Testing rich comparisons...
3080 class Z(complex):
3081 pass
3082 z = Z(1)
3083 self.assertEqual(z, 1+0j)
3084 self.assertEqual(1+0j, z)
3085 class ZZ(complex):
3086 def __eq__(self, other):
3087 try:
3088 return abs(self - other) <= 1e-6
3089 except:
3090 return NotImplemented
3091 zz = ZZ(1.0000003)
3092 self.assertEqual(zz, 1+0j)
3093 self.assertEqual(1+0j, zz)
3094
3095 class classic:
3096 pass
3097 for base in (classic, int, object, list):
3098 class C(base):
3099 def __init__(self, value):
3100 self.value = int(value)
3101 def __cmp__(self_, other):
3102 self.fail("shouldn't call __cmp__")
3103 def __eq__(self, other):
3104 if isinstance(other, C):
3105 return self.value == other.value
3106 if isinstance(other, int) or isinstance(other, int):
3107 return self.value == other
3108 return NotImplemented
3109 def __ne__(self, other):
3110 if isinstance(other, C):
3111 return self.value != other.value
3112 if isinstance(other, int) or isinstance(other, int):
3113 return self.value != other
3114 return NotImplemented
3115 def __lt__(self, other):
3116 if isinstance(other, C):
3117 return self.value < other.value
3118 if isinstance(other, int) or isinstance(other, int):
3119 return self.value < other
3120 return NotImplemented
3121 def __le__(self, other):
3122 if isinstance(other, C):
3123 return self.value <= other.value
3124 if isinstance(other, int) or isinstance(other, int):
3125 return self.value <= other
3126 return NotImplemented
3127 def __gt__(self, other):
3128 if isinstance(other, C):
3129 return self.value > other.value
3130 if isinstance(other, int) or isinstance(other, int):
3131 return self.value > other
3132 return NotImplemented
3133 def __ge__(self, other):
3134 if isinstance(other, C):
3135 return self.value >= other.value
3136 if isinstance(other, int) or isinstance(other, int):
3137 return self.value >= other
3138 return NotImplemented
3139 c1 = C(1)
3140 c2 = C(2)
3141 c3 = C(3)
3142 self.assertEqual(c1, 1)
3143 c = {1: c1, 2: c2, 3: c3}
3144 for x in 1, 2, 3:
3145 for y in 1, 2, 3:
3146 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003147 self.assertEqual(eval("c[x] %s c[y]" % op),
3148 eval("x %s y" % op),
3149 "x=%d, y=%d" % (x, y))
3150 self.assertEqual(eval("c[x] %s y" % op),
3151 eval("x %s y" % op),
3152 "x=%d, y=%d" % (x, y))
3153 self.assertEqual(eval("x %s c[y]" % op),
3154 eval("x %s y" % op),
3155 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003156
3157 def test_descrdoc(self):
3158 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003159 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003160 def check(descr, what):
3161 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003162 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003163 check(complex.real, "the real part of a complex number") # member descriptor
3164
3165 def test_doc_descriptor(self):
3166 # Testing __doc__ descriptor...
3167 # SF bug 542984
3168 class DocDescr(object):
3169 def __get__(self, object, otype):
3170 if object:
3171 object = object.__class__.__name__ + ' instance'
3172 if otype:
3173 otype = otype.__name__
3174 return 'object=%s; type=%s' % (object, otype)
3175 class OldClass:
3176 __doc__ = DocDescr()
3177 class NewClass(object):
3178 __doc__ = DocDescr()
3179 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3180 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3181 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3182 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3183
3184 def test_set_class(self):
3185 # Testing __class__ assignment...
3186 class C(object): pass
3187 class D(object): pass
3188 class E(object): pass
3189 class F(D, E): pass
3190 for cls in C, D, E, F:
3191 for cls2 in C, D, E, F:
3192 x = cls()
3193 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003194 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003195 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003196 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003197 def cant(x, C):
3198 try:
3199 x.__class__ = C
3200 except TypeError:
3201 pass
3202 else:
3203 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3204 try:
3205 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003206 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003207 pass
3208 else:
3209 self.fail("shouldn't allow del %r.__class__" % x)
3210 cant(C(), list)
3211 cant(list(), C)
3212 cant(C(), 1)
3213 cant(C(), object)
3214 cant(object(), list)
3215 cant(list(), object)
3216 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003217 cant(True, int)
3218 cant(2, bool)
3219 o = object()
3220 cant(o, type(1))
3221 cant(o, type(None))
3222 del o
3223 class G(object):
3224 __slots__ = ["a", "b"]
3225 class H(object):
3226 __slots__ = ["b", "a"]
3227 class I(object):
3228 __slots__ = ["a", "b"]
3229 class J(object):
3230 __slots__ = ["c", "b"]
3231 class K(object):
3232 __slots__ = ["a", "b", "d"]
3233 class L(H):
3234 __slots__ = ["e"]
3235 class M(I):
3236 __slots__ = ["e"]
3237 class N(J):
3238 __slots__ = ["__weakref__"]
3239 class P(J):
3240 __slots__ = ["__dict__"]
3241 class Q(J):
3242 pass
3243 class R(J):
3244 __slots__ = ["__dict__", "__weakref__"]
3245
3246 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3247 x = cls()
3248 x.a = 1
3249 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003250 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003251 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3252 self.assertEqual(x.a, 1)
3253 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003254 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003255 "assigning %r as __class__ for %r silently failed" % (cls, x))
3256 self.assertEqual(x.a, 1)
3257 for cls in G, J, K, L, M, N, P, R, list, Int:
3258 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3259 if cls is cls2:
3260 continue
3261 cant(cls(), cls2)
3262
Benjamin Peterson193152c2009-04-25 01:08:45 +00003263 # Issue5283: when __class__ changes in __del__, the wrong
3264 # type gets DECREF'd.
3265 class O(object):
3266 pass
3267 class A(object):
3268 def __del__(self):
3269 self.__class__ = O
3270 l = [A() for x in range(100)]
3271 del l
3272
Georg Brandl479a7e72008-02-05 18:13:15 +00003273 def test_set_dict(self):
3274 # Testing __dict__ assignment...
3275 class C(object): pass
3276 a = C()
3277 a.__dict__ = {'b': 1}
3278 self.assertEqual(a.b, 1)
3279 def cant(x, dict):
3280 try:
3281 x.__dict__ = dict
3282 except (AttributeError, TypeError):
3283 pass
3284 else:
3285 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3286 cant(a, None)
3287 cant(a, [])
3288 cant(a, 1)
3289 del a.__dict__ # Deleting __dict__ is allowed
3290
3291 class Base(object):
3292 pass
3293 def verify_dict_readonly(x):
3294 """
3295 x has to be an instance of a class inheriting from Base.
3296 """
3297 cant(x, {})
3298 try:
3299 del x.__dict__
3300 except (AttributeError, TypeError):
3301 pass
3302 else:
3303 self.fail("shouldn't allow del %r.__dict__" % x)
3304 dict_descr = Base.__dict__["__dict__"]
3305 try:
3306 dict_descr.__set__(x, {})
3307 except (AttributeError, TypeError):
3308 pass
3309 else:
3310 self.fail("dict_descr allowed access to %r's dict" % x)
3311
3312 # Classes don't allow __dict__ assignment and have readonly dicts
3313 class Meta1(type, Base):
3314 pass
3315 class Meta2(Base, type):
3316 pass
3317 class D(object, metaclass=Meta1):
3318 pass
3319 class E(object, metaclass=Meta2):
3320 pass
3321 for cls in C, D, E:
3322 verify_dict_readonly(cls)
3323 class_dict = cls.__dict__
3324 try:
3325 class_dict["spam"] = "eggs"
3326 except TypeError:
3327 pass
3328 else:
3329 self.fail("%r's __dict__ can be modified" % cls)
3330
3331 # Modules also disallow __dict__ assignment
3332 class Module1(types.ModuleType, Base):
3333 pass
3334 class Module2(Base, types.ModuleType):
3335 pass
3336 for ModuleType in Module1, Module2:
3337 mod = ModuleType("spam")
3338 verify_dict_readonly(mod)
3339 mod.__dict__["spam"] = "eggs"
3340
3341 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003342 # (at least not any more than regular exception's __dict__ can
3343 # be deleted; on CPython it is not the case, whereas on PyPy they
3344 # can, just like any other new-style instance's __dict__.)
3345 def can_delete_dict(e):
3346 try:
3347 del e.__dict__
3348 except (TypeError, AttributeError):
3349 return False
3350 else:
3351 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003352 class Exception1(Exception, Base):
3353 pass
3354 class Exception2(Base, Exception):
3355 pass
3356 for ExceptionType in Exception, Exception1, Exception2:
3357 e = ExceptionType()
3358 e.__dict__ = {"a": 1}
3359 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003360 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003361
Georg Brandl479a7e72008-02-05 18:13:15 +00003362 def test_binary_operator_override(self):
3363 # Testing overrides of binary operations...
3364 class I(int):
3365 def __repr__(self):
3366 return "I(%r)" % int(self)
3367 def __add__(self, other):
3368 return I(int(self) + int(other))
3369 __radd__ = __add__
3370 def __pow__(self, other, mod=None):
3371 if mod is None:
3372 return I(pow(int(self), int(other)))
3373 else:
3374 return I(pow(int(self), int(other), int(mod)))
3375 def __rpow__(self, other, mod=None):
3376 if mod is None:
3377 return I(pow(int(other), int(self), mod))
3378 else:
3379 return I(pow(int(other), int(self), int(mod)))
3380
3381 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3382 self.assertEqual(repr(I(1) + 2), "I(3)")
3383 self.assertEqual(repr(1 + I(2)), "I(3)")
3384 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3385 self.assertEqual(repr(2 ** I(3)), "I(8)")
3386 self.assertEqual(repr(I(2) ** 3), "I(8)")
3387 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3388 class S(str):
3389 def __eq__(self, other):
3390 return self.lower() == other.lower()
3391
3392 def test_subclass_propagation(self):
3393 # Testing propagation of slot functions to subclasses...
3394 class A(object):
3395 pass
3396 class B(A):
3397 pass
3398 class C(A):
3399 pass
3400 class D(B, C):
3401 pass
3402 d = D()
3403 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3404 A.__hash__ = lambda self: 42
3405 self.assertEqual(hash(d), 42)
3406 C.__hash__ = lambda self: 314
3407 self.assertEqual(hash(d), 314)
3408 B.__hash__ = lambda self: 144
3409 self.assertEqual(hash(d), 144)
3410 D.__hash__ = lambda self: 100
3411 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003412 D.__hash__ = None
3413 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003414 del D.__hash__
3415 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003416 B.__hash__ = None
3417 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003418 del B.__hash__
3419 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003420 C.__hash__ = None
3421 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003422 del C.__hash__
3423 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003424 A.__hash__ = None
3425 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003426 del A.__hash__
3427 self.assertEqual(hash(d), orig_hash)
3428 d.foo = 42
3429 d.bar = 42
3430 self.assertEqual(d.foo, 42)
3431 self.assertEqual(d.bar, 42)
3432 def __getattribute__(self, name):
3433 if name == "foo":
3434 return 24
3435 return object.__getattribute__(self, name)
3436 A.__getattribute__ = __getattribute__
3437 self.assertEqual(d.foo, 24)
3438 self.assertEqual(d.bar, 42)
3439 def __getattr__(self, name):
3440 if name in ("spam", "foo", "bar"):
3441 return "hello"
3442 raise AttributeError(name)
3443 B.__getattr__ = __getattr__
3444 self.assertEqual(d.spam, "hello")
3445 self.assertEqual(d.foo, 24)
3446 self.assertEqual(d.bar, 42)
3447 del A.__getattribute__
3448 self.assertEqual(d.foo, 42)
3449 del d.foo
3450 self.assertEqual(d.foo, "hello")
3451 self.assertEqual(d.bar, 42)
3452 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003453 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003454 d.foo
3455 except AttributeError:
3456 pass
3457 else:
3458 self.fail("d.foo should be undefined now")
3459
3460 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003461 class A(object):
3462 pass
3463 class B(A):
3464 pass
3465 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003466 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003467 A.__setitem__ = lambda *a: None # crash
3468
3469 def test_buffer_inheritance(self):
3470 # Testing that buffer interface is inherited ...
3471
3472 import binascii
3473 # SF bug [#470040] ParseTuple t# vs subclasses.
3474
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003475 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003476 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003477 base = b'abc'
3478 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003479 # b2a_hex uses the buffer interface to get its argument's value, via
3480 # PyArg_ParseTuple 't#' code.
3481 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3482
Georg Brandl479a7e72008-02-05 18:13:15 +00003483 class MyInt(int):
3484 pass
3485 m = MyInt(42)
3486 try:
3487 binascii.b2a_hex(m)
3488 self.fail('subclass of int should not have a buffer interface')
3489 except TypeError:
3490 pass
3491
3492 def test_str_of_str_subclass(self):
3493 # Testing __str__ defined in subclass of str ...
3494 import binascii
3495 import io
3496
3497 class octetstring(str):
3498 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003499 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003500 def __repr__(self):
3501 return self + " repr"
3502
3503 o = octetstring('A')
3504 self.assertEqual(type(o), octetstring)
3505 self.assertEqual(type(str(o)), str)
3506 self.assertEqual(type(repr(o)), str)
3507 self.assertEqual(ord(o), 0x41)
3508 self.assertEqual(str(o), '41')
3509 self.assertEqual(repr(o), 'A repr')
3510 self.assertEqual(o.__str__(), '41')
3511 self.assertEqual(o.__repr__(), 'A repr')
3512
3513 capture = io.StringIO()
3514 # Calling str() or not exercises different internal paths.
3515 print(o, file=capture)
3516 print(str(o), file=capture)
3517 self.assertEqual(capture.getvalue(), '41\n41\n')
3518 capture.close()
3519
3520 def test_keyword_arguments(self):
3521 # Testing keyword arguments to __init__, __call__...
3522 def f(a): return a
3523 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003524 ba = bytearray()
3525 bytearray.__init__(ba, 'abc\xbd\u20ac',
3526 encoding='latin1', errors='replace')
3527 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003528
3529 def test_recursive_call(self):
3530 # Testing recursive __call__() by setting to instance of class...
3531 class A(object):
3532 pass
3533
3534 A.__call__ = A()
3535 try:
3536 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003537 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003538 pass
3539 else:
3540 self.fail("Recursion limit should have been reached for __call__()")
3541
3542 def test_delete_hook(self):
3543 # Testing __del__ hook...
3544 log = []
3545 class C(object):
3546 def __del__(self):
3547 log.append(1)
3548 c = C()
3549 self.assertEqual(log, [])
3550 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003551 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003552 self.assertEqual(log, [1])
3553
3554 class D(object): pass
3555 d = D()
3556 try: del d[0]
3557 except TypeError: pass
3558 else: self.fail("invalid del() didn't raise TypeError")
3559
3560 def test_hash_inheritance(self):
3561 # Testing hash of mutable subclasses...
3562
3563 class mydict(dict):
3564 pass
3565 d = mydict()
3566 try:
3567 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003568 except TypeError:
3569 pass
3570 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003571 self.fail("hash() of dict subclass should fail")
3572
3573 class mylist(list):
3574 pass
3575 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003576 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003577 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003578 except TypeError:
3579 pass
3580 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003581 self.fail("hash() of list subclass should fail")
3582
3583 def test_str_operations(self):
3584 try: 'a' + 5
3585 except TypeError: pass
3586 else: self.fail("'' + 5 doesn't raise TypeError")
3587
3588 try: ''.split('')
3589 except ValueError: pass
3590 else: self.fail("''.split('') doesn't raise ValueError")
3591
3592 try: ''.join([0])
3593 except TypeError: pass
3594 else: self.fail("''.join([0]) doesn't raise TypeError")
3595
3596 try: ''.rindex('5')
3597 except ValueError: pass
3598 else: self.fail("''.rindex('5') doesn't raise ValueError")
3599
3600 try: '%(n)s' % None
3601 except TypeError: pass
3602 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3603
3604 try: '%(n' % {}
3605 except ValueError: pass
3606 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3607
3608 try: '%*s' % ('abc')
3609 except TypeError: pass
3610 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3611
3612 try: '%*.*s' % ('abc', 5)
3613 except TypeError: pass
3614 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3615
3616 try: '%s' % (1, 2)
3617 except TypeError: pass
3618 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3619
3620 try: '%' % None
3621 except ValueError: pass
3622 else: self.fail("'%' % None doesn't raise ValueError")
3623
3624 self.assertEqual('534253'.isdigit(), 1)
3625 self.assertEqual('534253x'.isdigit(), 0)
3626 self.assertEqual('%c' % 5, '\x05')
3627 self.assertEqual('%c' % '5', '5')
3628
3629 def test_deepcopy_recursive(self):
3630 # Testing deepcopy of recursive objects...
3631 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003632 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003633 a = Node()
3634 b = Node()
3635 a.b = b
3636 b.a = a
3637 z = deepcopy(a) # This blew up before
3638
Martin Panterf05641642016-05-08 13:48:10 +00003639 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003640 # Testing uninitialized module objects...
3641 from types import ModuleType as M
3642 m = M.__new__(M)
3643 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003644 self.assertNotHasAttr(m, "__name__")
3645 self.assertNotHasAttr(m, "__file__")
3646 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003647 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003648 m.foo = 1
3649 self.assertEqual(m.__dict__, {"foo": 1})
3650
3651 def test_funny_new(self):
3652 # Testing __new__ returning something unexpected...
3653 class C(object):
3654 def __new__(cls, arg):
3655 if isinstance(arg, str): return [1, 2, 3]
3656 elif isinstance(arg, int): return object.__new__(D)
3657 else: return object.__new__(cls)
3658 class D(C):
3659 def __init__(self, arg):
3660 self.foo = arg
3661 self.assertEqual(C("1"), [1, 2, 3])
3662 self.assertEqual(D("1"), [1, 2, 3])
3663 d = D(None)
3664 self.assertEqual(d.foo, None)
3665 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003666 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003667 self.assertEqual(d.foo, 1)
3668 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003669 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003670 self.assertEqual(d.foo, 1)
3671
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003672 class C(object):
3673 @staticmethod
3674 def __new__(*args):
3675 return args
3676 self.assertEqual(C(1, 2), (C, 1, 2))
3677 class D(C):
3678 pass
3679 self.assertEqual(D(1, 2), (D, 1, 2))
3680
3681 class C(object):
3682 @classmethod
3683 def __new__(*args):
3684 return args
3685 self.assertEqual(C(1, 2), (C, C, 1, 2))
3686 class D(C):
3687 pass
3688 self.assertEqual(D(1, 2), (D, D, 1, 2))
3689
Georg Brandl479a7e72008-02-05 18:13:15 +00003690 def test_imul_bug(self):
3691 # Testing for __imul__ problems...
3692 # SF bug 544647
3693 class C(object):
3694 def __imul__(self, other):
3695 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003696 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003697 y = x
3698 y *= 1.0
3699 self.assertEqual(y, (x, 1.0))
3700 y = x
3701 y *= 2
3702 self.assertEqual(y, (x, 2))
3703 y = x
3704 y *= 3
3705 self.assertEqual(y, (x, 3))
3706 y = x
3707 y *= 1<<100
3708 self.assertEqual(y, (x, 1<<100))
3709 y = x
3710 y *= None
3711 self.assertEqual(y, (x, None))
3712 y = x
3713 y *= "foo"
3714 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003715
Georg Brandl479a7e72008-02-05 18:13:15 +00003716 def test_copy_setstate(self):
3717 # Testing that copy.*copy() correctly uses __setstate__...
3718 import copy
3719 class C(object):
3720 def __init__(self, foo=None):
3721 self.foo = foo
3722 self.__foo = foo
3723 def setfoo(self, foo=None):
3724 self.foo = foo
3725 def getfoo(self):
3726 return self.__foo
3727 def __getstate__(self):
3728 return [self.foo]
3729 def __setstate__(self_, lst):
3730 self.assertEqual(len(lst), 1)
3731 self_.__foo = self_.foo = lst[0]
3732 a = C(42)
3733 a.setfoo(24)
3734 self.assertEqual(a.foo, 24)
3735 self.assertEqual(a.getfoo(), 42)
3736 b = copy.copy(a)
3737 self.assertEqual(b.foo, 24)
3738 self.assertEqual(b.getfoo(), 24)
3739 b = copy.deepcopy(a)
3740 self.assertEqual(b.foo, 24)
3741 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003742
Georg Brandl479a7e72008-02-05 18:13:15 +00003743 def test_slices(self):
3744 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003745
Georg Brandl479a7e72008-02-05 18:13:15 +00003746 # Strings
3747 self.assertEqual("hello"[:4], "hell")
3748 self.assertEqual("hello"[slice(4)], "hell")
3749 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3750 class S(str):
3751 def __getitem__(self, x):
3752 return str.__getitem__(self, x)
3753 self.assertEqual(S("hello")[:4], "hell")
3754 self.assertEqual(S("hello")[slice(4)], "hell")
3755 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3756 # Tuples
3757 self.assertEqual((1,2,3)[:2], (1,2))
3758 self.assertEqual((1,2,3)[slice(2)], (1,2))
3759 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3760 class T(tuple):
3761 def __getitem__(self, x):
3762 return tuple.__getitem__(self, x)
3763 self.assertEqual(T((1,2,3))[:2], (1,2))
3764 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3765 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3766 # Lists
3767 self.assertEqual([1,2,3][:2], [1,2])
3768 self.assertEqual([1,2,3][slice(2)], [1,2])
3769 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3770 class L(list):
3771 def __getitem__(self, x):
3772 return list.__getitem__(self, x)
3773 self.assertEqual(L([1,2,3])[:2], [1,2])
3774 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3775 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3776 # Now do lists and __setitem__
3777 a = L([1,2,3])
3778 a[slice(1, 3)] = [3,2]
3779 self.assertEqual(a, [1,3,2])
3780 a[slice(0, 2, 1)] = [3,1]
3781 self.assertEqual(a, [3,1,2])
3782 a.__setitem__(slice(1, 3), [2,1])
3783 self.assertEqual(a, [3,2,1])
3784 a.__setitem__(slice(0, 2, 1), [2,3])
3785 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003786
Georg Brandl479a7e72008-02-05 18:13:15 +00003787 def test_subtype_resurrection(self):
3788 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003789
Georg Brandl479a7e72008-02-05 18:13:15 +00003790 class C(object):
3791 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003792
Georg Brandl479a7e72008-02-05 18:13:15 +00003793 def __del__(self):
3794 # resurrect the instance
3795 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003796
Georg Brandl479a7e72008-02-05 18:13:15 +00003797 c = C()
3798 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003799
Benjamin Petersone549ead2009-03-28 21:42:05 +00003800 # The most interesting thing here is whether this blows up, due to
3801 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3802 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003803 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003804
Benjamin Petersone549ead2009-03-28 21:42:05 +00003805 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003806 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003807
Georg Brandl479a7e72008-02-05 18:13:15 +00003808 # Make c mortal again, so that the test framework with -l doesn't report
3809 # it as a leak.
3810 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003811
Georg Brandl479a7e72008-02-05 18:13:15 +00003812 def test_slots_trash(self):
3813 # Testing slot trash...
3814 # Deallocating deeply nested slotted trash caused stack overflows
3815 class trash(object):
3816 __slots__ = ['x']
3817 def __init__(self, x):
3818 self.x = x
3819 o = None
3820 for i in range(50000):
3821 o = trash(o)
3822 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003823
Georg Brandl479a7e72008-02-05 18:13:15 +00003824 def test_slots_multiple_inheritance(self):
3825 # SF bug 575229, multiple inheritance w/ slots dumps core
3826 class A(object):
3827 __slots__=()
3828 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003829 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003830 class C(A,B) :
3831 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003832 if support.check_impl_detail():
3833 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003834 self.assertHasAttr(C, '__dict__')
3835 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003836 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003837
Georg Brandl479a7e72008-02-05 18:13:15 +00003838 def test_rmul(self):
3839 # Testing correct invocation of __rmul__...
3840 # SF patch 592646
3841 class C(object):
3842 def __mul__(self, other):
3843 return "mul"
3844 def __rmul__(self, other):
3845 return "rmul"
3846 a = C()
3847 self.assertEqual(a*2, "mul")
3848 self.assertEqual(a*2.2, "mul")
3849 self.assertEqual(2*a, "rmul")
3850 self.assertEqual(2.2*a, "rmul")
3851
3852 def test_ipow(self):
3853 # Testing correct invocation of __ipow__...
3854 # [SF bug 620179]
3855 class C(object):
3856 def __ipow__(self, other):
3857 pass
3858 a = C()
3859 a **= 2
3860
3861 def test_mutable_bases(self):
3862 # Testing mutable bases...
3863
3864 # stuff that should work:
3865 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003866 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003867 class C2(object):
3868 def __getattribute__(self, attr):
3869 if attr == 'a':
3870 return 2
3871 else:
3872 return super(C2, self).__getattribute__(attr)
3873 def meth(self):
3874 return 1
3875 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003876 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003877 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003878 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003879 d = D()
3880 e = E()
3881 D.__bases__ = (C,)
3882 D.__bases__ = (C2,)
3883 self.assertEqual(d.meth(), 1)
3884 self.assertEqual(e.meth(), 1)
3885 self.assertEqual(d.a, 2)
3886 self.assertEqual(e.a, 2)
3887 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003888
Georg Brandl479a7e72008-02-05 18:13:15 +00003889 try:
3890 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003891 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003892 pass
3893 else:
3894 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003895
Georg Brandl479a7e72008-02-05 18:13:15 +00003896 try:
3897 D.__bases__ = ()
3898 except TypeError as msg:
3899 if str(msg) == "a new-style class can't have only classic bases":
3900 self.fail("wrong error message for .__bases__ = ()")
3901 else:
3902 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003903
Georg Brandl479a7e72008-02-05 18:13:15 +00003904 try:
3905 D.__bases__ = (D,)
3906 except TypeError:
3907 pass
3908 else:
3909 # actually, we'll have crashed by here...
3910 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003911
Georg Brandl479a7e72008-02-05 18:13:15 +00003912 try:
3913 D.__bases__ = (C, C)
3914 except TypeError:
3915 pass
3916 else:
3917 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003918
Georg Brandl479a7e72008-02-05 18:13:15 +00003919 try:
3920 D.__bases__ = (E,)
3921 except TypeError:
3922 pass
3923 else:
3924 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003925
Benjamin Petersonae937c02009-04-18 20:54:08 +00003926 def test_builtin_bases(self):
3927 # Make sure all the builtin types can have their base queried without
3928 # segfaulting. See issue #5787.
3929 builtin_types = [tp for tp in builtins.__dict__.values()
3930 if isinstance(tp, type)]
3931 for tp in builtin_types:
3932 object.__getattribute__(tp, "__bases__")
3933 if tp is not object:
3934 self.assertEqual(len(tp.__bases__), 1, tp)
3935
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003936 class L(list):
3937 pass
3938
3939 class C(object):
3940 pass
3941
3942 class D(C):
3943 pass
3944
3945 try:
3946 L.__bases__ = (dict,)
3947 except TypeError:
3948 pass
3949 else:
3950 self.fail("shouldn't turn list subclass into dict subclass")
3951
3952 try:
3953 list.__bases__ = (dict,)
3954 except TypeError:
3955 pass
3956 else:
3957 self.fail("shouldn't be able to assign to list.__bases__")
3958
3959 try:
3960 D.__bases__ = (C, list)
3961 except TypeError:
3962 pass
3963 else:
3964 assert 0, "best_base calculation found wanting"
3965
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003966 def test_unsubclassable_types(self):
3967 with self.assertRaises(TypeError):
3968 class X(type(None)):
3969 pass
3970 with self.assertRaises(TypeError):
3971 class X(object, type(None)):
3972 pass
3973 with self.assertRaises(TypeError):
3974 class X(type(None), object):
3975 pass
3976 class O(object):
3977 pass
3978 with self.assertRaises(TypeError):
3979 class X(O, type(None)):
3980 pass
3981 with self.assertRaises(TypeError):
3982 class X(type(None), O):
3983 pass
3984
3985 class X(object):
3986 pass
3987 with self.assertRaises(TypeError):
3988 X.__bases__ = type(None),
3989 with self.assertRaises(TypeError):
3990 X.__bases__ = object, type(None)
3991 with self.assertRaises(TypeError):
3992 X.__bases__ = type(None), object
3993 with self.assertRaises(TypeError):
3994 X.__bases__ = O, type(None)
3995 with self.assertRaises(TypeError):
3996 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00003997
Georg Brandl479a7e72008-02-05 18:13:15 +00003998 def test_mutable_bases_with_failing_mro(self):
3999 # Testing mutable bases with failing mro...
4000 class WorkOnce(type):
4001 def __new__(self, name, bases, ns):
4002 self.flag = 0
4003 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4004 def mro(self):
4005 if self.flag > 0:
4006 raise RuntimeError("bozo")
4007 else:
4008 self.flag += 1
4009 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004010
Georg Brandl479a7e72008-02-05 18:13:15 +00004011 class WorkAlways(type):
4012 def mro(self):
4013 # this is here to make sure that .mro()s aren't called
4014 # with an exception set (which was possible at one point).
4015 # An error message will be printed in a debug build.
4016 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004017 return type.mro(self)
4018
Georg Brandl479a7e72008-02-05 18:13:15 +00004019 class C(object):
4020 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004021
Georg Brandl479a7e72008-02-05 18:13:15 +00004022 class C2(object):
4023 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004024
Georg Brandl479a7e72008-02-05 18:13:15 +00004025 class D(C):
4026 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004027
Georg Brandl479a7e72008-02-05 18:13:15 +00004028 class E(D):
4029 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004030
Georg Brandl479a7e72008-02-05 18:13:15 +00004031 class F(D, metaclass=WorkOnce):
4032 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004033
Georg Brandl479a7e72008-02-05 18:13:15 +00004034 class G(D, metaclass=WorkAlways):
4035 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004036
Georg Brandl479a7e72008-02-05 18:13:15 +00004037 # Immediate subclasses have their mro's adjusted in alphabetical
4038 # order, so E's will get adjusted before adjusting F's fails. We
4039 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004040
Georg Brandl479a7e72008-02-05 18:13:15 +00004041 E_mro_before = E.__mro__
4042 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004043
Armin Rigofd163f92005-12-29 15:59:19 +00004044 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004045 D.__bases__ = (C2,)
4046 except RuntimeError:
4047 self.assertEqual(E.__mro__, E_mro_before)
4048 self.assertEqual(D.__mro__, D_mro_before)
4049 else:
4050 self.fail("exception not propagated")
4051
4052 def test_mutable_bases_catch_mro_conflict(self):
4053 # Testing mutable bases catch mro conflict...
4054 class A(object):
4055 pass
4056
4057 class B(object):
4058 pass
4059
4060 class C(A, B):
4061 pass
4062
4063 class D(A, B):
4064 pass
4065
4066 class E(C, D):
4067 pass
4068
4069 try:
4070 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004071 except TypeError:
4072 pass
4073 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004074 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004075
Georg Brandl479a7e72008-02-05 18:13:15 +00004076 def test_mutable_names(self):
4077 # Testing mutable names...
4078 class C(object):
4079 pass
4080
4081 # C.__module__ could be 'test_descr' or '__main__'
4082 mod = C.__module__
4083
4084 C.__name__ = 'D'
4085 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4086
4087 C.__name__ = 'D.E'
4088 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4089
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004090 def test_evil_type_name(self):
4091 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4092 # execution while the type structure was not in a sane state, and a
4093 # possible segmentation fault as a result. See bug #16447.
4094 class Nasty(str):
4095 def __del__(self):
4096 C.__name__ = "other"
4097
4098 class C:
4099 pass
4100
4101 C.__name__ = Nasty("abc")
4102 C.__name__ = "normal"
4103
Georg Brandl479a7e72008-02-05 18:13:15 +00004104 def test_subclass_right_op(self):
4105 # Testing correct dispatch of subclass overloading __r<op>__...
4106
4107 # This code tests various cases where right-dispatch of a subclass
4108 # should be preferred over left-dispatch of a base class.
4109
4110 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4111
4112 class B(int):
4113 def __floordiv__(self, other):
4114 return "B.__floordiv__"
4115 def __rfloordiv__(self, other):
4116 return "B.__rfloordiv__"
4117
4118 self.assertEqual(B(1) // 1, "B.__floordiv__")
4119 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4120
4121 # Case 2: subclass of object; this is just the baseline for case 3
4122
4123 class C(object):
4124 def __floordiv__(self, other):
4125 return "C.__floordiv__"
4126 def __rfloordiv__(self, other):
4127 return "C.__rfloordiv__"
4128
4129 self.assertEqual(C() // 1, "C.__floordiv__")
4130 self.assertEqual(1 // C(), "C.__rfloordiv__")
4131
4132 # Case 3: subclass of new-style class; here it gets interesting
4133
4134 class D(C):
4135 def __floordiv__(self, other):
4136 return "D.__floordiv__"
4137 def __rfloordiv__(self, other):
4138 return "D.__rfloordiv__"
4139
4140 self.assertEqual(D() // C(), "D.__floordiv__")
4141 self.assertEqual(C() // D(), "D.__rfloordiv__")
4142
4143 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4144
4145 class E(C):
4146 pass
4147
4148 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4149
4150 self.assertEqual(E() // 1, "C.__floordiv__")
4151 self.assertEqual(1 // E(), "C.__rfloordiv__")
4152 self.assertEqual(E() // C(), "C.__floordiv__")
4153 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4154
Benjamin Petersone549ead2009-03-28 21:42:05 +00004155 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004156 def test_meth_class_get(self):
4157 # Testing __get__ method of METH_CLASS C methods...
4158 # Full coverage of descrobject.c::classmethod_get()
4159
4160 # Baseline
4161 arg = [1, 2, 3]
4162 res = {1: None, 2: None, 3: None}
4163 self.assertEqual(dict.fromkeys(arg), res)
4164 self.assertEqual({}.fromkeys(arg), res)
4165
4166 # Now get the descriptor
4167 descr = dict.__dict__["fromkeys"]
4168
4169 # More baseline using the descriptor directly
4170 self.assertEqual(descr.__get__(None, dict)(arg), res)
4171 self.assertEqual(descr.__get__({})(arg), res)
4172
4173 # Now check various error cases
4174 try:
4175 descr.__get__(None, None)
4176 except TypeError:
4177 pass
4178 else:
4179 self.fail("shouldn't have allowed descr.__get__(None, None)")
4180 try:
4181 descr.__get__(42)
4182 except TypeError:
4183 pass
4184 else:
4185 self.fail("shouldn't have allowed descr.__get__(42)")
4186 try:
4187 descr.__get__(None, 42)
4188 except TypeError:
4189 pass
4190 else:
4191 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4192 try:
4193 descr.__get__(None, int)
4194 except TypeError:
4195 pass
4196 else:
4197 self.fail("shouldn't have allowed descr.__get__(None, int)")
4198
4199 def test_isinst_isclass(self):
4200 # Testing proxy isinstance() and isclass()...
4201 class Proxy(object):
4202 def __init__(self, obj):
4203 self.__obj = obj
4204 def __getattribute__(self, name):
4205 if name.startswith("_Proxy__"):
4206 return object.__getattribute__(self, name)
4207 else:
4208 return getattr(self.__obj, name)
4209 # Test with a classic class
4210 class C:
4211 pass
4212 a = C()
4213 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004214 self.assertIsInstance(a, C) # Baseline
4215 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004216 # Test with a classic subclass
4217 class D(C):
4218 pass
4219 a = D()
4220 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004221 self.assertIsInstance(a, C) # Baseline
4222 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004223 # Test with a new-style class
4224 class C(object):
4225 pass
4226 a = C()
4227 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004228 self.assertIsInstance(a, C) # Baseline
4229 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004230 # Test with a new-style subclass
4231 class D(C):
4232 pass
4233 a = D()
4234 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004235 self.assertIsInstance(a, C) # Baseline
4236 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004237
4238 def test_proxy_super(self):
4239 # Testing super() for a proxy object...
4240 class Proxy(object):
4241 def __init__(self, obj):
4242 self.__obj = obj
4243 def __getattribute__(self, name):
4244 if name.startswith("_Proxy__"):
4245 return object.__getattribute__(self, name)
4246 else:
4247 return getattr(self.__obj, name)
4248
4249 class B(object):
4250 def f(self):
4251 return "B.f"
4252
4253 class C(B):
4254 def f(self):
4255 return super(C, self).f() + "->C.f"
4256
4257 obj = C()
4258 p = Proxy(obj)
4259 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4260
4261 def test_carloverre(self):
4262 # Testing prohibition of Carlo Verre's hack...
4263 try:
4264 object.__setattr__(str, "foo", 42)
4265 except TypeError:
4266 pass
4267 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004268 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004269 try:
4270 object.__delattr__(str, "lower")
4271 except TypeError:
4272 pass
4273 else:
4274 self.fail("Carlo Verre __delattr__ succeeded!")
4275
4276 def test_weakref_segfault(self):
4277 # Testing weakref segfault...
4278 # SF 742911
4279 import weakref
4280
4281 class Provoker:
4282 def __init__(self, referrent):
4283 self.ref = weakref.ref(referrent)
4284
4285 def __del__(self):
4286 x = self.ref()
4287
4288 class Oops(object):
4289 pass
4290
4291 o = Oops()
4292 o.whatever = Provoker(o)
4293 del o
4294
4295 def test_wrapper_segfault(self):
4296 # SF 927248: deeply nested wrappers could cause stack overflow
4297 f = lambda:None
4298 for i in range(1000000):
4299 f = f.__call__
4300 f = None
4301
4302 def test_file_fault(self):
4303 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004304 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004305 class StdoutGuard:
4306 def __getattr__(self, attr):
4307 sys.stdout = sys.__stdout__
4308 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4309 sys.stdout = StdoutGuard()
4310 try:
4311 print("Oops!")
4312 except RuntimeError:
4313 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004314 finally:
4315 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004316
4317 def test_vicious_descriptor_nonsense(self):
4318 # Testing vicious_descriptor_nonsense...
4319
4320 # A potential segfault spotted by Thomas Wouters in mail to
4321 # python-dev 2003-04-17, turned into an example & fixed by Michael
4322 # Hudson just less than four months later...
4323
4324 class Evil(object):
4325 def __hash__(self):
4326 return hash('attr')
4327 def __eq__(self, other):
4328 del C.attr
4329 return 0
4330
4331 class Descr(object):
4332 def __get__(self, ob, type=None):
4333 return 1
4334
4335 class C(object):
4336 attr = Descr()
4337
4338 c = C()
4339 c.__dict__[Evil()] = 0
4340
4341 self.assertEqual(c.attr, 1)
4342 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004343 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004344 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004345
4346 def test_init(self):
4347 # SF 1155938
4348 class Foo(object):
4349 def __init__(self):
4350 return 10
4351 try:
4352 Foo()
4353 except TypeError:
4354 pass
4355 else:
4356 self.fail("did not test __init__() for None return")
4357
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004358 def assertNotOrderable(self, a, b):
4359 with self.assertRaises(TypeError):
4360 a < b
4361 with self.assertRaises(TypeError):
4362 a > b
4363 with self.assertRaises(TypeError):
4364 a <= b
4365 with self.assertRaises(TypeError):
4366 a >= b
4367
Georg Brandl479a7e72008-02-05 18:13:15 +00004368 def test_method_wrapper(self):
4369 # Testing method-wrapper objects...
4370 # <type 'method-wrapper'> did not support any reflection before 2.5
Georg Brandl479a7e72008-02-05 18:13:15 +00004371 l = []
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004372 self.assertTrue(l.__add__ == l.__add__)
4373 self.assertFalse(l.__add__ != l.__add__)
4374 self.assertFalse(l.__add__ == [].__add__)
4375 self.assertTrue(l.__add__ != [].__add__)
4376 self.assertFalse(l.__add__ == l.__mul__)
4377 self.assertTrue(l.__add__ != l.__mul__)
4378 self.assertNotOrderable(l.__add__, l.__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004379 self.assertEqual(l.__add__.__name__, '__add__')
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004380 self.assertIs(l.__add__.__self__, l)
4381 self.assertIs(l.__add__.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004382 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004383 # hash([].__add__) should not be based on hash([])
4384 hash(l.__add__)
Georg Brandl479a7e72008-02-05 18:13:15 +00004385
Serhiy Storchakaac20e0f2018-07-31 09:18:24 +03004386 def test_builtin_function_or_method(self):
4387 # Not really belonging to test_descr, but introspection and
4388 # comparison on <type 'builtin_function_or_method'> seems not
4389 # to be tested elsewhere
4390 l = []
4391 self.assertTrue(l.append == l.append)
4392 self.assertFalse(l.append != l.append)
4393 self.assertFalse(l.append == [].append)
4394 self.assertTrue(l.append != [].append)
4395 self.assertFalse(l.append == l.pop)
4396 self.assertTrue(l.append != l.pop)
4397 self.assertNotOrderable(l.append, l.append)
4398 self.assertEqual(l.append.__name__, 'append')
4399 self.assertIs(l.append.__self__, l)
4400 # self.assertIs(l.append.__objclass__, list) --- could be added?
4401 self.assertEqual(l.append.__doc__, list.append.__doc__)
4402 # hash([].append) should not be based on hash([])
4403 hash(l.append)
4404
4405 def test_special_unbound_method_types(self):
4406 # Testing objects of <type 'wrapper_descriptor'>...
4407 self.assertTrue(list.__add__ == list.__add__)
4408 self.assertFalse(list.__add__ != list.__add__)
4409 self.assertFalse(list.__add__ == list.__mul__)
4410 self.assertTrue(list.__add__ != list.__mul__)
4411 self.assertNotOrderable(list.__add__, list.__add__)
4412 self.assertEqual(list.__add__.__name__, '__add__')
4413 self.assertIs(list.__add__.__objclass__, list)
4414
4415 # Testing objects of <type 'method_descriptor'>...
4416 self.assertTrue(list.append == list.append)
4417 self.assertFalse(list.append != list.append)
4418 self.assertFalse(list.append == list.pop)
4419 self.assertTrue(list.append != list.pop)
4420 self.assertNotOrderable(list.append, list.append)
4421 self.assertEqual(list.append.__name__, 'append')
4422 self.assertIs(list.append.__objclass__, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004423
4424 def test_not_implemented(self):
4425 # Testing NotImplemented...
4426 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004427 import operator
4428
4429 def specialmethod(self, other):
4430 return NotImplemented
4431
4432 def check(expr, x, y):
4433 try:
4434 exec(expr, {'x': x, 'y': y, 'operator': operator})
4435 except TypeError:
4436 pass
4437 else:
4438 self.fail("no TypeError from %r" % (expr,))
4439
4440 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4441 # TypeErrors
4442 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4443 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004444 for name, expr, iexpr in [
4445 ('__add__', 'x + y', 'x += y'),
4446 ('__sub__', 'x - y', 'x -= y'),
4447 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004448 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004449 ('__truediv__', 'x / y', 'x /= y'),
4450 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004451 ('__mod__', 'x % y', 'x %= y'),
4452 ('__divmod__', 'divmod(x, y)', None),
4453 ('__pow__', 'x ** y', 'x **= y'),
4454 ('__lshift__', 'x << y', 'x <<= y'),
4455 ('__rshift__', 'x >> y', 'x >>= y'),
4456 ('__and__', 'x & y', 'x &= y'),
4457 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004458 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004459 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004460 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004461 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004462 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004463 check(expr, a, N1)
4464 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004465 if iexpr:
4466 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004467 check(iexpr, a, N1)
4468 check(iexpr, a, N2)
4469 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004470 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004471 c = C()
4472 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004473 check(iexpr, c, N1)
4474 check(iexpr, c, N2)
4475
Georg Brandl479a7e72008-02-05 18:13:15 +00004476 def test_assign_slice(self):
4477 # ceval.c's assign_slice used to check for
4478 # tp->tp_as_sequence->sq_slice instead of
4479 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004480
Georg Brandl479a7e72008-02-05 18:13:15 +00004481 class C(object):
4482 def __setitem__(self, idx, value):
4483 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004484
Georg Brandl479a7e72008-02-05 18:13:15 +00004485 c = C()
4486 c[1:2] = 3
4487 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004488
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004489 def test_set_and_no_get(self):
4490 # See
4491 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4492 class Descr(object):
4493
4494 def __init__(self, name):
4495 self.name = name
4496
4497 def __set__(self, obj, value):
4498 obj.__dict__[self.name] = value
4499 descr = Descr("a")
4500
4501 class X(object):
4502 a = descr
4503
4504 x = X()
4505 self.assertIs(x.a, descr)
4506 x.a = 42
4507 self.assertEqual(x.a, 42)
4508
Benjamin Peterson21896a32010-03-21 22:03:03 +00004509 # Also check type_getattro for correctness.
4510 class Meta(type):
4511 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004512 class X(metaclass=Meta):
4513 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004514 X.a = 42
4515 Meta.a = Descr("a")
4516 self.assertEqual(X.a, 42)
4517
Benjamin Peterson9262b842008-11-17 22:45:50 +00004518 def test_getattr_hooks(self):
4519 # issue 4230
4520
4521 class Descriptor(object):
4522 counter = 0
4523 def __get__(self, obj, objtype=None):
4524 def getter(name):
4525 self.counter += 1
4526 raise AttributeError(name)
4527 return getter
4528
4529 descr = Descriptor()
4530 class A(object):
4531 __getattribute__ = descr
4532 class B(object):
4533 __getattr__ = descr
4534 class C(object):
4535 __getattribute__ = descr
4536 __getattr__ = descr
4537
4538 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004539 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004540 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004541 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004542 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004543 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004544
Benjamin Peterson9262b842008-11-17 22:45:50 +00004545 class EvilGetattribute(object):
4546 # This used to segfault
4547 def __getattr__(self, name):
4548 raise AttributeError(name)
4549 def __getattribute__(self, name):
4550 del EvilGetattribute.__getattr__
4551 for i in range(5):
4552 gc.collect()
4553 raise AttributeError(name)
4554
4555 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4556
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004557 def test_type___getattribute__(self):
4558 self.assertRaises(TypeError, type.__getattribute__, list, type)
4559
Benjamin Peterson477ba912011-01-12 15:34:01 +00004560 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004561 # type pretends not to have __abstractmethods__.
4562 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4563 class meta(type):
4564 pass
4565 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004566 class X(object):
4567 pass
4568 with self.assertRaises(AttributeError):
4569 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004570
Victor Stinner3249dec2011-05-01 23:19:15 +02004571 def test_proxy_call(self):
4572 class FakeStr:
4573 __class__ = str
4574
4575 fake_str = FakeStr()
4576 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004577 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004578
4579 # call a method descriptor
4580 with self.assertRaises(TypeError):
4581 str.split(fake_str)
4582
4583 # call a slot wrapper descriptor
4584 with self.assertRaises(TypeError):
4585 str.__add__(fake_str, "abc")
4586
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004587 def test_repr_as_str(self):
4588 # Issue #11603: crash or infinite loop when rebinding __str__ as
4589 # __repr__.
4590 class Foo:
4591 pass
4592 Foo.__repr__ = Foo.__str__
4593 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004594 self.assertRaises(RecursionError, str, foo)
4595 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004596
4597 def test_mixing_slot_wrappers(self):
4598 class X(dict):
4599 __setattr__ = dict.__setitem__
4600 x = X()
4601 x.y = 42
4602 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004603
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004604 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004605 with self.assertRaises(ValueError) as cm:
4606 class X:
4607 __slots__ = ["foo"]
4608 foo = None
4609 m = str(cm.exception)
4610 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4611
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004612 def test_set_doc(self):
4613 class X:
4614 "elephant"
4615 X.__doc__ = "banana"
4616 self.assertEqual(X.__doc__, "banana")
4617 with self.assertRaises(TypeError) as cm:
4618 type(list).__dict__["__doc__"].__set__(list, "blah")
4619 self.assertIn("can't set list.__doc__", str(cm.exception))
4620 with self.assertRaises(TypeError) as cm:
4621 type(X).__dict__["__doc__"].__delete__(X)
4622 self.assertIn("can't delete X.__doc__", str(cm.exception))
4623 self.assertEqual(X.__doc__, "banana")
4624
Antoine Pitrou9d574812011-12-12 13:47:25 +01004625 def test_qualname(self):
4626 descriptors = [str.lower, complex.real, float.real, int.__add__]
4627 types = ['method', 'member', 'getset', 'wrapper']
4628
4629 # make sure we have an example of each type of descriptor
4630 for d, n in zip(descriptors, types):
4631 self.assertEqual(type(d).__name__, n + '_descriptor')
4632
4633 for d in descriptors:
4634 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4635 self.assertEqual(d.__qualname__, qualname)
4636
4637 self.assertEqual(str.lower.__qualname__, 'str.lower')
4638 self.assertEqual(complex.real.__qualname__, 'complex.real')
4639 self.assertEqual(float.real.__qualname__, 'float.real')
4640 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4641
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004642 class X:
4643 pass
4644 with self.assertRaises(TypeError):
4645 del X.__qualname__
4646
4647 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4648 str, 'Oink')
4649
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004650 global Y
4651 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004652 class Inside:
4653 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004654 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004655 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004656
Victor Stinner6f738742012-02-25 01:22:36 +01004657 def test_qualname_dict(self):
4658 ns = {'__qualname__': 'some.name'}
4659 tp = type('Foo', (), ns)
4660 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004661 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004662 self.assertEqual(ns, {'__qualname__': 'some.name'})
4663
4664 ns = {'__qualname__': 1}
4665 self.assertRaises(TypeError, type, 'Foo', (), ns)
4666
Benjamin Peterson52c42432012-03-07 18:41:11 -06004667 def test_cycle_through_dict(self):
4668 # See bug #1469629
4669 class X(dict):
4670 def __init__(self):
4671 dict.__init__(self)
4672 self.__dict__ = self
4673 x = X()
4674 x.attr = 42
4675 wr = weakref.ref(x)
4676 del x
4677 support.gc_collect()
4678 self.assertIsNone(wr())
4679 for o in gc.get_objects():
4680 self.assertIsNot(type(o), X)
4681
Benjamin Peterson96384b92012-03-17 00:05:44 -05004682 def test_object_new_and_init_with_parameters(self):
4683 # See issue #1683368
4684 class OverrideNeither:
4685 pass
4686 self.assertRaises(TypeError, OverrideNeither, 1)
4687 self.assertRaises(TypeError, OverrideNeither, kw=1)
4688 class OverrideNew:
4689 def __new__(cls, foo, kw=0, *args, **kwds):
4690 return object.__new__(cls, *args, **kwds)
4691 class OverrideInit:
4692 def __init__(self, foo, kw=0, *args, **kwargs):
4693 return object.__init__(self, *args, **kwargs)
4694 class OverrideBoth(OverrideNew, OverrideInit):
4695 pass
4696 for case in OverrideNew, OverrideInit, OverrideBoth:
4697 case(1)
4698 case(1, kw=2)
4699 self.assertRaises(TypeError, case, 1, 2, 3)
4700 self.assertRaises(TypeError, case, 1, 2, foo=3)
4701
Benjamin Petersondf813792014-03-17 15:57:17 -05004702 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4703 class Base:
4704 pass
4705 class Sub(Base):
4706 pass
4707 self.assertIn("__dict__", Base.__dict__)
4708 self.assertNotIn("__dict__", Sub.__dict__)
4709
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004710 def test_bound_method_repr(self):
4711 class Foo:
4712 def method(self):
4713 pass
4714 self.assertRegex(repr(Foo().method),
4715 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4716
4717
4718 class Base:
4719 def method(self):
4720 pass
4721 class Derived1(Base):
4722 pass
4723 class Derived2(Base):
4724 def method(self):
4725 pass
4726 base = Base()
4727 derived1 = Derived1()
4728 derived2 = Derived2()
4729 super_d2 = super(Derived2, derived2)
4730 self.assertRegex(repr(base.method),
4731 r"<bound method .*Base\.method of <.*Base object at .*>>")
4732 self.assertRegex(repr(derived1.method),
4733 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4734 self.assertRegex(repr(derived2.method),
4735 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4736 self.assertRegex(repr(super_d2.method),
4737 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4738
4739 class Foo:
4740 @classmethod
4741 def method(cls):
4742 pass
4743 foo = Foo()
4744 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004745 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004746 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004747 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004748
4749
4750 class MyCallable:
4751 def __call__(self, arg):
4752 pass
4753 func = MyCallable() # func has no __name__ or __qualname__ attributes
4754 instance = object()
4755 method = types.MethodType(func, instance)
4756 self.assertRegex(repr(method),
4757 r"<bound method \? of <object object at .*>>")
4758 func.__name__ = "name"
4759 self.assertRegex(repr(method),
4760 r"<bound method name of <object object at .*>>")
4761 func.__qualname__ = "qualname"
4762 self.assertRegex(repr(method),
4763 r"<bound method qualname of <object object at .*>>")
4764
jdemeyer5a306202018-10-19 23:50:06 +02004765 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4766 def test_bpo25750(self):
4767 # bpo-25750: calling a descriptor (implemented as built-in
4768 # function with METH_FASTCALL) should not crash CPython if the
4769 # descriptor deletes itself from the class.
4770 class Descr:
4771 __get__ = _testcapi.bad_get
4772
4773 class X:
4774 descr = Descr()
4775 def __new__(cls):
4776 cls.descr = None
4777 # Create this large list to corrupt some unused memory
4778 cls.lst = [2**i for i in range(10000)]
4779 X.descr
4780
Antoine Pitrou9d574812011-12-12 13:47:25 +01004781
Georg Brandl479a7e72008-02-05 18:13:15 +00004782class DictProxyTests(unittest.TestCase):
4783 def setUp(self):
4784 class C(object):
4785 def meth(self):
4786 pass
4787 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004788
Brett Cannon7a540732011-02-22 03:04:06 +00004789 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4790 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004791 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004792 # Testing dict-proxy keys...
4793 it = self.C.__dict__.keys()
4794 self.assertNotIsInstance(it, list)
4795 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004796 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004797 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004798 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004799
Brett Cannon7a540732011-02-22 03:04:06 +00004800 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4801 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004802 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004803 # Testing dict-proxy values...
4804 it = self.C.__dict__.values()
4805 self.assertNotIsInstance(it, list)
4806 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004807 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004808
Brett Cannon7a540732011-02-22 03:04:06 +00004809 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4810 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004811 def test_iter_items(self):
4812 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004813 it = self.C.__dict__.items()
4814 self.assertNotIsInstance(it, list)
4815 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004816 keys.sort()
4817 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004818 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004819
Georg Brandl479a7e72008-02-05 18:13:15 +00004820 def test_dict_type_with_metaclass(self):
4821 # Testing type of __dict__ when metaclass set...
4822 class B(object):
4823 pass
4824 class M(type):
4825 pass
4826 class C(metaclass=M):
4827 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4828 pass
4829 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004830
Ezio Melottiac53ab62010-12-18 14:59:43 +00004831 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004832 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004833 # We can't blindly compare with the repr of another dict as ordering
4834 # of keys and values is arbitrary and may differ.
4835 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004836 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004837 self.assertTrue(r.endswith(')'), r)
4838 for k, v in self.C.__dict__.items():
4839 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004840
Christian Heimesbbffeb62008-01-24 09:42:52 +00004841
Georg Brandl479a7e72008-02-05 18:13:15 +00004842class PTypesLongInitTest(unittest.TestCase):
4843 # This is in its own TestCase so that it can be run before any other tests.
4844 def test_pytype_long_ready(self):
4845 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004846
Georg Brandl479a7e72008-02-05 18:13:15 +00004847 # This dumps core when SF bug 551412 isn't fixed --
4848 # but only when test_descr.py is run separately.
4849 # (That can't be helped -- as soon as PyType_Ready()
4850 # is called for PyLong_Type, the bug is gone.)
4851 class UserLong(object):
4852 def __pow__(self, *args):
4853 pass
4854 try:
4855 pow(0, UserLong(), 0)
4856 except:
4857 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004858
Georg Brandl479a7e72008-02-05 18:13:15 +00004859 # Another segfault only when run early
4860 # (before PyType_Ready(tuple) is called)
4861 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004862
4863
Victor Stinnerd74782b2012-03-09 00:39:08 +01004864class MiscTests(unittest.TestCase):
4865 def test_type_lookup_mro_reference(self):
4866 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4867 # the type MRO because it may be modified during the lookup, if
4868 # __bases__ is set during the lookup for example.
4869 class MyKey(object):
4870 def __hash__(self):
4871 return hash('mykey')
4872
4873 def __eq__(self, other):
4874 X.__bases__ = (Base2,)
4875
4876 class Base(object):
4877 mykey = 'from Base'
4878 mykey2 = 'from Base'
4879
4880 class Base2(object):
4881 mykey = 'from Base2'
4882 mykey2 = 'from Base2'
4883
4884 X = type('X', (Base,), {MyKey(): 5})
4885 # mykey is read from Base
4886 self.assertEqual(X.mykey, 'from Base')
4887 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4888 self.assertEqual(X.mykey2, 'from Base2')
4889
4890
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004891class PicklingTests(unittest.TestCase):
4892
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004893 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004894 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004895 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004896 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004897 if kwargs:
4898 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4899 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004900 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004901 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4902 self.assertEqual(reduce_value[1], (type(obj),) + args)
4903 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004904 if listitems is not None:
4905 self.assertListEqual(list(reduce_value[3]), listitems)
4906 else:
4907 self.assertIsNone(reduce_value[3])
4908 if dictitems is not None:
4909 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4910 else:
4911 self.assertIsNone(reduce_value[4])
4912 else:
4913 base_type = type(obj).__base__
4914 reduce_value = (copyreg._reconstructor,
4915 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004916 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004917 None if base_type is object else base_type(obj)))
4918 if state is not None:
4919 reduce_value += (state,)
4920 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4921 self.assertEqual(obj.__reduce__(), reduce_value)
4922
4923 def test_reduce(self):
4924 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4925 args = (-101, "spam")
4926 kwargs = {'bacon': -201, 'fish': -301}
4927 state = {'cheese': -401}
4928
4929 class C1:
4930 def __getnewargs__(self):
4931 return args
4932 obj = C1()
4933 for proto in protocols:
4934 self._check_reduce(proto, obj, args)
4935
4936 for name, value in state.items():
4937 setattr(obj, name, value)
4938 for proto in protocols:
4939 self._check_reduce(proto, obj, args, state=state)
4940
4941 class C2:
4942 def __getnewargs__(self):
4943 return "bad args"
4944 obj = C2()
4945 for proto in protocols:
4946 if proto >= 2:
4947 with self.assertRaises(TypeError):
4948 obj.__reduce_ex__(proto)
4949
4950 class C3:
4951 def __getnewargs_ex__(self):
4952 return (args, kwargs)
4953 obj = C3()
4954 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03004955 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004956 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004957
4958 class C4:
4959 def __getnewargs_ex__(self):
4960 return (args, "bad dict")
4961 class C5:
4962 def __getnewargs_ex__(self):
4963 return ("bad tuple", kwargs)
4964 class C6:
4965 def __getnewargs_ex__(self):
4966 return ()
4967 class C7:
4968 def __getnewargs_ex__(self):
4969 return "bad args"
4970 for proto in protocols:
4971 for cls in C4, C5, C6, C7:
4972 obj = cls()
4973 if proto >= 2:
4974 with self.assertRaises((TypeError, ValueError)):
4975 obj.__reduce_ex__(proto)
4976
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004977 class C9:
4978 def __getnewargs_ex__(self):
4979 return (args, {})
4980 obj = C9()
4981 for proto in protocols:
4982 self._check_reduce(proto, obj, args)
4983
4984 class C10:
4985 def __getnewargs_ex__(self):
4986 raise IndexError
4987 obj = C10()
4988 for proto in protocols:
4989 if proto >= 2:
4990 with self.assertRaises(IndexError):
4991 obj.__reduce_ex__(proto)
4992
4993 class C11:
4994 def __getstate__(self):
4995 return state
4996 obj = C11()
4997 for proto in protocols:
4998 self._check_reduce(proto, obj, state=state)
4999
5000 class C12:
5001 def __getstate__(self):
5002 return "not dict"
5003 obj = C12()
5004 for proto in protocols:
5005 self._check_reduce(proto, obj, state="not dict")
5006
5007 class C13:
5008 def __getstate__(self):
5009 raise IndexError
5010 obj = C13()
5011 for proto in protocols:
5012 with self.assertRaises(IndexError):
5013 obj.__reduce_ex__(proto)
5014 if proto < 2:
5015 with self.assertRaises(IndexError):
5016 obj.__reduce__()
5017
5018 class C14:
5019 __slots__ = tuple(state)
5020 def __init__(self):
5021 for name, value in state.items():
5022 setattr(self, name, value)
5023
5024 obj = C14()
5025 for proto in protocols:
5026 if proto >= 2:
5027 self._check_reduce(proto, obj, state=(None, state))
5028 else:
5029 with self.assertRaises(TypeError):
5030 obj.__reduce_ex__(proto)
5031 with self.assertRaises(TypeError):
5032 obj.__reduce__()
5033
5034 class C15(dict):
5035 pass
5036 obj = C15({"quebec": -601})
5037 for proto in protocols:
5038 self._check_reduce(proto, obj, dictitems=dict(obj))
5039
5040 class C16(list):
5041 pass
5042 obj = C16(["yukon"])
5043 for proto in protocols:
5044 self._check_reduce(proto, obj, listitems=list(obj))
5045
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005046 def test_special_method_lookup(self):
5047 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5048 class Picky:
5049 def __getstate__(self):
5050 return {}
5051
5052 def __getattr__(self, attr):
5053 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5054 raise AssertionError(attr)
5055 return None
5056 for protocol in protocols:
5057 state = {} if protocol >= 2 else None
5058 self._check_reduce(protocol, Picky(), state=state)
5059
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005060 def _assert_is_copy(self, obj, objcopy, msg=None):
5061 """Utility method to verify if two objects are copies of each others.
5062 """
5063 if msg is None:
5064 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5065 if type(obj).__repr__ is object.__repr__:
5066 # We have this limitation for now because we use the object's repr
5067 # to help us verify that the two objects are copies. This allows
5068 # us to delegate the non-generic verification logic to the objects
5069 # themselves.
5070 raise ValueError("object passed to _assert_is_copy must " +
5071 "override the __repr__ method.")
5072 self.assertIsNot(obj, objcopy, msg=msg)
5073 self.assertIs(type(obj), type(objcopy), msg=msg)
5074 if hasattr(obj, '__dict__'):
5075 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5076 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5077 if hasattr(obj, '__slots__'):
5078 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5079 for slot in obj.__slots__:
5080 self.assertEqual(
5081 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5082 self.assertEqual(getattr(obj, slot, None),
5083 getattr(objcopy, slot, None), msg=msg)
5084 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5085
5086 @staticmethod
5087 def _generate_pickle_copiers():
5088 """Utility method to generate the many possible pickle configurations.
5089 """
5090 class PickleCopier:
5091 "This class copies object using pickle."
5092 def __init__(self, proto, dumps, loads):
5093 self.proto = proto
5094 self.dumps = dumps
5095 self.loads = loads
5096 def copy(self, obj):
5097 return self.loads(self.dumps(obj, self.proto))
5098 def __repr__(self):
5099 # We try to be as descriptive as possible here since this is
5100 # the string which we will allow us to tell the pickle
5101 # configuration we are using during debugging.
5102 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5103 .format(self.proto,
5104 self.dumps.__module__, self.dumps.__qualname__,
5105 self.loads.__module__, self.loads.__qualname__))
5106 return (PickleCopier(*args) for args in
5107 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5108 {pickle.dumps, pickle._dumps},
5109 {pickle.loads, pickle._loads}))
5110
5111 def test_pickle_slots(self):
5112 # Tests pickling of classes with __slots__.
5113
5114 # Pickling of classes with __slots__ but without __getstate__ should
5115 # fail (if using protocol 0 or 1)
5116 global C
5117 class C:
5118 __slots__ = ['a']
5119 with self.assertRaises(TypeError):
5120 pickle.dumps(C(), 0)
5121
5122 global D
5123 class D(C):
5124 pass
5125 with self.assertRaises(TypeError):
5126 pickle.dumps(D(), 0)
5127
5128 class C:
5129 "A class with __getstate__ and __setstate__ implemented."
5130 __slots__ = ['a']
5131 def __getstate__(self):
5132 state = getattr(self, '__dict__', {}).copy()
5133 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005134 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005135 try:
5136 state[slot] = getattr(self, slot)
5137 except AttributeError:
5138 pass
5139 return state
5140 def __setstate__(self, state):
5141 for k, v in state.items():
5142 setattr(self, k, v)
5143 def __repr__(self):
5144 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5145
5146 class D(C):
5147 "A subclass of a class with slots."
5148 pass
5149
5150 global E
5151 class E(C):
5152 "A subclass with an extra slot."
5153 __slots__ = ['b']
5154
5155 # Now it should work
5156 for pickle_copier in self._generate_pickle_copiers():
5157 with self.subTest(pickle_copier=pickle_copier):
5158 x = C()
5159 y = pickle_copier.copy(x)
5160 self._assert_is_copy(x, y)
5161
5162 x.a = 42
5163 y = pickle_copier.copy(x)
5164 self._assert_is_copy(x, y)
5165
5166 x = D()
5167 x.a = 42
5168 x.b = 100
5169 y = pickle_copier.copy(x)
5170 self._assert_is_copy(x, y)
5171
5172 x = E()
5173 x.a = 42
5174 x.b = "foo"
5175 y = pickle_copier.copy(x)
5176 self._assert_is_copy(x, y)
5177
5178 def test_reduce_copying(self):
5179 # Tests pickling and copying new-style classes and objects.
5180 global C1
5181 class C1:
5182 "The state of this class is copyable via its instance dict."
5183 ARGS = (1, 2)
5184 NEED_DICT_COPYING = True
5185 def __init__(self, a, b):
5186 super().__init__()
5187 self.a = a
5188 self.b = b
5189 def __repr__(self):
5190 return "C1(%r, %r)" % (self.a, self.b)
5191
5192 global C2
5193 class C2(list):
5194 "A list subclass copyable via __getnewargs__."
5195 ARGS = (1, 2)
5196 NEED_DICT_COPYING = False
5197 def __new__(cls, a, b):
5198 self = super().__new__(cls)
5199 self.a = a
5200 self.b = b
5201 return self
5202 def __init__(self, *args):
5203 super().__init__()
5204 # This helps testing that __init__ is not called during the
5205 # unpickling process, which would cause extra appends.
5206 self.append("cheese")
5207 @classmethod
5208 def __getnewargs__(cls):
5209 return cls.ARGS
5210 def __repr__(self):
5211 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5212
5213 global C3
5214 class C3(list):
5215 "A list subclass copyable via __getstate__."
5216 ARGS = (1, 2)
5217 NEED_DICT_COPYING = False
5218 def __init__(self, a, b):
5219 self.a = a
5220 self.b = b
5221 # This helps testing that __init__ is not called during the
5222 # unpickling process, which would cause extra appends.
5223 self.append("cheese")
5224 @classmethod
5225 def __getstate__(cls):
5226 return cls.ARGS
5227 def __setstate__(self, state):
5228 a, b = state
5229 self.a = a
5230 self.b = b
5231 def __repr__(self):
5232 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5233
5234 global C4
5235 class C4(int):
5236 "An int subclass copyable via __getnewargs__."
5237 ARGS = ("hello", "world", 1)
5238 NEED_DICT_COPYING = False
5239 def __new__(cls, a, b, value):
5240 self = super().__new__(cls, value)
5241 self.a = a
5242 self.b = b
5243 return self
5244 @classmethod
5245 def __getnewargs__(cls):
5246 return cls.ARGS
5247 def __repr__(self):
5248 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5249
5250 global C5
5251 class C5(int):
5252 "An int subclass copyable via __getnewargs_ex__."
5253 ARGS = (1, 2)
5254 KWARGS = {'value': 3}
5255 NEED_DICT_COPYING = False
5256 def __new__(cls, a, b, *, value=0):
5257 self = super().__new__(cls, value)
5258 self.a = a
5259 self.b = b
5260 return self
5261 @classmethod
5262 def __getnewargs_ex__(cls):
5263 return (cls.ARGS, cls.KWARGS)
5264 def __repr__(self):
5265 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5266
5267 test_classes = (C1, C2, C3, C4, C5)
5268 # Testing copying through pickle
5269 pickle_copiers = self._generate_pickle_copiers()
5270 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5271 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5272 kwargs = getattr(cls, 'KWARGS', {})
5273 obj = cls(*cls.ARGS, **kwargs)
5274 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005275 objcopy = pickle_copier.copy(obj)
5276 self._assert_is_copy(obj, objcopy)
5277 # For test classes that supports this, make sure we didn't go
5278 # around the reduce protocol by simply copying the attribute
5279 # dictionary. We clear attributes using the previous copy to
5280 # not mutate the original argument.
5281 if proto >= 2 and not cls.NEED_DICT_COPYING:
5282 objcopy.__dict__.clear()
5283 objcopy2 = pickle_copier.copy(objcopy)
5284 self._assert_is_copy(obj, objcopy2)
5285
5286 # Testing copying through copy.deepcopy()
5287 for cls in test_classes:
5288 with self.subTest(cls=cls):
5289 kwargs = getattr(cls, 'KWARGS', {})
5290 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005291 objcopy = deepcopy(obj)
5292 self._assert_is_copy(obj, objcopy)
5293 # For test classes that supports this, make sure we didn't go
5294 # around the reduce protocol by simply copying the attribute
5295 # dictionary. We clear attributes using the previous copy to
5296 # not mutate the original argument.
5297 if not cls.NEED_DICT_COPYING:
5298 objcopy.__dict__.clear()
5299 objcopy2 = deepcopy(objcopy)
5300 self._assert_is_copy(obj, objcopy2)
5301
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005302 def test_issue24097(self):
5303 # Slot name is freed inside __getattr__ and is later used.
5304 class S(str): # Not interned
5305 pass
5306 class A:
5307 __slotnames__ = [S('spam')]
5308 def __getattr__(self, attr):
5309 if attr == 'spam':
5310 A.__slotnames__[:] = [S('spam')]
5311 return 42
5312 else:
5313 raise AttributeError
5314
5315 import copyreg
5316 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005317 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5318
5319 def test_object_reduce(self):
5320 # Issue #29914
5321 # __reduce__() takes no arguments
5322 object().__reduce__()
5323 with self.assertRaises(TypeError):
5324 object().__reduce__(0)
5325 # __reduce_ex__() takes one integer argument
5326 object().__reduce_ex__(0)
5327 with self.assertRaises(TypeError):
5328 object().__reduce_ex__()
5329 with self.assertRaises(TypeError):
5330 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005331
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005332
Benjamin Peterson2a605342014-03-17 16:20:12 -05005333class SharedKeyTests(unittest.TestCase):
5334
5335 @support.cpython_only
5336 def test_subclasses(self):
5337 # Verify that subclasses can share keys (per PEP 412)
5338 class A:
5339 pass
5340 class B(A):
5341 pass
5342
5343 a, b = A(), B()
5344 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5345 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005346 # Initial hash table can contain at most 5 elements.
5347 # Set 6 attributes to cause internal resizing.
5348 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005349 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5350 a2 = A()
5351 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5352 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005353 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005354 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5355
5356
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005357class DebugHelperMeta(type):
5358 """
5359 Sets default __doc__ and simplifies repr() output.
5360 """
5361 def __new__(mcls, name, bases, attrs):
5362 if attrs.get('__doc__') is None:
5363 attrs['__doc__'] = name # helps when debugging with gdb
5364 return type.__new__(mcls, name, bases, attrs)
5365 def __repr__(cls):
5366 return repr(cls.__name__)
5367
5368
5369class MroTest(unittest.TestCase):
5370 """
5371 Regressions for some bugs revealed through
5372 mcsl.mro() customization (typeobject.c: mro_internal()) and
5373 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5374 """
5375
5376 def setUp(self):
5377 self.step = 0
5378 self.ready = False
5379
5380 def step_until(self, limit):
5381 ret = (self.step < limit)
5382 if ret:
5383 self.step += 1
5384 return ret
5385
5386 def test_incomplete_set_bases_on_self(self):
5387 """
5388 type_set_bases must be aware that type->tp_mro can be NULL.
5389 """
5390 class M(DebugHelperMeta):
5391 def mro(cls):
5392 if self.step_until(1):
5393 assert cls.__mro__ is None
5394 cls.__bases__ += ()
5395
5396 return type.mro(cls)
5397
5398 class A(metaclass=M):
5399 pass
5400
5401 def test_reent_set_bases_on_base(self):
5402 """
5403 Deep reentrancy must not over-decref old_mro.
5404 """
5405 class M(DebugHelperMeta):
5406 def mro(cls):
5407 if cls.__mro__ is not None and cls.__name__ == 'B':
5408 # 4-5 steps are usually enough to make it crash somewhere
5409 if self.step_until(10):
5410 A.__bases__ += ()
5411
5412 return type.mro(cls)
5413
5414 class A(metaclass=M):
5415 pass
5416 class B(A):
5417 pass
5418 B.__bases__ += ()
5419
5420 def test_reent_set_bases_on_direct_base(self):
5421 """
5422 Similar to test_reent_set_bases_on_base, but may crash differently.
5423 """
5424 class M(DebugHelperMeta):
5425 def mro(cls):
5426 base = cls.__bases__[0]
5427 if base is not object:
5428 if self.step_until(5):
5429 base.__bases__ += ()
5430
5431 return type.mro(cls)
5432
5433 class A(metaclass=M):
5434 pass
5435 class B(A):
5436 pass
5437 class C(B):
5438 pass
5439
5440 def test_reent_set_bases_tp_base_cycle(self):
5441 """
5442 type_set_bases must check for an inheritance cycle not only through
5443 MRO of the type, which may be not yet updated in case of reentrance,
5444 but also through tp_base chain, which is assigned before diving into
5445 inner calls to mro().
5446
5447 Otherwise, the following snippet can loop forever:
5448 do {
5449 // ...
5450 type = type->tp_base;
5451 } while (type != NULL);
5452
5453 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5454 would not be happy in that case, causing a stack overflow.
5455 """
5456 class M(DebugHelperMeta):
5457 def mro(cls):
5458 if self.ready:
5459 if cls.__name__ == 'B1':
5460 B2.__bases__ = (B1,)
5461 if cls.__name__ == 'B2':
5462 B1.__bases__ = (B2,)
5463 return type.mro(cls)
5464
5465 class A(metaclass=M):
5466 pass
5467 class B1(A):
5468 pass
5469 class B2(A):
5470 pass
5471
5472 self.ready = True
5473 with self.assertRaises(TypeError):
5474 B1.__bases__ += ()
5475
5476 def test_tp_subclasses_cycle_in_update_slots(self):
5477 """
5478 type_set_bases must check for reentrancy upon finishing its job
5479 by updating tp_subclasses of old/new bases of the type.
5480 Otherwise, an implicit inheritance cycle through tp_subclasses
5481 can break functions that recurse on elements of that field
5482 (like recurse_down_subclasses and mro_hierarchy) eventually
5483 leading to a stack overflow.
5484 """
5485 class M(DebugHelperMeta):
5486 def mro(cls):
5487 if self.ready and cls.__name__ == 'C':
5488 self.ready = False
5489 C.__bases__ = (B2,)
5490 return type.mro(cls)
5491
5492 class A(metaclass=M):
5493 pass
5494 class B1(A):
5495 pass
5496 class B2(A):
5497 pass
5498 class C(A):
5499 pass
5500
5501 self.ready = True
5502 C.__bases__ = (B1,)
5503 B1.__bases__ = (C,)
5504
5505 self.assertEqual(C.__bases__, (B2,))
5506 self.assertEqual(B2.__subclasses__(), [C])
5507 self.assertEqual(B1.__subclasses__(), [])
5508
5509 self.assertEqual(B1.__bases__, (C,))
5510 self.assertEqual(C.__subclasses__(), [B1])
5511
5512 def test_tp_subclasses_cycle_error_return_path(self):
5513 """
5514 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5515 a code path executed on error (goto bail).
5516 """
5517 class E(Exception):
5518 pass
5519 class M(DebugHelperMeta):
5520 def mro(cls):
5521 if self.ready and cls.__name__ == 'C':
5522 if C.__bases__ == (B2,):
5523 self.ready = False
5524 else:
5525 C.__bases__ = (B2,)
5526 raise E
5527 return type.mro(cls)
5528
5529 class A(metaclass=M):
5530 pass
5531 class B1(A):
5532 pass
5533 class B2(A):
5534 pass
5535 class C(A):
5536 pass
5537
5538 self.ready = True
5539 with self.assertRaises(E):
5540 C.__bases__ = (B1,)
5541 B1.__bases__ = (C,)
5542
5543 self.assertEqual(C.__bases__, (B2,))
5544 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5545
5546 def test_incomplete_extend(self):
5547 """
5548 Extending an unitialized type with type->tp_mro == NULL must
5549 throw a reasonable TypeError exception, instead of failing
5550 with PyErr_BadInternalCall.
5551 """
5552 class M(DebugHelperMeta):
5553 def mro(cls):
5554 if cls.__mro__ is None and cls.__name__ != 'X':
5555 with self.assertRaises(TypeError):
5556 class X(cls):
5557 pass
5558
5559 return type.mro(cls)
5560
5561 class A(metaclass=M):
5562 pass
5563
5564 def test_incomplete_super(self):
5565 """
5566 Attrubute lookup on a super object must be aware that
5567 its target type can be uninitialized (type->tp_mro == NULL).
5568 """
5569 class M(DebugHelperMeta):
5570 def mro(cls):
5571 if cls.__mro__ is None:
5572 with self.assertRaises(AttributeError):
5573 super(cls, cls).xxx
5574
5575 return type.mro(cls)
5576
5577 class A(metaclass=M):
5578 pass
5579
5580
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005581def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005582 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005583 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005584 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005585 MiscTests, PicklingTests, SharedKeyTests,
5586 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005587
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005588if __name__ == "__main__":
5589 test_main()