blob: d24d005ccfaa9403a4bc1b8023c97fc980aa7b79 [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
Tim Peters6d6c1a32001-08-02 04:15:00 +000016
Georg Brandl479a7e72008-02-05 18:13:15 +000017class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000018
Georg Brandl479a7e72008-02-05 18:13:15 +000019 def __init__(self, *args, **kwargs):
20 unittest.TestCase.__init__(self, *args, **kwargs)
21 self.binops = {
22 'add': '+',
23 'sub': '-',
24 'mul': '*',
Serhiy Storchakac2ccce72015-03-12 22:01:30 +020025 'matmul': '@',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +020026 'truediv': '/',
27 'floordiv': '//',
Georg Brandl479a7e72008-02-05 18:13:15 +000028 'divmod': 'divmod',
29 'pow': '**',
30 'lshift': '<<',
31 'rshift': '>>',
32 'and': '&',
33 'xor': '^',
34 'or': '|',
35 'cmp': 'cmp',
36 'lt': '<',
37 'le': '<=',
38 'eq': '==',
39 'ne': '!=',
40 'gt': '>',
41 'ge': '>=',
42 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000043
Georg Brandl479a7e72008-02-05 18:13:15 +000044 for name, expr in list(self.binops.items()):
45 if expr.islower():
46 expr = expr + "(a, b)"
47 else:
48 expr = 'a %s b' % expr
49 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000050
Georg Brandl479a7e72008-02-05 18:13:15 +000051 self.unops = {
52 'pos': '+',
53 'neg': '-',
54 'abs': 'abs',
55 'invert': '~',
56 'int': 'int',
57 'float': 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +000058 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000059
Georg Brandl479a7e72008-02-05 18:13:15 +000060 for name, expr in list(self.unops.items()):
61 if expr.islower():
62 expr = expr + "(a)"
63 else:
64 expr = '%s a' % expr
65 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl479a7e72008-02-05 18:13:15 +000067 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
68 d = {'a': a}
69 self.assertEqual(eval(expr, d), res)
70 t = type(a)
71 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000072
Georg Brandl479a7e72008-02-05 18:13:15 +000073 # Find method in parent class
74 while meth not in t.__dict__:
75 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000076 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
77 # method object; the getattr() below obtains its underlying function.
78 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000079 self.assertEqual(m(a), res)
80 bm = getattr(a, meth)
81 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000082
Georg Brandl479a7e72008-02-05 18:13:15 +000083 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
84 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl479a7e72008-02-05 18:13:15 +000086 self.assertEqual(eval(expr, d), res)
87 t = type(a)
88 m = getattr(t, meth)
89 while meth not in t.__dict__:
90 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000091 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000094 self.assertEqual(m(a, b), res)
95 bm = getattr(a, meth)
96 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000097
Georg Brandl479a7e72008-02-05 18:13:15 +000098 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
99 d = {'a': a, 'b': b, 'c': c}
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000108 self.assertEqual(m(a, slice(b, c)), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl479a7e72008-02-05 18:13:15 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec(stmt, d)
115 self.assertEqual(d['a'], res)
116 t = type(a)
117 m = getattr(t, meth)
118 while meth not in t.__dict__:
119 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000123 d['a'] = deepcopy(a)
124 m(d['a'], b)
125 self.assertEqual(d['a'], res)
126 d['a'] = deepcopy(a)
127 bm = getattr(d['a'], meth)
128 bm(b)
129 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130
Georg Brandl479a7e72008-02-05 18:13:15 +0000131 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132 d = {'a': deepcopy(a), 'b': b, 'c': c}
133 exec(stmt, d)
134 self.assertEqual(d['a'], res)
135 t = type(a)
136 m = getattr(t, meth)
137 while meth not in t.__dict__:
138 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000142 d['a'] = deepcopy(a)
143 m(d['a'], b, c)
144 self.assertEqual(d['a'], res)
145 d['a'] = deepcopy(a)
146 bm = getattr(d['a'], meth)
147 bm(b, c)
148 self.assertEqual(d['a'], res)
149
150 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec(stmt, dictionary)
153 self.assertEqual(dictionary['a'], res)
154 t = type(a)
155 while meth not in t.__dict__:
156 t = t.__bases__[0]
157 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], slice(b, c), d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(slice(b, c), d)
167 self.assertEqual(dictionary['a'], res)
168
169 def test_lists(self):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
177 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setitem__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000188 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
190 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
191
192 d = {1:2, 3:4}
193 l1 = []
194 for i in list(d.keys()):
195 l1.append(i)
196 l = []
197 for i in iter(d):
198 l.append(i)
199 self.assertEqual(l, l1)
200 l = []
201 for i in d.__iter__():
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in dict.__iter__(d):
206 l.append(i)
207 self.assertEqual(l, l1)
208 d = {1:2, 3:4}
209 self.unop_test(d, 2, "len(a)", "__len__")
210 self.assertEqual(eval(repr(d), {}), d)
211 self.assertEqual(eval(d.__repr__(), {}), d)
212 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
213 "__setitem__")
214
215 # Tests for unary and binary operators
216 def number_operators(self, a, b, skip=[]):
217 dict = {'a': a, 'b': b}
218
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200219 for name, expr in self.binops.items():
Georg Brandl479a7e72008-02-05 18:13:15 +0000220 if name not in skip:
221 name = "__%s__" % name
222 if hasattr(a, name):
223 res = eval(expr, dict)
224 self.binop_test(a, b, res, expr, name)
225
226 for name, expr in list(self.unops.items()):
227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.unop_test(a, res, expr, name)
232
233 def test_ints(self):
234 # Testing int operations...
235 self.number_operators(100, 3)
236 # The following crashes in Python 2.2
237 self.assertEqual((1).__bool__(), 1)
238 self.assertEqual((0).__bool__(), 0)
239 # This returns 'NotImplemented' in Python 2.2
240 class C(int):
241 def __add__(self, other):
242 return NotImplemented
243 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000244 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000245 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000246 except TypeError:
247 pass
248 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000249 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000250
Georg Brandl479a7e72008-02-05 18:13:15 +0000251 def test_floats(self):
252 # Testing float operations...
253 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000254
Georg Brandl479a7e72008-02-05 18:13:15 +0000255 def test_complexes(self):
256 # Testing complex operations...
257 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000258 'int', 'float',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200259 'floordiv', 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000260
Georg Brandl479a7e72008-02-05 18:13:15 +0000261 class Number(complex):
262 __slots__ = ['prec']
263 def __new__(cls, *args, **kwds):
264 result = complex.__new__(cls, *args)
265 result.prec = kwds.get('prec', 12)
266 return result
267 def __repr__(self):
268 prec = self.prec
269 if self.imag == 0.0:
270 return "%.*g" % (prec, self.real)
271 if self.real == 0.0:
272 return "%.*gj" % (prec, self.imag)
273 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
274 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000275
Georg Brandl479a7e72008-02-05 18:13:15 +0000276 a = Number(3.14, prec=6)
277 self.assertEqual(repr(a), "3.14")
278 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000279
Georg Brandl479a7e72008-02-05 18:13:15 +0000280 a = Number(a, prec=2)
281 self.assertEqual(repr(a), "3.1")
282 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000283
Georg Brandl479a7e72008-02-05 18:13:15 +0000284 a = Number(234.5)
285 self.assertEqual(repr(a), "234.5")
286 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000287
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000288 def test_explicit_reverse_methods(self):
289 # see issue 9930
290 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
291 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
292
Benjamin Petersone549ead2009-03-28 21:42:05 +0000293 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000294 def test_spam_lists(self):
295 # Testing spamlist operations...
296 import copy, xxsubtype as spam
297
298 def spamlist(l, memo=None):
299 import xxsubtype as spam
300 return spam.spamlist(l)
301
302 # This is an ugly hack:
303 copy._deepcopy_dispatch[spam.spamlist] = spamlist
304
305 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
306 "__add__")
307 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
308 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
309 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
310 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
311 "__getitem__")
312 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
313 "__iadd__")
314 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
315 "__imul__")
316 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
317 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
318 "__mul__")
319 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
320 "__rmul__")
321 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
322 "__setitem__")
323 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
324 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
325 # Test subclassing
326 class C(spam.spamlist):
327 def foo(self): return 1
328 a = C()
329 self.assertEqual(a, [])
330 self.assertEqual(a.foo(), 1)
331 a.append(100)
332 self.assertEqual(a, [100])
333 self.assertEqual(a.getstate(), 0)
334 a.setstate(42)
335 self.assertEqual(a.getstate(), 42)
336
Benjamin Petersone549ead2009-03-28 21:42:05 +0000337 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000338 def test_spam_dicts(self):
339 # Testing spamdict operations...
340 import copy, xxsubtype as spam
341 def spamdict(d, memo=None):
342 import xxsubtype as spam
343 sd = spam.spamdict()
344 for k, v in list(d.items()):
345 sd[k] = v
346 return sd
347 # This is an ugly hack:
348 copy._deepcopy_dispatch[spam.spamdict] = spamdict
349
Georg Brandl479a7e72008-02-05 18:13:15 +0000350 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
351 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
352 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
353 d = spamdict({1:2,3:4})
354 l1 = []
355 for i in list(d.keys()):
356 l1.append(i)
357 l = []
358 for i in iter(d):
359 l.append(i)
360 self.assertEqual(l, l1)
361 l = []
362 for i in d.__iter__():
363 l.append(i)
364 self.assertEqual(l, l1)
365 l = []
366 for i in type(spamdict({})).__iter__(d):
367 l.append(i)
368 self.assertEqual(l, l1)
369 straightd = {1:2, 3:4}
370 spamd = spamdict(straightd)
371 self.unop_test(spamd, 2, "len(a)", "__len__")
372 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
373 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
374 "a[b]=c", "__setitem__")
375 # Test subclassing
376 class C(spam.spamdict):
377 def foo(self): return 1
378 a = C()
379 self.assertEqual(list(a.items()), [])
380 self.assertEqual(a.foo(), 1)
381 a['foo'] = 'bar'
382 self.assertEqual(list(a.items()), [('foo', 'bar')])
383 self.assertEqual(a.getstate(), 0)
384 a.setstate(100)
385 self.assertEqual(a.getstate(), 100)
386
387class ClassPropertiesAndMethods(unittest.TestCase):
388
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200389 def assertHasAttr(self, obj, name):
390 self.assertTrue(hasattr(obj, name),
391 '%r has no attribute %r' % (obj, name))
392
393 def assertNotHasAttr(self, obj, name):
394 self.assertFalse(hasattr(obj, name),
395 '%r has unexpected attribute %r' % (obj, name))
396
Georg Brandl479a7e72008-02-05 18:13:15 +0000397 def test_python_dicts(self):
398 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000399 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000400 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000401 d = dict()
402 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200403 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000404 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000405 class C(dict):
406 state = -1
407 def __init__(self_local, *a, **kw):
408 if a:
409 self.assertEqual(len(a), 1)
410 self_local.state = a[0]
411 if kw:
412 for k, v in list(kw.items()):
413 self_local[v] = k
414 def __getitem__(self, key):
415 return self.get(key, 0)
416 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000417 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000418 dict.__setitem__(self_local, key, value)
419 def setstate(self, state):
420 self.state = state
421 def getstate(self):
422 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000423 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000424 a1 = C(12)
425 self.assertEqual(a1.state, 12)
426 a2 = C(foo=1, bar=2)
427 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
428 a = C()
429 self.assertEqual(a.state, -1)
430 self.assertEqual(a.getstate(), -1)
431 a.setstate(0)
432 self.assertEqual(a.state, 0)
433 self.assertEqual(a.getstate(), 0)
434 a.setstate(10)
435 self.assertEqual(a.state, 10)
436 self.assertEqual(a.getstate(), 10)
437 self.assertEqual(a[42], 0)
438 a[42] = 24
439 self.assertEqual(a[42], 24)
440 N = 50
441 for i in range(N):
442 a[i] = C()
443 for j in range(N):
444 a[i][j] = i*j
445 for i in range(N):
446 for j in range(N):
447 self.assertEqual(a[i][j], i*j)
448
449 def test_python_lists(self):
450 # Testing Python subclass of list...
451 class C(list):
452 def __getitem__(self, i):
453 if isinstance(i, slice):
454 return i.start, i.stop
455 return list.__getitem__(self, i) + 100
456 a = C()
457 a.extend([0,1,2])
458 self.assertEqual(a[0], 100)
459 self.assertEqual(a[1], 101)
460 self.assertEqual(a[2], 102)
461 self.assertEqual(a[100:200], (100,200))
462
463 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000464 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000465 class C(metaclass=type):
466 def __init__(self):
467 self.__state = 0
468 def getstate(self):
469 return self.__state
470 def setstate(self, state):
471 self.__state = state
472 a = C()
473 self.assertEqual(a.getstate(), 0)
474 a.setstate(10)
475 self.assertEqual(a.getstate(), 10)
476 class _metaclass(type):
477 def myself(cls): return cls
478 class D(metaclass=_metaclass):
479 pass
480 self.assertEqual(D.myself(), D)
481 d = D()
482 self.assertEqual(d.__class__, D)
483 class M1(type):
484 def __new__(cls, name, bases, dict):
485 dict['__spam__'] = 1
486 return type.__new__(cls, name, bases, dict)
487 class C(metaclass=M1):
488 pass
489 self.assertEqual(C.__spam__, 1)
490 c = C()
491 self.assertEqual(c.__spam__, 1)
492
493 class _instance(object):
494 pass
495 class M2(object):
496 @staticmethod
497 def __new__(cls, name, bases, dict):
498 self = object.__new__(cls)
499 self.name = name
500 self.bases = bases
501 self.dict = dict
502 return self
503 def __call__(self):
504 it = _instance()
505 # Early binding of methods
506 for key in self.dict:
507 if key.startswith("__"):
508 continue
509 setattr(it, key, self.dict[key].__get__(it, self))
510 return it
511 class C(metaclass=M2):
512 def spam(self):
513 return 42
514 self.assertEqual(C.name, 'C')
515 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000516 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000517 c = C()
518 self.assertEqual(c.spam(), 42)
519
520 # More metaclass examples
521
522 class autosuper(type):
523 # Automatically add __super to the class
524 # This trick only works for dynamic classes
525 def __new__(metaclass, name, bases, dict):
526 cls = super(autosuper, metaclass).__new__(metaclass,
527 name, bases, dict)
528 # Name mangling for __super removes leading underscores
529 while name[:1] == "_":
530 name = name[1:]
531 if name:
532 name = "_%s__super" % name
533 else:
534 name = "__super"
535 setattr(cls, name, super(cls))
536 return cls
537 class A(metaclass=autosuper):
538 def meth(self):
539 return "A"
540 class B(A):
541 def meth(self):
542 return "B" + self.__super.meth()
543 class C(A):
544 def meth(self):
545 return "C" + self.__super.meth()
546 class D(C, B):
547 def meth(self):
548 return "D" + self.__super.meth()
549 self.assertEqual(D().meth(), "DCBA")
550 class E(B, C):
551 def meth(self):
552 return "E" + self.__super.meth()
553 self.assertEqual(E().meth(), "EBCA")
554
555 class autoproperty(type):
556 # Automatically create property attributes when methods
557 # named _get_x and/or _set_x are found
558 def __new__(metaclass, name, bases, dict):
559 hits = {}
560 for key, val in dict.items():
561 if key.startswith("_get_"):
562 key = key[5:]
563 get, set = hits.get(key, (None, None))
564 get = val
565 hits[key] = get, set
566 elif key.startswith("_set_"):
567 key = key[5:]
568 get, set = hits.get(key, (None, None))
569 set = val
570 hits[key] = get, set
571 for key, (get, set) in hits.items():
572 dict[key] = property(get, set)
573 return super(autoproperty, metaclass).__new__(metaclass,
574 name, bases, dict)
575 class A(metaclass=autoproperty):
576 def _get_x(self):
577 return -self.__x
578 def _set_x(self, x):
579 self.__x = -x
580 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200581 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000582 a.x = 12
583 self.assertEqual(a.x, 12)
584 self.assertEqual(a._A__x, -12)
585
586 class multimetaclass(autoproperty, autosuper):
587 # Merge of multiple cooperating metaclasses
588 pass
589 class A(metaclass=multimetaclass):
590 def _get_x(self):
591 return "A"
592 class B(A):
593 def _get_x(self):
594 return "B" + self.__super._get_x()
595 class C(A):
596 def _get_x(self):
597 return "C" + self.__super._get_x()
598 class D(C, B):
599 def _get_x(self):
600 return "D" + self.__super._get_x()
601 self.assertEqual(D().x, "DCBA")
602
603 # Make sure type(x) doesn't call x.__class__.__init__
604 class T(type):
605 counter = 0
606 def __init__(self, *args):
607 T.counter += 1
608 class C(metaclass=T):
609 pass
610 self.assertEqual(T.counter, 1)
611 a = C()
612 self.assertEqual(type(a), C)
613 self.assertEqual(T.counter, 1)
614
615 class C(object): pass
616 c = C()
617 try: c()
618 except TypeError: pass
619 else: self.fail("calling object w/o call method should raise "
620 "TypeError")
621
622 # Testing code to find most derived baseclass
623 class A(type):
624 def __new__(*args, **kwargs):
625 return type.__new__(*args, **kwargs)
626
627 class B(object):
628 pass
629
630 class C(object, metaclass=A):
631 pass
632
633 # The most derived metaclass of D is A rather than type.
634 class D(B, C):
635 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000636 self.assertIs(A, type(D))
637
638 # issue1294232: correct metaclass calculation
639 new_calls = [] # to check the order of __new__ calls
640 class AMeta(type):
641 @staticmethod
642 def __new__(mcls, name, bases, ns):
643 new_calls.append('AMeta')
644 return super().__new__(mcls, name, bases, ns)
645 @classmethod
646 def __prepare__(mcls, name, bases):
647 return {}
648
649 class BMeta(AMeta):
650 @staticmethod
651 def __new__(mcls, name, bases, ns):
652 new_calls.append('BMeta')
653 return super().__new__(mcls, name, bases, ns)
654 @classmethod
655 def __prepare__(mcls, name, bases):
656 ns = super().__prepare__(name, bases)
657 ns['BMeta_was_here'] = True
658 return ns
659
660 class A(metaclass=AMeta):
661 pass
662 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000663 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000664
665 class B(metaclass=BMeta):
666 pass
667 # BMeta.__new__ calls AMeta.__new__ with super:
668 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000669 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000670
671 class C(A, B):
672 pass
673 # The most derived metaclass is BMeta:
674 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000675 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000676 # BMeta.__prepare__ should've been called:
677 self.assertIn('BMeta_was_here', C.__dict__)
678
679 # The order of the bases shouldn't matter:
680 class C2(B, A):
681 pass
682 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000683 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000684 self.assertIn('BMeta_was_here', C2.__dict__)
685
686 # Check correct metaclass calculation when a metaclass is declared:
687 class D(C, metaclass=type):
688 pass
689 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000690 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000691 self.assertIn('BMeta_was_here', D.__dict__)
692
693 class E(C, metaclass=AMeta):
694 pass
695 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000696 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000697 self.assertIn('BMeta_was_here', E.__dict__)
698
699 # Special case: the given metaclass isn't a class,
700 # so there is no metaclass calculation.
701 marker = object()
702 def func(*args, **kwargs):
703 return marker
704 class X(metaclass=func):
705 pass
706 class Y(object, metaclass=func):
707 pass
708 class Z(D, metaclass=func):
709 pass
710 self.assertIs(marker, X)
711 self.assertIs(marker, Y)
712 self.assertIs(marker, Z)
713
714 # The given metaclass is a class,
715 # but not a descendant of type.
716 prepare_calls = [] # to track __prepare__ calls
717 class ANotMeta:
718 def __new__(mcls, *args, **kwargs):
719 new_calls.append('ANotMeta')
720 return super().__new__(mcls)
721 @classmethod
722 def __prepare__(mcls, name, bases):
723 prepare_calls.append('ANotMeta')
724 return {}
725 class BNotMeta(ANotMeta):
726 def __new__(mcls, *args, **kwargs):
727 new_calls.append('BNotMeta')
728 return super().__new__(mcls)
729 @classmethod
730 def __prepare__(mcls, name, bases):
731 prepare_calls.append('BNotMeta')
732 return super().__prepare__(name, bases)
733
734 class A(metaclass=ANotMeta):
735 pass
736 self.assertIs(ANotMeta, type(A))
737 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000738 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000739 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000740 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000741
742 class B(metaclass=BNotMeta):
743 pass
744 self.assertIs(BNotMeta, type(B))
745 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000746 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000747 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000748 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000749
750 class C(A, B):
751 pass
752 self.assertIs(BNotMeta, type(C))
753 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000754 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000755 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000756 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000757
758 class C2(B, A):
759 pass
760 self.assertIs(BNotMeta, type(C2))
761 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000762 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000763 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000764 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000765
766 # This is a TypeError, because of a metaclass conflict:
767 # BNotMeta is neither a subclass, nor a superclass of type
768 with self.assertRaises(TypeError):
769 class D(C, metaclass=type):
770 pass
771
772 class E(C, metaclass=ANotMeta):
773 pass
774 self.assertIs(BNotMeta, type(E))
775 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000776 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000777 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000778 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000779
780 class F(object(), C):
781 pass
782 self.assertIs(BNotMeta, type(F))
783 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000784 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000785 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000786 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000787
788 class F2(C, object()):
789 pass
790 self.assertIs(BNotMeta, type(F2))
791 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000792 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000793 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000794 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000795
796 # TypeError: BNotMeta is neither a
797 # subclass, nor a superclass of int
798 with self.assertRaises(TypeError):
799 class X(C, int()):
800 pass
801 with self.assertRaises(TypeError):
802 class X(int(), C):
803 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000804
805 def test_module_subclasses(self):
806 # Testing Python subclass of module...
807 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000808 MT = type(sys)
809 class MM(MT):
810 def __init__(self, name):
811 MT.__init__(self, name)
812 def __getattribute__(self, name):
813 log.append(("getattr", name))
814 return MT.__getattribute__(self, name)
815 def __setattr__(self, name, value):
816 log.append(("setattr", name, value))
817 MT.__setattr__(self, name, value)
818 def __delattr__(self, name):
819 log.append(("delattr", name))
820 MT.__delattr__(self, name)
821 a = MM("a")
822 a.foo = 12
823 x = a.foo
824 del a.foo
825 self.assertEqual(log, [("setattr", "foo", 12),
826 ("getattr", "foo"),
827 ("delattr", "foo")])
828
829 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000830 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000831 class Module(types.ModuleType, str):
832 pass
833 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000834 pass
835 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000836 self.fail("inheriting from ModuleType and str at the same time "
837 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000838
Georg Brandl479a7e72008-02-05 18:13:15 +0000839 def test_multiple_inheritance(self):
840 # Testing multiple inheritance...
841 class C(object):
842 def __init__(self):
843 self.__state = 0
844 def getstate(self):
845 return self.__state
846 def setstate(self, state):
847 self.__state = state
848 a = C()
849 self.assertEqual(a.getstate(), 0)
850 a.setstate(10)
851 self.assertEqual(a.getstate(), 10)
852 class D(dict, C):
853 def __init__(self):
854 type({}).__init__(self)
855 C.__init__(self)
856 d = D()
857 self.assertEqual(list(d.keys()), [])
858 d["hello"] = "world"
859 self.assertEqual(list(d.items()), [("hello", "world")])
860 self.assertEqual(d["hello"], "world")
861 self.assertEqual(d.getstate(), 0)
862 d.setstate(10)
863 self.assertEqual(d.getstate(), 10)
864 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000865
Georg Brandl479a7e72008-02-05 18:13:15 +0000866 # SF bug #442833
867 class Node(object):
868 def __int__(self):
869 return int(self.foo())
870 def foo(self):
871 return "23"
872 class Frag(Node, list):
873 def foo(self):
874 return "42"
875 self.assertEqual(Node().__int__(), 23)
876 self.assertEqual(int(Node()), 23)
877 self.assertEqual(Frag().__int__(), 42)
878 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000879
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700880 def test_diamond_inheritance(self):
Georg Brandl479a7e72008-02-05 18:13:15 +0000881 # Testing multiple inheritance special cases...
882 class A(object):
883 def spam(self): return "A"
884 self.assertEqual(A().spam(), "A")
885 class B(A):
886 def boo(self): return "B"
887 def spam(self): return "B"
888 self.assertEqual(B().spam(), "B")
889 self.assertEqual(B().boo(), "B")
890 class C(A):
891 def boo(self): return "C"
892 self.assertEqual(C().spam(), "A")
893 self.assertEqual(C().boo(), "C")
894 class D(B, C): pass
895 self.assertEqual(D().spam(), "B")
896 self.assertEqual(D().boo(), "B")
897 self.assertEqual(D.__mro__, (D, B, C, A, object))
898 class E(C, B): pass
899 self.assertEqual(E().spam(), "B")
900 self.assertEqual(E().boo(), "C")
901 self.assertEqual(E.__mro__, (E, C, B, A, object))
902 # MRO order disagreement
903 try:
904 class F(D, E): pass
905 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000906 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000907 else:
908 self.fail("expected MRO order disagreement (F)")
909 try:
910 class G(E, D): pass
911 except TypeError:
912 pass
913 else:
914 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000915
Georg Brandl479a7e72008-02-05 18:13:15 +0000916 # see thread python-dev/2002-October/029035.html
917 def test_ex5_from_c3_switch(self):
918 # Testing ex5 from C3 switch discussion...
919 class A(object): pass
920 class B(object): pass
921 class C(object): pass
922 class X(A): pass
923 class Y(A): pass
924 class Z(X,B,Y,C): pass
925 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926
Georg Brandl479a7e72008-02-05 18:13:15 +0000927 # see "A Monotonic Superclass Linearization for Dylan",
928 # by Kim Barrett et al. (OOPSLA 1996)
929 def test_monotonicity(self):
930 # Testing MRO monotonicity...
931 class Boat(object): pass
932 class DayBoat(Boat): pass
933 class WheelBoat(Boat): pass
934 class EngineLess(DayBoat): pass
935 class SmallMultihull(DayBoat): pass
936 class PedalWheelBoat(EngineLess,WheelBoat): pass
937 class SmallCatamaran(SmallMultihull): pass
938 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000939
Georg Brandl479a7e72008-02-05 18:13:15 +0000940 self.assertEqual(PedalWheelBoat.__mro__,
941 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
942 self.assertEqual(SmallCatamaran.__mro__,
943 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
944 self.assertEqual(Pedalo.__mro__,
945 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
946 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000947
Georg Brandl479a7e72008-02-05 18:13:15 +0000948 # see "A Monotonic Superclass Linearization for Dylan",
949 # by Kim Barrett et al. (OOPSLA 1996)
950 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200951 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000952 class Pane(object): pass
953 class ScrollingMixin(object): pass
954 class EditingMixin(object): pass
955 class ScrollablePane(Pane,ScrollingMixin): pass
956 class EditablePane(Pane,EditingMixin): pass
957 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000958
Georg Brandl479a7e72008-02-05 18:13:15 +0000959 self.assertEqual(EditableScrollablePane.__mro__,
960 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
961 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000962
Georg Brandl479a7e72008-02-05 18:13:15 +0000963 def test_mro_disagreement(self):
964 # Testing error messages for MRO disagreement...
965 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000966order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000967
Georg Brandl479a7e72008-02-05 18:13:15 +0000968 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000969 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000970 callable(*args)
971 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000972 # the exact msg is generally considered an impl detail
973 if support.check_impl_detail():
974 if not str(msg).startswith(expected):
975 self.fail("Message %r, expected %r" %
976 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000977 else:
978 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000979
Georg Brandl479a7e72008-02-05 18:13:15 +0000980 class A(object): pass
981 class B(A): pass
982 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000983
Georg Brandl479a7e72008-02-05 18:13:15 +0000984 # Test some very simple errors
985 raises(TypeError, "duplicate base class A",
986 type, "X", (A, A), {})
987 raises(TypeError, mro_err_msg,
988 type, "X", (A, B), {})
989 raises(TypeError, mro_err_msg,
990 type, "X", (A, C, B), {})
991 # Test a slightly more complex error
992 class GridLayout(object): pass
993 class HorizontalGrid(GridLayout): pass
994 class VerticalGrid(GridLayout): pass
995 class HVGrid(HorizontalGrid, VerticalGrid): pass
996 class VHGrid(VerticalGrid, HorizontalGrid): pass
997 raises(TypeError, mro_err_msg,
998 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000999
Georg Brandl479a7e72008-02-05 18:13:15 +00001000 def test_object_class(self):
1001 # Testing object class...
1002 a = object()
1003 self.assertEqual(a.__class__, object)
1004 self.assertEqual(type(a), object)
1005 b = object()
1006 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001007 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001008 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001009 a.foo = 12
1010 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001011 pass
1012 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001013 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001014 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001015
Georg Brandl479a7e72008-02-05 18:13:15 +00001016 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001017 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 x = Cdict()
1019 self.assertEqual(x.__dict__, {})
1020 x.foo = 1
1021 self.assertEqual(x.foo, 1)
1022 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001024 def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1025 class SubType(types.ModuleType):
1026 a = 1
1027
1028 m = types.ModuleType("m")
1029 self.assertTrue(m.__class__ is types.ModuleType)
1030 self.assertFalse(hasattr(m, "a"))
1031
1032 m.__class__ = SubType
1033 self.assertTrue(m.__class__ is SubType)
1034 self.assertTrue(hasattr(m, "a"))
1035
1036 m.__class__ = types.ModuleType
1037 self.assertTrue(m.__class__ is types.ModuleType)
1038 self.assertFalse(hasattr(m, "a"))
1039
Guido van Rossum7d293ee2015-09-04 20:54:07 -07001040 # Make sure that builtin immutable objects don't support __class__
1041 # assignment, because the object instances may be interned.
1042 # We set __slots__ = () to ensure that the subclasses are
1043 # memory-layout compatible, and thus otherwise reasonable candidates
1044 # for __class__ assignment.
1045
1046 # The following types have immutable instances, but are not
1047 # subclassable and thus don't need to be checked:
1048 # NoneType, bool
1049
1050 class MyInt(int):
1051 __slots__ = ()
1052 with self.assertRaises(TypeError):
1053 (1).__class__ = MyInt
1054
1055 class MyFloat(float):
1056 __slots__ = ()
1057 with self.assertRaises(TypeError):
1058 (1.0).__class__ = MyFloat
1059
1060 class MyComplex(complex):
1061 __slots__ = ()
1062 with self.assertRaises(TypeError):
1063 (1 + 2j).__class__ = MyComplex
1064
1065 class MyStr(str):
1066 __slots__ = ()
1067 with self.assertRaises(TypeError):
1068 "a".__class__ = MyStr
1069
1070 class MyBytes(bytes):
1071 __slots__ = ()
1072 with self.assertRaises(TypeError):
1073 b"a".__class__ = MyBytes
1074
1075 class MyTuple(tuple):
1076 __slots__ = ()
1077 with self.assertRaises(TypeError):
1078 ().__class__ = MyTuple
1079
1080 class MyFrozenSet(frozenset):
1081 __slots__ = ()
1082 with self.assertRaises(TypeError):
1083 frozenset().__class__ = MyFrozenSet
1084
Georg Brandl479a7e72008-02-05 18:13:15 +00001085 def test_slots(self):
1086 # Testing __slots__...
1087 class C0(object):
1088 __slots__ = []
1089 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001090 self.assertNotHasAttr(x, "__dict__")
1091 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001092
1093 class C1(object):
1094 __slots__ = ['a']
1095 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001096 self.assertNotHasAttr(x, "__dict__")
1097 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001098 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001099 self.assertEqual(x.a, 1)
1100 x.a = None
1101 self.assertEqual(x.a, None)
1102 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001103 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001104
Georg Brandl479a7e72008-02-05 18:13:15 +00001105 class C3(object):
1106 __slots__ = ['a', 'b', 'c']
1107 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001108 self.assertNotHasAttr(x, "__dict__")
1109 self.assertNotHasAttr(x, 'a')
1110 self.assertNotHasAttr(x, 'b')
1111 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001112 x.a = 1
1113 x.b = 2
1114 x.c = 3
1115 self.assertEqual(x.a, 1)
1116 self.assertEqual(x.b, 2)
1117 self.assertEqual(x.c, 3)
1118
1119 class C4(object):
1120 """Validate name mangling"""
1121 __slots__ = ['__a']
1122 def __init__(self, value):
1123 self.__a = value
1124 def get(self):
1125 return self.__a
1126 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001127 self.assertNotHasAttr(x, '__dict__')
1128 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001129 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001130 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001131 x.__a = 6
1132 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001133 pass
1134 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001135 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001136
Georg Brandl479a7e72008-02-05 18:13:15 +00001137 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001138 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001139 class C(object):
1140 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001141 except TypeError:
1142 pass
1143 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001144 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001145 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001146 class C(object):
1147 __slots__ = ["foo bar"]
1148 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001149 pass
1150 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001151 self.fail("['foo bar'] slots not caught")
1152 try:
1153 class C(object):
1154 __slots__ = ["foo\0bar"]
1155 except TypeError:
1156 pass
1157 else:
1158 self.fail("['foo\\0bar'] slots not caught")
1159 try:
1160 class C(object):
1161 __slots__ = ["1"]
1162 except TypeError:
1163 pass
1164 else:
1165 self.fail("['1'] slots not caught")
1166 try:
1167 class C(object):
1168 __slots__ = [""]
1169 except TypeError:
1170 pass
1171 else:
1172 self.fail("[''] slots not caught")
1173 class C(object):
1174 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1175 # XXX(nnorwitz): was there supposed to be something tested
1176 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001177
Georg Brandl479a7e72008-02-05 18:13:15 +00001178 # Test a single string is not expanded as a sequence.
1179 class C(object):
1180 __slots__ = "abc"
1181 c = C()
1182 c.abc = 5
1183 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001184
Georg Brandl479a7e72008-02-05 18:13:15 +00001185 # Test unicode slot names
1186 # Test a single unicode string is not expanded as a sequence.
1187 class C(object):
1188 __slots__ = "abc"
1189 c = C()
1190 c.abc = 5
1191 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001192
Georg Brandl479a7e72008-02-05 18:13:15 +00001193 # _unicode_to_string used to modify slots in certain circumstances
1194 slots = ("foo", "bar")
1195 class C(object):
1196 __slots__ = slots
1197 x = C()
1198 x.foo = 5
1199 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001200 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001201 # this used to leak references
1202 try:
1203 class C(object):
1204 __slots__ = [chr(128)]
1205 except (TypeError, UnicodeEncodeError):
1206 pass
1207 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001208 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001209
Georg Brandl479a7e72008-02-05 18:13:15 +00001210 # Test leaks
1211 class Counted(object):
1212 counter = 0 # counts the number of instances alive
1213 def __init__(self):
1214 Counted.counter += 1
1215 def __del__(self):
1216 Counted.counter -= 1
1217 class C(object):
1218 __slots__ = ['a', 'b', 'c']
1219 x = C()
1220 x.a = Counted()
1221 x.b = Counted()
1222 x.c = Counted()
1223 self.assertEqual(Counted.counter, 3)
1224 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001225 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001226 self.assertEqual(Counted.counter, 0)
1227 class D(C):
1228 pass
1229 x = D()
1230 x.a = Counted()
1231 x.z = Counted()
1232 self.assertEqual(Counted.counter, 2)
1233 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001234 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001235 self.assertEqual(Counted.counter, 0)
1236 class E(D):
1237 __slots__ = ['e']
1238 x = E()
1239 x.a = Counted()
1240 x.z = Counted()
1241 x.e = Counted()
1242 self.assertEqual(Counted.counter, 3)
1243 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001244 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001245 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001246
Georg Brandl479a7e72008-02-05 18:13:15 +00001247 # Test cyclical leaks [SF bug 519621]
1248 class F(object):
1249 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001250 s = F()
1251 s.a = [Counted(), s]
1252 self.assertEqual(Counted.counter, 1)
1253 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001254 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001255 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001256
Georg Brandl479a7e72008-02-05 18:13:15 +00001257 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001258 if hasattr(gc, 'get_objects'):
1259 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001260 def __eq__(self, other):
1261 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001262 g = G()
1263 orig_objects = len(gc.get_objects())
1264 for i in range(10):
1265 g==g
1266 new_objects = len(gc.get_objects())
1267 self.assertEqual(orig_objects, new_objects)
1268
Georg Brandl479a7e72008-02-05 18:13:15 +00001269 class H(object):
1270 __slots__ = ['a', 'b']
1271 def __init__(self):
1272 self.a = 1
1273 self.b = 2
1274 def __del__(self_):
1275 self.assertEqual(self_.a, 1)
1276 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001277 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001278 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001279 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001280 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001281
Benjamin Petersond12362a2009-12-30 19:44:54 +00001282 class X(object):
1283 __slots__ = "a"
1284 with self.assertRaises(AttributeError):
1285 del X().a
1286
Georg Brandl479a7e72008-02-05 18:13:15 +00001287 def test_slots_special(self):
1288 # Testing __dict__ and __weakref__ in __slots__...
1289 class D(object):
1290 __slots__ = ["__dict__"]
1291 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001292 self.assertHasAttr(a, "__dict__")
1293 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001294 a.foo = 42
1295 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001296
Georg Brandl479a7e72008-02-05 18:13:15 +00001297 class W(object):
1298 __slots__ = ["__weakref__"]
1299 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001300 self.assertHasAttr(a, "__weakref__")
1301 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001302 try:
1303 a.foo = 42
1304 except AttributeError:
1305 pass
1306 else:
1307 self.fail("shouldn't be allowed to set a.foo")
1308
1309 class C1(W, D):
1310 __slots__ = []
1311 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001312 self.assertHasAttr(a, "__dict__")
1313 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001314 a.foo = 42
1315 self.assertEqual(a.__dict__, {"foo": 42})
1316
1317 class C2(D, W):
1318 __slots__ = []
1319 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001320 self.assertHasAttr(a, "__dict__")
1321 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001322 a.foo = 42
1323 self.assertEqual(a.__dict__, {"foo": 42})
1324
Xiang Zhangc393ee82017-03-08 11:18:49 +08001325 def test_slots_special2(self):
1326 # Testing __qualname__ and __classcell__ in __slots__
1327 class Meta(type):
1328 def __new__(cls, name, bases, namespace, attr):
1329 self.assertIn(attr, namespace)
1330 return super().__new__(cls, name, bases, namespace)
1331
1332 class C1:
1333 def __init__(self):
1334 self.b = 42
1335 class C2(C1, metaclass=Meta, attr="__classcell__"):
1336 __slots__ = ["__classcell__"]
1337 def __init__(self):
1338 super().__init__()
1339 self.assertIsInstance(C2.__dict__["__classcell__"],
1340 types.MemberDescriptorType)
1341 c = C2()
1342 self.assertEqual(c.b, 42)
1343 self.assertNotHasAttr(c, "__classcell__")
1344 c.__classcell__ = 42
1345 self.assertEqual(c.__classcell__, 42)
1346 with self.assertRaises(TypeError):
1347 class C3:
1348 __classcell__ = 42
1349 __slots__ = ["__classcell__"]
1350
1351 class Q1(metaclass=Meta, attr="__qualname__"):
1352 __slots__ = ["__qualname__"]
1353 self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
1354 self.assertIsInstance(Q1.__dict__["__qualname__"],
1355 types.MemberDescriptorType)
1356 q = Q1()
1357 self.assertNotHasAttr(q, "__qualname__")
1358 q.__qualname__ = "q"
1359 self.assertEqual(q.__qualname__, "q")
1360 with self.assertRaises(TypeError):
1361 class Q2:
1362 __qualname__ = object()
1363 __slots__ = ["__qualname__"]
1364
Christian Heimesa156e092008-02-16 07:38:31 +00001365 def test_slots_descriptor(self):
1366 # Issue2115: slot descriptors did not correctly check
1367 # the type of the given object
1368 import abc
1369 class MyABC(metaclass=abc.ABCMeta):
1370 __slots__ = "a"
1371
1372 class Unrelated(object):
1373 pass
1374 MyABC.register(Unrelated)
1375
1376 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001377 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001378
1379 # This used to crash
1380 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1381
Georg Brandl479a7e72008-02-05 18:13:15 +00001382 def test_dynamics(self):
1383 # Testing class attribute propagation...
1384 class D(object):
1385 pass
1386 class E(D):
1387 pass
1388 class F(D):
1389 pass
1390 D.foo = 1
1391 self.assertEqual(D.foo, 1)
1392 # Test that dynamic attributes are inherited
1393 self.assertEqual(E.foo, 1)
1394 self.assertEqual(F.foo, 1)
1395 # Test dynamic instances
1396 class C(object):
1397 pass
1398 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001399 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001400 C.foobar = 2
1401 self.assertEqual(a.foobar, 2)
1402 C.method = lambda self: 42
1403 self.assertEqual(a.method(), 42)
1404 C.__repr__ = lambda self: "C()"
1405 self.assertEqual(repr(a), "C()")
1406 C.__int__ = lambda self: 100
1407 self.assertEqual(int(a), 100)
1408 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001409 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001410 def mygetattr(self, name):
1411 if name == "spam":
1412 return "spam"
1413 raise AttributeError
1414 C.__getattr__ = mygetattr
1415 self.assertEqual(a.spam, "spam")
1416 a.new = 12
1417 self.assertEqual(a.new, 12)
1418 def mysetattr(self, name, value):
1419 if name == "spam":
1420 raise AttributeError
1421 return object.__setattr__(self, name, value)
1422 C.__setattr__ = mysetattr
1423 try:
1424 a.spam = "not spam"
1425 except AttributeError:
1426 pass
1427 else:
1428 self.fail("expected AttributeError")
1429 self.assertEqual(a.spam, "spam")
1430 class D(C):
1431 pass
1432 d = D()
1433 d.foo = 1
1434 self.assertEqual(d.foo, 1)
1435
1436 # Test handling of int*seq and seq*int
1437 class I(int):
1438 pass
1439 self.assertEqual("a"*I(2), "aa")
1440 self.assertEqual(I(2)*"a", "aa")
1441 self.assertEqual(2*I(3), 6)
1442 self.assertEqual(I(3)*2, 6)
1443 self.assertEqual(I(3)*I(2), 6)
1444
Georg Brandl479a7e72008-02-05 18:13:15 +00001445 # Test comparison of classes with dynamic metaclasses
1446 class dynamicmetaclass(type):
1447 pass
1448 class someclass(metaclass=dynamicmetaclass):
1449 pass
1450 self.assertNotEqual(someclass, object)
1451
1452 def test_errors(self):
1453 # Testing errors...
1454 try:
1455 class C(list, dict):
1456 pass
1457 except TypeError:
1458 pass
1459 else:
1460 self.fail("inheritance from both list and dict should be illegal")
1461
1462 try:
1463 class C(object, None):
1464 pass
1465 except TypeError:
1466 pass
1467 else:
1468 self.fail("inheritance from non-type should be illegal")
1469 class Classic:
1470 pass
1471
1472 try:
1473 class C(type(len)):
1474 pass
1475 except TypeError:
1476 pass
1477 else:
1478 self.fail("inheritance from CFunction should be illegal")
1479
1480 try:
1481 class C(object):
1482 __slots__ = 1
1483 except TypeError:
1484 pass
1485 else:
1486 self.fail("__slots__ = 1 should be illegal")
1487
1488 try:
1489 class C(object):
1490 __slots__ = [1]
1491 except TypeError:
1492 pass
1493 else:
1494 self.fail("__slots__ = [1] should be illegal")
1495
1496 class M1(type):
1497 pass
1498 class M2(type):
1499 pass
1500 class A1(object, metaclass=M1):
1501 pass
1502 class A2(object, metaclass=M2):
1503 pass
1504 try:
1505 class B(A1, A2):
1506 pass
1507 except TypeError:
1508 pass
1509 else:
1510 self.fail("finding the most derived metaclass should have failed")
1511
1512 def test_classmethods(self):
1513 # Testing class methods...
1514 class C(object):
1515 def foo(*a): return a
1516 goo = classmethod(foo)
1517 c = C()
1518 self.assertEqual(C.goo(1), (C, 1))
1519 self.assertEqual(c.goo(1), (C, 1))
1520 self.assertEqual(c.foo(1), (c, 1))
1521 class D(C):
1522 pass
1523 d = D()
1524 self.assertEqual(D.goo(1), (D, 1))
1525 self.assertEqual(d.goo(1), (D, 1))
1526 self.assertEqual(d.foo(1), (d, 1))
1527 self.assertEqual(D.foo(d, 1), (d, 1))
1528 # Test for a specific crash (SF bug 528132)
1529 def f(cls, arg): return (cls, arg)
1530 ff = classmethod(f)
1531 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1532 self.assertEqual(ff.__get__(0)(42), (int, 42))
1533
1534 # Test super() with classmethods (SF bug 535444)
1535 self.assertEqual(C.goo.__self__, C)
1536 self.assertEqual(D.goo.__self__, D)
1537 self.assertEqual(super(D,D).goo.__self__, D)
1538 self.assertEqual(super(D,d).goo.__self__, D)
1539 self.assertEqual(super(D,D).goo(), (D,))
1540 self.assertEqual(super(D,d).goo(), (D,))
1541
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001542 # Verify that a non-callable will raise
1543 meth = classmethod(1).__get__(1)
1544 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001545
1546 # Verify that classmethod() doesn't allow keyword args
1547 try:
1548 classmethod(f, kw=1)
1549 except TypeError:
1550 pass
1551 else:
1552 self.fail("classmethod shouldn't accept keyword args")
1553
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001554 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001555 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001556 cm.x = 42
1557 self.assertEqual(cm.x, 42)
1558 self.assertEqual(cm.__dict__, {"x" : 42})
1559 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001560 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001561
Benjamin Petersone549ead2009-03-28 21:42:05 +00001562 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001563 def test_classmethods_in_c(self):
1564 # Testing C-based class methods...
1565 import xxsubtype as spam
1566 a = (1, 2, 3)
1567 d = {'abc': 123}
1568 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1569 self.assertEqual(x, spam.spamlist)
1570 self.assertEqual(a, a1)
1571 self.assertEqual(d, d1)
1572 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1573 self.assertEqual(x, spam.spamlist)
1574 self.assertEqual(a, a1)
1575 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001576 spam_cm = spam.spamlist.__dict__['classmeth']
1577 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1578 self.assertEqual(x2, spam.spamlist)
1579 self.assertEqual(a2, a1)
1580 self.assertEqual(d2, d1)
1581 class SubSpam(spam.spamlist): pass
1582 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1583 self.assertEqual(x2, SubSpam)
1584 self.assertEqual(a2, a1)
1585 self.assertEqual(d2, d1)
1586 with self.assertRaises(TypeError):
1587 spam_cm()
1588 with self.assertRaises(TypeError):
1589 spam_cm(spam.spamlist())
1590 with self.assertRaises(TypeError):
1591 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001592
1593 def test_staticmethods(self):
1594 # Testing static methods...
1595 class C(object):
1596 def foo(*a): return a
1597 goo = staticmethod(foo)
1598 c = C()
1599 self.assertEqual(C.goo(1), (1,))
1600 self.assertEqual(c.goo(1), (1,))
1601 self.assertEqual(c.foo(1), (c, 1,))
1602 class D(C):
1603 pass
1604 d = D()
1605 self.assertEqual(D.goo(1), (1,))
1606 self.assertEqual(d.goo(1), (1,))
1607 self.assertEqual(d.foo(1), (d, 1))
1608 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001609 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001610 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001611 sm.x = 42
1612 self.assertEqual(sm.x, 42)
1613 self.assertEqual(sm.__dict__, {"x" : 42})
1614 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001615 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001616
Benjamin Petersone549ead2009-03-28 21:42:05 +00001617 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001618 def test_staticmethods_in_c(self):
1619 # Testing C-based static methods...
1620 import xxsubtype as spam
1621 a = (1, 2, 3)
1622 d = {"abc": 123}
1623 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1624 self.assertEqual(x, None)
1625 self.assertEqual(a, a1)
1626 self.assertEqual(d, d1)
1627 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1628 self.assertEqual(x, None)
1629 self.assertEqual(a, a1)
1630 self.assertEqual(d, d1)
1631
1632 def test_classic(self):
1633 # Testing classic classes...
1634 class C:
1635 def foo(*a): return a
1636 goo = classmethod(foo)
1637 c = C()
1638 self.assertEqual(C.goo(1), (C, 1))
1639 self.assertEqual(c.goo(1), (C, 1))
1640 self.assertEqual(c.foo(1), (c, 1))
1641 class D(C):
1642 pass
1643 d = D()
1644 self.assertEqual(D.goo(1), (D, 1))
1645 self.assertEqual(d.goo(1), (D, 1))
1646 self.assertEqual(d.foo(1), (d, 1))
1647 self.assertEqual(D.foo(d, 1), (d, 1))
1648 class E: # *not* subclassing from C
1649 foo = C.foo
1650 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001651 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001652
1653 def test_compattr(self):
1654 # Testing computed attributes...
1655 class C(object):
1656 class computed_attribute(object):
1657 def __init__(self, get, set=None, delete=None):
1658 self.__get = get
1659 self.__set = set
1660 self.__delete = delete
1661 def __get__(self, obj, type=None):
1662 return self.__get(obj)
1663 def __set__(self, obj, value):
1664 return self.__set(obj, value)
1665 def __delete__(self, obj):
1666 return self.__delete(obj)
1667 def __init__(self):
1668 self.__x = 0
1669 def __get_x(self):
1670 x = self.__x
1671 self.__x = x+1
1672 return x
1673 def __set_x(self, x):
1674 self.__x = x
1675 def __delete_x(self):
1676 del self.__x
1677 x = computed_attribute(__get_x, __set_x, __delete_x)
1678 a = C()
1679 self.assertEqual(a.x, 0)
1680 self.assertEqual(a.x, 1)
1681 a.x = 10
1682 self.assertEqual(a.x, 10)
1683 self.assertEqual(a.x, 11)
1684 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001685 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001686
1687 def test_newslots(self):
1688 # Testing __new__ slot override...
1689 class C(list):
1690 def __new__(cls):
1691 self = list.__new__(cls)
1692 self.foo = 1
1693 return self
1694 def __init__(self):
1695 self.foo = self.foo + 2
1696 a = C()
1697 self.assertEqual(a.foo, 3)
1698 self.assertEqual(a.__class__, C)
1699 class D(C):
1700 pass
1701 b = D()
1702 self.assertEqual(b.foo, 3)
1703 self.assertEqual(b.__class__, D)
1704
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001705 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001706 def test_bad_new(self):
1707 self.assertRaises(TypeError, object.__new__)
1708 self.assertRaises(TypeError, object.__new__, '')
1709 self.assertRaises(TypeError, list.__new__, object)
1710 self.assertRaises(TypeError, object.__new__, list)
1711 class C(object):
1712 __new__ = list.__new__
1713 self.assertRaises(TypeError, C)
1714 class C(list):
1715 __new__ = object.__new__
1716 self.assertRaises(TypeError, C)
1717
1718 def test_object_new(self):
1719 class A(object):
1720 pass
1721 object.__new__(A)
1722 self.assertRaises(TypeError, object.__new__, A, 5)
1723 object.__init__(A())
1724 self.assertRaises(TypeError, object.__init__, A(), 5)
1725
1726 class A(object):
1727 def __init__(self, foo):
1728 self.foo = foo
1729 object.__new__(A)
1730 object.__new__(A, 5)
1731 object.__init__(A(3))
1732 self.assertRaises(TypeError, object.__init__, A(3), 5)
1733
1734 class A(object):
1735 def __new__(cls, foo):
1736 return object.__new__(cls)
1737 object.__new__(A)
1738 self.assertRaises(TypeError, object.__new__, A, 5)
1739 object.__init__(A(3))
1740 object.__init__(A(3), 5)
1741
1742 class A(object):
1743 def __new__(cls, foo):
1744 return object.__new__(cls)
1745 def __init__(self, foo):
1746 self.foo = foo
1747 object.__new__(A)
1748 self.assertRaises(TypeError, object.__new__, A, 5)
1749 object.__init__(A(3))
1750 self.assertRaises(TypeError, object.__init__, A(3), 5)
1751
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001752 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001753 def test_restored_object_new(self):
1754 class A(object):
1755 def __new__(cls, *args, **kwargs):
1756 raise AssertionError
1757 self.assertRaises(AssertionError, A)
1758 class B(A):
1759 __new__ = object.__new__
1760 def __init__(self, foo):
1761 self.foo = foo
1762 with warnings.catch_warnings():
1763 warnings.simplefilter('error', DeprecationWarning)
1764 b = B(3)
1765 self.assertEqual(b.foo, 3)
1766 self.assertEqual(b.__class__, B)
1767 del B.__new__
1768 self.assertRaises(AssertionError, B)
1769 del A.__new__
1770 with warnings.catch_warnings():
1771 warnings.simplefilter('error', DeprecationWarning)
1772 b = B(3)
1773 self.assertEqual(b.foo, 3)
1774 self.assertEqual(b.__class__, B)
1775
Georg Brandl479a7e72008-02-05 18:13:15 +00001776 def test_altmro(self):
1777 # Testing mro() and overriding it...
1778 class A(object):
1779 def f(self): return "A"
1780 class B(A):
1781 pass
1782 class C(A):
1783 def f(self): return "C"
1784 class D(B, C):
1785 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001786 self.assertEqual(A.mro(), [A, object])
1787 self.assertEqual(A.__mro__, (A, object))
1788 self.assertEqual(B.mro(), [B, A, object])
1789 self.assertEqual(B.__mro__, (B, A, object))
1790 self.assertEqual(C.mro(), [C, A, object])
1791 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001792 self.assertEqual(D.mro(), [D, B, C, A, object])
1793 self.assertEqual(D.__mro__, (D, B, C, A, object))
1794 self.assertEqual(D().f(), "C")
1795
1796 class PerverseMetaType(type):
1797 def mro(cls):
1798 L = type.mro(cls)
1799 L.reverse()
1800 return L
1801 class X(D,B,C,A, metaclass=PerverseMetaType):
1802 pass
1803 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1804 self.assertEqual(X().f(), "A")
1805
1806 try:
1807 class _metaclass(type):
1808 def mro(self):
1809 return [self, dict, object]
1810 class X(object, metaclass=_metaclass):
1811 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001812 # In CPython, the class creation above already raises
1813 # TypeError, as a protection against the fact that
1814 # instances of X would segfault it. In other Python
1815 # implementations it would be ok to let the class X
1816 # be created, but instead get a clean TypeError on the
1817 # __setitem__ below.
1818 x = object.__new__(X)
1819 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001820 except TypeError:
1821 pass
1822 else:
1823 self.fail("devious mro() return not caught")
1824
1825 try:
1826 class _metaclass(type):
1827 def mro(self):
1828 return [1]
1829 class X(object, metaclass=_metaclass):
1830 pass
1831 except TypeError:
1832 pass
1833 else:
1834 self.fail("non-class mro() return not caught")
1835
1836 try:
1837 class _metaclass(type):
1838 def mro(self):
1839 return 1
1840 class X(object, metaclass=_metaclass):
1841 pass
1842 except TypeError:
1843 pass
1844 else:
1845 self.fail("non-sequence mro() return not caught")
1846
1847 def test_overloading(self):
1848 # Testing operator overloading...
1849
1850 class B(object):
1851 "Intermediate class because object doesn't have a __setattr__"
1852
1853 class C(B):
1854 def __getattr__(self, name):
1855 if name == "foo":
1856 return ("getattr", name)
1857 else:
1858 raise AttributeError
1859 def __setattr__(self, name, value):
1860 if name == "foo":
1861 self.setattr = (name, value)
1862 else:
1863 return B.__setattr__(self, name, value)
1864 def __delattr__(self, name):
1865 if name == "foo":
1866 self.delattr = name
1867 else:
1868 return B.__delattr__(self, name)
1869
1870 def __getitem__(self, key):
1871 return ("getitem", key)
1872 def __setitem__(self, key, value):
1873 self.setitem = (key, value)
1874 def __delitem__(self, key):
1875 self.delitem = key
1876
1877 a = C()
1878 self.assertEqual(a.foo, ("getattr", "foo"))
1879 a.foo = 12
1880 self.assertEqual(a.setattr, ("foo", 12))
1881 del a.foo
1882 self.assertEqual(a.delattr, "foo")
1883
1884 self.assertEqual(a[12], ("getitem", 12))
1885 a[12] = 21
1886 self.assertEqual(a.setitem, (12, 21))
1887 del a[12]
1888 self.assertEqual(a.delitem, 12)
1889
1890 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1891 a[0:10] = "foo"
1892 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1893 del a[0:10]
1894 self.assertEqual(a.delitem, (slice(0, 10)))
1895
1896 def test_methods(self):
1897 # Testing methods...
1898 class C(object):
1899 def __init__(self, x):
1900 self.x = x
1901 def foo(self):
1902 return self.x
1903 c1 = C(1)
1904 self.assertEqual(c1.foo(), 1)
1905 class D(C):
1906 boo = C.foo
1907 goo = c1.foo
1908 d2 = D(2)
1909 self.assertEqual(d2.foo(), 2)
1910 self.assertEqual(d2.boo(), 2)
1911 self.assertEqual(d2.goo(), 1)
1912 class E(object):
1913 foo = C.foo
1914 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001915 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001916
Benjamin Peterson224205f2009-05-08 03:25:19 +00001917 def test_special_method_lookup(self):
1918 # The lookup of special methods bypasses __getattr__ and
1919 # __getattribute__, but they still can be descriptors.
1920
1921 def run_context(manager):
1922 with manager:
1923 pass
1924 def iden(self):
1925 return self
1926 def hello(self):
1927 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001928 def empty_seq(self):
1929 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001930 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001931 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001932 def complex_num(self):
1933 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001934 def stop(self):
1935 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001936 def return_true(self, thing=None):
1937 return True
1938 def do_isinstance(obj):
1939 return isinstance(int, obj)
1940 def do_issubclass(obj):
1941 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001942 def do_dict_missing(checker):
1943 class DictSub(checker.__class__, dict):
1944 pass
1945 self.assertEqual(DictSub()["hi"], 4)
1946 def some_number(self_, key):
1947 self.assertEqual(key, "hi")
1948 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001949 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001950 def format_impl(self, spec):
1951 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001952
1953 # It would be nice to have every special method tested here, but I'm
1954 # only listing the ones I can remember outside of typeobject.c, since it
1955 # does it right.
1956 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001957 ("__bytes__", bytes, hello, set(), {}),
1958 ("__reversed__", reversed, empty_seq, set(), {}),
1959 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001960 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001961 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1962 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001963 ("__missing__", do_dict_missing, some_number,
1964 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001965 ("__subclasscheck__", do_issubclass, return_true,
1966 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001967 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1968 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001969 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001970 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001971 ("__floor__", math.floor, zero, set(), {}),
1972 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001973 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001974 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001975 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001976 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001977 ]
1978
1979 class Checker(object):
1980 def __getattr__(self, attr, test=self):
1981 test.fail("__getattr__ called with {0}".format(attr))
1982 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001983 if attr not in ok:
1984 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001985 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001986 class SpecialDescr(object):
1987 def __init__(self, impl):
1988 self.impl = impl
1989 def __get__(self, obj, owner):
1990 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001991 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001992 class MyException(Exception):
1993 pass
1994 class ErrDescr(object):
1995 def __get__(self, obj, owner):
1996 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001997
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001998 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001999 class X(Checker):
2000 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002001 for attr, obj in env.items():
2002 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002003 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002004 runner(X())
2005
2006 record = []
2007 class X(Checker):
2008 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002009 for attr, obj in env.items():
2010 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002011 setattr(X, name, SpecialDescr(meth_impl))
2012 runner(X())
2013 self.assertEqual(record, [1], name)
2014
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002015 class X(Checker):
2016 pass
2017 for attr, obj in env.items():
2018 setattr(X, attr, obj)
2019 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002020 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002021
Georg Brandl479a7e72008-02-05 18:13:15 +00002022 def test_specials(self):
2023 # Testing special operators...
2024 # Test operators like __hash__ for which a built-in default exists
2025
2026 # Test the default behavior for static classes
2027 class C(object):
2028 def __getitem__(self, i):
2029 if 0 <= i < 10: return i
2030 raise IndexError
2031 c1 = C()
2032 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002033 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002034 self.assertNotEqual(id(c1), id(c2))
2035 hash(c1)
2036 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002037 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002038 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002039 self.assertFalse(c1 != c1)
2040 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002041 # Note that the module name appears in str/repr, and that varies
2042 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002043 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002044 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002045 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002046 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002047 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002048 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002049 # Test the default behavior for dynamic classes
2050 class D(object):
2051 def __getitem__(self, i):
2052 if 0 <= i < 10: return i
2053 raise IndexError
2054 d1 = D()
2055 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002056 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002057 self.assertNotEqual(id(d1), id(d2))
2058 hash(d1)
2059 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002060 self.assertEqual(d1, d1)
2061 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002062 self.assertFalse(d1 != d1)
2063 self.assertFalse(d1 == d2)
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(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002067 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002068 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002069 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002070 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002071 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002072 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002073 class Proxy(object):
2074 def __init__(self, x):
2075 self.x = x
2076 def __bool__(self):
2077 return not not self.x
2078 def __hash__(self):
2079 return hash(self.x)
2080 def __eq__(self, other):
2081 return self.x == other
2082 def __ne__(self, other):
2083 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002084 def __ge__(self, other):
2085 return self.x >= other
2086 def __gt__(self, other):
2087 return self.x > other
2088 def __le__(self, other):
2089 return self.x <= other
2090 def __lt__(self, other):
2091 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002092 def __str__(self):
2093 return "Proxy:%s" % self.x
2094 def __repr__(self):
2095 return "Proxy(%r)" % self.x
2096 def __contains__(self, value):
2097 return value in self.x
2098 p0 = Proxy(0)
2099 p1 = Proxy(1)
2100 p_1 = Proxy(-1)
2101 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002102 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002103 self.assertEqual(hash(p0), hash(0))
2104 self.assertEqual(p0, p0)
2105 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002106 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002107 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002108 self.assertTrue(p0 < p1)
2109 self.assertTrue(p0 <= p1)
2110 self.assertTrue(p1 > p0)
2111 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002112 self.assertEqual(str(p0), "Proxy:0")
2113 self.assertEqual(repr(p0), "Proxy(0)")
2114 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002115 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002116 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002117 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002118 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002119
Georg Brandl479a7e72008-02-05 18:13:15 +00002120 def test_weakrefs(self):
2121 # Testing weak references...
2122 import weakref
2123 class C(object):
2124 pass
2125 c = C()
2126 r = weakref.ref(c)
2127 self.assertEqual(r(), c)
2128 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002129 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002130 self.assertEqual(r(), None)
2131 del r
2132 class NoWeak(object):
2133 __slots__ = ['foo']
2134 no = NoWeak()
2135 try:
2136 weakref.ref(no)
2137 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002138 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002139 else:
2140 self.fail("weakref.ref(no) should be illegal")
2141 class Weak(object):
2142 __slots__ = ['foo', '__weakref__']
2143 yes = Weak()
2144 r = weakref.ref(yes)
2145 self.assertEqual(r(), yes)
2146 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002147 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002148 self.assertEqual(r(), None)
2149 del r
2150
2151 def test_properties(self):
2152 # Testing property...
2153 class C(object):
2154 def getx(self):
2155 return self.__x
2156 def setx(self, value):
2157 self.__x = value
2158 def delx(self):
2159 del self.__x
2160 x = property(getx, setx, delx, doc="I'm the x property.")
2161 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002162 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002163 a.x = 42
2164 self.assertEqual(a._C__x, 42)
2165 self.assertEqual(a.x, 42)
2166 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002167 self.assertNotHasAttr(a, "x")
2168 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002169 C.x.__set__(a, 100)
2170 self.assertEqual(C.x.__get__(a), 100)
2171 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002172 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002173
2174 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002175 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002176
2177 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002178 self.assertIn("__doc__", attrs)
2179 self.assertIn("fget", attrs)
2180 self.assertIn("fset", attrs)
2181 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002182
2183 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002184 self.assertIs(raw.fget, C.__dict__['getx'])
2185 self.assertIs(raw.fset, C.__dict__['setx'])
2186 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002187
Raymond Hettingereac503a2015-05-13 01:09:59 -07002188 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002189 try:
2190 setattr(raw, attr, 42)
2191 except AttributeError as msg:
2192 if str(msg).find('readonly') < 0:
2193 self.fail("when setting readonly attr %r on a property, "
2194 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2195 else:
2196 self.fail("expected AttributeError from trying to set readonly %r "
2197 "attr on a property" % attr)
2198
Raymond Hettingereac503a2015-05-13 01:09:59 -07002199 raw.__doc__ = 42
2200 self.assertEqual(raw.__doc__, 42)
2201
Georg Brandl479a7e72008-02-05 18:13:15 +00002202 class D(object):
2203 __getitem__ = property(lambda s: 1/0)
2204
2205 d = D()
2206 try:
2207 for i in d:
2208 str(i)
2209 except ZeroDivisionError:
2210 pass
2211 else:
2212 self.fail("expected ZeroDivisionError from bad property")
2213
R. David Murray378c0cf2010-02-24 01:46:21 +00002214 @unittest.skipIf(sys.flags.optimize >= 2,
2215 "Docstrings are omitted with -O2 and above")
2216 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002217 class E(object):
2218 def getter(self):
2219 "getter method"
2220 return 0
2221 def setter(self_, value):
2222 "setter method"
2223 pass
2224 prop = property(getter)
2225 self.assertEqual(prop.__doc__, "getter method")
2226 prop2 = property(fset=setter)
2227 self.assertEqual(prop2.__doc__, None)
2228
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002229 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002230 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002231 # this segfaulted in 2.5b2
2232 try:
2233 import _testcapi
2234 except ImportError:
2235 pass
2236 else:
2237 class X(object):
2238 p = property(_testcapi.test_with_docstring)
2239
2240 def test_properties_plus(self):
2241 class C(object):
2242 foo = property(doc="hello")
2243 @foo.getter
2244 def foo(self):
2245 return self._foo
2246 @foo.setter
2247 def foo(self, value):
2248 self._foo = abs(value)
2249 @foo.deleter
2250 def foo(self):
2251 del self._foo
2252 c = C()
2253 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002254 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002255 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002256 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002257 self.assertEqual(c._foo, 42)
2258 self.assertEqual(c.foo, 42)
2259 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002260 self.assertNotHasAttr(c, '_foo')
2261 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002262
2263 class D(C):
2264 @C.foo.deleter
2265 def foo(self):
2266 try:
2267 del self._foo
2268 except AttributeError:
2269 pass
2270 d = D()
2271 d.foo = 24
2272 self.assertEqual(d.foo, 24)
2273 del d.foo
2274 del d.foo
2275
2276 class E(object):
2277 @property
2278 def foo(self):
2279 return self._foo
2280 @foo.setter
2281 def foo(self, value):
2282 raise RuntimeError
2283 @foo.setter
2284 def foo(self, value):
2285 self._foo = abs(value)
2286 @foo.deleter
2287 def foo(self, value=None):
2288 del self._foo
2289
2290 e = E()
2291 e.foo = -42
2292 self.assertEqual(e.foo, 42)
2293 del e.foo
2294
2295 class F(E):
2296 @E.foo.deleter
2297 def foo(self):
2298 del self._foo
2299 @foo.setter
2300 def foo(self, value):
2301 self._foo = max(0, value)
2302 f = F()
2303 f.foo = -10
2304 self.assertEqual(f.foo, 0)
2305 del f.foo
2306
2307 def test_dict_constructors(self):
2308 # Testing dict constructor ...
2309 d = dict()
2310 self.assertEqual(d, {})
2311 d = dict({})
2312 self.assertEqual(d, {})
2313 d = dict({1: 2, 'a': 'b'})
2314 self.assertEqual(d, {1: 2, 'a': 'b'})
2315 self.assertEqual(d, dict(list(d.items())))
2316 self.assertEqual(d, dict(iter(d.items())))
2317 d = dict({'one':1, 'two':2})
2318 self.assertEqual(d, dict(one=1, two=2))
2319 self.assertEqual(d, dict(**d))
2320 self.assertEqual(d, dict({"one": 1}, two=2))
2321 self.assertEqual(d, dict([("two", 2)], one=1))
2322 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2323 self.assertEqual(d, dict(**d))
2324
2325 for badarg in 0, 0, 0j, "0", [0], (0,):
2326 try:
2327 dict(badarg)
2328 except TypeError:
2329 pass
2330 except ValueError:
2331 if badarg == "0":
2332 # It's a sequence, and its elements are also sequences (gotta
2333 # love strings <wink>), but they aren't of length 2, so this
2334 # one seemed better as a ValueError than a TypeError.
2335 pass
2336 else:
2337 self.fail("no TypeError from dict(%r)" % badarg)
2338 else:
2339 self.fail("no TypeError from dict(%r)" % badarg)
2340
2341 try:
2342 dict({}, {})
2343 except TypeError:
2344 pass
2345 else:
2346 self.fail("no TypeError from dict({}, {})")
2347
2348 class Mapping:
2349 # Lacks a .keys() method; will be added later.
2350 dict = {1:2, 3:4, 'a':1j}
2351
2352 try:
2353 dict(Mapping())
2354 except TypeError:
2355 pass
2356 else:
2357 self.fail("no TypeError from dict(incomplete mapping)")
2358
2359 Mapping.keys = lambda self: list(self.dict.keys())
2360 Mapping.__getitem__ = lambda self, i: self.dict[i]
2361 d = dict(Mapping())
2362 self.assertEqual(d, Mapping.dict)
2363
2364 # Init from sequence of iterable objects, each producing a 2-sequence.
2365 class AddressBookEntry:
2366 def __init__(self, first, last):
2367 self.first = first
2368 self.last = last
2369 def __iter__(self):
2370 return iter([self.first, self.last])
2371
2372 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2373 AddressBookEntry('Barry', 'Peters'),
2374 AddressBookEntry('Tim', 'Peters'),
2375 AddressBookEntry('Barry', 'Warsaw')])
2376 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2377
2378 d = dict(zip(range(4), range(1, 5)))
2379 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2380
2381 # Bad sequence lengths.
2382 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2383 try:
2384 dict(bad)
2385 except ValueError:
2386 pass
2387 else:
2388 self.fail("no ValueError from dict(%r)" % bad)
2389
2390 def test_dir(self):
2391 # Testing dir() ...
2392 junk = 12
2393 self.assertEqual(dir(), ['junk', 'self'])
2394 del junk
2395
2396 # Just make sure these don't blow up!
2397 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2398 dir(arg)
2399
2400 # Test dir on new-style classes. Since these have object as a
2401 # base class, a lot more gets sucked in.
2402 def interesting(strings):
2403 return [s for s in strings if not s.startswith('_')]
2404
2405 class C(object):
2406 Cdata = 1
2407 def Cmethod(self): pass
2408
2409 cstuff = ['Cdata', 'Cmethod']
2410 self.assertEqual(interesting(dir(C)), cstuff)
2411
2412 c = C()
2413 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002414 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002415
2416 c.cdata = 2
2417 c.cmethod = lambda self: 0
2418 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002419 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002420
2421 class A(C):
2422 Adata = 1
2423 def Amethod(self): pass
2424
2425 astuff = ['Adata', 'Amethod'] + cstuff
2426 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002427 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002428 a = A()
2429 self.assertEqual(interesting(dir(a)), astuff)
2430 a.adata = 42
2431 a.amethod = lambda self: 3
2432 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002433 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002434
2435 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002436 class M(type(sys)):
2437 pass
2438 minstance = M("m")
2439 minstance.b = 2
2440 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002441 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002442 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002443 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002444 self.assertEqual(names, ['a', 'b'])
2445
2446 class M2(M):
2447 def getdict(self):
2448 return "Not a dict!"
2449 __dict__ = property(getdict)
2450
2451 m2instance = M2("m2")
2452 m2instance.b = 2
2453 m2instance.a = 1
2454 self.assertEqual(m2instance.__dict__, "Not a dict!")
2455 try:
2456 dir(m2instance)
2457 except TypeError:
2458 pass
2459
2460 # Two essentially featureless objects, just inheriting stuff from
2461 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002462 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002463
2464 # Nasty test case for proxied objects
2465 class Wrapper(object):
2466 def __init__(self, obj):
2467 self.__obj = obj
2468 def __repr__(self):
2469 return "Wrapper(%s)" % repr(self.__obj)
2470 def __getitem__(self, key):
2471 return Wrapper(self.__obj[key])
2472 def __len__(self):
2473 return len(self.__obj)
2474 def __getattr__(self, name):
2475 return Wrapper(getattr(self.__obj, name))
2476
2477 class C(object):
2478 def __getclass(self):
2479 return Wrapper(type(self))
2480 __class__ = property(__getclass)
2481
2482 dir(C()) # This used to segfault
2483
2484 def test_supers(self):
2485 # Testing super...
2486
2487 class A(object):
2488 def meth(self, a):
2489 return "A(%r)" % a
2490
2491 self.assertEqual(A().meth(1), "A(1)")
2492
2493 class B(A):
2494 def __init__(self):
2495 self.__super = super(B, self)
2496 def meth(self, a):
2497 return "B(%r)" % a + self.__super.meth(a)
2498
2499 self.assertEqual(B().meth(2), "B(2)A(2)")
2500
2501 class C(A):
2502 def meth(self, a):
2503 return "C(%r)" % a + self.__super.meth(a)
2504 C._C__super = super(C)
2505
2506 self.assertEqual(C().meth(3), "C(3)A(3)")
2507
2508 class D(C, B):
2509 def meth(self, a):
2510 return "D(%r)" % a + super(D, self).meth(a)
2511
2512 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2513
2514 # Test for subclassing super
2515
2516 class mysuper(super):
2517 def __init__(self, *args):
2518 return super(mysuper, self).__init__(*args)
2519
2520 class E(D):
2521 def meth(self, a):
2522 return "E(%r)" % a + mysuper(E, self).meth(a)
2523
2524 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2525
2526 class F(E):
2527 def meth(self, a):
2528 s = self.__super # == mysuper(F, self)
2529 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2530 F._F__super = mysuper(F)
2531
2532 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2533
2534 # Make sure certain errors are raised
2535
2536 try:
2537 super(D, 42)
2538 except TypeError:
2539 pass
2540 else:
2541 self.fail("shouldn't allow super(D, 42)")
2542
2543 try:
2544 super(D, C())
2545 except TypeError:
2546 pass
2547 else:
2548 self.fail("shouldn't allow super(D, C())")
2549
2550 try:
2551 super(D).__get__(12)
2552 except TypeError:
2553 pass
2554 else:
2555 self.fail("shouldn't allow super(D).__get__(12)")
2556
2557 try:
2558 super(D).__get__(C())
2559 except TypeError:
2560 pass
2561 else:
2562 self.fail("shouldn't allow super(D).__get__(C())")
2563
2564 # Make sure data descriptors can be overridden and accessed via super
2565 # (new feature in Python 2.3)
2566
2567 class DDbase(object):
2568 def getx(self): return 42
2569 x = property(getx)
2570
2571 class DDsub(DDbase):
2572 def getx(self): return "hello"
2573 x = property(getx)
2574
2575 dd = DDsub()
2576 self.assertEqual(dd.x, "hello")
2577 self.assertEqual(super(DDsub, dd).x, 42)
2578
2579 # Ensure that super() lookup of descriptor from classmethod
2580 # works (SF ID# 743627)
2581
2582 class Base(object):
2583 aProp = property(lambda self: "foo")
2584
2585 class Sub(Base):
2586 @classmethod
2587 def test(klass):
2588 return super(Sub,klass).aProp
2589
2590 self.assertEqual(Sub.test(), Base.aProp)
2591
2592 # Verify that super() doesn't allow keyword args
2593 try:
2594 super(Base, kw=1)
2595 except TypeError:
2596 pass
2597 else:
2598 self.assertEqual("super shouldn't accept keyword args")
2599
2600 def test_basic_inheritance(self):
2601 # Testing inheritance from basic types...
2602
2603 class hexint(int):
2604 def __repr__(self):
2605 return hex(self)
2606 def __add__(self, other):
2607 return hexint(int.__add__(self, other))
2608 # (Note that overriding __radd__ doesn't work,
2609 # because the int type gets first dibs.)
2610 self.assertEqual(repr(hexint(7) + 9), "0x10")
2611 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2612 a = hexint(12345)
2613 self.assertEqual(a, 12345)
2614 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002615 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002616 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002617 self.assertIs((+a).__class__, int)
2618 self.assertIs((a >> 0).__class__, int)
2619 self.assertIs((a << 0).__class__, int)
2620 self.assertIs((hexint(0) << 12).__class__, int)
2621 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002622
2623 class octlong(int):
2624 __slots__ = []
2625 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002626 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002627 def __add__(self, other):
2628 return self.__class__(super(octlong, self).__add__(other))
2629 __radd__ = __add__
2630 self.assertEqual(str(octlong(3) + 5), "0o10")
2631 # (Note that overriding __radd__ here only seems to work
2632 # because the example uses a short int left argument.)
2633 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2634 a = octlong(12345)
2635 self.assertEqual(a, 12345)
2636 self.assertEqual(int(a), 12345)
2637 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002638 self.assertIs(int(a).__class__, int)
2639 self.assertIs((+a).__class__, int)
2640 self.assertIs((-a).__class__, int)
2641 self.assertIs((-octlong(0)).__class__, int)
2642 self.assertIs((a >> 0).__class__, int)
2643 self.assertIs((a << 0).__class__, int)
2644 self.assertIs((a - 0).__class__, int)
2645 self.assertIs((a * 1).__class__, int)
2646 self.assertIs((a ** 1).__class__, int)
2647 self.assertIs((a // 1).__class__, int)
2648 self.assertIs((1 * a).__class__, int)
2649 self.assertIs((a | 0).__class__, int)
2650 self.assertIs((a ^ 0).__class__, int)
2651 self.assertIs((a & -1).__class__, int)
2652 self.assertIs((octlong(0) << 12).__class__, int)
2653 self.assertIs((octlong(0) >> 12).__class__, int)
2654 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002655
2656 # Because octlong overrides __add__, we can't check the absence of +0
2657 # optimizations using octlong.
2658 class longclone(int):
2659 pass
2660 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002661 self.assertIs((a + 0).__class__, int)
2662 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002663
2664 # Check that negative clones don't segfault
2665 a = longclone(-1)
2666 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002667 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002668
2669 class precfloat(float):
2670 __slots__ = ['prec']
2671 def __init__(self, value=0.0, prec=12):
2672 self.prec = int(prec)
2673 def __repr__(self):
2674 return "%.*g" % (self.prec, self)
2675 self.assertEqual(repr(precfloat(1.1)), "1.1")
2676 a = precfloat(12345)
2677 self.assertEqual(a, 12345.0)
2678 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002679 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002680 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002681 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682
2683 class madcomplex(complex):
2684 def __repr__(self):
2685 return "%.17gj%+.17g" % (self.imag, self.real)
2686 a = madcomplex(-3, 4)
2687 self.assertEqual(repr(a), "4j-3")
2688 base = complex(-3, 4)
2689 self.assertEqual(base.__class__, complex)
2690 self.assertEqual(a, base)
2691 self.assertEqual(complex(a), base)
2692 self.assertEqual(complex(a).__class__, complex)
2693 a = madcomplex(a) # just trying another form of the constructor
2694 self.assertEqual(repr(a), "4j-3")
2695 self.assertEqual(a, base)
2696 self.assertEqual(complex(a), base)
2697 self.assertEqual(complex(a).__class__, complex)
2698 self.assertEqual(hash(a), hash(base))
2699 self.assertEqual((+a).__class__, complex)
2700 self.assertEqual((a + 0).__class__, complex)
2701 self.assertEqual(a + 0, base)
2702 self.assertEqual((a - 0).__class__, complex)
2703 self.assertEqual(a - 0, base)
2704 self.assertEqual((a * 1).__class__, complex)
2705 self.assertEqual(a * 1, base)
2706 self.assertEqual((a / 1).__class__, complex)
2707 self.assertEqual(a / 1, base)
2708
2709 class madtuple(tuple):
2710 _rev = None
2711 def rev(self):
2712 if self._rev is not None:
2713 return self._rev
2714 L = list(self)
2715 L.reverse()
2716 self._rev = self.__class__(L)
2717 return self._rev
2718 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2719 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2720 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2721 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2722 for i in range(512):
2723 t = madtuple(range(i))
2724 u = t.rev()
2725 v = u.rev()
2726 self.assertEqual(v, t)
2727 a = madtuple((1,2,3,4,5))
2728 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002729 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002730 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002731 self.assertIs(a[:].__class__, tuple)
2732 self.assertIs((a * 1).__class__, tuple)
2733 self.assertIs((a * 0).__class__, tuple)
2734 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002735 a = madtuple(())
2736 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002737 self.assertIs(tuple(a).__class__, tuple)
2738 self.assertIs((a + a).__class__, tuple)
2739 self.assertIs((a * 0).__class__, tuple)
2740 self.assertIs((a * 1).__class__, tuple)
2741 self.assertIs((a * 2).__class__, tuple)
2742 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002743
2744 class madstring(str):
2745 _rev = None
2746 def rev(self):
2747 if self._rev is not None:
2748 return self._rev
2749 L = list(self)
2750 L.reverse()
2751 self._rev = self.__class__("".join(L))
2752 return self._rev
2753 s = madstring("abcdefghijklmnopqrstuvwxyz")
2754 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2755 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2756 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2757 for i in range(256):
2758 s = madstring("".join(map(chr, range(i))))
2759 t = s.rev()
2760 u = t.rev()
2761 self.assertEqual(u, s)
2762 s = madstring("12345")
2763 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002764 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002765
2766 base = "\x00" * 5
2767 s = madstring(base)
2768 self.assertEqual(s, base)
2769 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002770 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002771 self.assertEqual(hash(s), hash(base))
2772 self.assertEqual({s: 1}[base], 1)
2773 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002774 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002775 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002776 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002777 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002778 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002779 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002780 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002781 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002782 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002783 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002784 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002785 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002786 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002787 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002788 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002789 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002790 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002791 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002792 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002793 self.assertEqual(s.rstrip(), base)
2794 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002795 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002796 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002797 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002798 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002799 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002800 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002801 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002802 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002803 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002804 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002805 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002806 self.assertEqual(s.lower(), base)
2807
2808 class madunicode(str):
2809 _rev = None
2810 def rev(self):
2811 if self._rev is not None:
2812 return self._rev
2813 L = list(self)
2814 L.reverse()
2815 self._rev = self.__class__("".join(L))
2816 return self._rev
2817 u = madunicode("ABCDEF")
2818 self.assertEqual(u, "ABCDEF")
2819 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2820 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2821 base = "12345"
2822 u = madunicode(base)
2823 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002824 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002825 self.assertEqual(hash(u), hash(base))
2826 self.assertEqual({u: 1}[base], 1)
2827 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002828 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002829 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002830 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002831 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002832 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002833 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002834 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002835 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002836 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002837 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002838 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002839 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002840 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002841 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002842 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002843 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002844 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002845 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002846 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002847 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002848 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002849 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002850 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002851 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002852 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002853 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002854 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002855 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002856 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002857 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002858 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002859 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002860 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002861 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002862 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002863 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002864 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002865 self.assertEqual(u[0:0], "")
2866
2867 class sublist(list):
2868 pass
2869 a = sublist(range(5))
2870 self.assertEqual(a, list(range(5)))
2871 a.append("hello")
2872 self.assertEqual(a, list(range(5)) + ["hello"])
2873 a[5] = 5
2874 self.assertEqual(a, list(range(6)))
2875 a.extend(range(6, 20))
2876 self.assertEqual(a, list(range(20)))
2877 a[-5:] = []
2878 self.assertEqual(a, list(range(15)))
2879 del a[10:15]
2880 self.assertEqual(len(a), 10)
2881 self.assertEqual(a, list(range(10)))
2882 self.assertEqual(list(a), list(range(10)))
2883 self.assertEqual(a[0], 0)
2884 self.assertEqual(a[9], 9)
2885 self.assertEqual(a[-10], 0)
2886 self.assertEqual(a[-1], 9)
2887 self.assertEqual(a[:5], list(range(5)))
2888
2889 ## class CountedInput(file):
2890 ## """Counts lines read by self.readline().
2891 ##
2892 ## self.lineno is the 0-based ordinal of the last line read, up to
2893 ## a maximum of one greater than the number of lines in the file.
2894 ##
2895 ## self.ateof is true if and only if the final "" line has been read,
2896 ## at which point self.lineno stops incrementing, and further calls
2897 ## to readline() continue to return "".
2898 ## """
2899 ##
2900 ## lineno = 0
2901 ## ateof = 0
2902 ## def readline(self):
2903 ## if self.ateof:
2904 ## return ""
2905 ## s = file.readline(self)
2906 ## # Next line works too.
2907 ## # s = super(CountedInput, self).readline()
2908 ## self.lineno += 1
2909 ## if s == "":
2910 ## self.ateof = 1
2911 ## return s
2912 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002913 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 ## lines = ['a\n', 'b\n', 'c\n']
2915 ## try:
2916 ## f.writelines(lines)
2917 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002918 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002919 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2920 ## got = f.readline()
2921 ## self.assertEqual(expected, got)
2922 ## self.assertEqual(f.lineno, i)
2923 ## self.assertEqual(f.ateof, (i > len(lines)))
2924 ## f.close()
2925 ## finally:
2926 ## try:
2927 ## f.close()
2928 ## except:
2929 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002930 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002931
2932 def test_keywords(self):
2933 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002934 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2935 int(x=1)
2936 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2937 float(x=2)
2938 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2939 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002940 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2941 self.assertEqual(str(object=500), '500')
2942 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002943 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2944 tuple(sequence=range(3))
2945 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2946 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00002947 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2948
2949 for constructor in (int, float, int, complex, str, str,
2950 tuple, list):
2951 try:
2952 constructor(bogus_keyword_arg=1)
2953 except TypeError:
2954 pass
2955 else:
2956 self.fail("expected TypeError from bogus keyword argument to %r"
2957 % constructor)
2958
2959 def test_str_subclass_as_dict_key(self):
2960 # Testing a str subclass used as dict key ..
2961
2962 class cistr(str):
2963 """Sublcass of str that computes __eq__ case-insensitively.
2964
2965 Also computes a hash code of the string in canonical form.
2966 """
2967
2968 def __init__(self, value):
2969 self.canonical = value.lower()
2970 self.hashcode = hash(self.canonical)
2971
2972 def __eq__(self, other):
2973 if not isinstance(other, cistr):
2974 other = cistr(other)
2975 return self.canonical == other.canonical
2976
2977 def __hash__(self):
2978 return self.hashcode
2979
2980 self.assertEqual(cistr('ABC'), 'abc')
2981 self.assertEqual('aBc', cistr('ABC'))
2982 self.assertEqual(str(cistr('ABC')), 'ABC')
2983
2984 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2985 self.assertEqual(d[cistr('one')], 1)
2986 self.assertEqual(d[cistr('tWo')], 2)
2987 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002988 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002989 self.assertEqual(d.get(cistr('thrEE')), 3)
2990
2991 def test_classic_comparisons(self):
2992 # Testing classic comparisons...
2993 class classic:
2994 pass
2995
2996 for base in (classic, int, object):
2997 class C(base):
2998 def __init__(self, value):
2999 self.value = int(value)
3000 def __eq__(self, other):
3001 if isinstance(other, C):
3002 return self.value == other.value
3003 if isinstance(other, int) or isinstance(other, int):
3004 return self.value == other
3005 return NotImplemented
3006 def __ne__(self, other):
3007 if isinstance(other, C):
3008 return self.value != other.value
3009 if isinstance(other, int) or isinstance(other, int):
3010 return self.value != other
3011 return NotImplemented
3012 def __lt__(self, other):
3013 if isinstance(other, C):
3014 return self.value < other.value
3015 if isinstance(other, int) or isinstance(other, int):
3016 return self.value < other
3017 return NotImplemented
3018 def __le__(self, other):
3019 if isinstance(other, C):
3020 return self.value <= other.value
3021 if isinstance(other, int) or isinstance(other, int):
3022 return self.value <= other
3023 return NotImplemented
3024 def __gt__(self, other):
3025 if isinstance(other, C):
3026 return self.value > other.value
3027 if isinstance(other, int) or isinstance(other, int):
3028 return self.value > other
3029 return NotImplemented
3030 def __ge__(self, other):
3031 if isinstance(other, C):
3032 return self.value >= other.value
3033 if isinstance(other, int) or isinstance(other, int):
3034 return self.value >= other
3035 return NotImplemented
3036
3037 c1 = C(1)
3038 c2 = C(2)
3039 c3 = C(3)
3040 self.assertEqual(c1, 1)
3041 c = {1: c1, 2: c2, 3: c3}
3042 for x in 1, 2, 3:
3043 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003044 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003045 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003046 eval("x %s y" % op),
3047 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003048 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003049 eval("x %s y" % op),
3050 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003051 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003052 eval("x %s y" % op),
3053 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003054
3055 def test_rich_comparisons(self):
3056 # Testing rich comparisons...
3057 class Z(complex):
3058 pass
3059 z = Z(1)
3060 self.assertEqual(z, 1+0j)
3061 self.assertEqual(1+0j, z)
3062 class ZZ(complex):
3063 def __eq__(self, other):
3064 try:
3065 return abs(self - other) <= 1e-6
3066 except:
3067 return NotImplemented
3068 zz = ZZ(1.0000003)
3069 self.assertEqual(zz, 1+0j)
3070 self.assertEqual(1+0j, zz)
3071
3072 class classic:
3073 pass
3074 for base in (classic, int, object, list):
3075 class C(base):
3076 def __init__(self, value):
3077 self.value = int(value)
3078 def __cmp__(self_, other):
3079 self.fail("shouldn't call __cmp__")
3080 def __eq__(self, other):
3081 if isinstance(other, C):
3082 return self.value == other.value
3083 if isinstance(other, int) or isinstance(other, int):
3084 return self.value == other
3085 return NotImplemented
3086 def __ne__(self, other):
3087 if isinstance(other, C):
3088 return self.value != other.value
3089 if isinstance(other, int) or isinstance(other, int):
3090 return self.value != other
3091 return NotImplemented
3092 def __lt__(self, other):
3093 if isinstance(other, C):
3094 return self.value < other.value
3095 if isinstance(other, int) or isinstance(other, int):
3096 return self.value < other
3097 return NotImplemented
3098 def __le__(self, other):
3099 if isinstance(other, C):
3100 return self.value <= other.value
3101 if isinstance(other, int) or isinstance(other, int):
3102 return self.value <= other
3103 return NotImplemented
3104 def __gt__(self, other):
3105 if isinstance(other, C):
3106 return self.value > other.value
3107 if isinstance(other, int) or isinstance(other, int):
3108 return self.value > other
3109 return NotImplemented
3110 def __ge__(self, other):
3111 if isinstance(other, C):
3112 return self.value >= other.value
3113 if isinstance(other, int) or isinstance(other, int):
3114 return self.value >= other
3115 return NotImplemented
3116 c1 = C(1)
3117 c2 = C(2)
3118 c3 = C(3)
3119 self.assertEqual(c1, 1)
3120 c = {1: c1, 2: c2, 3: c3}
3121 for x in 1, 2, 3:
3122 for y in 1, 2, 3:
3123 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003124 self.assertEqual(eval("c[x] %s c[y]" % op),
3125 eval("x %s y" % op),
3126 "x=%d, y=%d" % (x, y))
3127 self.assertEqual(eval("c[x] %s y" % op),
3128 eval("x %s y" % op),
3129 "x=%d, y=%d" % (x, y))
3130 self.assertEqual(eval("x %s c[y]" % op),
3131 eval("x %s y" % op),
3132 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003133
3134 def test_descrdoc(self):
3135 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003136 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003137 def check(descr, what):
3138 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003139 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003140 check(complex.real, "the real part of a complex number") # member descriptor
3141
3142 def test_doc_descriptor(self):
3143 # Testing __doc__ descriptor...
3144 # SF bug 542984
3145 class DocDescr(object):
3146 def __get__(self, object, otype):
3147 if object:
3148 object = object.__class__.__name__ + ' instance'
3149 if otype:
3150 otype = otype.__name__
3151 return 'object=%s; type=%s' % (object, otype)
3152 class OldClass:
3153 __doc__ = DocDescr()
3154 class NewClass(object):
3155 __doc__ = DocDescr()
3156 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3157 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3158 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3159 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3160
3161 def test_set_class(self):
3162 # Testing __class__ assignment...
3163 class C(object): pass
3164 class D(object): pass
3165 class E(object): pass
3166 class F(D, E): pass
3167 for cls in C, D, E, F:
3168 for cls2 in C, D, E, F:
3169 x = cls()
3170 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003171 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003172 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003173 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003174 def cant(x, C):
3175 try:
3176 x.__class__ = C
3177 except TypeError:
3178 pass
3179 else:
3180 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3181 try:
3182 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003183 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003184 pass
3185 else:
3186 self.fail("shouldn't allow del %r.__class__" % x)
3187 cant(C(), list)
3188 cant(list(), C)
3189 cant(C(), 1)
3190 cant(C(), object)
3191 cant(object(), list)
3192 cant(list(), object)
3193 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003194 cant(True, int)
3195 cant(2, bool)
3196 o = object()
3197 cant(o, type(1))
3198 cant(o, type(None))
3199 del o
3200 class G(object):
3201 __slots__ = ["a", "b"]
3202 class H(object):
3203 __slots__ = ["b", "a"]
3204 class I(object):
3205 __slots__ = ["a", "b"]
3206 class J(object):
3207 __slots__ = ["c", "b"]
3208 class K(object):
3209 __slots__ = ["a", "b", "d"]
3210 class L(H):
3211 __slots__ = ["e"]
3212 class M(I):
3213 __slots__ = ["e"]
3214 class N(J):
3215 __slots__ = ["__weakref__"]
3216 class P(J):
3217 __slots__ = ["__dict__"]
3218 class Q(J):
3219 pass
3220 class R(J):
3221 __slots__ = ["__dict__", "__weakref__"]
3222
3223 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3224 x = cls()
3225 x.a = 1
3226 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003227 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3229 self.assertEqual(x.a, 1)
3230 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003231 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003232 "assigning %r as __class__ for %r silently failed" % (cls, x))
3233 self.assertEqual(x.a, 1)
3234 for cls in G, J, K, L, M, N, P, R, list, Int:
3235 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3236 if cls is cls2:
3237 continue
3238 cant(cls(), cls2)
3239
Benjamin Peterson193152c2009-04-25 01:08:45 +00003240 # Issue5283: when __class__ changes in __del__, the wrong
3241 # type gets DECREF'd.
3242 class O(object):
3243 pass
3244 class A(object):
3245 def __del__(self):
3246 self.__class__ = O
3247 l = [A() for x in range(100)]
3248 del l
3249
Georg Brandl479a7e72008-02-05 18:13:15 +00003250 def test_set_dict(self):
3251 # Testing __dict__ assignment...
3252 class C(object): pass
3253 a = C()
3254 a.__dict__ = {'b': 1}
3255 self.assertEqual(a.b, 1)
3256 def cant(x, dict):
3257 try:
3258 x.__dict__ = dict
3259 except (AttributeError, TypeError):
3260 pass
3261 else:
3262 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3263 cant(a, None)
3264 cant(a, [])
3265 cant(a, 1)
3266 del a.__dict__ # Deleting __dict__ is allowed
3267
3268 class Base(object):
3269 pass
3270 def verify_dict_readonly(x):
3271 """
3272 x has to be an instance of a class inheriting from Base.
3273 """
3274 cant(x, {})
3275 try:
3276 del x.__dict__
3277 except (AttributeError, TypeError):
3278 pass
3279 else:
3280 self.fail("shouldn't allow del %r.__dict__" % x)
3281 dict_descr = Base.__dict__["__dict__"]
3282 try:
3283 dict_descr.__set__(x, {})
3284 except (AttributeError, TypeError):
3285 pass
3286 else:
3287 self.fail("dict_descr allowed access to %r's dict" % x)
3288
3289 # Classes don't allow __dict__ assignment and have readonly dicts
3290 class Meta1(type, Base):
3291 pass
3292 class Meta2(Base, type):
3293 pass
3294 class D(object, metaclass=Meta1):
3295 pass
3296 class E(object, metaclass=Meta2):
3297 pass
3298 for cls in C, D, E:
3299 verify_dict_readonly(cls)
3300 class_dict = cls.__dict__
3301 try:
3302 class_dict["spam"] = "eggs"
3303 except TypeError:
3304 pass
3305 else:
3306 self.fail("%r's __dict__ can be modified" % cls)
3307
3308 # Modules also disallow __dict__ assignment
3309 class Module1(types.ModuleType, Base):
3310 pass
3311 class Module2(Base, types.ModuleType):
3312 pass
3313 for ModuleType in Module1, Module2:
3314 mod = ModuleType("spam")
3315 verify_dict_readonly(mod)
3316 mod.__dict__["spam"] = "eggs"
3317
3318 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003319 # (at least not any more than regular exception's __dict__ can
3320 # be deleted; on CPython it is not the case, whereas on PyPy they
3321 # can, just like any other new-style instance's __dict__.)
3322 def can_delete_dict(e):
3323 try:
3324 del e.__dict__
3325 except (TypeError, AttributeError):
3326 return False
3327 else:
3328 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003329 class Exception1(Exception, Base):
3330 pass
3331 class Exception2(Base, Exception):
3332 pass
3333 for ExceptionType in Exception, Exception1, Exception2:
3334 e = ExceptionType()
3335 e.__dict__ = {"a": 1}
3336 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003337 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003338
Georg Brandl479a7e72008-02-05 18:13:15 +00003339 def test_binary_operator_override(self):
3340 # Testing overrides of binary operations...
3341 class I(int):
3342 def __repr__(self):
3343 return "I(%r)" % int(self)
3344 def __add__(self, other):
3345 return I(int(self) + int(other))
3346 __radd__ = __add__
3347 def __pow__(self, other, mod=None):
3348 if mod is None:
3349 return I(pow(int(self), int(other)))
3350 else:
3351 return I(pow(int(self), int(other), int(mod)))
3352 def __rpow__(self, other, mod=None):
3353 if mod is None:
3354 return I(pow(int(other), int(self), mod))
3355 else:
3356 return I(pow(int(other), int(self), int(mod)))
3357
3358 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3359 self.assertEqual(repr(I(1) + 2), "I(3)")
3360 self.assertEqual(repr(1 + I(2)), "I(3)")
3361 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3362 self.assertEqual(repr(2 ** I(3)), "I(8)")
3363 self.assertEqual(repr(I(2) ** 3), "I(8)")
3364 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3365 class S(str):
3366 def __eq__(self, other):
3367 return self.lower() == other.lower()
3368
3369 def test_subclass_propagation(self):
3370 # Testing propagation of slot functions to subclasses...
3371 class A(object):
3372 pass
3373 class B(A):
3374 pass
3375 class C(A):
3376 pass
3377 class D(B, C):
3378 pass
3379 d = D()
3380 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3381 A.__hash__ = lambda self: 42
3382 self.assertEqual(hash(d), 42)
3383 C.__hash__ = lambda self: 314
3384 self.assertEqual(hash(d), 314)
3385 B.__hash__ = lambda self: 144
3386 self.assertEqual(hash(d), 144)
3387 D.__hash__ = lambda self: 100
3388 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003389 D.__hash__ = None
3390 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003391 del D.__hash__
3392 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003393 B.__hash__ = None
3394 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003395 del B.__hash__
3396 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003397 C.__hash__ = None
3398 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003399 del C.__hash__
3400 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003401 A.__hash__ = None
3402 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003403 del A.__hash__
3404 self.assertEqual(hash(d), orig_hash)
3405 d.foo = 42
3406 d.bar = 42
3407 self.assertEqual(d.foo, 42)
3408 self.assertEqual(d.bar, 42)
3409 def __getattribute__(self, name):
3410 if name == "foo":
3411 return 24
3412 return object.__getattribute__(self, name)
3413 A.__getattribute__ = __getattribute__
3414 self.assertEqual(d.foo, 24)
3415 self.assertEqual(d.bar, 42)
3416 def __getattr__(self, name):
3417 if name in ("spam", "foo", "bar"):
3418 return "hello"
3419 raise AttributeError(name)
3420 B.__getattr__ = __getattr__
3421 self.assertEqual(d.spam, "hello")
3422 self.assertEqual(d.foo, 24)
3423 self.assertEqual(d.bar, 42)
3424 del A.__getattribute__
3425 self.assertEqual(d.foo, 42)
3426 del d.foo
3427 self.assertEqual(d.foo, "hello")
3428 self.assertEqual(d.bar, 42)
3429 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003430 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003431 d.foo
3432 except AttributeError:
3433 pass
3434 else:
3435 self.fail("d.foo should be undefined now")
3436
3437 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003438 class A(object):
3439 pass
3440 class B(A):
3441 pass
3442 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003443 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003444 A.__setitem__ = lambda *a: None # crash
3445
3446 def test_buffer_inheritance(self):
3447 # Testing that buffer interface is inherited ...
3448
3449 import binascii
3450 # SF bug [#470040] ParseTuple t# vs subclasses.
3451
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003452 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003453 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003454 base = b'abc'
3455 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003456 # b2a_hex uses the buffer interface to get its argument's value, via
3457 # PyArg_ParseTuple 't#' code.
3458 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3459
Georg Brandl479a7e72008-02-05 18:13:15 +00003460 class MyInt(int):
3461 pass
3462 m = MyInt(42)
3463 try:
3464 binascii.b2a_hex(m)
3465 self.fail('subclass of int should not have a buffer interface')
3466 except TypeError:
3467 pass
3468
3469 def test_str_of_str_subclass(self):
3470 # Testing __str__ defined in subclass of str ...
3471 import binascii
3472 import io
3473
3474 class octetstring(str):
3475 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003476 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003477 def __repr__(self):
3478 return self + " repr"
3479
3480 o = octetstring('A')
3481 self.assertEqual(type(o), octetstring)
3482 self.assertEqual(type(str(o)), str)
3483 self.assertEqual(type(repr(o)), str)
3484 self.assertEqual(ord(o), 0x41)
3485 self.assertEqual(str(o), '41')
3486 self.assertEqual(repr(o), 'A repr')
3487 self.assertEqual(o.__str__(), '41')
3488 self.assertEqual(o.__repr__(), 'A repr')
3489
3490 capture = io.StringIO()
3491 # Calling str() or not exercises different internal paths.
3492 print(o, file=capture)
3493 print(str(o), file=capture)
3494 self.assertEqual(capture.getvalue(), '41\n41\n')
3495 capture.close()
3496
3497 def test_keyword_arguments(self):
3498 # Testing keyword arguments to __init__, __call__...
3499 def f(a): return a
3500 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003501 ba = bytearray()
3502 bytearray.__init__(ba, 'abc\xbd\u20ac',
3503 encoding='latin1', errors='replace')
3504 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003505
3506 def test_recursive_call(self):
3507 # Testing recursive __call__() by setting to instance of class...
3508 class A(object):
3509 pass
3510
3511 A.__call__ = A()
3512 try:
3513 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003514 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003515 pass
3516 else:
3517 self.fail("Recursion limit should have been reached for __call__()")
3518
3519 def test_delete_hook(self):
3520 # Testing __del__ hook...
3521 log = []
3522 class C(object):
3523 def __del__(self):
3524 log.append(1)
3525 c = C()
3526 self.assertEqual(log, [])
3527 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003528 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003529 self.assertEqual(log, [1])
3530
3531 class D(object): pass
3532 d = D()
3533 try: del d[0]
3534 except TypeError: pass
3535 else: self.fail("invalid del() didn't raise TypeError")
3536
3537 def test_hash_inheritance(self):
3538 # Testing hash of mutable subclasses...
3539
3540 class mydict(dict):
3541 pass
3542 d = mydict()
3543 try:
3544 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003545 except TypeError:
3546 pass
3547 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003548 self.fail("hash() of dict subclass should fail")
3549
3550 class mylist(list):
3551 pass
3552 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003553 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003554 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003555 except TypeError:
3556 pass
3557 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003558 self.fail("hash() of list subclass should fail")
3559
3560 def test_str_operations(self):
3561 try: 'a' + 5
3562 except TypeError: pass
3563 else: self.fail("'' + 5 doesn't raise TypeError")
3564
3565 try: ''.split('')
3566 except ValueError: pass
3567 else: self.fail("''.split('') doesn't raise ValueError")
3568
3569 try: ''.join([0])
3570 except TypeError: pass
3571 else: self.fail("''.join([0]) doesn't raise TypeError")
3572
3573 try: ''.rindex('5')
3574 except ValueError: pass
3575 else: self.fail("''.rindex('5') doesn't raise ValueError")
3576
3577 try: '%(n)s' % None
3578 except TypeError: pass
3579 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3580
3581 try: '%(n' % {}
3582 except ValueError: pass
3583 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3584
3585 try: '%*s' % ('abc')
3586 except TypeError: pass
3587 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3588
3589 try: '%*.*s' % ('abc', 5)
3590 except TypeError: pass
3591 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3592
3593 try: '%s' % (1, 2)
3594 except TypeError: pass
3595 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3596
3597 try: '%' % None
3598 except ValueError: pass
3599 else: self.fail("'%' % None doesn't raise ValueError")
3600
3601 self.assertEqual('534253'.isdigit(), 1)
3602 self.assertEqual('534253x'.isdigit(), 0)
3603 self.assertEqual('%c' % 5, '\x05')
3604 self.assertEqual('%c' % '5', '5')
3605
3606 def test_deepcopy_recursive(self):
3607 # Testing deepcopy of recursive objects...
3608 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003609 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003610 a = Node()
3611 b = Node()
3612 a.b = b
3613 b.a = a
3614 z = deepcopy(a) # This blew up before
3615
Martin Panterf05641642016-05-08 13:48:10 +00003616 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 # Testing uninitialized module objects...
3618 from types import ModuleType as M
3619 m = M.__new__(M)
3620 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003621 self.assertNotHasAttr(m, "__name__")
3622 self.assertNotHasAttr(m, "__file__")
3623 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003624 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003625 m.foo = 1
3626 self.assertEqual(m.__dict__, {"foo": 1})
3627
3628 def test_funny_new(self):
3629 # Testing __new__ returning something unexpected...
3630 class C(object):
3631 def __new__(cls, arg):
3632 if isinstance(arg, str): return [1, 2, 3]
3633 elif isinstance(arg, int): return object.__new__(D)
3634 else: return object.__new__(cls)
3635 class D(C):
3636 def __init__(self, arg):
3637 self.foo = arg
3638 self.assertEqual(C("1"), [1, 2, 3])
3639 self.assertEqual(D("1"), [1, 2, 3])
3640 d = D(None)
3641 self.assertEqual(d.foo, None)
3642 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003643 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003644 self.assertEqual(d.foo, 1)
3645 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003646 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003647 self.assertEqual(d.foo, 1)
3648
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003649 class C(object):
3650 @staticmethod
3651 def __new__(*args):
3652 return args
3653 self.assertEqual(C(1, 2), (C, 1, 2))
3654 class D(C):
3655 pass
3656 self.assertEqual(D(1, 2), (D, 1, 2))
3657
3658 class C(object):
3659 @classmethod
3660 def __new__(*args):
3661 return args
3662 self.assertEqual(C(1, 2), (C, C, 1, 2))
3663 class D(C):
3664 pass
3665 self.assertEqual(D(1, 2), (D, D, 1, 2))
3666
Georg Brandl479a7e72008-02-05 18:13:15 +00003667 def test_imul_bug(self):
3668 # Testing for __imul__ problems...
3669 # SF bug 544647
3670 class C(object):
3671 def __imul__(self, other):
3672 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003673 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003674 y = x
3675 y *= 1.0
3676 self.assertEqual(y, (x, 1.0))
3677 y = x
3678 y *= 2
3679 self.assertEqual(y, (x, 2))
3680 y = x
3681 y *= 3
3682 self.assertEqual(y, (x, 3))
3683 y = x
3684 y *= 1<<100
3685 self.assertEqual(y, (x, 1<<100))
3686 y = x
3687 y *= None
3688 self.assertEqual(y, (x, None))
3689 y = x
3690 y *= "foo"
3691 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003692
Georg Brandl479a7e72008-02-05 18:13:15 +00003693 def test_copy_setstate(self):
3694 # Testing that copy.*copy() correctly uses __setstate__...
3695 import copy
3696 class C(object):
3697 def __init__(self, foo=None):
3698 self.foo = foo
3699 self.__foo = foo
3700 def setfoo(self, foo=None):
3701 self.foo = foo
3702 def getfoo(self):
3703 return self.__foo
3704 def __getstate__(self):
3705 return [self.foo]
3706 def __setstate__(self_, lst):
3707 self.assertEqual(len(lst), 1)
3708 self_.__foo = self_.foo = lst[0]
3709 a = C(42)
3710 a.setfoo(24)
3711 self.assertEqual(a.foo, 24)
3712 self.assertEqual(a.getfoo(), 42)
3713 b = copy.copy(a)
3714 self.assertEqual(b.foo, 24)
3715 self.assertEqual(b.getfoo(), 24)
3716 b = copy.deepcopy(a)
3717 self.assertEqual(b.foo, 24)
3718 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003719
Georg Brandl479a7e72008-02-05 18:13:15 +00003720 def test_slices(self):
3721 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003722
Georg Brandl479a7e72008-02-05 18:13:15 +00003723 # Strings
3724 self.assertEqual("hello"[:4], "hell")
3725 self.assertEqual("hello"[slice(4)], "hell")
3726 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3727 class S(str):
3728 def __getitem__(self, x):
3729 return str.__getitem__(self, x)
3730 self.assertEqual(S("hello")[:4], "hell")
3731 self.assertEqual(S("hello")[slice(4)], "hell")
3732 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3733 # Tuples
3734 self.assertEqual((1,2,3)[:2], (1,2))
3735 self.assertEqual((1,2,3)[slice(2)], (1,2))
3736 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3737 class T(tuple):
3738 def __getitem__(self, x):
3739 return tuple.__getitem__(self, x)
3740 self.assertEqual(T((1,2,3))[:2], (1,2))
3741 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3742 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3743 # Lists
3744 self.assertEqual([1,2,3][:2], [1,2])
3745 self.assertEqual([1,2,3][slice(2)], [1,2])
3746 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3747 class L(list):
3748 def __getitem__(self, x):
3749 return list.__getitem__(self, x)
3750 self.assertEqual(L([1,2,3])[:2], [1,2])
3751 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3752 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3753 # Now do lists and __setitem__
3754 a = L([1,2,3])
3755 a[slice(1, 3)] = [3,2]
3756 self.assertEqual(a, [1,3,2])
3757 a[slice(0, 2, 1)] = [3,1]
3758 self.assertEqual(a, [3,1,2])
3759 a.__setitem__(slice(1, 3), [2,1])
3760 self.assertEqual(a, [3,2,1])
3761 a.__setitem__(slice(0, 2, 1), [2,3])
3762 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003763
Georg Brandl479a7e72008-02-05 18:13:15 +00003764 def test_subtype_resurrection(self):
3765 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003766
Georg Brandl479a7e72008-02-05 18:13:15 +00003767 class C(object):
3768 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003769
Georg Brandl479a7e72008-02-05 18:13:15 +00003770 def __del__(self):
3771 # resurrect the instance
3772 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003773
Georg Brandl479a7e72008-02-05 18:13:15 +00003774 c = C()
3775 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003776
Benjamin Petersone549ead2009-03-28 21:42:05 +00003777 # The most interesting thing here is whether this blows up, due to
3778 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3779 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003780 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003781
Benjamin Petersone549ead2009-03-28 21:42:05 +00003782 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003784
Georg Brandl479a7e72008-02-05 18:13:15 +00003785 # Make c mortal again, so that the test framework with -l doesn't report
3786 # it as a leak.
3787 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003788
Georg Brandl479a7e72008-02-05 18:13:15 +00003789 def test_slots_trash(self):
3790 # Testing slot trash...
3791 # Deallocating deeply nested slotted trash caused stack overflows
3792 class trash(object):
3793 __slots__ = ['x']
3794 def __init__(self, x):
3795 self.x = x
3796 o = None
3797 for i in range(50000):
3798 o = trash(o)
3799 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003800
Georg Brandl479a7e72008-02-05 18:13:15 +00003801 def test_slots_multiple_inheritance(self):
3802 # SF bug 575229, multiple inheritance w/ slots dumps core
3803 class A(object):
3804 __slots__=()
3805 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003806 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003807 class C(A,B) :
3808 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003809 if support.check_impl_detail():
3810 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003811 self.assertHasAttr(C, '__dict__')
3812 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003813 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003814
Georg Brandl479a7e72008-02-05 18:13:15 +00003815 def test_rmul(self):
3816 # Testing correct invocation of __rmul__...
3817 # SF patch 592646
3818 class C(object):
3819 def __mul__(self, other):
3820 return "mul"
3821 def __rmul__(self, other):
3822 return "rmul"
3823 a = C()
3824 self.assertEqual(a*2, "mul")
3825 self.assertEqual(a*2.2, "mul")
3826 self.assertEqual(2*a, "rmul")
3827 self.assertEqual(2.2*a, "rmul")
3828
3829 def test_ipow(self):
3830 # Testing correct invocation of __ipow__...
3831 # [SF bug 620179]
3832 class C(object):
3833 def __ipow__(self, other):
3834 pass
3835 a = C()
3836 a **= 2
3837
3838 def test_mutable_bases(self):
3839 # Testing mutable bases...
3840
3841 # stuff that should work:
3842 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003843 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003844 class C2(object):
3845 def __getattribute__(self, attr):
3846 if attr == 'a':
3847 return 2
3848 else:
3849 return super(C2, self).__getattribute__(attr)
3850 def meth(self):
3851 return 1
3852 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003853 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003854 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003855 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003856 d = D()
3857 e = E()
3858 D.__bases__ = (C,)
3859 D.__bases__ = (C2,)
3860 self.assertEqual(d.meth(), 1)
3861 self.assertEqual(e.meth(), 1)
3862 self.assertEqual(d.a, 2)
3863 self.assertEqual(e.a, 2)
3864 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003865
Georg Brandl479a7e72008-02-05 18:13:15 +00003866 try:
3867 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003868 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003869 pass
3870 else:
3871 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003872
Georg Brandl479a7e72008-02-05 18:13:15 +00003873 try:
3874 D.__bases__ = ()
3875 except TypeError as msg:
3876 if str(msg) == "a new-style class can't have only classic bases":
3877 self.fail("wrong error message for .__bases__ = ()")
3878 else:
3879 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003880
Georg Brandl479a7e72008-02-05 18:13:15 +00003881 try:
3882 D.__bases__ = (D,)
3883 except TypeError:
3884 pass
3885 else:
3886 # actually, we'll have crashed by here...
3887 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003888
Georg Brandl479a7e72008-02-05 18:13:15 +00003889 try:
3890 D.__bases__ = (C, C)
3891 except TypeError:
3892 pass
3893 else:
3894 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003895
Georg Brandl479a7e72008-02-05 18:13:15 +00003896 try:
3897 D.__bases__ = (E,)
3898 except TypeError:
3899 pass
3900 else:
3901 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003902
Benjamin Petersonae937c02009-04-18 20:54:08 +00003903 def test_builtin_bases(self):
3904 # Make sure all the builtin types can have their base queried without
3905 # segfaulting. See issue #5787.
3906 builtin_types = [tp for tp in builtins.__dict__.values()
3907 if isinstance(tp, type)]
3908 for tp in builtin_types:
3909 object.__getattribute__(tp, "__bases__")
3910 if tp is not object:
3911 self.assertEqual(len(tp.__bases__), 1, tp)
3912
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003913 class L(list):
3914 pass
3915
3916 class C(object):
3917 pass
3918
3919 class D(C):
3920 pass
3921
3922 try:
3923 L.__bases__ = (dict,)
3924 except TypeError:
3925 pass
3926 else:
3927 self.fail("shouldn't turn list subclass into dict subclass")
3928
3929 try:
3930 list.__bases__ = (dict,)
3931 except TypeError:
3932 pass
3933 else:
3934 self.fail("shouldn't be able to assign to list.__bases__")
3935
3936 try:
3937 D.__bases__ = (C, list)
3938 except TypeError:
3939 pass
3940 else:
3941 assert 0, "best_base calculation found wanting"
3942
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003943 def test_unsubclassable_types(self):
3944 with self.assertRaises(TypeError):
3945 class X(type(None)):
3946 pass
3947 with self.assertRaises(TypeError):
3948 class X(object, type(None)):
3949 pass
3950 with self.assertRaises(TypeError):
3951 class X(type(None), object):
3952 pass
3953 class O(object):
3954 pass
3955 with self.assertRaises(TypeError):
3956 class X(O, type(None)):
3957 pass
3958 with self.assertRaises(TypeError):
3959 class X(type(None), O):
3960 pass
3961
3962 class X(object):
3963 pass
3964 with self.assertRaises(TypeError):
3965 X.__bases__ = type(None),
3966 with self.assertRaises(TypeError):
3967 X.__bases__ = object, type(None)
3968 with self.assertRaises(TypeError):
3969 X.__bases__ = type(None), object
3970 with self.assertRaises(TypeError):
3971 X.__bases__ = O, type(None)
3972 with self.assertRaises(TypeError):
3973 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00003974
Georg Brandl479a7e72008-02-05 18:13:15 +00003975 def test_mutable_bases_with_failing_mro(self):
3976 # Testing mutable bases with failing mro...
3977 class WorkOnce(type):
3978 def __new__(self, name, bases, ns):
3979 self.flag = 0
3980 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3981 def mro(self):
3982 if self.flag > 0:
3983 raise RuntimeError("bozo")
3984 else:
3985 self.flag += 1
3986 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003987
Georg Brandl479a7e72008-02-05 18:13:15 +00003988 class WorkAlways(type):
3989 def mro(self):
3990 # this is here to make sure that .mro()s aren't called
3991 # with an exception set (which was possible at one point).
3992 # An error message will be printed in a debug build.
3993 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003994 return type.mro(self)
3995
Georg Brandl479a7e72008-02-05 18:13:15 +00003996 class C(object):
3997 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003998
Georg Brandl479a7e72008-02-05 18:13:15 +00003999 class C2(object):
4000 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004001
Georg Brandl479a7e72008-02-05 18:13:15 +00004002 class D(C):
4003 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004004
Georg Brandl479a7e72008-02-05 18:13:15 +00004005 class E(D):
4006 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004007
Georg Brandl479a7e72008-02-05 18:13:15 +00004008 class F(D, metaclass=WorkOnce):
4009 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004010
Georg Brandl479a7e72008-02-05 18:13:15 +00004011 class G(D, metaclass=WorkAlways):
4012 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004013
Georg Brandl479a7e72008-02-05 18:13:15 +00004014 # Immediate subclasses have their mro's adjusted in alphabetical
4015 # order, so E's will get adjusted before adjusting F's fails. We
4016 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004017
Georg Brandl479a7e72008-02-05 18:13:15 +00004018 E_mro_before = E.__mro__
4019 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004020
Armin Rigofd163f92005-12-29 15:59:19 +00004021 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004022 D.__bases__ = (C2,)
4023 except RuntimeError:
4024 self.assertEqual(E.__mro__, E_mro_before)
4025 self.assertEqual(D.__mro__, D_mro_before)
4026 else:
4027 self.fail("exception not propagated")
4028
4029 def test_mutable_bases_catch_mro_conflict(self):
4030 # Testing mutable bases catch mro conflict...
4031 class A(object):
4032 pass
4033
4034 class B(object):
4035 pass
4036
4037 class C(A, B):
4038 pass
4039
4040 class D(A, B):
4041 pass
4042
4043 class E(C, D):
4044 pass
4045
4046 try:
4047 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004048 except TypeError:
4049 pass
4050 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004051 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004052
Georg Brandl479a7e72008-02-05 18:13:15 +00004053 def test_mutable_names(self):
4054 # Testing mutable names...
4055 class C(object):
4056 pass
4057
4058 # C.__module__ could be 'test_descr' or '__main__'
4059 mod = C.__module__
4060
4061 C.__name__ = 'D'
4062 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4063
4064 C.__name__ = 'D.E'
4065 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4066
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004067 def test_evil_type_name(self):
4068 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4069 # execution while the type structure was not in a sane state, and a
4070 # possible segmentation fault as a result. See bug #16447.
4071 class Nasty(str):
4072 def __del__(self):
4073 C.__name__ = "other"
4074
4075 class C:
4076 pass
4077
4078 C.__name__ = Nasty("abc")
4079 C.__name__ = "normal"
4080
Georg Brandl479a7e72008-02-05 18:13:15 +00004081 def test_subclass_right_op(self):
4082 # Testing correct dispatch of subclass overloading __r<op>__...
4083
4084 # This code tests various cases where right-dispatch of a subclass
4085 # should be preferred over left-dispatch of a base class.
4086
4087 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4088
4089 class B(int):
4090 def __floordiv__(self, other):
4091 return "B.__floordiv__"
4092 def __rfloordiv__(self, other):
4093 return "B.__rfloordiv__"
4094
4095 self.assertEqual(B(1) // 1, "B.__floordiv__")
4096 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4097
4098 # Case 2: subclass of object; this is just the baseline for case 3
4099
4100 class C(object):
4101 def __floordiv__(self, other):
4102 return "C.__floordiv__"
4103 def __rfloordiv__(self, other):
4104 return "C.__rfloordiv__"
4105
4106 self.assertEqual(C() // 1, "C.__floordiv__")
4107 self.assertEqual(1 // C(), "C.__rfloordiv__")
4108
4109 # Case 3: subclass of new-style class; here it gets interesting
4110
4111 class D(C):
4112 def __floordiv__(self, other):
4113 return "D.__floordiv__"
4114 def __rfloordiv__(self, other):
4115 return "D.__rfloordiv__"
4116
4117 self.assertEqual(D() // C(), "D.__floordiv__")
4118 self.assertEqual(C() // D(), "D.__rfloordiv__")
4119
4120 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4121
4122 class E(C):
4123 pass
4124
4125 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4126
4127 self.assertEqual(E() // 1, "C.__floordiv__")
4128 self.assertEqual(1 // E(), "C.__rfloordiv__")
4129 self.assertEqual(E() // C(), "C.__floordiv__")
4130 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4131
Benjamin Petersone549ead2009-03-28 21:42:05 +00004132 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004133 def test_meth_class_get(self):
4134 # Testing __get__ method of METH_CLASS C methods...
4135 # Full coverage of descrobject.c::classmethod_get()
4136
4137 # Baseline
4138 arg = [1, 2, 3]
4139 res = {1: None, 2: None, 3: None}
4140 self.assertEqual(dict.fromkeys(arg), res)
4141 self.assertEqual({}.fromkeys(arg), res)
4142
4143 # Now get the descriptor
4144 descr = dict.__dict__["fromkeys"]
4145
4146 # More baseline using the descriptor directly
4147 self.assertEqual(descr.__get__(None, dict)(arg), res)
4148 self.assertEqual(descr.__get__({})(arg), res)
4149
4150 # Now check various error cases
4151 try:
4152 descr.__get__(None, None)
4153 except TypeError:
4154 pass
4155 else:
4156 self.fail("shouldn't have allowed descr.__get__(None, None)")
4157 try:
4158 descr.__get__(42)
4159 except TypeError:
4160 pass
4161 else:
4162 self.fail("shouldn't have allowed descr.__get__(42)")
4163 try:
4164 descr.__get__(None, 42)
4165 except TypeError:
4166 pass
4167 else:
4168 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4169 try:
4170 descr.__get__(None, int)
4171 except TypeError:
4172 pass
4173 else:
4174 self.fail("shouldn't have allowed descr.__get__(None, int)")
4175
4176 def test_isinst_isclass(self):
4177 # Testing proxy isinstance() and isclass()...
4178 class Proxy(object):
4179 def __init__(self, obj):
4180 self.__obj = obj
4181 def __getattribute__(self, name):
4182 if name.startswith("_Proxy__"):
4183 return object.__getattribute__(self, name)
4184 else:
4185 return getattr(self.__obj, name)
4186 # Test with a classic class
4187 class C:
4188 pass
4189 a = C()
4190 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004191 self.assertIsInstance(a, C) # Baseline
4192 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004193 # Test with a classic subclass
4194 class D(C):
4195 pass
4196 a = D()
4197 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004198 self.assertIsInstance(a, C) # Baseline
4199 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004200 # Test with a new-style class
4201 class C(object):
4202 pass
4203 a = C()
4204 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004205 self.assertIsInstance(a, C) # Baseline
4206 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004207 # Test with a new-style subclass
4208 class D(C):
4209 pass
4210 a = D()
4211 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004212 self.assertIsInstance(a, C) # Baseline
4213 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004214
4215 def test_proxy_super(self):
4216 # Testing super() for a proxy object...
4217 class Proxy(object):
4218 def __init__(self, obj):
4219 self.__obj = obj
4220 def __getattribute__(self, name):
4221 if name.startswith("_Proxy__"):
4222 return object.__getattribute__(self, name)
4223 else:
4224 return getattr(self.__obj, name)
4225
4226 class B(object):
4227 def f(self):
4228 return "B.f"
4229
4230 class C(B):
4231 def f(self):
4232 return super(C, self).f() + "->C.f"
4233
4234 obj = C()
4235 p = Proxy(obj)
4236 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4237
4238 def test_carloverre(self):
4239 # Testing prohibition of Carlo Verre's hack...
4240 try:
4241 object.__setattr__(str, "foo", 42)
4242 except TypeError:
4243 pass
4244 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004245 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004246 try:
4247 object.__delattr__(str, "lower")
4248 except TypeError:
4249 pass
4250 else:
4251 self.fail("Carlo Verre __delattr__ succeeded!")
4252
4253 def test_weakref_segfault(self):
4254 # Testing weakref segfault...
4255 # SF 742911
4256 import weakref
4257
4258 class Provoker:
4259 def __init__(self, referrent):
4260 self.ref = weakref.ref(referrent)
4261
4262 def __del__(self):
4263 x = self.ref()
4264
4265 class Oops(object):
4266 pass
4267
4268 o = Oops()
4269 o.whatever = Provoker(o)
4270 del o
4271
4272 def test_wrapper_segfault(self):
4273 # SF 927248: deeply nested wrappers could cause stack overflow
4274 f = lambda:None
4275 for i in range(1000000):
4276 f = f.__call__
4277 f = None
4278
4279 def test_file_fault(self):
4280 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004281 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004282 class StdoutGuard:
4283 def __getattr__(self, attr):
4284 sys.stdout = sys.__stdout__
4285 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4286 sys.stdout = StdoutGuard()
4287 try:
4288 print("Oops!")
4289 except RuntimeError:
4290 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004291 finally:
4292 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004293
4294 def test_vicious_descriptor_nonsense(self):
4295 # Testing vicious_descriptor_nonsense...
4296
4297 # A potential segfault spotted by Thomas Wouters in mail to
4298 # python-dev 2003-04-17, turned into an example & fixed by Michael
4299 # Hudson just less than four months later...
4300
4301 class Evil(object):
4302 def __hash__(self):
4303 return hash('attr')
4304 def __eq__(self, other):
4305 del C.attr
4306 return 0
4307
4308 class Descr(object):
4309 def __get__(self, ob, type=None):
4310 return 1
4311
4312 class C(object):
4313 attr = Descr()
4314
4315 c = C()
4316 c.__dict__[Evil()] = 0
4317
4318 self.assertEqual(c.attr, 1)
4319 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004320 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004321 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004322
4323 def test_init(self):
4324 # SF 1155938
4325 class Foo(object):
4326 def __init__(self):
4327 return 10
4328 try:
4329 Foo()
4330 except TypeError:
4331 pass
4332 else:
4333 self.fail("did not test __init__() for None return")
4334
4335 def test_method_wrapper(self):
4336 # Testing method-wrapper objects...
4337 # <type 'method-wrapper'> did not support any reflection before 2.5
4338
Mark Dickinson211c6252009-02-01 10:28:51 +00004339 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004340
4341 l = []
4342 self.assertEqual(l.__add__, l.__add__)
4343 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004344 self.assertNotEqual(l.__add__, [5].__add__)
4345 self.assertNotEqual(l.__add__, l.__mul__)
4346 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004347 if hasattr(l.__add__, '__self__'):
4348 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004349 self.assertIs(l.__add__.__self__, l)
4350 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004351 else:
4352 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004353 self.assertIs(l.__add__.im_self, l)
4354 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004355 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4356 try:
4357 hash(l.__add__)
4358 except TypeError:
4359 pass
4360 else:
4361 self.fail("no TypeError from hash([].__add__)")
4362
4363 t = ()
4364 t += (7,)
4365 self.assertEqual(t.__add__, (7,).__add__)
4366 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4367
4368 def test_not_implemented(self):
4369 # Testing NotImplemented...
4370 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004371 import operator
4372
4373 def specialmethod(self, other):
4374 return NotImplemented
4375
4376 def check(expr, x, y):
4377 try:
4378 exec(expr, {'x': x, 'y': y, 'operator': operator})
4379 except TypeError:
4380 pass
4381 else:
4382 self.fail("no TypeError from %r" % (expr,))
4383
4384 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4385 # TypeErrors
4386 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4387 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004388 for name, expr, iexpr in [
4389 ('__add__', 'x + y', 'x += y'),
4390 ('__sub__', 'x - y', 'x -= y'),
4391 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004392 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004393 ('__truediv__', 'x / y', 'x /= y'),
4394 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004395 ('__mod__', 'x % y', 'x %= y'),
4396 ('__divmod__', 'divmod(x, y)', None),
4397 ('__pow__', 'x ** y', 'x **= y'),
4398 ('__lshift__', 'x << y', 'x <<= y'),
4399 ('__rshift__', 'x >> y', 'x >>= y'),
4400 ('__and__', 'x & y', 'x &= y'),
4401 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004402 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004403 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004404 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004405 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004406 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004407 check(expr, a, N1)
4408 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004409 if iexpr:
4410 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004411 check(iexpr, a, N1)
4412 check(iexpr, a, N2)
4413 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004414 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004415 c = C()
4416 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004417 check(iexpr, c, N1)
4418 check(iexpr, c, N2)
4419
Georg Brandl479a7e72008-02-05 18:13:15 +00004420 def test_assign_slice(self):
4421 # ceval.c's assign_slice used to check for
4422 # tp->tp_as_sequence->sq_slice instead of
4423 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004424
Georg Brandl479a7e72008-02-05 18:13:15 +00004425 class C(object):
4426 def __setitem__(self, idx, value):
4427 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004428
Georg Brandl479a7e72008-02-05 18:13:15 +00004429 c = C()
4430 c[1:2] = 3
4431 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004432
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004433 def test_set_and_no_get(self):
4434 # See
4435 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4436 class Descr(object):
4437
4438 def __init__(self, name):
4439 self.name = name
4440
4441 def __set__(self, obj, value):
4442 obj.__dict__[self.name] = value
4443 descr = Descr("a")
4444
4445 class X(object):
4446 a = descr
4447
4448 x = X()
4449 self.assertIs(x.a, descr)
4450 x.a = 42
4451 self.assertEqual(x.a, 42)
4452
Benjamin Peterson21896a32010-03-21 22:03:03 +00004453 # Also check type_getattro for correctness.
4454 class Meta(type):
4455 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004456 class X(metaclass=Meta):
4457 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004458 X.a = 42
4459 Meta.a = Descr("a")
4460 self.assertEqual(X.a, 42)
4461
Benjamin Peterson9262b842008-11-17 22:45:50 +00004462 def test_getattr_hooks(self):
4463 # issue 4230
4464
4465 class Descriptor(object):
4466 counter = 0
4467 def __get__(self, obj, objtype=None):
4468 def getter(name):
4469 self.counter += 1
4470 raise AttributeError(name)
4471 return getter
4472
4473 descr = Descriptor()
4474 class A(object):
4475 __getattribute__ = descr
4476 class B(object):
4477 __getattr__ = descr
4478 class C(object):
4479 __getattribute__ = descr
4480 __getattr__ = descr
4481
4482 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004483 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004484 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004485 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004486 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004487 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004488
Benjamin Peterson9262b842008-11-17 22:45:50 +00004489 class EvilGetattribute(object):
4490 # This used to segfault
4491 def __getattr__(self, name):
4492 raise AttributeError(name)
4493 def __getattribute__(self, name):
4494 del EvilGetattribute.__getattr__
4495 for i in range(5):
4496 gc.collect()
4497 raise AttributeError(name)
4498
4499 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4500
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004501 def test_type___getattribute__(self):
4502 self.assertRaises(TypeError, type.__getattribute__, list, type)
4503
Benjamin Peterson477ba912011-01-12 15:34:01 +00004504 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004505 # type pretends not to have __abstractmethods__.
4506 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4507 class meta(type):
4508 pass
4509 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004510 class X(object):
4511 pass
4512 with self.assertRaises(AttributeError):
4513 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004514
Victor Stinner3249dec2011-05-01 23:19:15 +02004515 def test_proxy_call(self):
4516 class FakeStr:
4517 __class__ = str
4518
4519 fake_str = FakeStr()
4520 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004521 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004522
4523 # call a method descriptor
4524 with self.assertRaises(TypeError):
4525 str.split(fake_str)
4526
4527 # call a slot wrapper descriptor
4528 with self.assertRaises(TypeError):
4529 str.__add__(fake_str, "abc")
4530
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004531 def test_repr_as_str(self):
4532 # Issue #11603: crash or infinite loop when rebinding __str__ as
4533 # __repr__.
4534 class Foo:
4535 pass
4536 Foo.__repr__ = Foo.__str__
4537 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004538 self.assertRaises(RecursionError, str, foo)
4539 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004540
4541 def test_mixing_slot_wrappers(self):
4542 class X(dict):
4543 __setattr__ = dict.__setitem__
4544 x = X()
4545 x.y = 42
4546 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004547
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004548 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004549 with self.assertRaises(ValueError) as cm:
4550 class X:
4551 __slots__ = ["foo"]
4552 foo = None
4553 m = str(cm.exception)
4554 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4555
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004556 def test_set_doc(self):
4557 class X:
4558 "elephant"
4559 X.__doc__ = "banana"
4560 self.assertEqual(X.__doc__, "banana")
4561 with self.assertRaises(TypeError) as cm:
4562 type(list).__dict__["__doc__"].__set__(list, "blah")
4563 self.assertIn("can't set list.__doc__", str(cm.exception))
4564 with self.assertRaises(TypeError) as cm:
4565 type(X).__dict__["__doc__"].__delete__(X)
4566 self.assertIn("can't delete X.__doc__", str(cm.exception))
4567 self.assertEqual(X.__doc__, "banana")
4568
Antoine Pitrou9d574812011-12-12 13:47:25 +01004569 def test_qualname(self):
4570 descriptors = [str.lower, complex.real, float.real, int.__add__]
4571 types = ['method', 'member', 'getset', 'wrapper']
4572
4573 # make sure we have an example of each type of descriptor
4574 for d, n in zip(descriptors, types):
4575 self.assertEqual(type(d).__name__, n + '_descriptor')
4576
4577 for d in descriptors:
4578 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4579 self.assertEqual(d.__qualname__, qualname)
4580
4581 self.assertEqual(str.lower.__qualname__, 'str.lower')
4582 self.assertEqual(complex.real.__qualname__, 'complex.real')
4583 self.assertEqual(float.real.__qualname__, 'float.real')
4584 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4585
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004586 class X:
4587 pass
4588 with self.assertRaises(TypeError):
4589 del X.__qualname__
4590
4591 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4592 str, 'Oink')
4593
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004594 global Y
4595 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004596 class Inside:
4597 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004598 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004599 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004600
Victor Stinner6f738742012-02-25 01:22:36 +01004601 def test_qualname_dict(self):
4602 ns = {'__qualname__': 'some.name'}
4603 tp = type('Foo', (), ns)
4604 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004605 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004606 self.assertEqual(ns, {'__qualname__': 'some.name'})
4607
4608 ns = {'__qualname__': 1}
4609 self.assertRaises(TypeError, type, 'Foo', (), ns)
4610
Benjamin Peterson52c42432012-03-07 18:41:11 -06004611 def test_cycle_through_dict(self):
4612 # See bug #1469629
4613 class X(dict):
4614 def __init__(self):
4615 dict.__init__(self)
4616 self.__dict__ = self
4617 x = X()
4618 x.attr = 42
4619 wr = weakref.ref(x)
4620 del x
4621 support.gc_collect()
4622 self.assertIsNone(wr())
4623 for o in gc.get_objects():
4624 self.assertIsNot(type(o), X)
4625
Benjamin Peterson96384b92012-03-17 00:05:44 -05004626 def test_object_new_and_init_with_parameters(self):
4627 # See issue #1683368
4628 class OverrideNeither:
4629 pass
4630 self.assertRaises(TypeError, OverrideNeither, 1)
4631 self.assertRaises(TypeError, OverrideNeither, kw=1)
4632 class OverrideNew:
4633 def __new__(cls, foo, kw=0, *args, **kwds):
4634 return object.__new__(cls, *args, **kwds)
4635 class OverrideInit:
4636 def __init__(self, foo, kw=0, *args, **kwargs):
4637 return object.__init__(self, *args, **kwargs)
4638 class OverrideBoth(OverrideNew, OverrideInit):
4639 pass
4640 for case in OverrideNew, OverrideInit, OverrideBoth:
4641 case(1)
4642 case(1, kw=2)
4643 self.assertRaises(TypeError, case, 1, 2, 3)
4644 self.assertRaises(TypeError, case, 1, 2, foo=3)
4645
Benjamin Petersondf813792014-03-17 15:57:17 -05004646 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4647 class Base:
4648 pass
4649 class Sub(Base):
4650 pass
4651 self.assertIn("__dict__", Base.__dict__)
4652 self.assertNotIn("__dict__", Sub.__dict__)
4653
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004654 def test_bound_method_repr(self):
4655 class Foo:
4656 def method(self):
4657 pass
4658 self.assertRegex(repr(Foo().method),
4659 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4660
4661
4662 class Base:
4663 def method(self):
4664 pass
4665 class Derived1(Base):
4666 pass
4667 class Derived2(Base):
4668 def method(self):
4669 pass
4670 base = Base()
4671 derived1 = Derived1()
4672 derived2 = Derived2()
4673 super_d2 = super(Derived2, derived2)
4674 self.assertRegex(repr(base.method),
4675 r"<bound method .*Base\.method of <.*Base object at .*>>")
4676 self.assertRegex(repr(derived1.method),
4677 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4678 self.assertRegex(repr(derived2.method),
4679 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4680 self.assertRegex(repr(super_d2.method),
4681 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4682
4683 class Foo:
4684 @classmethod
4685 def method(cls):
4686 pass
4687 foo = Foo()
4688 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004689 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004690 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004691 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004692
4693
4694 class MyCallable:
4695 def __call__(self, arg):
4696 pass
4697 func = MyCallable() # func has no __name__ or __qualname__ attributes
4698 instance = object()
4699 method = types.MethodType(func, instance)
4700 self.assertRegex(repr(method),
4701 r"<bound method \? of <object object at .*>>")
4702 func.__name__ = "name"
4703 self.assertRegex(repr(method),
4704 r"<bound method name of <object object at .*>>")
4705 func.__qualname__ = "qualname"
4706 self.assertRegex(repr(method),
4707 r"<bound method qualname of <object object at .*>>")
4708
Antoine Pitrou9d574812011-12-12 13:47:25 +01004709
Georg Brandl479a7e72008-02-05 18:13:15 +00004710class DictProxyTests(unittest.TestCase):
4711 def setUp(self):
4712 class C(object):
4713 def meth(self):
4714 pass
4715 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004716
Brett Cannon7a540732011-02-22 03:04:06 +00004717 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4718 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004719 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004720 # Testing dict-proxy keys...
4721 it = self.C.__dict__.keys()
4722 self.assertNotIsInstance(it, list)
4723 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004724 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004725 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004726 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004727
Brett Cannon7a540732011-02-22 03:04:06 +00004728 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4729 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004730 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004731 # Testing dict-proxy values...
4732 it = self.C.__dict__.values()
4733 self.assertNotIsInstance(it, list)
4734 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004735 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004736
Brett Cannon7a540732011-02-22 03:04:06 +00004737 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4738 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004739 def test_iter_items(self):
4740 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004741 it = self.C.__dict__.items()
4742 self.assertNotIsInstance(it, list)
4743 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004744 keys.sort()
4745 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004746 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004747
Georg Brandl479a7e72008-02-05 18:13:15 +00004748 def test_dict_type_with_metaclass(self):
4749 # Testing type of __dict__ when metaclass set...
4750 class B(object):
4751 pass
4752 class M(type):
4753 pass
4754 class C(metaclass=M):
4755 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4756 pass
4757 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004758
Ezio Melottiac53ab62010-12-18 14:59:43 +00004759 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004760 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004761 # We can't blindly compare with the repr of another dict as ordering
4762 # of keys and values is arbitrary and may differ.
4763 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004764 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004765 self.assertTrue(r.endswith(')'), r)
4766 for k, v in self.C.__dict__.items():
4767 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004768
Christian Heimesbbffeb62008-01-24 09:42:52 +00004769
Georg Brandl479a7e72008-02-05 18:13:15 +00004770class PTypesLongInitTest(unittest.TestCase):
4771 # This is in its own TestCase so that it can be run before any other tests.
4772 def test_pytype_long_ready(self):
4773 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004774
Georg Brandl479a7e72008-02-05 18:13:15 +00004775 # This dumps core when SF bug 551412 isn't fixed --
4776 # but only when test_descr.py is run separately.
4777 # (That can't be helped -- as soon as PyType_Ready()
4778 # is called for PyLong_Type, the bug is gone.)
4779 class UserLong(object):
4780 def __pow__(self, *args):
4781 pass
4782 try:
4783 pow(0, UserLong(), 0)
4784 except:
4785 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004786
Georg Brandl479a7e72008-02-05 18:13:15 +00004787 # Another segfault only when run early
4788 # (before PyType_Ready(tuple) is called)
4789 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004790
4791
Victor Stinnerd74782b2012-03-09 00:39:08 +01004792class MiscTests(unittest.TestCase):
4793 def test_type_lookup_mro_reference(self):
4794 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4795 # the type MRO because it may be modified during the lookup, if
4796 # __bases__ is set during the lookup for example.
4797 class MyKey(object):
4798 def __hash__(self):
4799 return hash('mykey')
4800
4801 def __eq__(self, other):
4802 X.__bases__ = (Base2,)
4803
4804 class Base(object):
4805 mykey = 'from Base'
4806 mykey2 = 'from Base'
4807
4808 class Base2(object):
4809 mykey = 'from Base2'
4810 mykey2 = 'from Base2'
4811
4812 X = type('X', (Base,), {MyKey(): 5})
4813 # mykey is read from Base
4814 self.assertEqual(X.mykey, 'from Base')
4815 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4816 self.assertEqual(X.mykey2, 'from Base2')
4817
4818
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004819class PicklingTests(unittest.TestCase):
4820
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004821 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004822 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004823 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004824 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004825 if kwargs:
4826 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4827 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004828 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004829 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4830 self.assertEqual(reduce_value[1], (type(obj),) + args)
4831 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004832 if listitems is not None:
4833 self.assertListEqual(list(reduce_value[3]), listitems)
4834 else:
4835 self.assertIsNone(reduce_value[3])
4836 if dictitems is not None:
4837 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4838 else:
4839 self.assertIsNone(reduce_value[4])
4840 else:
4841 base_type = type(obj).__base__
4842 reduce_value = (copyreg._reconstructor,
4843 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004844 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004845 None if base_type is object else base_type(obj)))
4846 if state is not None:
4847 reduce_value += (state,)
4848 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4849 self.assertEqual(obj.__reduce__(), reduce_value)
4850
4851 def test_reduce(self):
4852 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4853 args = (-101, "spam")
4854 kwargs = {'bacon': -201, 'fish': -301}
4855 state = {'cheese': -401}
4856
4857 class C1:
4858 def __getnewargs__(self):
4859 return args
4860 obj = C1()
4861 for proto in protocols:
4862 self._check_reduce(proto, obj, args)
4863
4864 for name, value in state.items():
4865 setattr(obj, name, value)
4866 for proto in protocols:
4867 self._check_reduce(proto, obj, args, state=state)
4868
4869 class C2:
4870 def __getnewargs__(self):
4871 return "bad args"
4872 obj = C2()
4873 for proto in protocols:
4874 if proto >= 2:
4875 with self.assertRaises(TypeError):
4876 obj.__reduce_ex__(proto)
4877
4878 class C3:
4879 def __getnewargs_ex__(self):
4880 return (args, kwargs)
4881 obj = C3()
4882 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03004883 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004884 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004885
4886 class C4:
4887 def __getnewargs_ex__(self):
4888 return (args, "bad dict")
4889 class C5:
4890 def __getnewargs_ex__(self):
4891 return ("bad tuple", kwargs)
4892 class C6:
4893 def __getnewargs_ex__(self):
4894 return ()
4895 class C7:
4896 def __getnewargs_ex__(self):
4897 return "bad args"
4898 for proto in protocols:
4899 for cls in C4, C5, C6, C7:
4900 obj = cls()
4901 if proto >= 2:
4902 with self.assertRaises((TypeError, ValueError)):
4903 obj.__reduce_ex__(proto)
4904
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004905 class C9:
4906 def __getnewargs_ex__(self):
4907 return (args, {})
4908 obj = C9()
4909 for proto in protocols:
4910 self._check_reduce(proto, obj, args)
4911
4912 class C10:
4913 def __getnewargs_ex__(self):
4914 raise IndexError
4915 obj = C10()
4916 for proto in protocols:
4917 if proto >= 2:
4918 with self.assertRaises(IndexError):
4919 obj.__reduce_ex__(proto)
4920
4921 class C11:
4922 def __getstate__(self):
4923 return state
4924 obj = C11()
4925 for proto in protocols:
4926 self._check_reduce(proto, obj, state=state)
4927
4928 class C12:
4929 def __getstate__(self):
4930 return "not dict"
4931 obj = C12()
4932 for proto in protocols:
4933 self._check_reduce(proto, obj, state="not dict")
4934
4935 class C13:
4936 def __getstate__(self):
4937 raise IndexError
4938 obj = C13()
4939 for proto in protocols:
4940 with self.assertRaises(IndexError):
4941 obj.__reduce_ex__(proto)
4942 if proto < 2:
4943 with self.assertRaises(IndexError):
4944 obj.__reduce__()
4945
4946 class C14:
4947 __slots__ = tuple(state)
4948 def __init__(self):
4949 for name, value in state.items():
4950 setattr(self, name, value)
4951
4952 obj = C14()
4953 for proto in protocols:
4954 if proto >= 2:
4955 self._check_reduce(proto, obj, state=(None, state))
4956 else:
4957 with self.assertRaises(TypeError):
4958 obj.__reduce_ex__(proto)
4959 with self.assertRaises(TypeError):
4960 obj.__reduce__()
4961
4962 class C15(dict):
4963 pass
4964 obj = C15({"quebec": -601})
4965 for proto in protocols:
4966 self._check_reduce(proto, obj, dictitems=dict(obj))
4967
4968 class C16(list):
4969 pass
4970 obj = C16(["yukon"])
4971 for proto in protocols:
4972 self._check_reduce(proto, obj, listitems=list(obj))
4973
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004974 def test_special_method_lookup(self):
4975 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4976 class Picky:
4977 def __getstate__(self):
4978 return {}
4979
4980 def __getattr__(self, attr):
4981 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4982 raise AssertionError(attr)
4983 return None
4984 for protocol in protocols:
4985 state = {} if protocol >= 2 else None
4986 self._check_reduce(protocol, Picky(), state=state)
4987
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004988 def _assert_is_copy(self, obj, objcopy, msg=None):
4989 """Utility method to verify if two objects are copies of each others.
4990 """
4991 if msg is None:
4992 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4993 if type(obj).__repr__ is object.__repr__:
4994 # We have this limitation for now because we use the object's repr
4995 # to help us verify that the two objects are copies. This allows
4996 # us to delegate the non-generic verification logic to the objects
4997 # themselves.
4998 raise ValueError("object passed to _assert_is_copy must " +
4999 "override the __repr__ method.")
5000 self.assertIsNot(obj, objcopy, msg=msg)
5001 self.assertIs(type(obj), type(objcopy), msg=msg)
5002 if hasattr(obj, '__dict__'):
5003 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5004 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5005 if hasattr(obj, '__slots__'):
5006 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5007 for slot in obj.__slots__:
5008 self.assertEqual(
5009 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5010 self.assertEqual(getattr(obj, slot, None),
5011 getattr(objcopy, slot, None), msg=msg)
5012 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5013
5014 @staticmethod
5015 def _generate_pickle_copiers():
5016 """Utility method to generate the many possible pickle configurations.
5017 """
5018 class PickleCopier:
5019 "This class copies object using pickle."
5020 def __init__(self, proto, dumps, loads):
5021 self.proto = proto
5022 self.dumps = dumps
5023 self.loads = loads
5024 def copy(self, obj):
5025 return self.loads(self.dumps(obj, self.proto))
5026 def __repr__(self):
5027 # We try to be as descriptive as possible here since this is
5028 # the string which we will allow us to tell the pickle
5029 # configuration we are using during debugging.
5030 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5031 .format(self.proto,
5032 self.dumps.__module__, self.dumps.__qualname__,
5033 self.loads.__module__, self.loads.__qualname__))
5034 return (PickleCopier(*args) for args in
5035 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5036 {pickle.dumps, pickle._dumps},
5037 {pickle.loads, pickle._loads}))
5038
5039 def test_pickle_slots(self):
5040 # Tests pickling of classes with __slots__.
5041
5042 # Pickling of classes with __slots__ but without __getstate__ should
5043 # fail (if using protocol 0 or 1)
5044 global C
5045 class C:
5046 __slots__ = ['a']
5047 with self.assertRaises(TypeError):
5048 pickle.dumps(C(), 0)
5049
5050 global D
5051 class D(C):
5052 pass
5053 with self.assertRaises(TypeError):
5054 pickle.dumps(D(), 0)
5055
5056 class C:
5057 "A class with __getstate__ and __setstate__ implemented."
5058 __slots__ = ['a']
5059 def __getstate__(self):
5060 state = getattr(self, '__dict__', {}).copy()
5061 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005062 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005063 try:
5064 state[slot] = getattr(self, slot)
5065 except AttributeError:
5066 pass
5067 return state
5068 def __setstate__(self, state):
5069 for k, v in state.items():
5070 setattr(self, k, v)
5071 def __repr__(self):
5072 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5073
5074 class D(C):
5075 "A subclass of a class with slots."
5076 pass
5077
5078 global E
5079 class E(C):
5080 "A subclass with an extra slot."
5081 __slots__ = ['b']
5082
5083 # Now it should work
5084 for pickle_copier in self._generate_pickle_copiers():
5085 with self.subTest(pickle_copier=pickle_copier):
5086 x = C()
5087 y = pickle_copier.copy(x)
5088 self._assert_is_copy(x, y)
5089
5090 x.a = 42
5091 y = pickle_copier.copy(x)
5092 self._assert_is_copy(x, y)
5093
5094 x = D()
5095 x.a = 42
5096 x.b = 100
5097 y = pickle_copier.copy(x)
5098 self._assert_is_copy(x, y)
5099
5100 x = E()
5101 x.a = 42
5102 x.b = "foo"
5103 y = pickle_copier.copy(x)
5104 self._assert_is_copy(x, y)
5105
5106 def test_reduce_copying(self):
5107 # Tests pickling and copying new-style classes and objects.
5108 global C1
5109 class C1:
5110 "The state of this class is copyable via its instance dict."
5111 ARGS = (1, 2)
5112 NEED_DICT_COPYING = True
5113 def __init__(self, a, b):
5114 super().__init__()
5115 self.a = a
5116 self.b = b
5117 def __repr__(self):
5118 return "C1(%r, %r)" % (self.a, self.b)
5119
5120 global C2
5121 class C2(list):
5122 "A list subclass copyable via __getnewargs__."
5123 ARGS = (1, 2)
5124 NEED_DICT_COPYING = False
5125 def __new__(cls, a, b):
5126 self = super().__new__(cls)
5127 self.a = a
5128 self.b = b
5129 return self
5130 def __init__(self, *args):
5131 super().__init__()
5132 # This helps testing that __init__ is not called during the
5133 # unpickling process, which would cause extra appends.
5134 self.append("cheese")
5135 @classmethod
5136 def __getnewargs__(cls):
5137 return cls.ARGS
5138 def __repr__(self):
5139 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5140
5141 global C3
5142 class C3(list):
5143 "A list subclass copyable via __getstate__."
5144 ARGS = (1, 2)
5145 NEED_DICT_COPYING = False
5146 def __init__(self, a, b):
5147 self.a = a
5148 self.b = b
5149 # This helps testing that __init__ is not called during the
5150 # unpickling process, which would cause extra appends.
5151 self.append("cheese")
5152 @classmethod
5153 def __getstate__(cls):
5154 return cls.ARGS
5155 def __setstate__(self, state):
5156 a, b = state
5157 self.a = a
5158 self.b = b
5159 def __repr__(self):
5160 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5161
5162 global C4
5163 class C4(int):
5164 "An int subclass copyable via __getnewargs__."
5165 ARGS = ("hello", "world", 1)
5166 NEED_DICT_COPYING = False
5167 def __new__(cls, a, b, value):
5168 self = super().__new__(cls, value)
5169 self.a = a
5170 self.b = b
5171 return self
5172 @classmethod
5173 def __getnewargs__(cls):
5174 return cls.ARGS
5175 def __repr__(self):
5176 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5177
5178 global C5
5179 class C5(int):
5180 "An int subclass copyable via __getnewargs_ex__."
5181 ARGS = (1, 2)
5182 KWARGS = {'value': 3}
5183 NEED_DICT_COPYING = False
5184 def __new__(cls, a, b, *, value=0):
5185 self = super().__new__(cls, value)
5186 self.a = a
5187 self.b = b
5188 return self
5189 @classmethod
5190 def __getnewargs_ex__(cls):
5191 return (cls.ARGS, cls.KWARGS)
5192 def __repr__(self):
5193 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5194
5195 test_classes = (C1, C2, C3, C4, C5)
5196 # Testing copying through pickle
5197 pickle_copiers = self._generate_pickle_copiers()
5198 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5199 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5200 kwargs = getattr(cls, 'KWARGS', {})
5201 obj = cls(*cls.ARGS, **kwargs)
5202 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005203 objcopy = pickle_copier.copy(obj)
5204 self._assert_is_copy(obj, objcopy)
5205 # For test classes that supports this, make sure we didn't go
5206 # around the reduce protocol by simply copying the attribute
5207 # dictionary. We clear attributes using the previous copy to
5208 # not mutate the original argument.
5209 if proto >= 2 and not cls.NEED_DICT_COPYING:
5210 objcopy.__dict__.clear()
5211 objcopy2 = pickle_copier.copy(objcopy)
5212 self._assert_is_copy(obj, objcopy2)
5213
5214 # Testing copying through copy.deepcopy()
5215 for cls in test_classes:
5216 with self.subTest(cls=cls):
5217 kwargs = getattr(cls, 'KWARGS', {})
5218 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005219 objcopy = deepcopy(obj)
5220 self._assert_is_copy(obj, objcopy)
5221 # For test classes that supports this, make sure we didn't go
5222 # around the reduce protocol by simply copying the attribute
5223 # dictionary. We clear attributes using the previous copy to
5224 # not mutate the original argument.
5225 if not cls.NEED_DICT_COPYING:
5226 objcopy.__dict__.clear()
5227 objcopy2 = deepcopy(objcopy)
5228 self._assert_is_copy(obj, objcopy2)
5229
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005230 def test_issue24097(self):
5231 # Slot name is freed inside __getattr__ and is later used.
5232 class S(str): # Not interned
5233 pass
5234 class A:
5235 __slotnames__ = [S('spam')]
5236 def __getattr__(self, attr):
5237 if attr == 'spam':
5238 A.__slotnames__[:] = [S('spam')]
5239 return 42
5240 else:
5241 raise AttributeError
5242
5243 import copyreg
5244 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005245 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5246
5247 def test_object_reduce(self):
5248 # Issue #29914
5249 # __reduce__() takes no arguments
5250 object().__reduce__()
5251 with self.assertRaises(TypeError):
5252 object().__reduce__(0)
5253 # __reduce_ex__() takes one integer argument
5254 object().__reduce_ex__(0)
5255 with self.assertRaises(TypeError):
5256 object().__reduce_ex__()
5257 with self.assertRaises(TypeError):
5258 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005259
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005260
Benjamin Peterson2a605342014-03-17 16:20:12 -05005261class SharedKeyTests(unittest.TestCase):
5262
5263 @support.cpython_only
5264 def test_subclasses(self):
5265 # Verify that subclasses can share keys (per PEP 412)
5266 class A:
5267 pass
5268 class B(A):
5269 pass
5270
5271 a, b = A(), B()
5272 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5273 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005274 # Initial hash table can contain at most 5 elements.
5275 # Set 6 attributes to cause internal resizing.
5276 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005277 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5278 a2 = A()
5279 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5280 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005281 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005282 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5283
5284
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005285class DebugHelperMeta(type):
5286 """
5287 Sets default __doc__ and simplifies repr() output.
5288 """
5289 def __new__(mcls, name, bases, attrs):
5290 if attrs.get('__doc__') is None:
5291 attrs['__doc__'] = name # helps when debugging with gdb
5292 return type.__new__(mcls, name, bases, attrs)
5293 def __repr__(cls):
5294 return repr(cls.__name__)
5295
5296
5297class MroTest(unittest.TestCase):
5298 """
5299 Regressions for some bugs revealed through
5300 mcsl.mro() customization (typeobject.c: mro_internal()) and
5301 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5302 """
5303
5304 def setUp(self):
5305 self.step = 0
5306 self.ready = False
5307
5308 def step_until(self, limit):
5309 ret = (self.step < limit)
5310 if ret:
5311 self.step += 1
5312 return ret
5313
5314 def test_incomplete_set_bases_on_self(self):
5315 """
5316 type_set_bases must be aware that type->tp_mro can be NULL.
5317 """
5318 class M(DebugHelperMeta):
5319 def mro(cls):
5320 if self.step_until(1):
5321 assert cls.__mro__ is None
5322 cls.__bases__ += ()
5323
5324 return type.mro(cls)
5325
5326 class A(metaclass=M):
5327 pass
5328
5329 def test_reent_set_bases_on_base(self):
5330 """
5331 Deep reentrancy must not over-decref old_mro.
5332 """
5333 class M(DebugHelperMeta):
5334 def mro(cls):
5335 if cls.__mro__ is not None and cls.__name__ == 'B':
5336 # 4-5 steps are usually enough to make it crash somewhere
5337 if self.step_until(10):
5338 A.__bases__ += ()
5339
5340 return type.mro(cls)
5341
5342 class A(metaclass=M):
5343 pass
5344 class B(A):
5345 pass
5346 B.__bases__ += ()
5347
5348 def test_reent_set_bases_on_direct_base(self):
5349 """
5350 Similar to test_reent_set_bases_on_base, but may crash differently.
5351 """
5352 class M(DebugHelperMeta):
5353 def mro(cls):
5354 base = cls.__bases__[0]
5355 if base is not object:
5356 if self.step_until(5):
5357 base.__bases__ += ()
5358
5359 return type.mro(cls)
5360
5361 class A(metaclass=M):
5362 pass
5363 class B(A):
5364 pass
5365 class C(B):
5366 pass
5367
5368 def test_reent_set_bases_tp_base_cycle(self):
5369 """
5370 type_set_bases must check for an inheritance cycle not only through
5371 MRO of the type, which may be not yet updated in case of reentrance,
5372 but also through tp_base chain, which is assigned before diving into
5373 inner calls to mro().
5374
5375 Otherwise, the following snippet can loop forever:
5376 do {
5377 // ...
5378 type = type->tp_base;
5379 } while (type != NULL);
5380
5381 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5382 would not be happy in that case, causing a stack overflow.
5383 """
5384 class M(DebugHelperMeta):
5385 def mro(cls):
5386 if self.ready:
5387 if cls.__name__ == 'B1':
5388 B2.__bases__ = (B1,)
5389 if cls.__name__ == 'B2':
5390 B1.__bases__ = (B2,)
5391 return type.mro(cls)
5392
5393 class A(metaclass=M):
5394 pass
5395 class B1(A):
5396 pass
5397 class B2(A):
5398 pass
5399
5400 self.ready = True
5401 with self.assertRaises(TypeError):
5402 B1.__bases__ += ()
5403
5404 def test_tp_subclasses_cycle_in_update_slots(self):
5405 """
5406 type_set_bases must check for reentrancy upon finishing its job
5407 by updating tp_subclasses of old/new bases of the type.
5408 Otherwise, an implicit inheritance cycle through tp_subclasses
5409 can break functions that recurse on elements of that field
5410 (like recurse_down_subclasses and mro_hierarchy) eventually
5411 leading to a stack overflow.
5412 """
5413 class M(DebugHelperMeta):
5414 def mro(cls):
5415 if self.ready and cls.__name__ == 'C':
5416 self.ready = False
5417 C.__bases__ = (B2,)
5418 return type.mro(cls)
5419
5420 class A(metaclass=M):
5421 pass
5422 class B1(A):
5423 pass
5424 class B2(A):
5425 pass
5426 class C(A):
5427 pass
5428
5429 self.ready = True
5430 C.__bases__ = (B1,)
5431 B1.__bases__ = (C,)
5432
5433 self.assertEqual(C.__bases__, (B2,))
5434 self.assertEqual(B2.__subclasses__(), [C])
5435 self.assertEqual(B1.__subclasses__(), [])
5436
5437 self.assertEqual(B1.__bases__, (C,))
5438 self.assertEqual(C.__subclasses__(), [B1])
5439
5440 def test_tp_subclasses_cycle_error_return_path(self):
5441 """
5442 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5443 a code path executed on error (goto bail).
5444 """
5445 class E(Exception):
5446 pass
5447 class M(DebugHelperMeta):
5448 def mro(cls):
5449 if self.ready and cls.__name__ == 'C':
5450 if C.__bases__ == (B2,):
5451 self.ready = False
5452 else:
5453 C.__bases__ = (B2,)
5454 raise E
5455 return type.mro(cls)
5456
5457 class A(metaclass=M):
5458 pass
5459 class B1(A):
5460 pass
5461 class B2(A):
5462 pass
5463 class C(A):
5464 pass
5465
5466 self.ready = True
5467 with self.assertRaises(E):
5468 C.__bases__ = (B1,)
5469 B1.__bases__ = (C,)
5470
5471 self.assertEqual(C.__bases__, (B2,))
5472 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5473
5474 def test_incomplete_extend(self):
5475 """
5476 Extending an unitialized type with type->tp_mro == NULL must
5477 throw a reasonable TypeError exception, instead of failing
5478 with PyErr_BadInternalCall.
5479 """
5480 class M(DebugHelperMeta):
5481 def mro(cls):
5482 if cls.__mro__ is None and cls.__name__ != 'X':
5483 with self.assertRaises(TypeError):
5484 class X(cls):
5485 pass
5486
5487 return type.mro(cls)
5488
5489 class A(metaclass=M):
5490 pass
5491
5492 def test_incomplete_super(self):
5493 """
5494 Attrubute lookup on a super object must be aware that
5495 its target type can be uninitialized (type->tp_mro == NULL).
5496 """
5497 class M(DebugHelperMeta):
5498 def mro(cls):
5499 if cls.__mro__ is None:
5500 with self.assertRaises(AttributeError):
5501 super(cls, cls).xxx
5502
5503 return type.mro(cls)
5504
5505 class A(metaclass=M):
5506 pass
5507
5508
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005509def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005510 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005511 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005512 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005513 MiscTests, PicklingTests, SharedKeyTests,
5514 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005515
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005516if __name__ == "__main__":
5517 test_main()