blob: ced25f3fc4424400063d90aa66cad43df07b2559 [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
1786 self.assertEqual(D.mro(), [D, B, C, A, object])
1787 self.assertEqual(D.__mro__, (D, B, C, A, object))
1788 self.assertEqual(D().f(), "C")
1789
1790 class PerverseMetaType(type):
1791 def mro(cls):
1792 L = type.mro(cls)
1793 L.reverse()
1794 return L
1795 class X(D,B,C,A, metaclass=PerverseMetaType):
1796 pass
1797 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1798 self.assertEqual(X().f(), "A")
1799
1800 try:
1801 class _metaclass(type):
1802 def mro(self):
1803 return [self, dict, object]
1804 class X(object, metaclass=_metaclass):
1805 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001806 # In CPython, the class creation above already raises
1807 # TypeError, as a protection against the fact that
1808 # instances of X would segfault it. In other Python
1809 # implementations it would be ok to let the class X
1810 # be created, but instead get a clean TypeError on the
1811 # __setitem__ below.
1812 x = object.__new__(X)
1813 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001814 except TypeError:
1815 pass
1816 else:
1817 self.fail("devious mro() return not caught")
1818
1819 try:
1820 class _metaclass(type):
1821 def mro(self):
1822 return [1]
1823 class X(object, metaclass=_metaclass):
1824 pass
1825 except TypeError:
1826 pass
1827 else:
1828 self.fail("non-class mro() return not caught")
1829
1830 try:
1831 class _metaclass(type):
1832 def mro(self):
1833 return 1
1834 class X(object, metaclass=_metaclass):
1835 pass
1836 except TypeError:
1837 pass
1838 else:
1839 self.fail("non-sequence mro() return not caught")
1840
1841 def test_overloading(self):
1842 # Testing operator overloading...
1843
1844 class B(object):
1845 "Intermediate class because object doesn't have a __setattr__"
1846
1847 class C(B):
1848 def __getattr__(self, name):
1849 if name == "foo":
1850 return ("getattr", name)
1851 else:
1852 raise AttributeError
1853 def __setattr__(self, name, value):
1854 if name == "foo":
1855 self.setattr = (name, value)
1856 else:
1857 return B.__setattr__(self, name, value)
1858 def __delattr__(self, name):
1859 if name == "foo":
1860 self.delattr = name
1861 else:
1862 return B.__delattr__(self, name)
1863
1864 def __getitem__(self, key):
1865 return ("getitem", key)
1866 def __setitem__(self, key, value):
1867 self.setitem = (key, value)
1868 def __delitem__(self, key):
1869 self.delitem = key
1870
1871 a = C()
1872 self.assertEqual(a.foo, ("getattr", "foo"))
1873 a.foo = 12
1874 self.assertEqual(a.setattr, ("foo", 12))
1875 del a.foo
1876 self.assertEqual(a.delattr, "foo")
1877
1878 self.assertEqual(a[12], ("getitem", 12))
1879 a[12] = 21
1880 self.assertEqual(a.setitem, (12, 21))
1881 del a[12]
1882 self.assertEqual(a.delitem, 12)
1883
1884 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1885 a[0:10] = "foo"
1886 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1887 del a[0:10]
1888 self.assertEqual(a.delitem, (slice(0, 10)))
1889
1890 def test_methods(self):
1891 # Testing methods...
1892 class C(object):
1893 def __init__(self, x):
1894 self.x = x
1895 def foo(self):
1896 return self.x
1897 c1 = C(1)
1898 self.assertEqual(c1.foo(), 1)
1899 class D(C):
1900 boo = C.foo
1901 goo = c1.foo
1902 d2 = D(2)
1903 self.assertEqual(d2.foo(), 2)
1904 self.assertEqual(d2.boo(), 2)
1905 self.assertEqual(d2.goo(), 1)
1906 class E(object):
1907 foo = C.foo
1908 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001909 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001910
Benjamin Peterson224205f2009-05-08 03:25:19 +00001911 def test_special_method_lookup(self):
1912 # The lookup of special methods bypasses __getattr__ and
1913 # __getattribute__, but they still can be descriptors.
1914
1915 def run_context(manager):
1916 with manager:
1917 pass
1918 def iden(self):
1919 return self
1920 def hello(self):
1921 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001922 def empty_seq(self):
1923 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001924 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001925 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001926 def complex_num(self):
1927 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001928 def stop(self):
1929 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001930 def return_true(self, thing=None):
1931 return True
1932 def do_isinstance(obj):
1933 return isinstance(int, obj)
1934 def do_issubclass(obj):
1935 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001936 def do_dict_missing(checker):
1937 class DictSub(checker.__class__, dict):
1938 pass
1939 self.assertEqual(DictSub()["hi"], 4)
1940 def some_number(self_, key):
1941 self.assertEqual(key, "hi")
1942 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001943 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001944 def format_impl(self, spec):
1945 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001946
1947 # It would be nice to have every special method tested here, but I'm
1948 # only listing the ones I can remember outside of typeobject.c, since it
1949 # does it right.
1950 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001951 ("__bytes__", bytes, hello, set(), {}),
1952 ("__reversed__", reversed, empty_seq, set(), {}),
1953 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001954 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001955 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1956 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001957 ("__missing__", do_dict_missing, some_number,
1958 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001959 ("__subclasscheck__", do_issubclass, return_true,
1960 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001961 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1962 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001963 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001964 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001965 ("__floor__", math.floor, zero, set(), {}),
1966 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001967 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001968 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001969 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001970 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001971 ]
1972
1973 class Checker(object):
1974 def __getattr__(self, attr, test=self):
1975 test.fail("__getattr__ called with {0}".format(attr))
1976 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001977 if attr not in ok:
1978 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001979 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001980 class SpecialDescr(object):
1981 def __init__(self, impl):
1982 self.impl = impl
1983 def __get__(self, obj, owner):
1984 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001985 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001986 class MyException(Exception):
1987 pass
1988 class ErrDescr(object):
1989 def __get__(self, obj, owner):
1990 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001991
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001992 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001993 class X(Checker):
1994 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001995 for attr, obj in env.items():
1996 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001997 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001998 runner(X())
1999
2000 record = []
2001 class X(Checker):
2002 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002003 for attr, obj in env.items():
2004 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002005 setattr(X, name, SpecialDescr(meth_impl))
2006 runner(X())
2007 self.assertEqual(record, [1], name)
2008
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002009 class X(Checker):
2010 pass
2011 for attr, obj in env.items():
2012 setattr(X, attr, obj)
2013 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002014 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002015
Georg Brandl479a7e72008-02-05 18:13:15 +00002016 def test_specials(self):
2017 # Testing special operators...
2018 # Test operators like __hash__ for which a built-in default exists
2019
2020 # Test the default behavior for static classes
2021 class C(object):
2022 def __getitem__(self, i):
2023 if 0 <= i < 10: return i
2024 raise IndexError
2025 c1 = C()
2026 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002027 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002028 self.assertNotEqual(id(c1), id(c2))
2029 hash(c1)
2030 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002031 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002032 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002033 self.assertFalse(c1 != c1)
2034 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002035 # Note that the module name appears in str/repr, and that varies
2036 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002037 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002038 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002039 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002040 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002041 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002042 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002043 # Test the default behavior for dynamic classes
2044 class D(object):
2045 def __getitem__(self, i):
2046 if 0 <= i < 10: return i
2047 raise IndexError
2048 d1 = D()
2049 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002050 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002051 self.assertNotEqual(id(d1), id(d2))
2052 hash(d1)
2053 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002054 self.assertEqual(d1, d1)
2055 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002056 self.assertFalse(d1 != d1)
2057 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002058 # Note that the module name appears in str/repr, and that varies
2059 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002060 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002061 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002062 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002063 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002064 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002065 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002066 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002067 class Proxy(object):
2068 def __init__(self, x):
2069 self.x = x
2070 def __bool__(self):
2071 return not not self.x
2072 def __hash__(self):
2073 return hash(self.x)
2074 def __eq__(self, other):
2075 return self.x == other
2076 def __ne__(self, other):
2077 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002078 def __ge__(self, other):
2079 return self.x >= other
2080 def __gt__(self, other):
2081 return self.x > other
2082 def __le__(self, other):
2083 return self.x <= other
2084 def __lt__(self, other):
2085 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002086 def __str__(self):
2087 return "Proxy:%s" % self.x
2088 def __repr__(self):
2089 return "Proxy(%r)" % self.x
2090 def __contains__(self, value):
2091 return value in self.x
2092 p0 = Proxy(0)
2093 p1 = Proxy(1)
2094 p_1 = Proxy(-1)
2095 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002096 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002097 self.assertEqual(hash(p0), hash(0))
2098 self.assertEqual(p0, p0)
2099 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002100 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002101 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002102 self.assertTrue(p0 < p1)
2103 self.assertTrue(p0 <= p1)
2104 self.assertTrue(p1 > p0)
2105 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002106 self.assertEqual(str(p0), "Proxy:0")
2107 self.assertEqual(repr(p0), "Proxy(0)")
2108 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002109 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002110 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002111 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002112 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002113
Georg Brandl479a7e72008-02-05 18:13:15 +00002114 def test_weakrefs(self):
2115 # Testing weak references...
2116 import weakref
2117 class C(object):
2118 pass
2119 c = C()
2120 r = weakref.ref(c)
2121 self.assertEqual(r(), c)
2122 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002123 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002124 self.assertEqual(r(), None)
2125 del r
2126 class NoWeak(object):
2127 __slots__ = ['foo']
2128 no = NoWeak()
2129 try:
2130 weakref.ref(no)
2131 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002132 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002133 else:
2134 self.fail("weakref.ref(no) should be illegal")
2135 class Weak(object):
2136 __slots__ = ['foo', '__weakref__']
2137 yes = Weak()
2138 r = weakref.ref(yes)
2139 self.assertEqual(r(), yes)
2140 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002141 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002142 self.assertEqual(r(), None)
2143 del r
2144
2145 def test_properties(self):
2146 # Testing property...
2147 class C(object):
2148 def getx(self):
2149 return self.__x
2150 def setx(self, value):
2151 self.__x = value
2152 def delx(self):
2153 del self.__x
2154 x = property(getx, setx, delx, doc="I'm the x property.")
2155 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002156 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002157 a.x = 42
2158 self.assertEqual(a._C__x, 42)
2159 self.assertEqual(a.x, 42)
2160 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002161 self.assertNotHasAttr(a, "x")
2162 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002163 C.x.__set__(a, 100)
2164 self.assertEqual(C.x.__get__(a), 100)
2165 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002166 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002167
2168 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002169 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002170
2171 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002172 self.assertIn("__doc__", attrs)
2173 self.assertIn("fget", attrs)
2174 self.assertIn("fset", attrs)
2175 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002176
2177 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002178 self.assertIs(raw.fget, C.__dict__['getx'])
2179 self.assertIs(raw.fset, C.__dict__['setx'])
2180 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002181
Raymond Hettingereac503a2015-05-13 01:09:59 -07002182 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002183 try:
2184 setattr(raw, attr, 42)
2185 except AttributeError as msg:
2186 if str(msg).find('readonly') < 0:
2187 self.fail("when setting readonly attr %r on a property, "
2188 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2189 else:
2190 self.fail("expected AttributeError from trying to set readonly %r "
2191 "attr on a property" % attr)
2192
Raymond Hettingereac503a2015-05-13 01:09:59 -07002193 raw.__doc__ = 42
2194 self.assertEqual(raw.__doc__, 42)
2195
Georg Brandl479a7e72008-02-05 18:13:15 +00002196 class D(object):
2197 __getitem__ = property(lambda s: 1/0)
2198
2199 d = D()
2200 try:
2201 for i in d:
2202 str(i)
2203 except ZeroDivisionError:
2204 pass
2205 else:
2206 self.fail("expected ZeroDivisionError from bad property")
2207
R. David Murray378c0cf2010-02-24 01:46:21 +00002208 @unittest.skipIf(sys.flags.optimize >= 2,
2209 "Docstrings are omitted with -O2 and above")
2210 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002211 class E(object):
2212 def getter(self):
2213 "getter method"
2214 return 0
2215 def setter(self_, value):
2216 "setter method"
2217 pass
2218 prop = property(getter)
2219 self.assertEqual(prop.__doc__, "getter method")
2220 prop2 = property(fset=setter)
2221 self.assertEqual(prop2.__doc__, None)
2222
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002223 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002224 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002225 # this segfaulted in 2.5b2
2226 try:
2227 import _testcapi
2228 except ImportError:
2229 pass
2230 else:
2231 class X(object):
2232 p = property(_testcapi.test_with_docstring)
2233
2234 def test_properties_plus(self):
2235 class C(object):
2236 foo = property(doc="hello")
2237 @foo.getter
2238 def foo(self):
2239 return self._foo
2240 @foo.setter
2241 def foo(self, value):
2242 self._foo = abs(value)
2243 @foo.deleter
2244 def foo(self):
2245 del self._foo
2246 c = C()
2247 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002248 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002249 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002250 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002251 self.assertEqual(c._foo, 42)
2252 self.assertEqual(c.foo, 42)
2253 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002254 self.assertNotHasAttr(c, '_foo')
2255 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002256
2257 class D(C):
2258 @C.foo.deleter
2259 def foo(self):
2260 try:
2261 del self._foo
2262 except AttributeError:
2263 pass
2264 d = D()
2265 d.foo = 24
2266 self.assertEqual(d.foo, 24)
2267 del d.foo
2268 del d.foo
2269
2270 class E(object):
2271 @property
2272 def foo(self):
2273 return self._foo
2274 @foo.setter
2275 def foo(self, value):
2276 raise RuntimeError
2277 @foo.setter
2278 def foo(self, value):
2279 self._foo = abs(value)
2280 @foo.deleter
2281 def foo(self, value=None):
2282 del self._foo
2283
2284 e = E()
2285 e.foo = -42
2286 self.assertEqual(e.foo, 42)
2287 del e.foo
2288
2289 class F(E):
2290 @E.foo.deleter
2291 def foo(self):
2292 del self._foo
2293 @foo.setter
2294 def foo(self, value):
2295 self._foo = max(0, value)
2296 f = F()
2297 f.foo = -10
2298 self.assertEqual(f.foo, 0)
2299 del f.foo
2300
2301 def test_dict_constructors(self):
2302 # Testing dict constructor ...
2303 d = dict()
2304 self.assertEqual(d, {})
2305 d = dict({})
2306 self.assertEqual(d, {})
2307 d = dict({1: 2, 'a': 'b'})
2308 self.assertEqual(d, {1: 2, 'a': 'b'})
2309 self.assertEqual(d, dict(list(d.items())))
2310 self.assertEqual(d, dict(iter(d.items())))
2311 d = dict({'one':1, 'two':2})
2312 self.assertEqual(d, dict(one=1, two=2))
2313 self.assertEqual(d, dict(**d))
2314 self.assertEqual(d, dict({"one": 1}, two=2))
2315 self.assertEqual(d, dict([("two", 2)], one=1))
2316 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2317 self.assertEqual(d, dict(**d))
2318
2319 for badarg in 0, 0, 0j, "0", [0], (0,):
2320 try:
2321 dict(badarg)
2322 except TypeError:
2323 pass
2324 except ValueError:
2325 if badarg == "0":
2326 # It's a sequence, and its elements are also sequences (gotta
2327 # love strings <wink>), but they aren't of length 2, so this
2328 # one seemed better as a ValueError than a TypeError.
2329 pass
2330 else:
2331 self.fail("no TypeError from dict(%r)" % badarg)
2332 else:
2333 self.fail("no TypeError from dict(%r)" % badarg)
2334
2335 try:
2336 dict({}, {})
2337 except TypeError:
2338 pass
2339 else:
2340 self.fail("no TypeError from dict({}, {})")
2341
2342 class Mapping:
2343 # Lacks a .keys() method; will be added later.
2344 dict = {1:2, 3:4, 'a':1j}
2345
2346 try:
2347 dict(Mapping())
2348 except TypeError:
2349 pass
2350 else:
2351 self.fail("no TypeError from dict(incomplete mapping)")
2352
2353 Mapping.keys = lambda self: list(self.dict.keys())
2354 Mapping.__getitem__ = lambda self, i: self.dict[i]
2355 d = dict(Mapping())
2356 self.assertEqual(d, Mapping.dict)
2357
2358 # Init from sequence of iterable objects, each producing a 2-sequence.
2359 class AddressBookEntry:
2360 def __init__(self, first, last):
2361 self.first = first
2362 self.last = last
2363 def __iter__(self):
2364 return iter([self.first, self.last])
2365
2366 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2367 AddressBookEntry('Barry', 'Peters'),
2368 AddressBookEntry('Tim', 'Peters'),
2369 AddressBookEntry('Barry', 'Warsaw')])
2370 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2371
2372 d = dict(zip(range(4), range(1, 5)))
2373 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2374
2375 # Bad sequence lengths.
2376 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2377 try:
2378 dict(bad)
2379 except ValueError:
2380 pass
2381 else:
2382 self.fail("no ValueError from dict(%r)" % bad)
2383
2384 def test_dir(self):
2385 # Testing dir() ...
2386 junk = 12
2387 self.assertEqual(dir(), ['junk', 'self'])
2388 del junk
2389
2390 # Just make sure these don't blow up!
2391 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2392 dir(arg)
2393
2394 # Test dir on new-style classes. Since these have object as a
2395 # base class, a lot more gets sucked in.
2396 def interesting(strings):
2397 return [s for s in strings if not s.startswith('_')]
2398
2399 class C(object):
2400 Cdata = 1
2401 def Cmethod(self): pass
2402
2403 cstuff = ['Cdata', 'Cmethod']
2404 self.assertEqual(interesting(dir(C)), cstuff)
2405
2406 c = C()
2407 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002408 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002409
2410 c.cdata = 2
2411 c.cmethod = lambda self: 0
2412 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002413 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002414
2415 class A(C):
2416 Adata = 1
2417 def Amethod(self): pass
2418
2419 astuff = ['Adata', 'Amethod'] + cstuff
2420 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002421 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002422 a = A()
2423 self.assertEqual(interesting(dir(a)), astuff)
2424 a.adata = 42
2425 a.amethod = lambda self: 3
2426 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002427 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002428
2429 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002430 class M(type(sys)):
2431 pass
2432 minstance = M("m")
2433 minstance.b = 2
2434 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002435 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002436 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002437 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002438 self.assertEqual(names, ['a', 'b'])
2439
2440 class M2(M):
2441 def getdict(self):
2442 return "Not a dict!"
2443 __dict__ = property(getdict)
2444
2445 m2instance = M2("m2")
2446 m2instance.b = 2
2447 m2instance.a = 1
2448 self.assertEqual(m2instance.__dict__, "Not a dict!")
2449 try:
2450 dir(m2instance)
2451 except TypeError:
2452 pass
2453
2454 # Two essentially featureless objects, just inheriting stuff from
2455 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002456 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002457
2458 # Nasty test case for proxied objects
2459 class Wrapper(object):
2460 def __init__(self, obj):
2461 self.__obj = obj
2462 def __repr__(self):
2463 return "Wrapper(%s)" % repr(self.__obj)
2464 def __getitem__(self, key):
2465 return Wrapper(self.__obj[key])
2466 def __len__(self):
2467 return len(self.__obj)
2468 def __getattr__(self, name):
2469 return Wrapper(getattr(self.__obj, name))
2470
2471 class C(object):
2472 def __getclass(self):
2473 return Wrapper(type(self))
2474 __class__ = property(__getclass)
2475
2476 dir(C()) # This used to segfault
2477
2478 def test_supers(self):
2479 # Testing super...
2480
2481 class A(object):
2482 def meth(self, a):
2483 return "A(%r)" % a
2484
2485 self.assertEqual(A().meth(1), "A(1)")
2486
2487 class B(A):
2488 def __init__(self):
2489 self.__super = super(B, self)
2490 def meth(self, a):
2491 return "B(%r)" % a + self.__super.meth(a)
2492
2493 self.assertEqual(B().meth(2), "B(2)A(2)")
2494
2495 class C(A):
2496 def meth(self, a):
2497 return "C(%r)" % a + self.__super.meth(a)
2498 C._C__super = super(C)
2499
2500 self.assertEqual(C().meth(3), "C(3)A(3)")
2501
2502 class D(C, B):
2503 def meth(self, a):
2504 return "D(%r)" % a + super(D, self).meth(a)
2505
2506 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2507
2508 # Test for subclassing super
2509
2510 class mysuper(super):
2511 def __init__(self, *args):
2512 return super(mysuper, self).__init__(*args)
2513
2514 class E(D):
2515 def meth(self, a):
2516 return "E(%r)" % a + mysuper(E, self).meth(a)
2517
2518 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2519
2520 class F(E):
2521 def meth(self, a):
2522 s = self.__super # == mysuper(F, self)
2523 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2524 F._F__super = mysuper(F)
2525
2526 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2527
2528 # Make sure certain errors are raised
2529
2530 try:
2531 super(D, 42)
2532 except TypeError:
2533 pass
2534 else:
2535 self.fail("shouldn't allow super(D, 42)")
2536
2537 try:
2538 super(D, C())
2539 except TypeError:
2540 pass
2541 else:
2542 self.fail("shouldn't allow super(D, C())")
2543
2544 try:
2545 super(D).__get__(12)
2546 except TypeError:
2547 pass
2548 else:
2549 self.fail("shouldn't allow super(D).__get__(12)")
2550
2551 try:
2552 super(D).__get__(C())
2553 except TypeError:
2554 pass
2555 else:
2556 self.fail("shouldn't allow super(D).__get__(C())")
2557
2558 # Make sure data descriptors can be overridden and accessed via super
2559 # (new feature in Python 2.3)
2560
2561 class DDbase(object):
2562 def getx(self): return 42
2563 x = property(getx)
2564
2565 class DDsub(DDbase):
2566 def getx(self): return "hello"
2567 x = property(getx)
2568
2569 dd = DDsub()
2570 self.assertEqual(dd.x, "hello")
2571 self.assertEqual(super(DDsub, dd).x, 42)
2572
2573 # Ensure that super() lookup of descriptor from classmethod
2574 # works (SF ID# 743627)
2575
2576 class Base(object):
2577 aProp = property(lambda self: "foo")
2578
2579 class Sub(Base):
2580 @classmethod
2581 def test(klass):
2582 return super(Sub,klass).aProp
2583
2584 self.assertEqual(Sub.test(), Base.aProp)
2585
2586 # Verify that super() doesn't allow keyword args
2587 try:
2588 super(Base, kw=1)
2589 except TypeError:
2590 pass
2591 else:
2592 self.assertEqual("super shouldn't accept keyword args")
2593
2594 def test_basic_inheritance(self):
2595 # Testing inheritance from basic types...
2596
2597 class hexint(int):
2598 def __repr__(self):
2599 return hex(self)
2600 def __add__(self, other):
2601 return hexint(int.__add__(self, other))
2602 # (Note that overriding __radd__ doesn't work,
2603 # because the int type gets first dibs.)
2604 self.assertEqual(repr(hexint(7) + 9), "0x10")
2605 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2606 a = hexint(12345)
2607 self.assertEqual(a, 12345)
2608 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002609 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002610 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002611 self.assertIs((+a).__class__, int)
2612 self.assertIs((a >> 0).__class__, int)
2613 self.assertIs((a << 0).__class__, int)
2614 self.assertIs((hexint(0) << 12).__class__, int)
2615 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002616
2617 class octlong(int):
2618 __slots__ = []
2619 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002620 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 def __add__(self, other):
2622 return self.__class__(super(octlong, self).__add__(other))
2623 __radd__ = __add__
2624 self.assertEqual(str(octlong(3) + 5), "0o10")
2625 # (Note that overriding __radd__ here only seems to work
2626 # because the example uses a short int left argument.)
2627 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2628 a = octlong(12345)
2629 self.assertEqual(a, 12345)
2630 self.assertEqual(int(a), 12345)
2631 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002632 self.assertIs(int(a).__class__, int)
2633 self.assertIs((+a).__class__, int)
2634 self.assertIs((-a).__class__, int)
2635 self.assertIs((-octlong(0)).__class__, int)
2636 self.assertIs((a >> 0).__class__, int)
2637 self.assertIs((a << 0).__class__, int)
2638 self.assertIs((a - 0).__class__, int)
2639 self.assertIs((a * 1).__class__, int)
2640 self.assertIs((a ** 1).__class__, int)
2641 self.assertIs((a // 1).__class__, int)
2642 self.assertIs((1 * a).__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((octlong(0) << 12).__class__, int)
2647 self.assertIs((octlong(0) >> 12).__class__, int)
2648 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002649
2650 # Because octlong overrides __add__, we can't check the absence of +0
2651 # optimizations using octlong.
2652 class longclone(int):
2653 pass
2654 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002655 self.assertIs((a + 0).__class__, int)
2656 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002657
2658 # Check that negative clones don't segfault
2659 a = longclone(-1)
2660 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002661 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002662
2663 class precfloat(float):
2664 __slots__ = ['prec']
2665 def __init__(self, value=0.0, prec=12):
2666 self.prec = int(prec)
2667 def __repr__(self):
2668 return "%.*g" % (self.prec, self)
2669 self.assertEqual(repr(precfloat(1.1)), "1.1")
2670 a = precfloat(12345)
2671 self.assertEqual(a, 12345.0)
2672 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002673 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002674 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002675 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002676
2677 class madcomplex(complex):
2678 def __repr__(self):
2679 return "%.17gj%+.17g" % (self.imag, self.real)
2680 a = madcomplex(-3, 4)
2681 self.assertEqual(repr(a), "4j-3")
2682 base = complex(-3, 4)
2683 self.assertEqual(base.__class__, complex)
2684 self.assertEqual(a, base)
2685 self.assertEqual(complex(a), base)
2686 self.assertEqual(complex(a).__class__, complex)
2687 a = madcomplex(a) # just trying another form of the constructor
2688 self.assertEqual(repr(a), "4j-3")
2689 self.assertEqual(a, base)
2690 self.assertEqual(complex(a), base)
2691 self.assertEqual(complex(a).__class__, complex)
2692 self.assertEqual(hash(a), hash(base))
2693 self.assertEqual((+a).__class__, complex)
2694 self.assertEqual((a + 0).__class__, complex)
2695 self.assertEqual(a + 0, base)
2696 self.assertEqual((a - 0).__class__, complex)
2697 self.assertEqual(a - 0, base)
2698 self.assertEqual((a * 1).__class__, complex)
2699 self.assertEqual(a * 1, base)
2700 self.assertEqual((a / 1).__class__, complex)
2701 self.assertEqual(a / 1, base)
2702
2703 class madtuple(tuple):
2704 _rev = None
2705 def rev(self):
2706 if self._rev is not None:
2707 return self._rev
2708 L = list(self)
2709 L.reverse()
2710 self._rev = self.__class__(L)
2711 return self._rev
2712 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2713 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2714 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2715 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2716 for i in range(512):
2717 t = madtuple(range(i))
2718 u = t.rev()
2719 v = u.rev()
2720 self.assertEqual(v, t)
2721 a = madtuple((1,2,3,4,5))
2722 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002723 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002724 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002725 self.assertIs(a[:].__class__, tuple)
2726 self.assertIs((a * 1).__class__, tuple)
2727 self.assertIs((a * 0).__class__, tuple)
2728 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002729 a = madtuple(())
2730 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002731 self.assertIs(tuple(a).__class__, tuple)
2732 self.assertIs((a + a).__class__, tuple)
2733 self.assertIs((a * 0).__class__, tuple)
2734 self.assertIs((a * 1).__class__, tuple)
2735 self.assertIs((a * 2).__class__, tuple)
2736 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002737
2738 class madstring(str):
2739 _rev = None
2740 def rev(self):
2741 if self._rev is not None:
2742 return self._rev
2743 L = list(self)
2744 L.reverse()
2745 self._rev = self.__class__("".join(L))
2746 return self._rev
2747 s = madstring("abcdefghijklmnopqrstuvwxyz")
2748 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2749 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2750 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2751 for i in range(256):
2752 s = madstring("".join(map(chr, range(i))))
2753 t = s.rev()
2754 u = t.rev()
2755 self.assertEqual(u, s)
2756 s = madstring("12345")
2757 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002758 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002759
2760 base = "\x00" * 5
2761 s = madstring(base)
2762 self.assertEqual(s, base)
2763 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002764 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002765 self.assertEqual(hash(s), hash(base))
2766 self.assertEqual({s: 1}[base], 1)
2767 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002768 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002769 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002770 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002771 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002772 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002773 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002774 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002775 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002776 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002777 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002778 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002779 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002780 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002781 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002782 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002783 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002784 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002785 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002786 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002787 self.assertEqual(s.rstrip(), base)
2788 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002789 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002790 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002791 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002792 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002793 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002794 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002795 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002796 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002797 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002798 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002799 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002800 self.assertEqual(s.lower(), base)
2801
2802 class madunicode(str):
2803 _rev = None
2804 def rev(self):
2805 if self._rev is not None:
2806 return self._rev
2807 L = list(self)
2808 L.reverse()
2809 self._rev = self.__class__("".join(L))
2810 return self._rev
2811 u = madunicode("ABCDEF")
2812 self.assertEqual(u, "ABCDEF")
2813 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2814 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2815 base = "12345"
2816 u = madunicode(base)
2817 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002818 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002819 self.assertEqual(hash(u), hash(base))
2820 self.assertEqual({u: 1}[base], 1)
2821 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002822 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002823 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002824 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002825 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002826 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002827 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002828 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002829 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002830 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002831 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002832 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002833 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002834 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002835 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002836 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002837 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002838 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002839 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002840 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002841 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002842 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002843 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002844 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002845 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002846 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002847 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002848 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002849 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002850 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002851 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002852 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002853 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002854 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002855 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002856 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002857 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002858 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002859 self.assertEqual(u[0:0], "")
2860
2861 class sublist(list):
2862 pass
2863 a = sublist(range(5))
2864 self.assertEqual(a, list(range(5)))
2865 a.append("hello")
2866 self.assertEqual(a, list(range(5)) + ["hello"])
2867 a[5] = 5
2868 self.assertEqual(a, list(range(6)))
2869 a.extend(range(6, 20))
2870 self.assertEqual(a, list(range(20)))
2871 a[-5:] = []
2872 self.assertEqual(a, list(range(15)))
2873 del a[10:15]
2874 self.assertEqual(len(a), 10)
2875 self.assertEqual(a, list(range(10)))
2876 self.assertEqual(list(a), list(range(10)))
2877 self.assertEqual(a[0], 0)
2878 self.assertEqual(a[9], 9)
2879 self.assertEqual(a[-10], 0)
2880 self.assertEqual(a[-1], 9)
2881 self.assertEqual(a[:5], list(range(5)))
2882
2883 ## class CountedInput(file):
2884 ## """Counts lines read by self.readline().
2885 ##
2886 ## self.lineno is the 0-based ordinal of the last line read, up to
2887 ## a maximum of one greater than the number of lines in the file.
2888 ##
2889 ## self.ateof is true if and only if the final "" line has been read,
2890 ## at which point self.lineno stops incrementing, and further calls
2891 ## to readline() continue to return "".
2892 ## """
2893 ##
2894 ## lineno = 0
2895 ## ateof = 0
2896 ## def readline(self):
2897 ## if self.ateof:
2898 ## return ""
2899 ## s = file.readline(self)
2900 ## # Next line works too.
2901 ## # s = super(CountedInput, self).readline()
2902 ## self.lineno += 1
2903 ## if s == "":
2904 ## self.ateof = 1
2905 ## return s
2906 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002907 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 ## lines = ['a\n', 'b\n', 'c\n']
2909 ## try:
2910 ## f.writelines(lines)
2911 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002912 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002913 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2914 ## got = f.readline()
2915 ## self.assertEqual(expected, got)
2916 ## self.assertEqual(f.lineno, i)
2917 ## self.assertEqual(f.ateof, (i > len(lines)))
2918 ## f.close()
2919 ## finally:
2920 ## try:
2921 ## f.close()
2922 ## except:
2923 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002924 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002925
2926 def test_keywords(self):
2927 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002928 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2929 int(x=1)
2930 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2931 float(x=2)
2932 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2933 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002934 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2935 self.assertEqual(str(object=500), '500')
2936 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002937 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2938 tuple(sequence=range(3))
2939 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2940 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00002941 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2942
2943 for constructor in (int, float, int, complex, str, str,
2944 tuple, list):
2945 try:
2946 constructor(bogus_keyword_arg=1)
2947 except TypeError:
2948 pass
2949 else:
2950 self.fail("expected TypeError from bogus keyword argument to %r"
2951 % constructor)
2952
2953 def test_str_subclass_as_dict_key(self):
2954 # Testing a str subclass used as dict key ..
2955
2956 class cistr(str):
2957 """Sublcass of str that computes __eq__ case-insensitively.
2958
2959 Also computes a hash code of the string in canonical form.
2960 """
2961
2962 def __init__(self, value):
2963 self.canonical = value.lower()
2964 self.hashcode = hash(self.canonical)
2965
2966 def __eq__(self, other):
2967 if not isinstance(other, cistr):
2968 other = cistr(other)
2969 return self.canonical == other.canonical
2970
2971 def __hash__(self):
2972 return self.hashcode
2973
2974 self.assertEqual(cistr('ABC'), 'abc')
2975 self.assertEqual('aBc', cistr('ABC'))
2976 self.assertEqual(str(cistr('ABC')), 'ABC')
2977
2978 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2979 self.assertEqual(d[cistr('one')], 1)
2980 self.assertEqual(d[cistr('tWo')], 2)
2981 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002982 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002983 self.assertEqual(d.get(cistr('thrEE')), 3)
2984
2985 def test_classic_comparisons(self):
2986 # Testing classic comparisons...
2987 class classic:
2988 pass
2989
2990 for base in (classic, int, object):
2991 class C(base):
2992 def __init__(self, value):
2993 self.value = int(value)
2994 def __eq__(self, other):
2995 if isinstance(other, C):
2996 return self.value == other.value
2997 if isinstance(other, int) or isinstance(other, int):
2998 return self.value == other
2999 return NotImplemented
3000 def __ne__(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 __lt__(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 __le__(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 __gt__(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 __ge__(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
3031 c1 = C(1)
3032 c2 = C(2)
3033 c3 = C(3)
3034 self.assertEqual(c1, 1)
3035 c = {1: c1, 2: c2, 3: c3}
3036 for x in 1, 2, 3:
3037 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003038 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003039 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003040 eval("x %s y" % op),
3041 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003042 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003043 eval("x %s y" % op),
3044 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003045 self.assertEqual(eval("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))
Georg Brandl479a7e72008-02-05 18:13:15 +00003048
3049 def test_rich_comparisons(self):
3050 # Testing rich comparisons...
3051 class Z(complex):
3052 pass
3053 z = Z(1)
3054 self.assertEqual(z, 1+0j)
3055 self.assertEqual(1+0j, z)
3056 class ZZ(complex):
3057 def __eq__(self, other):
3058 try:
3059 return abs(self - other) <= 1e-6
3060 except:
3061 return NotImplemented
3062 zz = ZZ(1.0000003)
3063 self.assertEqual(zz, 1+0j)
3064 self.assertEqual(1+0j, zz)
3065
3066 class classic:
3067 pass
3068 for base in (classic, int, object, list):
3069 class C(base):
3070 def __init__(self, value):
3071 self.value = int(value)
3072 def __cmp__(self_, other):
3073 self.fail("shouldn't call __cmp__")
3074 def __eq__(self, other):
3075 if isinstance(other, C):
3076 return self.value == other.value
3077 if isinstance(other, int) or isinstance(other, int):
3078 return self.value == other
3079 return NotImplemented
3080 def __ne__(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 __lt__(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 __le__(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 __gt__(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 __ge__(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 c1 = C(1)
3111 c2 = C(2)
3112 c3 = C(3)
3113 self.assertEqual(c1, 1)
3114 c = {1: c1, 2: c2, 3: c3}
3115 for x in 1, 2, 3:
3116 for y in 1, 2, 3:
3117 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003118 self.assertEqual(eval("c[x] %s c[y]" % op),
3119 eval("x %s y" % op),
3120 "x=%d, y=%d" % (x, y))
3121 self.assertEqual(eval("c[x] %s y" % op),
3122 eval("x %s y" % op),
3123 "x=%d, y=%d" % (x, y))
3124 self.assertEqual(eval("x %s c[y]" % op),
3125 eval("x %s y" % op),
3126 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003127
3128 def test_descrdoc(self):
3129 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003130 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003131 def check(descr, what):
3132 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003133 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003134 check(complex.real, "the real part of a complex number") # member descriptor
3135
3136 def test_doc_descriptor(self):
3137 # Testing __doc__ descriptor...
3138 # SF bug 542984
3139 class DocDescr(object):
3140 def __get__(self, object, otype):
3141 if object:
3142 object = object.__class__.__name__ + ' instance'
3143 if otype:
3144 otype = otype.__name__
3145 return 'object=%s; type=%s' % (object, otype)
3146 class OldClass:
3147 __doc__ = DocDescr()
3148 class NewClass(object):
3149 __doc__ = DocDescr()
3150 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3151 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3152 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3153 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3154
3155 def test_set_class(self):
3156 # Testing __class__ assignment...
3157 class C(object): pass
3158 class D(object): pass
3159 class E(object): pass
3160 class F(D, E): pass
3161 for cls in C, D, E, F:
3162 for cls2 in C, D, E, F:
3163 x = cls()
3164 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003165 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003166 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003167 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003168 def cant(x, C):
3169 try:
3170 x.__class__ = C
3171 except TypeError:
3172 pass
3173 else:
3174 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3175 try:
3176 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003177 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003178 pass
3179 else:
3180 self.fail("shouldn't allow del %r.__class__" % x)
3181 cant(C(), list)
3182 cant(list(), C)
3183 cant(C(), 1)
3184 cant(C(), object)
3185 cant(object(), list)
3186 cant(list(), object)
3187 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003188 cant(True, int)
3189 cant(2, bool)
3190 o = object()
3191 cant(o, type(1))
3192 cant(o, type(None))
3193 del o
3194 class G(object):
3195 __slots__ = ["a", "b"]
3196 class H(object):
3197 __slots__ = ["b", "a"]
3198 class I(object):
3199 __slots__ = ["a", "b"]
3200 class J(object):
3201 __slots__ = ["c", "b"]
3202 class K(object):
3203 __slots__ = ["a", "b", "d"]
3204 class L(H):
3205 __slots__ = ["e"]
3206 class M(I):
3207 __slots__ = ["e"]
3208 class N(J):
3209 __slots__ = ["__weakref__"]
3210 class P(J):
3211 __slots__ = ["__dict__"]
3212 class Q(J):
3213 pass
3214 class R(J):
3215 __slots__ = ["__dict__", "__weakref__"]
3216
3217 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3218 x = cls()
3219 x.a = 1
3220 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003221 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003222 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3223 self.assertEqual(x.a, 1)
3224 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003225 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003226 "assigning %r as __class__ for %r silently failed" % (cls, x))
3227 self.assertEqual(x.a, 1)
3228 for cls in G, J, K, L, M, N, P, R, list, Int:
3229 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3230 if cls is cls2:
3231 continue
3232 cant(cls(), cls2)
3233
Benjamin Peterson193152c2009-04-25 01:08:45 +00003234 # Issue5283: when __class__ changes in __del__, the wrong
3235 # type gets DECREF'd.
3236 class O(object):
3237 pass
3238 class A(object):
3239 def __del__(self):
3240 self.__class__ = O
3241 l = [A() for x in range(100)]
3242 del l
3243
Georg Brandl479a7e72008-02-05 18:13:15 +00003244 def test_set_dict(self):
3245 # Testing __dict__ assignment...
3246 class C(object): pass
3247 a = C()
3248 a.__dict__ = {'b': 1}
3249 self.assertEqual(a.b, 1)
3250 def cant(x, dict):
3251 try:
3252 x.__dict__ = dict
3253 except (AttributeError, TypeError):
3254 pass
3255 else:
3256 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3257 cant(a, None)
3258 cant(a, [])
3259 cant(a, 1)
3260 del a.__dict__ # Deleting __dict__ is allowed
3261
3262 class Base(object):
3263 pass
3264 def verify_dict_readonly(x):
3265 """
3266 x has to be an instance of a class inheriting from Base.
3267 """
3268 cant(x, {})
3269 try:
3270 del x.__dict__
3271 except (AttributeError, TypeError):
3272 pass
3273 else:
3274 self.fail("shouldn't allow del %r.__dict__" % x)
3275 dict_descr = Base.__dict__["__dict__"]
3276 try:
3277 dict_descr.__set__(x, {})
3278 except (AttributeError, TypeError):
3279 pass
3280 else:
3281 self.fail("dict_descr allowed access to %r's dict" % x)
3282
3283 # Classes don't allow __dict__ assignment and have readonly dicts
3284 class Meta1(type, Base):
3285 pass
3286 class Meta2(Base, type):
3287 pass
3288 class D(object, metaclass=Meta1):
3289 pass
3290 class E(object, metaclass=Meta2):
3291 pass
3292 for cls in C, D, E:
3293 verify_dict_readonly(cls)
3294 class_dict = cls.__dict__
3295 try:
3296 class_dict["spam"] = "eggs"
3297 except TypeError:
3298 pass
3299 else:
3300 self.fail("%r's __dict__ can be modified" % cls)
3301
3302 # Modules also disallow __dict__ assignment
3303 class Module1(types.ModuleType, Base):
3304 pass
3305 class Module2(Base, types.ModuleType):
3306 pass
3307 for ModuleType in Module1, Module2:
3308 mod = ModuleType("spam")
3309 verify_dict_readonly(mod)
3310 mod.__dict__["spam"] = "eggs"
3311
3312 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003313 # (at least not any more than regular exception's __dict__ can
3314 # be deleted; on CPython it is not the case, whereas on PyPy they
3315 # can, just like any other new-style instance's __dict__.)
3316 def can_delete_dict(e):
3317 try:
3318 del e.__dict__
3319 except (TypeError, AttributeError):
3320 return False
3321 else:
3322 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003323 class Exception1(Exception, Base):
3324 pass
3325 class Exception2(Base, Exception):
3326 pass
3327 for ExceptionType in Exception, Exception1, Exception2:
3328 e = ExceptionType()
3329 e.__dict__ = {"a": 1}
3330 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003331 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003332
Georg Brandl479a7e72008-02-05 18:13:15 +00003333 def test_binary_operator_override(self):
3334 # Testing overrides of binary operations...
3335 class I(int):
3336 def __repr__(self):
3337 return "I(%r)" % int(self)
3338 def __add__(self, other):
3339 return I(int(self) + int(other))
3340 __radd__ = __add__
3341 def __pow__(self, other, mod=None):
3342 if mod is None:
3343 return I(pow(int(self), int(other)))
3344 else:
3345 return I(pow(int(self), int(other), int(mod)))
3346 def __rpow__(self, other, mod=None):
3347 if mod is None:
3348 return I(pow(int(other), int(self), mod))
3349 else:
3350 return I(pow(int(other), int(self), int(mod)))
3351
3352 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3353 self.assertEqual(repr(I(1) + 2), "I(3)")
3354 self.assertEqual(repr(1 + I(2)), "I(3)")
3355 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3356 self.assertEqual(repr(2 ** I(3)), "I(8)")
3357 self.assertEqual(repr(I(2) ** 3), "I(8)")
3358 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3359 class S(str):
3360 def __eq__(self, other):
3361 return self.lower() == other.lower()
3362
3363 def test_subclass_propagation(self):
3364 # Testing propagation of slot functions to subclasses...
3365 class A(object):
3366 pass
3367 class B(A):
3368 pass
3369 class C(A):
3370 pass
3371 class D(B, C):
3372 pass
3373 d = D()
3374 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3375 A.__hash__ = lambda self: 42
3376 self.assertEqual(hash(d), 42)
3377 C.__hash__ = lambda self: 314
3378 self.assertEqual(hash(d), 314)
3379 B.__hash__ = lambda self: 144
3380 self.assertEqual(hash(d), 144)
3381 D.__hash__ = lambda self: 100
3382 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003383 D.__hash__ = None
3384 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003385 del D.__hash__
3386 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003387 B.__hash__ = None
3388 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003389 del B.__hash__
3390 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003391 C.__hash__ = None
3392 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003393 del C.__hash__
3394 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003395 A.__hash__ = None
3396 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003397 del A.__hash__
3398 self.assertEqual(hash(d), orig_hash)
3399 d.foo = 42
3400 d.bar = 42
3401 self.assertEqual(d.foo, 42)
3402 self.assertEqual(d.bar, 42)
3403 def __getattribute__(self, name):
3404 if name == "foo":
3405 return 24
3406 return object.__getattribute__(self, name)
3407 A.__getattribute__ = __getattribute__
3408 self.assertEqual(d.foo, 24)
3409 self.assertEqual(d.bar, 42)
3410 def __getattr__(self, name):
3411 if name in ("spam", "foo", "bar"):
3412 return "hello"
3413 raise AttributeError(name)
3414 B.__getattr__ = __getattr__
3415 self.assertEqual(d.spam, "hello")
3416 self.assertEqual(d.foo, 24)
3417 self.assertEqual(d.bar, 42)
3418 del A.__getattribute__
3419 self.assertEqual(d.foo, 42)
3420 del d.foo
3421 self.assertEqual(d.foo, "hello")
3422 self.assertEqual(d.bar, 42)
3423 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003424 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003425 d.foo
3426 except AttributeError:
3427 pass
3428 else:
3429 self.fail("d.foo should be undefined now")
3430
3431 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003432 class A(object):
3433 pass
3434 class B(A):
3435 pass
3436 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003437 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003438 A.__setitem__ = lambda *a: None # crash
3439
3440 def test_buffer_inheritance(self):
3441 # Testing that buffer interface is inherited ...
3442
3443 import binascii
3444 # SF bug [#470040] ParseTuple t# vs subclasses.
3445
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003446 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003447 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003448 base = b'abc'
3449 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003450 # b2a_hex uses the buffer interface to get its argument's value, via
3451 # PyArg_ParseTuple 't#' code.
3452 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3453
Georg Brandl479a7e72008-02-05 18:13:15 +00003454 class MyInt(int):
3455 pass
3456 m = MyInt(42)
3457 try:
3458 binascii.b2a_hex(m)
3459 self.fail('subclass of int should not have a buffer interface')
3460 except TypeError:
3461 pass
3462
3463 def test_str_of_str_subclass(self):
3464 # Testing __str__ defined in subclass of str ...
3465 import binascii
3466 import io
3467
3468 class octetstring(str):
3469 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003470 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003471 def __repr__(self):
3472 return self + " repr"
3473
3474 o = octetstring('A')
3475 self.assertEqual(type(o), octetstring)
3476 self.assertEqual(type(str(o)), str)
3477 self.assertEqual(type(repr(o)), str)
3478 self.assertEqual(ord(o), 0x41)
3479 self.assertEqual(str(o), '41')
3480 self.assertEqual(repr(o), 'A repr')
3481 self.assertEqual(o.__str__(), '41')
3482 self.assertEqual(o.__repr__(), 'A repr')
3483
3484 capture = io.StringIO()
3485 # Calling str() or not exercises different internal paths.
3486 print(o, file=capture)
3487 print(str(o), file=capture)
3488 self.assertEqual(capture.getvalue(), '41\n41\n')
3489 capture.close()
3490
3491 def test_keyword_arguments(self):
3492 # Testing keyword arguments to __init__, __call__...
3493 def f(a): return a
3494 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003495 ba = bytearray()
3496 bytearray.__init__(ba, 'abc\xbd\u20ac',
3497 encoding='latin1', errors='replace')
3498 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003499
3500 def test_recursive_call(self):
3501 # Testing recursive __call__() by setting to instance of class...
3502 class A(object):
3503 pass
3504
3505 A.__call__ = A()
3506 try:
3507 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003508 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003509 pass
3510 else:
3511 self.fail("Recursion limit should have been reached for __call__()")
3512
3513 def test_delete_hook(self):
3514 # Testing __del__ hook...
3515 log = []
3516 class C(object):
3517 def __del__(self):
3518 log.append(1)
3519 c = C()
3520 self.assertEqual(log, [])
3521 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003522 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003523 self.assertEqual(log, [1])
3524
3525 class D(object): pass
3526 d = D()
3527 try: del d[0]
3528 except TypeError: pass
3529 else: self.fail("invalid del() didn't raise TypeError")
3530
3531 def test_hash_inheritance(self):
3532 # Testing hash of mutable subclasses...
3533
3534 class mydict(dict):
3535 pass
3536 d = mydict()
3537 try:
3538 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003539 except TypeError:
3540 pass
3541 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003542 self.fail("hash() of dict subclass should fail")
3543
3544 class mylist(list):
3545 pass
3546 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003547 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003548 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003549 except TypeError:
3550 pass
3551 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003552 self.fail("hash() of list subclass should fail")
3553
3554 def test_str_operations(self):
3555 try: 'a' + 5
3556 except TypeError: pass
3557 else: self.fail("'' + 5 doesn't raise TypeError")
3558
3559 try: ''.split('')
3560 except ValueError: pass
3561 else: self.fail("''.split('') doesn't raise ValueError")
3562
3563 try: ''.join([0])
3564 except TypeError: pass
3565 else: self.fail("''.join([0]) doesn't raise TypeError")
3566
3567 try: ''.rindex('5')
3568 except ValueError: pass
3569 else: self.fail("''.rindex('5') doesn't raise ValueError")
3570
3571 try: '%(n)s' % None
3572 except TypeError: pass
3573 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3574
3575 try: '%(n' % {}
3576 except ValueError: pass
3577 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3578
3579 try: '%*s' % ('abc')
3580 except TypeError: pass
3581 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3582
3583 try: '%*.*s' % ('abc', 5)
3584 except TypeError: pass
3585 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3586
3587 try: '%s' % (1, 2)
3588 except TypeError: pass
3589 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3590
3591 try: '%' % None
3592 except ValueError: pass
3593 else: self.fail("'%' % None doesn't raise ValueError")
3594
3595 self.assertEqual('534253'.isdigit(), 1)
3596 self.assertEqual('534253x'.isdigit(), 0)
3597 self.assertEqual('%c' % 5, '\x05')
3598 self.assertEqual('%c' % '5', '5')
3599
3600 def test_deepcopy_recursive(self):
3601 # Testing deepcopy of recursive objects...
3602 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003603 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003604 a = Node()
3605 b = Node()
3606 a.b = b
3607 b.a = a
3608 z = deepcopy(a) # This blew up before
3609
Martin Panterf05641642016-05-08 13:48:10 +00003610 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003611 # Testing uninitialized module objects...
3612 from types import ModuleType as M
3613 m = M.__new__(M)
3614 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003615 self.assertNotHasAttr(m, "__name__")
3616 self.assertNotHasAttr(m, "__file__")
3617 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003618 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003619 m.foo = 1
3620 self.assertEqual(m.__dict__, {"foo": 1})
3621
3622 def test_funny_new(self):
3623 # Testing __new__ returning something unexpected...
3624 class C(object):
3625 def __new__(cls, arg):
3626 if isinstance(arg, str): return [1, 2, 3]
3627 elif isinstance(arg, int): return object.__new__(D)
3628 else: return object.__new__(cls)
3629 class D(C):
3630 def __init__(self, arg):
3631 self.foo = arg
3632 self.assertEqual(C("1"), [1, 2, 3])
3633 self.assertEqual(D("1"), [1, 2, 3])
3634 d = D(None)
3635 self.assertEqual(d.foo, None)
3636 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003637 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003638 self.assertEqual(d.foo, 1)
3639 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003640 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003641 self.assertEqual(d.foo, 1)
3642
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003643 class C(object):
3644 @staticmethod
3645 def __new__(*args):
3646 return args
3647 self.assertEqual(C(1, 2), (C, 1, 2))
3648 class D(C):
3649 pass
3650 self.assertEqual(D(1, 2), (D, 1, 2))
3651
3652 class C(object):
3653 @classmethod
3654 def __new__(*args):
3655 return args
3656 self.assertEqual(C(1, 2), (C, C, 1, 2))
3657 class D(C):
3658 pass
3659 self.assertEqual(D(1, 2), (D, D, 1, 2))
3660
Georg Brandl479a7e72008-02-05 18:13:15 +00003661 def test_imul_bug(self):
3662 # Testing for __imul__ problems...
3663 # SF bug 544647
3664 class C(object):
3665 def __imul__(self, other):
3666 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003667 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003668 y = x
3669 y *= 1.0
3670 self.assertEqual(y, (x, 1.0))
3671 y = x
3672 y *= 2
3673 self.assertEqual(y, (x, 2))
3674 y = x
3675 y *= 3
3676 self.assertEqual(y, (x, 3))
3677 y = x
3678 y *= 1<<100
3679 self.assertEqual(y, (x, 1<<100))
3680 y = x
3681 y *= None
3682 self.assertEqual(y, (x, None))
3683 y = x
3684 y *= "foo"
3685 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003686
Georg Brandl479a7e72008-02-05 18:13:15 +00003687 def test_copy_setstate(self):
3688 # Testing that copy.*copy() correctly uses __setstate__...
3689 import copy
3690 class C(object):
3691 def __init__(self, foo=None):
3692 self.foo = foo
3693 self.__foo = foo
3694 def setfoo(self, foo=None):
3695 self.foo = foo
3696 def getfoo(self):
3697 return self.__foo
3698 def __getstate__(self):
3699 return [self.foo]
3700 def __setstate__(self_, lst):
3701 self.assertEqual(len(lst), 1)
3702 self_.__foo = self_.foo = lst[0]
3703 a = C(42)
3704 a.setfoo(24)
3705 self.assertEqual(a.foo, 24)
3706 self.assertEqual(a.getfoo(), 42)
3707 b = copy.copy(a)
3708 self.assertEqual(b.foo, 24)
3709 self.assertEqual(b.getfoo(), 24)
3710 b = copy.deepcopy(a)
3711 self.assertEqual(b.foo, 24)
3712 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003713
Georg Brandl479a7e72008-02-05 18:13:15 +00003714 def test_slices(self):
3715 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003716
Georg Brandl479a7e72008-02-05 18:13:15 +00003717 # Strings
3718 self.assertEqual("hello"[:4], "hell")
3719 self.assertEqual("hello"[slice(4)], "hell")
3720 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3721 class S(str):
3722 def __getitem__(self, x):
3723 return str.__getitem__(self, x)
3724 self.assertEqual(S("hello")[:4], "hell")
3725 self.assertEqual(S("hello")[slice(4)], "hell")
3726 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3727 # Tuples
3728 self.assertEqual((1,2,3)[:2], (1,2))
3729 self.assertEqual((1,2,3)[slice(2)], (1,2))
3730 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3731 class T(tuple):
3732 def __getitem__(self, x):
3733 return tuple.__getitem__(self, x)
3734 self.assertEqual(T((1,2,3))[:2], (1,2))
3735 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3736 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3737 # Lists
3738 self.assertEqual([1,2,3][:2], [1,2])
3739 self.assertEqual([1,2,3][slice(2)], [1,2])
3740 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3741 class L(list):
3742 def __getitem__(self, x):
3743 return list.__getitem__(self, x)
3744 self.assertEqual(L([1,2,3])[:2], [1,2])
3745 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3746 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3747 # Now do lists and __setitem__
3748 a = L([1,2,3])
3749 a[slice(1, 3)] = [3,2]
3750 self.assertEqual(a, [1,3,2])
3751 a[slice(0, 2, 1)] = [3,1]
3752 self.assertEqual(a, [3,1,2])
3753 a.__setitem__(slice(1, 3), [2,1])
3754 self.assertEqual(a, [3,2,1])
3755 a.__setitem__(slice(0, 2, 1), [2,3])
3756 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003757
Georg Brandl479a7e72008-02-05 18:13:15 +00003758 def test_subtype_resurrection(self):
3759 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003760
Georg Brandl479a7e72008-02-05 18:13:15 +00003761 class C(object):
3762 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003763
Georg Brandl479a7e72008-02-05 18:13:15 +00003764 def __del__(self):
3765 # resurrect the instance
3766 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003767
Georg Brandl479a7e72008-02-05 18:13:15 +00003768 c = C()
3769 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003770
Benjamin Petersone549ead2009-03-28 21:42:05 +00003771 # The most interesting thing here is whether this blows up, due to
3772 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3773 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003774 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003775
Benjamin Petersone549ead2009-03-28 21:42:05 +00003776 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003777 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003778
Georg Brandl479a7e72008-02-05 18:13:15 +00003779 # Make c mortal again, so that the test framework with -l doesn't report
3780 # it as a leak.
3781 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003782
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 def test_slots_trash(self):
3784 # Testing slot trash...
3785 # Deallocating deeply nested slotted trash caused stack overflows
3786 class trash(object):
3787 __slots__ = ['x']
3788 def __init__(self, x):
3789 self.x = x
3790 o = None
3791 for i in range(50000):
3792 o = trash(o)
3793 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003794
Georg Brandl479a7e72008-02-05 18:13:15 +00003795 def test_slots_multiple_inheritance(self):
3796 # SF bug 575229, multiple inheritance w/ slots dumps core
3797 class A(object):
3798 __slots__=()
3799 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003800 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003801 class C(A,B) :
3802 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003803 if support.check_impl_detail():
3804 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003805 self.assertHasAttr(C, '__dict__')
3806 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003807 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003808
Georg Brandl479a7e72008-02-05 18:13:15 +00003809 def test_rmul(self):
3810 # Testing correct invocation of __rmul__...
3811 # SF patch 592646
3812 class C(object):
3813 def __mul__(self, other):
3814 return "mul"
3815 def __rmul__(self, other):
3816 return "rmul"
3817 a = C()
3818 self.assertEqual(a*2, "mul")
3819 self.assertEqual(a*2.2, "mul")
3820 self.assertEqual(2*a, "rmul")
3821 self.assertEqual(2.2*a, "rmul")
3822
3823 def test_ipow(self):
3824 # Testing correct invocation of __ipow__...
3825 # [SF bug 620179]
3826 class C(object):
3827 def __ipow__(self, other):
3828 pass
3829 a = C()
3830 a **= 2
3831
3832 def test_mutable_bases(self):
3833 # Testing mutable bases...
3834
3835 # stuff that should work:
3836 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003837 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003838 class C2(object):
3839 def __getattribute__(self, attr):
3840 if attr == 'a':
3841 return 2
3842 else:
3843 return super(C2, self).__getattribute__(attr)
3844 def meth(self):
3845 return 1
3846 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003847 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003848 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003849 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003850 d = D()
3851 e = E()
3852 D.__bases__ = (C,)
3853 D.__bases__ = (C2,)
3854 self.assertEqual(d.meth(), 1)
3855 self.assertEqual(e.meth(), 1)
3856 self.assertEqual(d.a, 2)
3857 self.assertEqual(e.a, 2)
3858 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003859
Georg Brandl479a7e72008-02-05 18:13:15 +00003860 try:
3861 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003862 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003863 pass
3864 else:
3865 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003866
Georg Brandl479a7e72008-02-05 18:13:15 +00003867 try:
3868 D.__bases__ = ()
3869 except TypeError as msg:
3870 if str(msg) == "a new-style class can't have only classic bases":
3871 self.fail("wrong error message for .__bases__ = ()")
3872 else:
3873 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003874
Georg Brandl479a7e72008-02-05 18:13:15 +00003875 try:
3876 D.__bases__ = (D,)
3877 except TypeError:
3878 pass
3879 else:
3880 # actually, we'll have crashed by here...
3881 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003882
Georg Brandl479a7e72008-02-05 18:13:15 +00003883 try:
3884 D.__bases__ = (C, C)
3885 except TypeError:
3886 pass
3887 else:
3888 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003889
Georg Brandl479a7e72008-02-05 18:13:15 +00003890 try:
3891 D.__bases__ = (E,)
3892 except TypeError:
3893 pass
3894 else:
3895 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003896
Benjamin Petersonae937c02009-04-18 20:54:08 +00003897 def test_builtin_bases(self):
3898 # Make sure all the builtin types can have their base queried without
3899 # segfaulting. See issue #5787.
3900 builtin_types = [tp for tp in builtins.__dict__.values()
3901 if isinstance(tp, type)]
3902 for tp in builtin_types:
3903 object.__getattribute__(tp, "__bases__")
3904 if tp is not object:
3905 self.assertEqual(len(tp.__bases__), 1, tp)
3906
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003907 class L(list):
3908 pass
3909
3910 class C(object):
3911 pass
3912
3913 class D(C):
3914 pass
3915
3916 try:
3917 L.__bases__ = (dict,)
3918 except TypeError:
3919 pass
3920 else:
3921 self.fail("shouldn't turn list subclass into dict subclass")
3922
3923 try:
3924 list.__bases__ = (dict,)
3925 except TypeError:
3926 pass
3927 else:
3928 self.fail("shouldn't be able to assign to list.__bases__")
3929
3930 try:
3931 D.__bases__ = (C, list)
3932 except TypeError:
3933 pass
3934 else:
3935 assert 0, "best_base calculation found wanting"
3936
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003937 def test_unsubclassable_types(self):
3938 with self.assertRaises(TypeError):
3939 class X(type(None)):
3940 pass
3941 with self.assertRaises(TypeError):
3942 class X(object, type(None)):
3943 pass
3944 with self.assertRaises(TypeError):
3945 class X(type(None), object):
3946 pass
3947 class O(object):
3948 pass
3949 with self.assertRaises(TypeError):
3950 class X(O, type(None)):
3951 pass
3952 with self.assertRaises(TypeError):
3953 class X(type(None), O):
3954 pass
3955
3956 class X(object):
3957 pass
3958 with self.assertRaises(TypeError):
3959 X.__bases__ = type(None),
3960 with self.assertRaises(TypeError):
3961 X.__bases__ = object, type(None)
3962 with self.assertRaises(TypeError):
3963 X.__bases__ = type(None), object
3964 with self.assertRaises(TypeError):
3965 X.__bases__ = O, type(None)
3966 with self.assertRaises(TypeError):
3967 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00003968
Georg Brandl479a7e72008-02-05 18:13:15 +00003969 def test_mutable_bases_with_failing_mro(self):
3970 # Testing mutable bases with failing mro...
3971 class WorkOnce(type):
3972 def __new__(self, name, bases, ns):
3973 self.flag = 0
3974 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3975 def mro(self):
3976 if self.flag > 0:
3977 raise RuntimeError("bozo")
3978 else:
3979 self.flag += 1
3980 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003981
Georg Brandl479a7e72008-02-05 18:13:15 +00003982 class WorkAlways(type):
3983 def mro(self):
3984 # this is here to make sure that .mro()s aren't called
3985 # with an exception set (which was possible at one point).
3986 # An error message will be printed in a debug build.
3987 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003988 return type.mro(self)
3989
Georg Brandl479a7e72008-02-05 18:13:15 +00003990 class C(object):
3991 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003992
Georg Brandl479a7e72008-02-05 18:13:15 +00003993 class C2(object):
3994 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003995
Georg Brandl479a7e72008-02-05 18:13:15 +00003996 class D(C):
3997 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003998
Georg Brandl479a7e72008-02-05 18:13:15 +00003999 class E(D):
4000 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004001
Georg Brandl479a7e72008-02-05 18:13:15 +00004002 class F(D, metaclass=WorkOnce):
4003 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004004
Georg Brandl479a7e72008-02-05 18:13:15 +00004005 class G(D, metaclass=WorkAlways):
4006 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004007
Georg Brandl479a7e72008-02-05 18:13:15 +00004008 # Immediate subclasses have their mro's adjusted in alphabetical
4009 # order, so E's will get adjusted before adjusting F's fails. We
4010 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004011
Georg Brandl479a7e72008-02-05 18:13:15 +00004012 E_mro_before = E.__mro__
4013 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004014
Armin Rigofd163f92005-12-29 15:59:19 +00004015 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004016 D.__bases__ = (C2,)
4017 except RuntimeError:
4018 self.assertEqual(E.__mro__, E_mro_before)
4019 self.assertEqual(D.__mro__, D_mro_before)
4020 else:
4021 self.fail("exception not propagated")
4022
4023 def test_mutable_bases_catch_mro_conflict(self):
4024 # Testing mutable bases catch mro conflict...
4025 class A(object):
4026 pass
4027
4028 class B(object):
4029 pass
4030
4031 class C(A, B):
4032 pass
4033
4034 class D(A, B):
4035 pass
4036
4037 class E(C, D):
4038 pass
4039
4040 try:
4041 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004042 except TypeError:
4043 pass
4044 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004045 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004046
Georg Brandl479a7e72008-02-05 18:13:15 +00004047 def test_mutable_names(self):
4048 # Testing mutable names...
4049 class C(object):
4050 pass
4051
4052 # C.__module__ could be 'test_descr' or '__main__'
4053 mod = C.__module__
4054
4055 C.__name__ = 'D'
4056 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4057
4058 C.__name__ = 'D.E'
4059 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4060
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004061 def test_evil_type_name(self):
4062 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4063 # execution while the type structure was not in a sane state, and a
4064 # possible segmentation fault as a result. See bug #16447.
4065 class Nasty(str):
4066 def __del__(self):
4067 C.__name__ = "other"
4068
4069 class C:
4070 pass
4071
4072 C.__name__ = Nasty("abc")
4073 C.__name__ = "normal"
4074
Georg Brandl479a7e72008-02-05 18:13:15 +00004075 def test_subclass_right_op(self):
4076 # Testing correct dispatch of subclass overloading __r<op>__...
4077
4078 # This code tests various cases where right-dispatch of a subclass
4079 # should be preferred over left-dispatch of a base class.
4080
4081 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4082
4083 class B(int):
4084 def __floordiv__(self, other):
4085 return "B.__floordiv__"
4086 def __rfloordiv__(self, other):
4087 return "B.__rfloordiv__"
4088
4089 self.assertEqual(B(1) // 1, "B.__floordiv__")
4090 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4091
4092 # Case 2: subclass of object; this is just the baseline for case 3
4093
4094 class C(object):
4095 def __floordiv__(self, other):
4096 return "C.__floordiv__"
4097 def __rfloordiv__(self, other):
4098 return "C.__rfloordiv__"
4099
4100 self.assertEqual(C() // 1, "C.__floordiv__")
4101 self.assertEqual(1 // C(), "C.__rfloordiv__")
4102
4103 # Case 3: subclass of new-style class; here it gets interesting
4104
4105 class D(C):
4106 def __floordiv__(self, other):
4107 return "D.__floordiv__"
4108 def __rfloordiv__(self, other):
4109 return "D.__rfloordiv__"
4110
4111 self.assertEqual(D() // C(), "D.__floordiv__")
4112 self.assertEqual(C() // D(), "D.__rfloordiv__")
4113
4114 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4115
4116 class E(C):
4117 pass
4118
4119 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4120
4121 self.assertEqual(E() // 1, "C.__floordiv__")
4122 self.assertEqual(1 // E(), "C.__rfloordiv__")
4123 self.assertEqual(E() // C(), "C.__floordiv__")
4124 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4125
Benjamin Petersone549ead2009-03-28 21:42:05 +00004126 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004127 def test_meth_class_get(self):
4128 # Testing __get__ method of METH_CLASS C methods...
4129 # Full coverage of descrobject.c::classmethod_get()
4130
4131 # Baseline
4132 arg = [1, 2, 3]
4133 res = {1: None, 2: None, 3: None}
4134 self.assertEqual(dict.fromkeys(arg), res)
4135 self.assertEqual({}.fromkeys(arg), res)
4136
4137 # Now get the descriptor
4138 descr = dict.__dict__["fromkeys"]
4139
4140 # More baseline using the descriptor directly
4141 self.assertEqual(descr.__get__(None, dict)(arg), res)
4142 self.assertEqual(descr.__get__({})(arg), res)
4143
4144 # Now check various error cases
4145 try:
4146 descr.__get__(None, None)
4147 except TypeError:
4148 pass
4149 else:
4150 self.fail("shouldn't have allowed descr.__get__(None, None)")
4151 try:
4152 descr.__get__(42)
4153 except TypeError:
4154 pass
4155 else:
4156 self.fail("shouldn't have allowed descr.__get__(42)")
4157 try:
4158 descr.__get__(None, 42)
4159 except TypeError:
4160 pass
4161 else:
4162 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4163 try:
4164 descr.__get__(None, int)
4165 except TypeError:
4166 pass
4167 else:
4168 self.fail("shouldn't have allowed descr.__get__(None, int)")
4169
4170 def test_isinst_isclass(self):
4171 # Testing proxy isinstance() and isclass()...
4172 class Proxy(object):
4173 def __init__(self, obj):
4174 self.__obj = obj
4175 def __getattribute__(self, name):
4176 if name.startswith("_Proxy__"):
4177 return object.__getattribute__(self, name)
4178 else:
4179 return getattr(self.__obj, name)
4180 # Test with a classic class
4181 class C:
4182 pass
4183 a = C()
4184 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004185 self.assertIsInstance(a, C) # Baseline
4186 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004187 # Test with a classic subclass
4188 class D(C):
4189 pass
4190 a = D()
4191 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004192 self.assertIsInstance(a, C) # Baseline
4193 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004194 # Test with a new-style class
4195 class C(object):
4196 pass
4197 a = C()
4198 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004199 self.assertIsInstance(a, C) # Baseline
4200 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004201 # Test with a new-style subclass
4202 class D(C):
4203 pass
4204 a = D()
4205 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004206 self.assertIsInstance(a, C) # Baseline
4207 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004208
4209 def test_proxy_super(self):
4210 # Testing super() for a proxy object...
4211 class Proxy(object):
4212 def __init__(self, obj):
4213 self.__obj = obj
4214 def __getattribute__(self, name):
4215 if name.startswith("_Proxy__"):
4216 return object.__getattribute__(self, name)
4217 else:
4218 return getattr(self.__obj, name)
4219
4220 class B(object):
4221 def f(self):
4222 return "B.f"
4223
4224 class C(B):
4225 def f(self):
4226 return super(C, self).f() + "->C.f"
4227
4228 obj = C()
4229 p = Proxy(obj)
4230 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4231
4232 def test_carloverre(self):
4233 # Testing prohibition of Carlo Verre's hack...
4234 try:
4235 object.__setattr__(str, "foo", 42)
4236 except TypeError:
4237 pass
4238 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004239 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004240 try:
4241 object.__delattr__(str, "lower")
4242 except TypeError:
4243 pass
4244 else:
4245 self.fail("Carlo Verre __delattr__ succeeded!")
4246
4247 def test_weakref_segfault(self):
4248 # Testing weakref segfault...
4249 # SF 742911
4250 import weakref
4251
4252 class Provoker:
4253 def __init__(self, referrent):
4254 self.ref = weakref.ref(referrent)
4255
4256 def __del__(self):
4257 x = self.ref()
4258
4259 class Oops(object):
4260 pass
4261
4262 o = Oops()
4263 o.whatever = Provoker(o)
4264 del o
4265
4266 def test_wrapper_segfault(self):
4267 # SF 927248: deeply nested wrappers could cause stack overflow
4268 f = lambda:None
4269 for i in range(1000000):
4270 f = f.__call__
4271 f = None
4272
4273 def test_file_fault(self):
4274 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004275 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004276 class StdoutGuard:
4277 def __getattr__(self, attr):
4278 sys.stdout = sys.__stdout__
4279 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4280 sys.stdout = StdoutGuard()
4281 try:
4282 print("Oops!")
4283 except RuntimeError:
4284 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004285 finally:
4286 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004287
4288 def test_vicious_descriptor_nonsense(self):
4289 # Testing vicious_descriptor_nonsense...
4290
4291 # A potential segfault spotted by Thomas Wouters in mail to
4292 # python-dev 2003-04-17, turned into an example & fixed by Michael
4293 # Hudson just less than four months later...
4294
4295 class Evil(object):
4296 def __hash__(self):
4297 return hash('attr')
4298 def __eq__(self, other):
4299 del C.attr
4300 return 0
4301
4302 class Descr(object):
4303 def __get__(self, ob, type=None):
4304 return 1
4305
4306 class C(object):
4307 attr = Descr()
4308
4309 c = C()
4310 c.__dict__[Evil()] = 0
4311
4312 self.assertEqual(c.attr, 1)
4313 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004314 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004315 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004316
4317 def test_init(self):
4318 # SF 1155938
4319 class Foo(object):
4320 def __init__(self):
4321 return 10
4322 try:
4323 Foo()
4324 except TypeError:
4325 pass
4326 else:
4327 self.fail("did not test __init__() for None return")
4328
4329 def test_method_wrapper(self):
4330 # Testing method-wrapper objects...
4331 # <type 'method-wrapper'> did not support any reflection before 2.5
4332
Mark Dickinson211c6252009-02-01 10:28:51 +00004333 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004334
4335 l = []
4336 self.assertEqual(l.__add__, l.__add__)
4337 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004338 self.assertNotEqual(l.__add__, [5].__add__)
4339 self.assertNotEqual(l.__add__, l.__mul__)
4340 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004341 if hasattr(l.__add__, '__self__'):
4342 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004343 self.assertIs(l.__add__.__self__, l)
4344 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004345 else:
4346 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004347 self.assertIs(l.__add__.im_self, l)
4348 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004349 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4350 try:
4351 hash(l.__add__)
4352 except TypeError:
4353 pass
4354 else:
4355 self.fail("no TypeError from hash([].__add__)")
4356
4357 t = ()
4358 t += (7,)
4359 self.assertEqual(t.__add__, (7,).__add__)
4360 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4361
4362 def test_not_implemented(self):
4363 # Testing NotImplemented...
4364 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004365 import operator
4366
4367 def specialmethod(self, other):
4368 return NotImplemented
4369
4370 def check(expr, x, y):
4371 try:
4372 exec(expr, {'x': x, 'y': y, 'operator': operator})
4373 except TypeError:
4374 pass
4375 else:
4376 self.fail("no TypeError from %r" % (expr,))
4377
4378 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4379 # TypeErrors
4380 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4381 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004382 for name, expr, iexpr in [
4383 ('__add__', 'x + y', 'x += y'),
4384 ('__sub__', 'x - y', 'x -= y'),
4385 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004386 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004387 ('__truediv__', 'x / y', 'x /= y'),
4388 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004389 ('__mod__', 'x % y', 'x %= y'),
4390 ('__divmod__', 'divmod(x, y)', None),
4391 ('__pow__', 'x ** y', 'x **= y'),
4392 ('__lshift__', 'x << y', 'x <<= y'),
4393 ('__rshift__', 'x >> y', 'x >>= y'),
4394 ('__and__', 'x & y', 'x &= y'),
4395 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004396 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004397 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004398 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004399 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004400 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004401 check(expr, a, N1)
4402 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004403 if iexpr:
4404 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004405 check(iexpr, a, N1)
4406 check(iexpr, a, N2)
4407 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004408 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004409 c = C()
4410 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004411 check(iexpr, c, N1)
4412 check(iexpr, c, N2)
4413
Georg Brandl479a7e72008-02-05 18:13:15 +00004414 def test_assign_slice(self):
4415 # ceval.c's assign_slice used to check for
4416 # tp->tp_as_sequence->sq_slice instead of
4417 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004418
Georg Brandl479a7e72008-02-05 18:13:15 +00004419 class C(object):
4420 def __setitem__(self, idx, value):
4421 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004422
Georg Brandl479a7e72008-02-05 18:13:15 +00004423 c = C()
4424 c[1:2] = 3
4425 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004426
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004427 def test_set_and_no_get(self):
4428 # See
4429 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4430 class Descr(object):
4431
4432 def __init__(self, name):
4433 self.name = name
4434
4435 def __set__(self, obj, value):
4436 obj.__dict__[self.name] = value
4437 descr = Descr("a")
4438
4439 class X(object):
4440 a = descr
4441
4442 x = X()
4443 self.assertIs(x.a, descr)
4444 x.a = 42
4445 self.assertEqual(x.a, 42)
4446
Benjamin Peterson21896a32010-03-21 22:03:03 +00004447 # Also check type_getattro for correctness.
4448 class Meta(type):
4449 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004450 class X(metaclass=Meta):
4451 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004452 X.a = 42
4453 Meta.a = Descr("a")
4454 self.assertEqual(X.a, 42)
4455
Benjamin Peterson9262b842008-11-17 22:45:50 +00004456 def test_getattr_hooks(self):
4457 # issue 4230
4458
4459 class Descriptor(object):
4460 counter = 0
4461 def __get__(self, obj, objtype=None):
4462 def getter(name):
4463 self.counter += 1
4464 raise AttributeError(name)
4465 return getter
4466
4467 descr = Descriptor()
4468 class A(object):
4469 __getattribute__ = descr
4470 class B(object):
4471 __getattr__ = descr
4472 class C(object):
4473 __getattribute__ = descr
4474 __getattr__ = descr
4475
4476 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004477 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004478 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004479 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004480 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004481 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004482
Benjamin Peterson9262b842008-11-17 22:45:50 +00004483 class EvilGetattribute(object):
4484 # This used to segfault
4485 def __getattr__(self, name):
4486 raise AttributeError(name)
4487 def __getattribute__(self, name):
4488 del EvilGetattribute.__getattr__
4489 for i in range(5):
4490 gc.collect()
4491 raise AttributeError(name)
4492
4493 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4494
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004495 def test_type___getattribute__(self):
4496 self.assertRaises(TypeError, type.__getattribute__, list, type)
4497
Benjamin Peterson477ba912011-01-12 15:34:01 +00004498 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004499 # type pretends not to have __abstractmethods__.
4500 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4501 class meta(type):
4502 pass
4503 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004504 class X(object):
4505 pass
4506 with self.assertRaises(AttributeError):
4507 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004508
Victor Stinner3249dec2011-05-01 23:19:15 +02004509 def test_proxy_call(self):
4510 class FakeStr:
4511 __class__ = str
4512
4513 fake_str = FakeStr()
4514 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004515 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004516
4517 # call a method descriptor
4518 with self.assertRaises(TypeError):
4519 str.split(fake_str)
4520
4521 # call a slot wrapper descriptor
4522 with self.assertRaises(TypeError):
4523 str.__add__(fake_str, "abc")
4524
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004525 def test_repr_as_str(self):
4526 # Issue #11603: crash or infinite loop when rebinding __str__ as
4527 # __repr__.
4528 class Foo:
4529 pass
4530 Foo.__repr__ = Foo.__str__
4531 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004532 self.assertRaises(RecursionError, str, foo)
4533 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004534
4535 def test_mixing_slot_wrappers(self):
4536 class X(dict):
4537 __setattr__ = dict.__setitem__
4538 x = X()
4539 x.y = 42
4540 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004541
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004542 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004543 with self.assertRaises(ValueError) as cm:
4544 class X:
4545 __slots__ = ["foo"]
4546 foo = None
4547 m = str(cm.exception)
4548 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4549
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004550 def test_set_doc(self):
4551 class X:
4552 "elephant"
4553 X.__doc__ = "banana"
4554 self.assertEqual(X.__doc__, "banana")
4555 with self.assertRaises(TypeError) as cm:
4556 type(list).__dict__["__doc__"].__set__(list, "blah")
4557 self.assertIn("can't set list.__doc__", str(cm.exception))
4558 with self.assertRaises(TypeError) as cm:
4559 type(X).__dict__["__doc__"].__delete__(X)
4560 self.assertIn("can't delete X.__doc__", str(cm.exception))
4561 self.assertEqual(X.__doc__, "banana")
4562
Antoine Pitrou9d574812011-12-12 13:47:25 +01004563 def test_qualname(self):
4564 descriptors = [str.lower, complex.real, float.real, int.__add__]
4565 types = ['method', 'member', 'getset', 'wrapper']
4566
4567 # make sure we have an example of each type of descriptor
4568 for d, n in zip(descriptors, types):
4569 self.assertEqual(type(d).__name__, n + '_descriptor')
4570
4571 for d in descriptors:
4572 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4573 self.assertEqual(d.__qualname__, qualname)
4574
4575 self.assertEqual(str.lower.__qualname__, 'str.lower')
4576 self.assertEqual(complex.real.__qualname__, 'complex.real')
4577 self.assertEqual(float.real.__qualname__, 'float.real')
4578 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4579
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004580 class X:
4581 pass
4582 with self.assertRaises(TypeError):
4583 del X.__qualname__
4584
4585 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4586 str, 'Oink')
4587
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004588 global Y
4589 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004590 class Inside:
4591 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004592 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004593 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004594
Victor Stinner6f738742012-02-25 01:22:36 +01004595 def test_qualname_dict(self):
4596 ns = {'__qualname__': 'some.name'}
4597 tp = type('Foo', (), ns)
4598 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004599 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004600 self.assertEqual(ns, {'__qualname__': 'some.name'})
4601
4602 ns = {'__qualname__': 1}
4603 self.assertRaises(TypeError, type, 'Foo', (), ns)
4604
Benjamin Peterson52c42432012-03-07 18:41:11 -06004605 def test_cycle_through_dict(self):
4606 # See bug #1469629
4607 class X(dict):
4608 def __init__(self):
4609 dict.__init__(self)
4610 self.__dict__ = self
4611 x = X()
4612 x.attr = 42
4613 wr = weakref.ref(x)
4614 del x
4615 support.gc_collect()
4616 self.assertIsNone(wr())
4617 for o in gc.get_objects():
4618 self.assertIsNot(type(o), X)
4619
Benjamin Peterson96384b92012-03-17 00:05:44 -05004620 def test_object_new_and_init_with_parameters(self):
4621 # See issue #1683368
4622 class OverrideNeither:
4623 pass
4624 self.assertRaises(TypeError, OverrideNeither, 1)
4625 self.assertRaises(TypeError, OverrideNeither, kw=1)
4626 class OverrideNew:
4627 def __new__(cls, foo, kw=0, *args, **kwds):
4628 return object.__new__(cls, *args, **kwds)
4629 class OverrideInit:
4630 def __init__(self, foo, kw=0, *args, **kwargs):
4631 return object.__init__(self, *args, **kwargs)
4632 class OverrideBoth(OverrideNew, OverrideInit):
4633 pass
4634 for case in OverrideNew, OverrideInit, OverrideBoth:
4635 case(1)
4636 case(1, kw=2)
4637 self.assertRaises(TypeError, case, 1, 2, 3)
4638 self.assertRaises(TypeError, case, 1, 2, foo=3)
4639
Benjamin Petersondf813792014-03-17 15:57:17 -05004640 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4641 class Base:
4642 pass
4643 class Sub(Base):
4644 pass
4645 self.assertIn("__dict__", Base.__dict__)
4646 self.assertNotIn("__dict__", Sub.__dict__)
4647
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004648 def test_bound_method_repr(self):
4649 class Foo:
4650 def method(self):
4651 pass
4652 self.assertRegex(repr(Foo().method),
4653 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4654
4655
4656 class Base:
4657 def method(self):
4658 pass
4659 class Derived1(Base):
4660 pass
4661 class Derived2(Base):
4662 def method(self):
4663 pass
4664 base = Base()
4665 derived1 = Derived1()
4666 derived2 = Derived2()
4667 super_d2 = super(Derived2, derived2)
4668 self.assertRegex(repr(base.method),
4669 r"<bound method .*Base\.method of <.*Base object at .*>>")
4670 self.assertRegex(repr(derived1.method),
4671 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4672 self.assertRegex(repr(derived2.method),
4673 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4674 self.assertRegex(repr(super_d2.method),
4675 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4676
4677 class Foo:
4678 @classmethod
4679 def method(cls):
4680 pass
4681 foo = Foo()
4682 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004683 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004684 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004685 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004686
4687
4688 class MyCallable:
4689 def __call__(self, arg):
4690 pass
4691 func = MyCallable() # func has no __name__ or __qualname__ attributes
4692 instance = object()
4693 method = types.MethodType(func, instance)
4694 self.assertRegex(repr(method),
4695 r"<bound method \? of <object object at .*>>")
4696 func.__name__ = "name"
4697 self.assertRegex(repr(method),
4698 r"<bound method name of <object object at .*>>")
4699 func.__qualname__ = "qualname"
4700 self.assertRegex(repr(method),
4701 r"<bound method qualname of <object object at .*>>")
4702
Antoine Pitrou9d574812011-12-12 13:47:25 +01004703
Georg Brandl479a7e72008-02-05 18:13:15 +00004704class DictProxyTests(unittest.TestCase):
4705 def setUp(self):
4706 class C(object):
4707 def meth(self):
4708 pass
4709 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004710
Brett Cannon7a540732011-02-22 03:04:06 +00004711 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4712 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004713 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004714 # Testing dict-proxy keys...
4715 it = self.C.__dict__.keys()
4716 self.assertNotIsInstance(it, list)
4717 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004718 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004719 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004720 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004721
Brett Cannon7a540732011-02-22 03:04:06 +00004722 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4723 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004724 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004725 # Testing dict-proxy values...
4726 it = self.C.__dict__.values()
4727 self.assertNotIsInstance(it, list)
4728 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004729 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004730
Brett Cannon7a540732011-02-22 03:04:06 +00004731 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4732 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004733 def test_iter_items(self):
4734 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004735 it = self.C.__dict__.items()
4736 self.assertNotIsInstance(it, list)
4737 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004738 keys.sort()
4739 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004740 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004741
Georg Brandl479a7e72008-02-05 18:13:15 +00004742 def test_dict_type_with_metaclass(self):
4743 # Testing type of __dict__ when metaclass set...
4744 class B(object):
4745 pass
4746 class M(type):
4747 pass
4748 class C(metaclass=M):
4749 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4750 pass
4751 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004752
Ezio Melottiac53ab62010-12-18 14:59:43 +00004753 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004754 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004755 # We can't blindly compare with the repr of another dict as ordering
4756 # of keys and values is arbitrary and may differ.
4757 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004758 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004759 self.assertTrue(r.endswith(')'), r)
4760 for k, v in self.C.__dict__.items():
4761 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004762
Christian Heimesbbffeb62008-01-24 09:42:52 +00004763
Georg Brandl479a7e72008-02-05 18:13:15 +00004764class PTypesLongInitTest(unittest.TestCase):
4765 # This is in its own TestCase so that it can be run before any other tests.
4766 def test_pytype_long_ready(self):
4767 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004768
Georg Brandl479a7e72008-02-05 18:13:15 +00004769 # This dumps core when SF bug 551412 isn't fixed --
4770 # but only when test_descr.py is run separately.
4771 # (That can't be helped -- as soon as PyType_Ready()
4772 # is called for PyLong_Type, the bug is gone.)
4773 class UserLong(object):
4774 def __pow__(self, *args):
4775 pass
4776 try:
4777 pow(0, UserLong(), 0)
4778 except:
4779 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004780
Georg Brandl479a7e72008-02-05 18:13:15 +00004781 # Another segfault only when run early
4782 # (before PyType_Ready(tuple) is called)
4783 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004784
4785
Victor Stinnerd74782b2012-03-09 00:39:08 +01004786class MiscTests(unittest.TestCase):
4787 def test_type_lookup_mro_reference(self):
4788 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4789 # the type MRO because it may be modified during the lookup, if
4790 # __bases__ is set during the lookup for example.
4791 class MyKey(object):
4792 def __hash__(self):
4793 return hash('mykey')
4794
4795 def __eq__(self, other):
4796 X.__bases__ = (Base2,)
4797
4798 class Base(object):
4799 mykey = 'from Base'
4800 mykey2 = 'from Base'
4801
4802 class Base2(object):
4803 mykey = 'from Base2'
4804 mykey2 = 'from Base2'
4805
4806 X = type('X', (Base,), {MyKey(): 5})
4807 # mykey is read from Base
4808 self.assertEqual(X.mykey, 'from Base')
4809 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4810 self.assertEqual(X.mykey2, 'from Base2')
4811
4812
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004813class PicklingTests(unittest.TestCase):
4814
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004815 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004816 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004817 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004818 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004819 if kwargs:
4820 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4821 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004822 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004823 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4824 self.assertEqual(reduce_value[1], (type(obj),) + args)
4825 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004826 if listitems is not None:
4827 self.assertListEqual(list(reduce_value[3]), listitems)
4828 else:
4829 self.assertIsNone(reduce_value[3])
4830 if dictitems is not None:
4831 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4832 else:
4833 self.assertIsNone(reduce_value[4])
4834 else:
4835 base_type = type(obj).__base__
4836 reduce_value = (copyreg._reconstructor,
4837 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004838 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004839 None if base_type is object else base_type(obj)))
4840 if state is not None:
4841 reduce_value += (state,)
4842 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4843 self.assertEqual(obj.__reduce__(), reduce_value)
4844
4845 def test_reduce(self):
4846 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4847 args = (-101, "spam")
4848 kwargs = {'bacon': -201, 'fish': -301}
4849 state = {'cheese': -401}
4850
4851 class C1:
4852 def __getnewargs__(self):
4853 return args
4854 obj = C1()
4855 for proto in protocols:
4856 self._check_reduce(proto, obj, args)
4857
4858 for name, value in state.items():
4859 setattr(obj, name, value)
4860 for proto in protocols:
4861 self._check_reduce(proto, obj, args, state=state)
4862
4863 class C2:
4864 def __getnewargs__(self):
4865 return "bad args"
4866 obj = C2()
4867 for proto in protocols:
4868 if proto >= 2:
4869 with self.assertRaises(TypeError):
4870 obj.__reduce_ex__(proto)
4871
4872 class C3:
4873 def __getnewargs_ex__(self):
4874 return (args, kwargs)
4875 obj = C3()
4876 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03004877 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004878 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004879
4880 class C4:
4881 def __getnewargs_ex__(self):
4882 return (args, "bad dict")
4883 class C5:
4884 def __getnewargs_ex__(self):
4885 return ("bad tuple", kwargs)
4886 class C6:
4887 def __getnewargs_ex__(self):
4888 return ()
4889 class C7:
4890 def __getnewargs_ex__(self):
4891 return "bad args"
4892 for proto in protocols:
4893 for cls in C4, C5, C6, C7:
4894 obj = cls()
4895 if proto >= 2:
4896 with self.assertRaises((TypeError, ValueError)):
4897 obj.__reduce_ex__(proto)
4898
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004899 class C9:
4900 def __getnewargs_ex__(self):
4901 return (args, {})
4902 obj = C9()
4903 for proto in protocols:
4904 self._check_reduce(proto, obj, args)
4905
4906 class C10:
4907 def __getnewargs_ex__(self):
4908 raise IndexError
4909 obj = C10()
4910 for proto in protocols:
4911 if proto >= 2:
4912 with self.assertRaises(IndexError):
4913 obj.__reduce_ex__(proto)
4914
4915 class C11:
4916 def __getstate__(self):
4917 return state
4918 obj = C11()
4919 for proto in protocols:
4920 self._check_reduce(proto, obj, state=state)
4921
4922 class C12:
4923 def __getstate__(self):
4924 return "not dict"
4925 obj = C12()
4926 for proto in protocols:
4927 self._check_reduce(proto, obj, state="not dict")
4928
4929 class C13:
4930 def __getstate__(self):
4931 raise IndexError
4932 obj = C13()
4933 for proto in protocols:
4934 with self.assertRaises(IndexError):
4935 obj.__reduce_ex__(proto)
4936 if proto < 2:
4937 with self.assertRaises(IndexError):
4938 obj.__reduce__()
4939
4940 class C14:
4941 __slots__ = tuple(state)
4942 def __init__(self):
4943 for name, value in state.items():
4944 setattr(self, name, value)
4945
4946 obj = C14()
4947 for proto in protocols:
4948 if proto >= 2:
4949 self._check_reduce(proto, obj, state=(None, state))
4950 else:
4951 with self.assertRaises(TypeError):
4952 obj.__reduce_ex__(proto)
4953 with self.assertRaises(TypeError):
4954 obj.__reduce__()
4955
4956 class C15(dict):
4957 pass
4958 obj = C15({"quebec": -601})
4959 for proto in protocols:
4960 self._check_reduce(proto, obj, dictitems=dict(obj))
4961
4962 class C16(list):
4963 pass
4964 obj = C16(["yukon"])
4965 for proto in protocols:
4966 self._check_reduce(proto, obj, listitems=list(obj))
4967
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004968 def test_special_method_lookup(self):
4969 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4970 class Picky:
4971 def __getstate__(self):
4972 return {}
4973
4974 def __getattr__(self, attr):
4975 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4976 raise AssertionError(attr)
4977 return None
4978 for protocol in protocols:
4979 state = {} if protocol >= 2 else None
4980 self._check_reduce(protocol, Picky(), state=state)
4981
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004982 def _assert_is_copy(self, obj, objcopy, msg=None):
4983 """Utility method to verify if two objects are copies of each others.
4984 """
4985 if msg is None:
4986 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4987 if type(obj).__repr__ is object.__repr__:
4988 # We have this limitation for now because we use the object's repr
4989 # to help us verify that the two objects are copies. This allows
4990 # us to delegate the non-generic verification logic to the objects
4991 # themselves.
4992 raise ValueError("object passed to _assert_is_copy must " +
4993 "override the __repr__ method.")
4994 self.assertIsNot(obj, objcopy, msg=msg)
4995 self.assertIs(type(obj), type(objcopy), msg=msg)
4996 if hasattr(obj, '__dict__'):
4997 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4998 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4999 if hasattr(obj, '__slots__'):
5000 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5001 for slot in obj.__slots__:
5002 self.assertEqual(
5003 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5004 self.assertEqual(getattr(obj, slot, None),
5005 getattr(objcopy, slot, None), msg=msg)
5006 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5007
5008 @staticmethod
5009 def _generate_pickle_copiers():
5010 """Utility method to generate the many possible pickle configurations.
5011 """
5012 class PickleCopier:
5013 "This class copies object using pickle."
5014 def __init__(self, proto, dumps, loads):
5015 self.proto = proto
5016 self.dumps = dumps
5017 self.loads = loads
5018 def copy(self, obj):
5019 return self.loads(self.dumps(obj, self.proto))
5020 def __repr__(self):
5021 # We try to be as descriptive as possible here since this is
5022 # the string which we will allow us to tell the pickle
5023 # configuration we are using during debugging.
5024 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5025 .format(self.proto,
5026 self.dumps.__module__, self.dumps.__qualname__,
5027 self.loads.__module__, self.loads.__qualname__))
5028 return (PickleCopier(*args) for args in
5029 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5030 {pickle.dumps, pickle._dumps},
5031 {pickle.loads, pickle._loads}))
5032
5033 def test_pickle_slots(self):
5034 # Tests pickling of classes with __slots__.
5035
5036 # Pickling of classes with __slots__ but without __getstate__ should
5037 # fail (if using protocol 0 or 1)
5038 global C
5039 class C:
5040 __slots__ = ['a']
5041 with self.assertRaises(TypeError):
5042 pickle.dumps(C(), 0)
5043
5044 global D
5045 class D(C):
5046 pass
5047 with self.assertRaises(TypeError):
5048 pickle.dumps(D(), 0)
5049
5050 class C:
5051 "A class with __getstate__ and __setstate__ implemented."
5052 __slots__ = ['a']
5053 def __getstate__(self):
5054 state = getattr(self, '__dict__', {}).copy()
5055 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005056 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005057 try:
5058 state[slot] = getattr(self, slot)
5059 except AttributeError:
5060 pass
5061 return state
5062 def __setstate__(self, state):
5063 for k, v in state.items():
5064 setattr(self, k, v)
5065 def __repr__(self):
5066 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5067
5068 class D(C):
5069 "A subclass of a class with slots."
5070 pass
5071
5072 global E
5073 class E(C):
5074 "A subclass with an extra slot."
5075 __slots__ = ['b']
5076
5077 # Now it should work
5078 for pickle_copier in self._generate_pickle_copiers():
5079 with self.subTest(pickle_copier=pickle_copier):
5080 x = C()
5081 y = pickle_copier.copy(x)
5082 self._assert_is_copy(x, y)
5083
5084 x.a = 42
5085 y = pickle_copier.copy(x)
5086 self._assert_is_copy(x, y)
5087
5088 x = D()
5089 x.a = 42
5090 x.b = 100
5091 y = pickle_copier.copy(x)
5092 self._assert_is_copy(x, y)
5093
5094 x = E()
5095 x.a = 42
5096 x.b = "foo"
5097 y = pickle_copier.copy(x)
5098 self._assert_is_copy(x, y)
5099
5100 def test_reduce_copying(self):
5101 # Tests pickling and copying new-style classes and objects.
5102 global C1
5103 class C1:
5104 "The state of this class is copyable via its instance dict."
5105 ARGS = (1, 2)
5106 NEED_DICT_COPYING = True
5107 def __init__(self, a, b):
5108 super().__init__()
5109 self.a = a
5110 self.b = b
5111 def __repr__(self):
5112 return "C1(%r, %r)" % (self.a, self.b)
5113
5114 global C2
5115 class C2(list):
5116 "A list subclass copyable via __getnewargs__."
5117 ARGS = (1, 2)
5118 NEED_DICT_COPYING = False
5119 def __new__(cls, a, b):
5120 self = super().__new__(cls)
5121 self.a = a
5122 self.b = b
5123 return self
5124 def __init__(self, *args):
5125 super().__init__()
5126 # This helps testing that __init__ is not called during the
5127 # unpickling process, which would cause extra appends.
5128 self.append("cheese")
5129 @classmethod
5130 def __getnewargs__(cls):
5131 return cls.ARGS
5132 def __repr__(self):
5133 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5134
5135 global C3
5136 class C3(list):
5137 "A list subclass copyable via __getstate__."
5138 ARGS = (1, 2)
5139 NEED_DICT_COPYING = False
5140 def __init__(self, a, b):
5141 self.a = a
5142 self.b = b
5143 # This helps testing that __init__ is not called during the
5144 # unpickling process, which would cause extra appends.
5145 self.append("cheese")
5146 @classmethod
5147 def __getstate__(cls):
5148 return cls.ARGS
5149 def __setstate__(self, state):
5150 a, b = state
5151 self.a = a
5152 self.b = b
5153 def __repr__(self):
5154 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5155
5156 global C4
5157 class C4(int):
5158 "An int subclass copyable via __getnewargs__."
5159 ARGS = ("hello", "world", 1)
5160 NEED_DICT_COPYING = False
5161 def __new__(cls, a, b, value):
5162 self = super().__new__(cls, value)
5163 self.a = a
5164 self.b = b
5165 return self
5166 @classmethod
5167 def __getnewargs__(cls):
5168 return cls.ARGS
5169 def __repr__(self):
5170 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5171
5172 global C5
5173 class C5(int):
5174 "An int subclass copyable via __getnewargs_ex__."
5175 ARGS = (1, 2)
5176 KWARGS = {'value': 3}
5177 NEED_DICT_COPYING = False
5178 def __new__(cls, a, b, *, value=0):
5179 self = super().__new__(cls, value)
5180 self.a = a
5181 self.b = b
5182 return self
5183 @classmethod
5184 def __getnewargs_ex__(cls):
5185 return (cls.ARGS, cls.KWARGS)
5186 def __repr__(self):
5187 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5188
5189 test_classes = (C1, C2, C3, C4, C5)
5190 # Testing copying through pickle
5191 pickle_copiers = self._generate_pickle_copiers()
5192 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5193 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5194 kwargs = getattr(cls, 'KWARGS', {})
5195 obj = cls(*cls.ARGS, **kwargs)
5196 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005197 objcopy = pickle_copier.copy(obj)
5198 self._assert_is_copy(obj, objcopy)
5199 # For test classes that supports this, make sure we didn't go
5200 # around the reduce protocol by simply copying the attribute
5201 # dictionary. We clear attributes using the previous copy to
5202 # not mutate the original argument.
5203 if proto >= 2 and not cls.NEED_DICT_COPYING:
5204 objcopy.__dict__.clear()
5205 objcopy2 = pickle_copier.copy(objcopy)
5206 self._assert_is_copy(obj, objcopy2)
5207
5208 # Testing copying through copy.deepcopy()
5209 for cls in test_classes:
5210 with self.subTest(cls=cls):
5211 kwargs = getattr(cls, 'KWARGS', {})
5212 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005213 objcopy = deepcopy(obj)
5214 self._assert_is_copy(obj, objcopy)
5215 # For test classes that supports this, make sure we didn't go
5216 # around the reduce protocol by simply copying the attribute
5217 # dictionary. We clear attributes using the previous copy to
5218 # not mutate the original argument.
5219 if not cls.NEED_DICT_COPYING:
5220 objcopy.__dict__.clear()
5221 objcopy2 = deepcopy(objcopy)
5222 self._assert_is_copy(obj, objcopy2)
5223
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005224 def test_issue24097(self):
5225 # Slot name is freed inside __getattr__ and is later used.
5226 class S(str): # Not interned
5227 pass
5228 class A:
5229 __slotnames__ = [S('spam')]
5230 def __getattr__(self, attr):
5231 if attr == 'spam':
5232 A.__slotnames__[:] = [S('spam')]
5233 return 42
5234 else:
5235 raise AttributeError
5236
5237 import copyreg
5238 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005239 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5240
5241 def test_object_reduce(self):
5242 # Issue #29914
5243 # __reduce__() takes no arguments
5244 object().__reduce__()
5245 with self.assertRaises(TypeError):
5246 object().__reduce__(0)
5247 # __reduce_ex__() takes one integer argument
5248 object().__reduce_ex__(0)
5249 with self.assertRaises(TypeError):
5250 object().__reduce_ex__()
5251 with self.assertRaises(TypeError):
5252 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005253
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005254
Benjamin Peterson2a605342014-03-17 16:20:12 -05005255class SharedKeyTests(unittest.TestCase):
5256
5257 @support.cpython_only
5258 def test_subclasses(self):
5259 # Verify that subclasses can share keys (per PEP 412)
5260 class A:
5261 pass
5262 class B(A):
5263 pass
5264
5265 a, b = A(), B()
5266 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5267 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005268 # Initial hash table can contain at most 5 elements.
5269 # Set 6 attributes to cause internal resizing.
5270 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005271 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5272 a2 = A()
5273 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5274 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005275 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005276 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5277
5278
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005279class DebugHelperMeta(type):
5280 """
5281 Sets default __doc__ and simplifies repr() output.
5282 """
5283 def __new__(mcls, name, bases, attrs):
5284 if attrs.get('__doc__') is None:
5285 attrs['__doc__'] = name # helps when debugging with gdb
5286 return type.__new__(mcls, name, bases, attrs)
5287 def __repr__(cls):
5288 return repr(cls.__name__)
5289
5290
5291class MroTest(unittest.TestCase):
5292 """
5293 Regressions for some bugs revealed through
5294 mcsl.mro() customization (typeobject.c: mro_internal()) and
5295 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5296 """
5297
5298 def setUp(self):
5299 self.step = 0
5300 self.ready = False
5301
5302 def step_until(self, limit):
5303 ret = (self.step < limit)
5304 if ret:
5305 self.step += 1
5306 return ret
5307
5308 def test_incomplete_set_bases_on_self(self):
5309 """
5310 type_set_bases must be aware that type->tp_mro can be NULL.
5311 """
5312 class M(DebugHelperMeta):
5313 def mro(cls):
5314 if self.step_until(1):
5315 assert cls.__mro__ is None
5316 cls.__bases__ += ()
5317
5318 return type.mro(cls)
5319
5320 class A(metaclass=M):
5321 pass
5322
5323 def test_reent_set_bases_on_base(self):
5324 """
5325 Deep reentrancy must not over-decref old_mro.
5326 """
5327 class M(DebugHelperMeta):
5328 def mro(cls):
5329 if cls.__mro__ is not None and cls.__name__ == 'B':
5330 # 4-5 steps are usually enough to make it crash somewhere
5331 if self.step_until(10):
5332 A.__bases__ += ()
5333
5334 return type.mro(cls)
5335
5336 class A(metaclass=M):
5337 pass
5338 class B(A):
5339 pass
5340 B.__bases__ += ()
5341
5342 def test_reent_set_bases_on_direct_base(self):
5343 """
5344 Similar to test_reent_set_bases_on_base, but may crash differently.
5345 """
5346 class M(DebugHelperMeta):
5347 def mro(cls):
5348 base = cls.__bases__[0]
5349 if base is not object:
5350 if self.step_until(5):
5351 base.__bases__ += ()
5352
5353 return type.mro(cls)
5354
5355 class A(metaclass=M):
5356 pass
5357 class B(A):
5358 pass
5359 class C(B):
5360 pass
5361
5362 def test_reent_set_bases_tp_base_cycle(self):
5363 """
5364 type_set_bases must check for an inheritance cycle not only through
5365 MRO of the type, which may be not yet updated in case of reentrance,
5366 but also through tp_base chain, which is assigned before diving into
5367 inner calls to mro().
5368
5369 Otherwise, the following snippet can loop forever:
5370 do {
5371 // ...
5372 type = type->tp_base;
5373 } while (type != NULL);
5374
5375 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5376 would not be happy in that case, causing a stack overflow.
5377 """
5378 class M(DebugHelperMeta):
5379 def mro(cls):
5380 if self.ready:
5381 if cls.__name__ == 'B1':
5382 B2.__bases__ = (B1,)
5383 if cls.__name__ == 'B2':
5384 B1.__bases__ = (B2,)
5385 return type.mro(cls)
5386
5387 class A(metaclass=M):
5388 pass
5389 class B1(A):
5390 pass
5391 class B2(A):
5392 pass
5393
5394 self.ready = True
5395 with self.assertRaises(TypeError):
5396 B1.__bases__ += ()
5397
5398 def test_tp_subclasses_cycle_in_update_slots(self):
5399 """
5400 type_set_bases must check for reentrancy upon finishing its job
5401 by updating tp_subclasses of old/new bases of the type.
5402 Otherwise, an implicit inheritance cycle through tp_subclasses
5403 can break functions that recurse on elements of that field
5404 (like recurse_down_subclasses and mro_hierarchy) eventually
5405 leading to a stack overflow.
5406 """
5407 class M(DebugHelperMeta):
5408 def mro(cls):
5409 if self.ready and cls.__name__ == 'C':
5410 self.ready = False
5411 C.__bases__ = (B2,)
5412 return type.mro(cls)
5413
5414 class A(metaclass=M):
5415 pass
5416 class B1(A):
5417 pass
5418 class B2(A):
5419 pass
5420 class C(A):
5421 pass
5422
5423 self.ready = True
5424 C.__bases__ = (B1,)
5425 B1.__bases__ = (C,)
5426
5427 self.assertEqual(C.__bases__, (B2,))
5428 self.assertEqual(B2.__subclasses__(), [C])
5429 self.assertEqual(B1.__subclasses__(), [])
5430
5431 self.assertEqual(B1.__bases__, (C,))
5432 self.assertEqual(C.__subclasses__(), [B1])
5433
5434 def test_tp_subclasses_cycle_error_return_path(self):
5435 """
5436 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5437 a code path executed on error (goto bail).
5438 """
5439 class E(Exception):
5440 pass
5441 class M(DebugHelperMeta):
5442 def mro(cls):
5443 if self.ready and cls.__name__ == 'C':
5444 if C.__bases__ == (B2,):
5445 self.ready = False
5446 else:
5447 C.__bases__ = (B2,)
5448 raise E
5449 return type.mro(cls)
5450
5451 class A(metaclass=M):
5452 pass
5453 class B1(A):
5454 pass
5455 class B2(A):
5456 pass
5457 class C(A):
5458 pass
5459
5460 self.ready = True
5461 with self.assertRaises(E):
5462 C.__bases__ = (B1,)
5463 B1.__bases__ = (C,)
5464
5465 self.assertEqual(C.__bases__, (B2,))
5466 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5467
5468 def test_incomplete_extend(self):
5469 """
5470 Extending an unitialized type with type->tp_mro == NULL must
5471 throw a reasonable TypeError exception, instead of failing
5472 with PyErr_BadInternalCall.
5473 """
5474 class M(DebugHelperMeta):
5475 def mro(cls):
5476 if cls.__mro__ is None and cls.__name__ != 'X':
5477 with self.assertRaises(TypeError):
5478 class X(cls):
5479 pass
5480
5481 return type.mro(cls)
5482
5483 class A(metaclass=M):
5484 pass
5485
5486 def test_incomplete_super(self):
5487 """
5488 Attrubute lookup on a super object must be aware that
5489 its target type can be uninitialized (type->tp_mro == NULL).
5490 """
5491 class M(DebugHelperMeta):
5492 def mro(cls):
5493 if cls.__mro__ is None:
5494 with self.assertRaises(AttributeError):
5495 super(cls, cls).xxx
5496
5497 return type.mro(cls)
5498
5499 class A(metaclass=M):
5500 pass
5501
5502
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005503def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005504 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005505 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005506 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005507 MiscTests, PicklingTests, SharedKeyTests,
5508 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005509
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005510if __name__ == "__main__":
5511 test_main()