blob: d9541b9133f1ab7e730f031ed0a6fe8b8268cb35 [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
Miss Islington (bot)ef20abe2018-02-13 03:32:18 -08001562 @support.refcount_test
1563 def test_refleaks_in_classmethod___init__(self):
1564 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1565 cm = classmethod(None)
1566 refs_before = gettotalrefcount()
1567 for i in range(100):
1568 cm.__init__(None)
1569 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1570
Benjamin Petersone549ead2009-03-28 21:42:05 +00001571 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001572 def test_classmethods_in_c(self):
1573 # Testing C-based class methods...
1574 import xxsubtype as spam
1575 a = (1, 2, 3)
1576 d = {'abc': 123}
1577 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1578 self.assertEqual(x, spam.spamlist)
1579 self.assertEqual(a, a1)
1580 self.assertEqual(d, d1)
1581 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1582 self.assertEqual(x, spam.spamlist)
1583 self.assertEqual(a, a1)
1584 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001585 spam_cm = spam.spamlist.__dict__['classmeth']
1586 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1587 self.assertEqual(x2, spam.spamlist)
1588 self.assertEqual(a2, a1)
1589 self.assertEqual(d2, d1)
1590 class SubSpam(spam.spamlist): pass
1591 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1592 self.assertEqual(x2, SubSpam)
1593 self.assertEqual(a2, a1)
1594 self.assertEqual(d2, d1)
Miss Islington (bot)03440852019-03-26 02:47:08 -07001595
1596 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001597 spam_cm()
Miss Islington (bot)03440852019-03-26 02:47:08 -07001598 self.assertEqual(
1599 str(cm.exception),
1600 "descriptor 'classmeth' of 'xxsubtype.spamlist' "
1601 "object needs an argument")
1602
1603 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001604 spam_cm(spam.spamlist())
Miss Islington (bot)03440852019-03-26 02:47:08 -07001605 self.assertEqual(
1606 str(cm.exception),
1607 "descriptor 'classmeth' requires a type "
1608 "but received a 'xxsubtype.spamlist' instance")
1609
1610 with self.assertRaises(TypeError) as cm:
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001611 spam_cm(list)
Miss Islington (bot)03440852019-03-26 02:47:08 -07001612 self.assertEqual(
1613 str(cm.exception),
1614 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
1615 "but received 'list'")
Georg Brandl479a7e72008-02-05 18:13:15 +00001616
1617 def test_staticmethods(self):
1618 # Testing static methods...
1619 class C(object):
1620 def foo(*a): return a
1621 goo = staticmethod(foo)
1622 c = C()
1623 self.assertEqual(C.goo(1), (1,))
1624 self.assertEqual(c.goo(1), (1,))
1625 self.assertEqual(c.foo(1), (c, 1,))
1626 class D(C):
1627 pass
1628 d = D()
1629 self.assertEqual(D.goo(1), (1,))
1630 self.assertEqual(d.goo(1), (1,))
1631 self.assertEqual(d.foo(1), (d, 1))
1632 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001633 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001634 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001635 sm.x = 42
1636 self.assertEqual(sm.x, 42)
1637 self.assertEqual(sm.__dict__, {"x" : 42})
1638 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001639 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001640
Miss Islington (bot)ef20abe2018-02-13 03:32:18 -08001641 @support.refcount_test
1642 def test_refleaks_in_staticmethod___init__(self):
1643 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1644 sm = staticmethod(None)
1645 refs_before = gettotalrefcount()
1646 for i in range(100):
1647 sm.__init__(None)
1648 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1649
Benjamin Petersone549ead2009-03-28 21:42:05 +00001650 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001651 def test_staticmethods_in_c(self):
1652 # Testing C-based static methods...
1653 import xxsubtype as spam
1654 a = (1, 2, 3)
1655 d = {"abc": 123}
1656 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1657 self.assertEqual(x, None)
1658 self.assertEqual(a, a1)
1659 self.assertEqual(d, d1)
1660 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1661 self.assertEqual(x, None)
1662 self.assertEqual(a, a1)
1663 self.assertEqual(d, d1)
1664
1665 def test_classic(self):
1666 # Testing classic classes...
1667 class C:
1668 def foo(*a): return a
1669 goo = classmethod(foo)
1670 c = C()
1671 self.assertEqual(C.goo(1), (C, 1))
1672 self.assertEqual(c.goo(1), (C, 1))
1673 self.assertEqual(c.foo(1), (c, 1))
1674 class D(C):
1675 pass
1676 d = D()
1677 self.assertEqual(D.goo(1), (D, 1))
1678 self.assertEqual(d.goo(1), (D, 1))
1679 self.assertEqual(d.foo(1), (d, 1))
1680 self.assertEqual(D.foo(d, 1), (d, 1))
1681 class E: # *not* subclassing from C
1682 foo = C.foo
1683 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001684 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001685
1686 def test_compattr(self):
1687 # Testing computed attributes...
1688 class C(object):
1689 class computed_attribute(object):
1690 def __init__(self, get, set=None, delete=None):
1691 self.__get = get
1692 self.__set = set
1693 self.__delete = delete
1694 def __get__(self, obj, type=None):
1695 return self.__get(obj)
1696 def __set__(self, obj, value):
1697 return self.__set(obj, value)
1698 def __delete__(self, obj):
1699 return self.__delete(obj)
1700 def __init__(self):
1701 self.__x = 0
1702 def __get_x(self):
1703 x = self.__x
1704 self.__x = x+1
1705 return x
1706 def __set_x(self, x):
1707 self.__x = x
1708 def __delete_x(self):
1709 del self.__x
1710 x = computed_attribute(__get_x, __set_x, __delete_x)
1711 a = C()
1712 self.assertEqual(a.x, 0)
1713 self.assertEqual(a.x, 1)
1714 a.x = 10
1715 self.assertEqual(a.x, 10)
1716 self.assertEqual(a.x, 11)
1717 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001718 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001719
1720 def test_newslots(self):
1721 # Testing __new__ slot override...
1722 class C(list):
1723 def __new__(cls):
1724 self = list.__new__(cls)
1725 self.foo = 1
1726 return self
1727 def __init__(self):
1728 self.foo = self.foo + 2
1729 a = C()
1730 self.assertEqual(a.foo, 3)
1731 self.assertEqual(a.__class__, C)
1732 class D(C):
1733 pass
1734 b = D()
1735 self.assertEqual(b.foo, 3)
1736 self.assertEqual(b.__class__, D)
1737
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001738 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001739 def test_bad_new(self):
1740 self.assertRaises(TypeError, object.__new__)
1741 self.assertRaises(TypeError, object.__new__, '')
1742 self.assertRaises(TypeError, list.__new__, object)
1743 self.assertRaises(TypeError, object.__new__, list)
1744 class C(object):
1745 __new__ = list.__new__
1746 self.assertRaises(TypeError, C)
1747 class C(list):
1748 __new__ = object.__new__
1749 self.assertRaises(TypeError, C)
1750
1751 def test_object_new(self):
1752 class A(object):
1753 pass
1754 object.__new__(A)
1755 self.assertRaises(TypeError, object.__new__, A, 5)
1756 object.__init__(A())
1757 self.assertRaises(TypeError, object.__init__, A(), 5)
1758
1759 class A(object):
1760 def __init__(self, foo):
1761 self.foo = foo
1762 object.__new__(A)
1763 object.__new__(A, 5)
1764 object.__init__(A(3))
1765 self.assertRaises(TypeError, object.__init__, A(3), 5)
1766
1767 class A(object):
1768 def __new__(cls, foo):
1769 return object.__new__(cls)
1770 object.__new__(A)
1771 self.assertRaises(TypeError, object.__new__, A, 5)
1772 object.__init__(A(3))
1773 object.__init__(A(3), 5)
1774
1775 class A(object):
1776 def __new__(cls, foo):
1777 return object.__new__(cls)
1778 def __init__(self, foo):
1779 self.foo = foo
1780 object.__new__(A)
1781 self.assertRaises(TypeError, object.__new__, A, 5)
1782 object.__init__(A(3))
1783 self.assertRaises(TypeError, object.__init__, A(3), 5)
1784
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001785 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001786 def test_restored_object_new(self):
1787 class A(object):
1788 def __new__(cls, *args, **kwargs):
1789 raise AssertionError
1790 self.assertRaises(AssertionError, A)
1791 class B(A):
1792 __new__ = object.__new__
1793 def __init__(self, foo):
1794 self.foo = foo
1795 with warnings.catch_warnings():
1796 warnings.simplefilter('error', DeprecationWarning)
1797 b = B(3)
1798 self.assertEqual(b.foo, 3)
1799 self.assertEqual(b.__class__, B)
1800 del B.__new__
1801 self.assertRaises(AssertionError, B)
1802 del A.__new__
1803 with warnings.catch_warnings():
1804 warnings.simplefilter('error', DeprecationWarning)
1805 b = B(3)
1806 self.assertEqual(b.foo, 3)
1807 self.assertEqual(b.__class__, B)
1808
Georg Brandl479a7e72008-02-05 18:13:15 +00001809 def test_altmro(self):
1810 # Testing mro() and overriding it...
1811 class A(object):
1812 def f(self): return "A"
1813 class B(A):
1814 pass
1815 class C(A):
1816 def f(self): return "C"
1817 class D(B, C):
1818 pass
Antoine Pitrou1f1a34c2017-12-20 15:58:21 +01001819 self.assertEqual(A.mro(), [A, object])
1820 self.assertEqual(A.__mro__, (A, object))
1821 self.assertEqual(B.mro(), [B, A, object])
1822 self.assertEqual(B.__mro__, (B, A, object))
1823 self.assertEqual(C.mro(), [C, A, object])
1824 self.assertEqual(C.__mro__, (C, A, object))
Georg Brandl479a7e72008-02-05 18:13:15 +00001825 self.assertEqual(D.mro(), [D, B, C, A, object])
1826 self.assertEqual(D.__mro__, (D, B, C, A, object))
1827 self.assertEqual(D().f(), "C")
1828
1829 class PerverseMetaType(type):
1830 def mro(cls):
1831 L = type.mro(cls)
1832 L.reverse()
1833 return L
1834 class X(D,B,C,A, metaclass=PerverseMetaType):
1835 pass
1836 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1837 self.assertEqual(X().f(), "A")
1838
1839 try:
1840 class _metaclass(type):
1841 def mro(self):
1842 return [self, dict, object]
1843 class X(object, metaclass=_metaclass):
1844 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001845 # In CPython, the class creation above already raises
1846 # TypeError, as a protection against the fact that
1847 # instances of X would segfault it. In other Python
1848 # implementations it would be ok to let the class X
1849 # be created, but instead get a clean TypeError on the
1850 # __setitem__ below.
1851 x = object.__new__(X)
1852 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001853 except TypeError:
1854 pass
1855 else:
1856 self.fail("devious mro() return not caught")
1857
1858 try:
1859 class _metaclass(type):
1860 def mro(self):
1861 return [1]
1862 class X(object, metaclass=_metaclass):
1863 pass
1864 except TypeError:
1865 pass
1866 else:
1867 self.fail("non-class mro() return not caught")
1868
1869 try:
1870 class _metaclass(type):
1871 def mro(self):
1872 return 1
1873 class X(object, metaclass=_metaclass):
1874 pass
1875 except TypeError:
1876 pass
1877 else:
1878 self.fail("non-sequence mro() return not caught")
1879
1880 def test_overloading(self):
1881 # Testing operator overloading...
1882
1883 class B(object):
1884 "Intermediate class because object doesn't have a __setattr__"
1885
1886 class C(B):
1887 def __getattr__(self, name):
1888 if name == "foo":
1889 return ("getattr", name)
1890 else:
1891 raise AttributeError
1892 def __setattr__(self, name, value):
1893 if name == "foo":
1894 self.setattr = (name, value)
1895 else:
1896 return B.__setattr__(self, name, value)
1897 def __delattr__(self, name):
1898 if name == "foo":
1899 self.delattr = name
1900 else:
1901 return B.__delattr__(self, name)
1902
1903 def __getitem__(self, key):
1904 return ("getitem", key)
1905 def __setitem__(self, key, value):
1906 self.setitem = (key, value)
1907 def __delitem__(self, key):
1908 self.delitem = key
1909
1910 a = C()
1911 self.assertEqual(a.foo, ("getattr", "foo"))
1912 a.foo = 12
1913 self.assertEqual(a.setattr, ("foo", 12))
1914 del a.foo
1915 self.assertEqual(a.delattr, "foo")
1916
1917 self.assertEqual(a[12], ("getitem", 12))
1918 a[12] = 21
1919 self.assertEqual(a.setitem, (12, 21))
1920 del a[12]
1921 self.assertEqual(a.delitem, 12)
1922
1923 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1924 a[0:10] = "foo"
1925 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1926 del a[0:10]
1927 self.assertEqual(a.delitem, (slice(0, 10)))
1928
1929 def test_methods(self):
1930 # Testing methods...
1931 class C(object):
1932 def __init__(self, x):
1933 self.x = x
1934 def foo(self):
1935 return self.x
1936 c1 = C(1)
1937 self.assertEqual(c1.foo(), 1)
1938 class D(C):
1939 boo = C.foo
1940 goo = c1.foo
1941 d2 = D(2)
1942 self.assertEqual(d2.foo(), 2)
1943 self.assertEqual(d2.boo(), 2)
1944 self.assertEqual(d2.goo(), 1)
1945 class E(object):
1946 foo = C.foo
1947 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001948 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001949
Benjamin Peterson224205f2009-05-08 03:25:19 +00001950 def test_special_method_lookup(self):
1951 # The lookup of special methods bypasses __getattr__ and
1952 # __getattribute__, but they still can be descriptors.
1953
1954 def run_context(manager):
1955 with manager:
1956 pass
1957 def iden(self):
1958 return self
1959 def hello(self):
1960 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001961 def empty_seq(self):
1962 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001963 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001964 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001965 def complex_num(self):
1966 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001967 def stop(self):
1968 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001969 def return_true(self, thing=None):
1970 return True
1971 def do_isinstance(obj):
1972 return isinstance(int, obj)
1973 def do_issubclass(obj):
1974 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001975 def do_dict_missing(checker):
1976 class DictSub(checker.__class__, dict):
1977 pass
1978 self.assertEqual(DictSub()["hi"], 4)
1979 def some_number(self_, key):
1980 self.assertEqual(key, "hi")
1981 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001982 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001983 def format_impl(self, spec):
1984 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001985
1986 # It would be nice to have every special method tested here, but I'm
1987 # only listing the ones I can remember outside of typeobject.c, since it
1988 # does it right.
1989 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001990 ("__bytes__", bytes, hello, set(), {}),
1991 ("__reversed__", reversed, empty_seq, set(), {}),
1992 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001993 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001994 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1995 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001996 ("__missing__", do_dict_missing, some_number,
1997 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001998 ("__subclasscheck__", do_issubclass, return_true,
1999 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002000 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
2001 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00002002 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00002003 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002004 ("__floor__", math.floor, zero, set(), {}),
2005 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04002006 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00002007 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05002008 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002009 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00002010 ]
2011
2012 class Checker(object):
2013 def __getattr__(self, attr, test=self):
2014 test.fail("__getattr__ called with {0}".format(attr))
2015 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002016 if attr not in ok:
2017 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00002018 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002019 class SpecialDescr(object):
2020 def __init__(self, impl):
2021 self.impl = impl
2022 def __get__(self, obj, owner):
2023 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002024 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002025 class MyException(Exception):
2026 pass
2027 class ErrDescr(object):
2028 def __get__(self, obj, owner):
2029 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00002030
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002031 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00002032 class X(Checker):
2033 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002034 for attr, obj in env.items():
2035 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00002036 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002037 runner(X())
2038
2039 record = []
2040 class X(Checker):
2041 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00002042 for attr, obj in env.items():
2043 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00002044 setattr(X, name, SpecialDescr(meth_impl))
2045 runner(X())
2046 self.assertEqual(record, [1], name)
2047
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002048 class X(Checker):
2049 pass
2050 for attr, obj in env.items():
2051 setattr(X, attr, obj)
2052 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05002053 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00002054
Georg Brandl479a7e72008-02-05 18:13:15 +00002055 def test_specials(self):
2056 # Testing special operators...
2057 # Test operators like __hash__ for which a built-in default exists
2058
2059 # Test the default behavior for static classes
2060 class C(object):
2061 def __getitem__(self, i):
2062 if 0 <= i < 10: return i
2063 raise IndexError
2064 c1 = C()
2065 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002066 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002067 self.assertNotEqual(id(c1), id(c2))
2068 hash(c1)
2069 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002070 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002071 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002072 self.assertFalse(c1 != c1)
2073 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002074 # Note that the module name appears in str/repr, and that varies
2075 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002076 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002077 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002078 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002079 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002080 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002081 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002082 # Test the default behavior for dynamic classes
2083 class D(object):
2084 def __getitem__(self, i):
2085 if 0 <= i < 10: return i
2086 raise IndexError
2087 d1 = D()
2088 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002089 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002090 self.assertNotEqual(id(d1), id(d2))
2091 hash(d1)
2092 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002093 self.assertEqual(d1, d1)
2094 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002095 self.assertFalse(d1 != d1)
2096 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002097 # Note that the module name appears in str/repr, and that varies
2098 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002099 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002100 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002101 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002102 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002103 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002104 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002105 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002106 class Proxy(object):
2107 def __init__(self, x):
2108 self.x = x
2109 def __bool__(self):
2110 return not not self.x
2111 def __hash__(self):
2112 return hash(self.x)
2113 def __eq__(self, other):
2114 return self.x == other
2115 def __ne__(self, other):
2116 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002117 def __ge__(self, other):
2118 return self.x >= other
2119 def __gt__(self, other):
2120 return self.x > other
2121 def __le__(self, other):
2122 return self.x <= other
2123 def __lt__(self, other):
2124 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002125 def __str__(self):
2126 return "Proxy:%s" % self.x
2127 def __repr__(self):
2128 return "Proxy(%r)" % self.x
2129 def __contains__(self, value):
2130 return value in self.x
2131 p0 = Proxy(0)
2132 p1 = Proxy(1)
2133 p_1 = Proxy(-1)
2134 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002135 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002136 self.assertEqual(hash(p0), hash(0))
2137 self.assertEqual(p0, p0)
2138 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002139 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002140 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002141 self.assertTrue(p0 < p1)
2142 self.assertTrue(p0 <= p1)
2143 self.assertTrue(p1 > p0)
2144 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002145 self.assertEqual(str(p0), "Proxy:0")
2146 self.assertEqual(repr(p0), "Proxy(0)")
2147 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002148 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002149 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002150 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002151 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002152
Georg Brandl479a7e72008-02-05 18:13:15 +00002153 def test_weakrefs(self):
2154 # Testing weak references...
2155 import weakref
2156 class C(object):
2157 pass
2158 c = C()
2159 r = weakref.ref(c)
2160 self.assertEqual(r(), c)
2161 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002162 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002163 self.assertEqual(r(), None)
2164 del r
2165 class NoWeak(object):
2166 __slots__ = ['foo']
2167 no = NoWeak()
2168 try:
2169 weakref.ref(no)
2170 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002171 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002172 else:
2173 self.fail("weakref.ref(no) should be illegal")
2174 class Weak(object):
2175 __slots__ = ['foo', '__weakref__']
2176 yes = Weak()
2177 r = weakref.ref(yes)
2178 self.assertEqual(r(), yes)
2179 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002180 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002181 self.assertEqual(r(), None)
2182 del r
2183
2184 def test_properties(self):
2185 # Testing property...
2186 class C(object):
2187 def getx(self):
2188 return self.__x
2189 def setx(self, value):
2190 self.__x = value
2191 def delx(self):
2192 del self.__x
2193 x = property(getx, setx, delx, doc="I'm the x property.")
2194 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002195 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002196 a.x = 42
2197 self.assertEqual(a._C__x, 42)
2198 self.assertEqual(a.x, 42)
2199 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002200 self.assertNotHasAttr(a, "x")
2201 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002202 C.x.__set__(a, 100)
2203 self.assertEqual(C.x.__get__(a), 100)
2204 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002205 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002206
2207 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002208 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002209
2210 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002211 self.assertIn("__doc__", attrs)
2212 self.assertIn("fget", attrs)
2213 self.assertIn("fset", attrs)
2214 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002215
2216 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002217 self.assertIs(raw.fget, C.__dict__['getx'])
2218 self.assertIs(raw.fset, C.__dict__['setx'])
2219 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002220
Raymond Hettingereac503a2015-05-13 01:09:59 -07002221 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002222 try:
2223 setattr(raw, attr, 42)
2224 except AttributeError as msg:
2225 if str(msg).find('readonly') < 0:
2226 self.fail("when setting readonly attr %r on a property, "
2227 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2228 else:
2229 self.fail("expected AttributeError from trying to set readonly %r "
2230 "attr on a property" % attr)
2231
Raymond Hettingereac503a2015-05-13 01:09:59 -07002232 raw.__doc__ = 42
2233 self.assertEqual(raw.__doc__, 42)
2234
Georg Brandl479a7e72008-02-05 18:13:15 +00002235 class D(object):
2236 __getitem__ = property(lambda s: 1/0)
2237
2238 d = D()
2239 try:
2240 for i in d:
2241 str(i)
2242 except ZeroDivisionError:
2243 pass
2244 else:
2245 self.fail("expected ZeroDivisionError from bad property")
2246
R. David Murray378c0cf2010-02-24 01:46:21 +00002247 @unittest.skipIf(sys.flags.optimize >= 2,
2248 "Docstrings are omitted with -O2 and above")
2249 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002250 class E(object):
2251 def getter(self):
2252 "getter method"
2253 return 0
2254 def setter(self_, value):
2255 "setter method"
2256 pass
2257 prop = property(getter)
2258 self.assertEqual(prop.__doc__, "getter method")
2259 prop2 = property(fset=setter)
2260 self.assertEqual(prop2.__doc__, None)
2261
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002262 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002263 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002264 # this segfaulted in 2.5b2
2265 try:
2266 import _testcapi
2267 except ImportError:
2268 pass
2269 else:
2270 class X(object):
2271 p = property(_testcapi.test_with_docstring)
2272
2273 def test_properties_plus(self):
2274 class C(object):
2275 foo = property(doc="hello")
2276 @foo.getter
2277 def foo(self):
2278 return self._foo
2279 @foo.setter
2280 def foo(self, value):
2281 self._foo = abs(value)
2282 @foo.deleter
2283 def foo(self):
2284 del self._foo
2285 c = C()
2286 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002287 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002288 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002289 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002290 self.assertEqual(c._foo, 42)
2291 self.assertEqual(c.foo, 42)
2292 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002293 self.assertNotHasAttr(c, '_foo')
2294 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002295
2296 class D(C):
2297 @C.foo.deleter
2298 def foo(self):
2299 try:
2300 del self._foo
2301 except AttributeError:
2302 pass
2303 d = D()
2304 d.foo = 24
2305 self.assertEqual(d.foo, 24)
2306 del d.foo
2307 del d.foo
2308
2309 class E(object):
2310 @property
2311 def foo(self):
2312 return self._foo
2313 @foo.setter
2314 def foo(self, value):
2315 raise RuntimeError
2316 @foo.setter
2317 def foo(self, value):
2318 self._foo = abs(value)
2319 @foo.deleter
2320 def foo(self, value=None):
2321 del self._foo
2322
2323 e = E()
2324 e.foo = -42
2325 self.assertEqual(e.foo, 42)
2326 del e.foo
2327
2328 class F(E):
2329 @E.foo.deleter
2330 def foo(self):
2331 del self._foo
2332 @foo.setter
2333 def foo(self, value):
2334 self._foo = max(0, value)
2335 f = F()
2336 f.foo = -10
2337 self.assertEqual(f.foo, 0)
2338 del f.foo
2339
2340 def test_dict_constructors(self):
2341 # Testing dict constructor ...
2342 d = dict()
2343 self.assertEqual(d, {})
2344 d = dict({})
2345 self.assertEqual(d, {})
2346 d = dict({1: 2, 'a': 'b'})
2347 self.assertEqual(d, {1: 2, 'a': 'b'})
2348 self.assertEqual(d, dict(list(d.items())))
2349 self.assertEqual(d, dict(iter(d.items())))
2350 d = dict({'one':1, 'two':2})
2351 self.assertEqual(d, dict(one=1, two=2))
2352 self.assertEqual(d, dict(**d))
2353 self.assertEqual(d, dict({"one": 1}, two=2))
2354 self.assertEqual(d, dict([("two", 2)], one=1))
2355 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2356 self.assertEqual(d, dict(**d))
2357
2358 for badarg in 0, 0, 0j, "0", [0], (0,):
2359 try:
2360 dict(badarg)
2361 except TypeError:
2362 pass
2363 except ValueError:
2364 if badarg == "0":
2365 # It's a sequence, and its elements are also sequences (gotta
2366 # love strings <wink>), but they aren't of length 2, so this
2367 # one seemed better as a ValueError than a TypeError.
2368 pass
2369 else:
2370 self.fail("no TypeError from dict(%r)" % badarg)
2371 else:
2372 self.fail("no TypeError from dict(%r)" % badarg)
2373
2374 try:
2375 dict({}, {})
2376 except TypeError:
2377 pass
2378 else:
2379 self.fail("no TypeError from dict({}, {})")
2380
2381 class Mapping:
2382 # Lacks a .keys() method; will be added later.
2383 dict = {1:2, 3:4, 'a':1j}
2384
2385 try:
2386 dict(Mapping())
2387 except TypeError:
2388 pass
2389 else:
2390 self.fail("no TypeError from dict(incomplete mapping)")
2391
2392 Mapping.keys = lambda self: list(self.dict.keys())
2393 Mapping.__getitem__ = lambda self, i: self.dict[i]
2394 d = dict(Mapping())
2395 self.assertEqual(d, Mapping.dict)
2396
2397 # Init from sequence of iterable objects, each producing a 2-sequence.
2398 class AddressBookEntry:
2399 def __init__(self, first, last):
2400 self.first = first
2401 self.last = last
2402 def __iter__(self):
2403 return iter([self.first, self.last])
2404
2405 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2406 AddressBookEntry('Barry', 'Peters'),
2407 AddressBookEntry('Tim', 'Peters'),
2408 AddressBookEntry('Barry', 'Warsaw')])
2409 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2410
2411 d = dict(zip(range(4), range(1, 5)))
2412 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2413
2414 # Bad sequence lengths.
2415 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2416 try:
2417 dict(bad)
2418 except ValueError:
2419 pass
2420 else:
2421 self.fail("no ValueError from dict(%r)" % bad)
2422
2423 def test_dir(self):
2424 # Testing dir() ...
2425 junk = 12
2426 self.assertEqual(dir(), ['junk', 'self'])
2427 del junk
2428
2429 # Just make sure these don't blow up!
2430 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2431 dir(arg)
2432
2433 # Test dir on new-style classes. Since these have object as a
2434 # base class, a lot more gets sucked in.
2435 def interesting(strings):
2436 return [s for s in strings if not s.startswith('_')]
2437
2438 class C(object):
2439 Cdata = 1
2440 def Cmethod(self): pass
2441
2442 cstuff = ['Cdata', 'Cmethod']
2443 self.assertEqual(interesting(dir(C)), cstuff)
2444
2445 c = C()
2446 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002447 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002448
2449 c.cdata = 2
2450 c.cmethod = lambda self: 0
2451 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002452 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002453
2454 class A(C):
2455 Adata = 1
2456 def Amethod(self): pass
2457
2458 astuff = ['Adata', 'Amethod'] + cstuff
2459 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002460 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002461 a = A()
2462 self.assertEqual(interesting(dir(a)), astuff)
2463 a.adata = 42
2464 a.amethod = lambda self: 3
2465 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002466 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002467
2468 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002469 class M(type(sys)):
2470 pass
2471 minstance = M("m")
2472 minstance.b = 2
2473 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002474 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002475 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002476 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002477 self.assertEqual(names, ['a', 'b'])
2478
2479 class M2(M):
2480 def getdict(self):
2481 return "Not a dict!"
2482 __dict__ = property(getdict)
2483
2484 m2instance = M2("m2")
2485 m2instance.b = 2
2486 m2instance.a = 1
2487 self.assertEqual(m2instance.__dict__, "Not a dict!")
2488 try:
2489 dir(m2instance)
2490 except TypeError:
2491 pass
2492
2493 # Two essentially featureless objects, just inheriting stuff from
2494 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002495 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002496
2497 # Nasty test case for proxied objects
2498 class Wrapper(object):
2499 def __init__(self, obj):
2500 self.__obj = obj
2501 def __repr__(self):
2502 return "Wrapper(%s)" % repr(self.__obj)
2503 def __getitem__(self, key):
2504 return Wrapper(self.__obj[key])
2505 def __len__(self):
2506 return len(self.__obj)
2507 def __getattr__(self, name):
2508 return Wrapper(getattr(self.__obj, name))
2509
2510 class C(object):
2511 def __getclass(self):
2512 return Wrapper(type(self))
2513 __class__ = property(__getclass)
2514
2515 dir(C()) # This used to segfault
2516
2517 def test_supers(self):
2518 # Testing super...
2519
2520 class A(object):
2521 def meth(self, a):
2522 return "A(%r)" % a
2523
2524 self.assertEqual(A().meth(1), "A(1)")
2525
2526 class B(A):
2527 def __init__(self):
2528 self.__super = super(B, self)
2529 def meth(self, a):
2530 return "B(%r)" % a + self.__super.meth(a)
2531
2532 self.assertEqual(B().meth(2), "B(2)A(2)")
2533
2534 class C(A):
2535 def meth(self, a):
2536 return "C(%r)" % a + self.__super.meth(a)
2537 C._C__super = super(C)
2538
2539 self.assertEqual(C().meth(3), "C(3)A(3)")
2540
2541 class D(C, B):
2542 def meth(self, a):
2543 return "D(%r)" % a + super(D, self).meth(a)
2544
2545 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2546
2547 # Test for subclassing super
2548
2549 class mysuper(super):
2550 def __init__(self, *args):
2551 return super(mysuper, self).__init__(*args)
2552
2553 class E(D):
2554 def meth(self, a):
2555 return "E(%r)" % a + mysuper(E, self).meth(a)
2556
2557 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2558
2559 class F(E):
2560 def meth(self, a):
2561 s = self.__super # == mysuper(F, self)
2562 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2563 F._F__super = mysuper(F)
2564
2565 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2566
2567 # Make sure certain errors are raised
2568
2569 try:
2570 super(D, 42)
2571 except TypeError:
2572 pass
2573 else:
2574 self.fail("shouldn't allow super(D, 42)")
2575
2576 try:
2577 super(D, C())
2578 except TypeError:
2579 pass
2580 else:
2581 self.fail("shouldn't allow super(D, C())")
2582
2583 try:
2584 super(D).__get__(12)
2585 except TypeError:
2586 pass
2587 else:
2588 self.fail("shouldn't allow super(D).__get__(12)")
2589
2590 try:
2591 super(D).__get__(C())
2592 except TypeError:
2593 pass
2594 else:
2595 self.fail("shouldn't allow super(D).__get__(C())")
2596
2597 # Make sure data descriptors can be overridden and accessed via super
2598 # (new feature in Python 2.3)
2599
2600 class DDbase(object):
2601 def getx(self): return 42
2602 x = property(getx)
2603
2604 class DDsub(DDbase):
2605 def getx(self): return "hello"
2606 x = property(getx)
2607
2608 dd = DDsub()
2609 self.assertEqual(dd.x, "hello")
2610 self.assertEqual(super(DDsub, dd).x, 42)
2611
2612 # Ensure that super() lookup of descriptor from classmethod
2613 # works (SF ID# 743627)
2614
2615 class Base(object):
2616 aProp = property(lambda self: "foo")
2617
2618 class Sub(Base):
2619 @classmethod
2620 def test(klass):
2621 return super(Sub,klass).aProp
2622
2623 self.assertEqual(Sub.test(), Base.aProp)
2624
2625 # Verify that super() doesn't allow keyword args
2626 try:
2627 super(Base, kw=1)
2628 except TypeError:
2629 pass
2630 else:
2631 self.assertEqual("super shouldn't accept keyword args")
2632
2633 def test_basic_inheritance(self):
2634 # Testing inheritance from basic types...
2635
2636 class hexint(int):
2637 def __repr__(self):
2638 return hex(self)
2639 def __add__(self, other):
2640 return hexint(int.__add__(self, other))
2641 # (Note that overriding __radd__ doesn't work,
2642 # because the int type gets first dibs.)
2643 self.assertEqual(repr(hexint(7) + 9), "0x10")
2644 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2645 a = hexint(12345)
2646 self.assertEqual(a, 12345)
2647 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002648 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002649 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002650 self.assertIs((+a).__class__, int)
2651 self.assertIs((a >> 0).__class__, int)
2652 self.assertIs((a << 0).__class__, int)
2653 self.assertIs((hexint(0) << 12).__class__, int)
2654 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002655
2656 class octlong(int):
2657 __slots__ = []
2658 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002659 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002660 def __add__(self, other):
2661 return self.__class__(super(octlong, self).__add__(other))
2662 __radd__ = __add__
2663 self.assertEqual(str(octlong(3) + 5), "0o10")
2664 # (Note that overriding __radd__ here only seems to work
2665 # because the example uses a short int left argument.)
2666 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2667 a = octlong(12345)
2668 self.assertEqual(a, 12345)
2669 self.assertEqual(int(a), 12345)
2670 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002671 self.assertIs(int(a).__class__, int)
2672 self.assertIs((+a).__class__, int)
2673 self.assertIs((-a).__class__, int)
2674 self.assertIs((-octlong(0)).__class__, int)
2675 self.assertIs((a >> 0).__class__, int)
2676 self.assertIs((a << 0).__class__, int)
2677 self.assertIs((a - 0).__class__, int)
2678 self.assertIs((a * 1).__class__, int)
2679 self.assertIs((a ** 1).__class__, int)
2680 self.assertIs((a // 1).__class__, int)
2681 self.assertIs((1 * a).__class__, int)
2682 self.assertIs((a | 0).__class__, int)
2683 self.assertIs((a ^ 0).__class__, int)
2684 self.assertIs((a & -1).__class__, int)
2685 self.assertIs((octlong(0) << 12).__class__, int)
2686 self.assertIs((octlong(0) >> 12).__class__, int)
2687 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002688
2689 # Because octlong overrides __add__, we can't check the absence of +0
2690 # optimizations using octlong.
2691 class longclone(int):
2692 pass
2693 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002694 self.assertIs((a + 0).__class__, int)
2695 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002696
2697 # Check that negative clones don't segfault
2698 a = longclone(-1)
2699 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002700 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002701
2702 class precfloat(float):
2703 __slots__ = ['prec']
2704 def __init__(self, value=0.0, prec=12):
2705 self.prec = int(prec)
2706 def __repr__(self):
2707 return "%.*g" % (self.prec, self)
2708 self.assertEqual(repr(precfloat(1.1)), "1.1")
2709 a = precfloat(12345)
2710 self.assertEqual(a, 12345.0)
2711 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002712 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002713 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002714 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002715
2716 class madcomplex(complex):
2717 def __repr__(self):
2718 return "%.17gj%+.17g" % (self.imag, self.real)
2719 a = madcomplex(-3, 4)
2720 self.assertEqual(repr(a), "4j-3")
2721 base = complex(-3, 4)
2722 self.assertEqual(base.__class__, complex)
2723 self.assertEqual(a, base)
2724 self.assertEqual(complex(a), base)
2725 self.assertEqual(complex(a).__class__, complex)
2726 a = madcomplex(a) # just trying another form of the constructor
2727 self.assertEqual(repr(a), "4j-3")
2728 self.assertEqual(a, base)
2729 self.assertEqual(complex(a), base)
2730 self.assertEqual(complex(a).__class__, complex)
2731 self.assertEqual(hash(a), hash(base))
2732 self.assertEqual((+a).__class__, complex)
2733 self.assertEqual((a + 0).__class__, complex)
2734 self.assertEqual(a + 0, base)
2735 self.assertEqual((a - 0).__class__, complex)
2736 self.assertEqual(a - 0, base)
2737 self.assertEqual((a * 1).__class__, complex)
2738 self.assertEqual(a * 1, base)
2739 self.assertEqual((a / 1).__class__, complex)
2740 self.assertEqual(a / 1, base)
2741
2742 class madtuple(tuple):
2743 _rev = None
2744 def rev(self):
2745 if self._rev is not None:
2746 return self._rev
2747 L = list(self)
2748 L.reverse()
2749 self._rev = self.__class__(L)
2750 return self._rev
2751 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2752 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2753 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2754 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2755 for i in range(512):
2756 t = madtuple(range(i))
2757 u = t.rev()
2758 v = u.rev()
2759 self.assertEqual(v, t)
2760 a = madtuple((1,2,3,4,5))
2761 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002762 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002763 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002764 self.assertIs(a[:].__class__, tuple)
2765 self.assertIs((a * 1).__class__, tuple)
2766 self.assertIs((a * 0).__class__, tuple)
2767 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002768 a = madtuple(())
2769 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002770 self.assertIs(tuple(a).__class__, tuple)
2771 self.assertIs((a + a).__class__, tuple)
2772 self.assertIs((a * 0).__class__, tuple)
2773 self.assertIs((a * 1).__class__, tuple)
2774 self.assertIs((a * 2).__class__, tuple)
2775 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002776
2777 class madstring(str):
2778 _rev = None
2779 def rev(self):
2780 if self._rev is not None:
2781 return self._rev
2782 L = list(self)
2783 L.reverse()
2784 self._rev = self.__class__("".join(L))
2785 return self._rev
2786 s = madstring("abcdefghijklmnopqrstuvwxyz")
2787 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2788 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2789 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2790 for i in range(256):
2791 s = madstring("".join(map(chr, range(i))))
2792 t = s.rev()
2793 u = t.rev()
2794 self.assertEqual(u, s)
2795 s = madstring("12345")
2796 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002797 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002798
2799 base = "\x00" * 5
2800 s = madstring(base)
2801 self.assertEqual(s, base)
2802 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002803 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002804 self.assertEqual(hash(s), hash(base))
2805 self.assertEqual({s: 1}[base], 1)
2806 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002807 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002808 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002809 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002810 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002811 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002812 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002813 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002814 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002815 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002816 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002817 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002818 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002819 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002820 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002821 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002822 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002823 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002824 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002825 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002826 self.assertEqual(s.rstrip(), base)
2827 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002828 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002829 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002830 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002831 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002832 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002833 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002834 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002835 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002836 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002837 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002838 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002839 self.assertEqual(s.lower(), base)
2840
2841 class madunicode(str):
2842 _rev = None
2843 def rev(self):
2844 if self._rev is not None:
2845 return self._rev
2846 L = list(self)
2847 L.reverse()
2848 self._rev = self.__class__("".join(L))
2849 return self._rev
2850 u = madunicode("ABCDEF")
2851 self.assertEqual(u, "ABCDEF")
2852 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2853 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2854 base = "12345"
2855 u = madunicode(base)
2856 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002858 self.assertEqual(hash(u), hash(base))
2859 self.assertEqual({u: 1}[base], 1)
2860 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002861 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002862 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002864 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002865 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002866 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002867 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002868 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002869 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002870 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002871 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002872 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002873 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002874 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002875 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002876 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002877 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002878 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002879 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002880 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002881 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002882 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002883 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002884 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002885 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002886 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002887 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002888 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002889 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002890 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002891 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002892 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002893 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002894 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002895 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002896 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002897 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002898 self.assertEqual(u[0:0], "")
2899
2900 class sublist(list):
2901 pass
2902 a = sublist(range(5))
2903 self.assertEqual(a, list(range(5)))
2904 a.append("hello")
2905 self.assertEqual(a, list(range(5)) + ["hello"])
2906 a[5] = 5
2907 self.assertEqual(a, list(range(6)))
2908 a.extend(range(6, 20))
2909 self.assertEqual(a, list(range(20)))
2910 a[-5:] = []
2911 self.assertEqual(a, list(range(15)))
2912 del a[10:15]
2913 self.assertEqual(len(a), 10)
2914 self.assertEqual(a, list(range(10)))
2915 self.assertEqual(list(a), list(range(10)))
2916 self.assertEqual(a[0], 0)
2917 self.assertEqual(a[9], 9)
2918 self.assertEqual(a[-10], 0)
2919 self.assertEqual(a[-1], 9)
2920 self.assertEqual(a[:5], list(range(5)))
2921
2922 ## class CountedInput(file):
2923 ## """Counts lines read by self.readline().
2924 ##
2925 ## self.lineno is the 0-based ordinal of the last line read, up to
2926 ## a maximum of one greater than the number of lines in the file.
2927 ##
2928 ## self.ateof is true if and only if the final "" line has been read,
2929 ## at which point self.lineno stops incrementing, and further calls
2930 ## to readline() continue to return "".
2931 ## """
2932 ##
2933 ## lineno = 0
2934 ## ateof = 0
2935 ## def readline(self):
2936 ## if self.ateof:
2937 ## return ""
2938 ## s = file.readline(self)
2939 ## # Next line works too.
2940 ## # s = super(CountedInput, self).readline()
2941 ## self.lineno += 1
2942 ## if s == "":
2943 ## self.ateof = 1
2944 ## return s
2945 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002946 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002947 ## lines = ['a\n', 'b\n', 'c\n']
2948 ## try:
2949 ## f.writelines(lines)
2950 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002951 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002952 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2953 ## got = f.readline()
2954 ## self.assertEqual(expected, got)
2955 ## self.assertEqual(f.lineno, i)
2956 ## self.assertEqual(f.ateof, (i > len(lines)))
2957 ## f.close()
2958 ## finally:
2959 ## try:
2960 ## f.close()
2961 ## except:
2962 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002963 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002964
2965 def test_keywords(self):
2966 # Testing keyword args to basic type constructors ...
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002967 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2968 int(x=1)
2969 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2970 float(x=2)
2971 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2972 bool(x=2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002973 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2974 self.assertEqual(str(object=500), '500')
2975 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
Serhiy Storchakad908fd92017-03-06 21:08:59 +02002976 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2977 tuple(sequence=range(3))
2978 with self.assertRaisesRegex(TypeError, 'keyword argument'):
2979 list(sequence=(0, 1, 2))
Georg Brandl479a7e72008-02-05 18:13:15 +00002980 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2981
2982 for constructor in (int, float, int, complex, str, str,
2983 tuple, list):
2984 try:
2985 constructor(bogus_keyword_arg=1)
2986 except TypeError:
2987 pass
2988 else:
2989 self.fail("expected TypeError from bogus keyword argument to %r"
2990 % constructor)
2991
2992 def test_str_subclass_as_dict_key(self):
2993 # Testing a str subclass used as dict key ..
2994
2995 class cistr(str):
2996 """Sublcass of str that computes __eq__ case-insensitively.
2997
2998 Also computes a hash code of the string in canonical form.
2999 """
3000
3001 def __init__(self, value):
3002 self.canonical = value.lower()
3003 self.hashcode = hash(self.canonical)
3004
3005 def __eq__(self, other):
3006 if not isinstance(other, cistr):
3007 other = cistr(other)
3008 return self.canonical == other.canonical
3009
3010 def __hash__(self):
3011 return self.hashcode
3012
3013 self.assertEqual(cistr('ABC'), 'abc')
3014 self.assertEqual('aBc', cistr('ABC'))
3015 self.assertEqual(str(cistr('ABC')), 'ABC')
3016
3017 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3018 self.assertEqual(d[cistr('one')], 1)
3019 self.assertEqual(d[cistr('tWo')], 2)
3020 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00003021 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003022 self.assertEqual(d.get(cistr('thrEE')), 3)
3023
3024 def test_classic_comparisons(self):
3025 # Testing classic comparisons...
3026 class classic:
3027 pass
3028
3029 for base in (classic, int, object):
3030 class C(base):
3031 def __init__(self, value):
3032 self.value = int(value)
3033 def __eq__(self, other):
3034 if isinstance(other, C):
3035 return self.value == other.value
3036 if isinstance(other, int) or isinstance(other, int):
3037 return self.value == other
3038 return NotImplemented
3039 def __ne__(self, other):
3040 if isinstance(other, C):
3041 return self.value != other.value
3042 if isinstance(other, int) or isinstance(other, int):
3043 return self.value != other
3044 return NotImplemented
3045 def __lt__(self, other):
3046 if isinstance(other, C):
3047 return self.value < other.value
3048 if isinstance(other, int) or isinstance(other, int):
3049 return self.value < other
3050 return NotImplemented
3051 def __le__(self, other):
3052 if isinstance(other, C):
3053 return self.value <= other.value
3054 if isinstance(other, int) or isinstance(other, int):
3055 return self.value <= other
3056 return NotImplemented
3057 def __gt__(self, other):
3058 if isinstance(other, C):
3059 return self.value > other.value
3060 if isinstance(other, int) or isinstance(other, int):
3061 return self.value > other
3062 return NotImplemented
3063 def __ge__(self, other):
3064 if isinstance(other, C):
3065 return self.value >= other.value
3066 if isinstance(other, int) or isinstance(other, int):
3067 return self.value >= other
3068 return NotImplemented
3069
3070 c1 = C(1)
3071 c2 = C(2)
3072 c3 = C(3)
3073 self.assertEqual(c1, 1)
3074 c = {1: c1, 2: c2, 3: c3}
3075 for x in 1, 2, 3:
3076 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00003077 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003078 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003079 eval("x %s y" % op),
3080 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003081 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003082 eval("x %s y" % op),
3083 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003084 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003085 eval("x %s y" % op),
3086 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003087
3088 def test_rich_comparisons(self):
3089 # Testing rich comparisons...
3090 class Z(complex):
3091 pass
3092 z = Z(1)
3093 self.assertEqual(z, 1+0j)
3094 self.assertEqual(1+0j, z)
3095 class ZZ(complex):
3096 def __eq__(self, other):
3097 try:
3098 return abs(self - other) <= 1e-6
3099 except:
3100 return NotImplemented
3101 zz = ZZ(1.0000003)
3102 self.assertEqual(zz, 1+0j)
3103 self.assertEqual(1+0j, zz)
3104
3105 class classic:
3106 pass
3107 for base in (classic, int, object, list):
3108 class C(base):
3109 def __init__(self, value):
3110 self.value = int(value)
3111 def __cmp__(self_, other):
3112 self.fail("shouldn't call __cmp__")
3113 def __eq__(self, other):
3114 if isinstance(other, C):
3115 return self.value == other.value
3116 if isinstance(other, int) or isinstance(other, int):
3117 return self.value == other
3118 return NotImplemented
3119 def __ne__(self, other):
3120 if isinstance(other, C):
3121 return self.value != other.value
3122 if isinstance(other, int) or isinstance(other, int):
3123 return self.value != other
3124 return NotImplemented
3125 def __lt__(self, other):
3126 if isinstance(other, C):
3127 return self.value < other.value
3128 if isinstance(other, int) or isinstance(other, int):
3129 return self.value < other
3130 return NotImplemented
3131 def __le__(self, other):
3132 if isinstance(other, C):
3133 return self.value <= other.value
3134 if isinstance(other, int) or isinstance(other, int):
3135 return self.value <= other
3136 return NotImplemented
3137 def __gt__(self, other):
3138 if isinstance(other, C):
3139 return self.value > other.value
3140 if isinstance(other, int) or isinstance(other, int):
3141 return self.value > other
3142 return NotImplemented
3143 def __ge__(self, other):
3144 if isinstance(other, C):
3145 return self.value >= other.value
3146 if isinstance(other, int) or isinstance(other, int):
3147 return self.value >= other
3148 return NotImplemented
3149 c1 = C(1)
3150 c2 = C(2)
3151 c3 = C(3)
3152 self.assertEqual(c1, 1)
3153 c = {1: c1, 2: c2, 3: c3}
3154 for x in 1, 2, 3:
3155 for y in 1, 2, 3:
3156 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003157 self.assertEqual(eval("c[x] %s c[y]" % op),
3158 eval("x %s y" % op),
3159 "x=%d, y=%d" % (x, y))
3160 self.assertEqual(eval("c[x] %s y" % op),
3161 eval("x %s y" % op),
3162 "x=%d, y=%d" % (x, y))
3163 self.assertEqual(eval("x %s c[y]" % op),
3164 eval("x %s y" % op),
3165 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003166
3167 def test_descrdoc(self):
3168 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003169 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003170 def check(descr, what):
3171 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003172 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003173 check(complex.real, "the real part of a complex number") # member descriptor
3174
3175 def test_doc_descriptor(self):
3176 # Testing __doc__ descriptor...
3177 # SF bug 542984
3178 class DocDescr(object):
3179 def __get__(self, object, otype):
3180 if object:
3181 object = object.__class__.__name__ + ' instance'
3182 if otype:
3183 otype = otype.__name__
3184 return 'object=%s; type=%s' % (object, otype)
3185 class OldClass:
3186 __doc__ = DocDescr()
3187 class NewClass(object):
3188 __doc__ = DocDescr()
3189 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3190 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3191 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3192 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3193
3194 def test_set_class(self):
3195 # Testing __class__ assignment...
3196 class C(object): pass
3197 class D(object): pass
3198 class E(object): pass
3199 class F(D, E): pass
3200 for cls in C, D, E, F:
3201 for cls2 in C, D, E, F:
3202 x = cls()
3203 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003204 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003205 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003206 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003207 def cant(x, C):
3208 try:
3209 x.__class__ = C
3210 except TypeError:
3211 pass
3212 else:
3213 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3214 try:
3215 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003216 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003217 pass
3218 else:
3219 self.fail("shouldn't allow del %r.__class__" % x)
3220 cant(C(), list)
3221 cant(list(), C)
3222 cant(C(), 1)
3223 cant(C(), object)
3224 cant(object(), list)
3225 cant(list(), object)
3226 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003227 cant(True, int)
3228 cant(2, bool)
3229 o = object()
3230 cant(o, type(1))
3231 cant(o, type(None))
3232 del o
3233 class G(object):
3234 __slots__ = ["a", "b"]
3235 class H(object):
3236 __slots__ = ["b", "a"]
3237 class I(object):
3238 __slots__ = ["a", "b"]
3239 class J(object):
3240 __slots__ = ["c", "b"]
3241 class K(object):
3242 __slots__ = ["a", "b", "d"]
3243 class L(H):
3244 __slots__ = ["e"]
3245 class M(I):
3246 __slots__ = ["e"]
3247 class N(J):
3248 __slots__ = ["__weakref__"]
3249 class P(J):
3250 __slots__ = ["__dict__"]
3251 class Q(J):
3252 pass
3253 class R(J):
3254 __slots__ = ["__dict__", "__weakref__"]
3255
3256 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3257 x = cls()
3258 x.a = 1
3259 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003260 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003261 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3262 self.assertEqual(x.a, 1)
3263 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003264 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003265 "assigning %r as __class__ for %r silently failed" % (cls, x))
3266 self.assertEqual(x.a, 1)
3267 for cls in G, J, K, L, M, N, P, R, list, Int:
3268 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3269 if cls is cls2:
3270 continue
3271 cant(cls(), cls2)
3272
Benjamin Peterson193152c2009-04-25 01:08:45 +00003273 # Issue5283: when __class__ changes in __del__, the wrong
3274 # type gets DECREF'd.
3275 class O(object):
3276 pass
3277 class A(object):
3278 def __del__(self):
3279 self.__class__ = O
3280 l = [A() for x in range(100)]
3281 del l
3282
Georg Brandl479a7e72008-02-05 18:13:15 +00003283 def test_set_dict(self):
3284 # Testing __dict__ assignment...
3285 class C(object): pass
3286 a = C()
3287 a.__dict__ = {'b': 1}
3288 self.assertEqual(a.b, 1)
3289 def cant(x, dict):
3290 try:
3291 x.__dict__ = dict
3292 except (AttributeError, TypeError):
3293 pass
3294 else:
3295 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3296 cant(a, None)
3297 cant(a, [])
3298 cant(a, 1)
3299 del a.__dict__ # Deleting __dict__ is allowed
3300
3301 class Base(object):
3302 pass
3303 def verify_dict_readonly(x):
3304 """
3305 x has to be an instance of a class inheriting from Base.
3306 """
3307 cant(x, {})
3308 try:
3309 del x.__dict__
3310 except (AttributeError, TypeError):
3311 pass
3312 else:
3313 self.fail("shouldn't allow del %r.__dict__" % x)
3314 dict_descr = Base.__dict__["__dict__"]
3315 try:
3316 dict_descr.__set__(x, {})
3317 except (AttributeError, TypeError):
3318 pass
3319 else:
3320 self.fail("dict_descr allowed access to %r's dict" % x)
3321
3322 # Classes don't allow __dict__ assignment and have readonly dicts
3323 class Meta1(type, Base):
3324 pass
3325 class Meta2(Base, type):
3326 pass
3327 class D(object, metaclass=Meta1):
3328 pass
3329 class E(object, metaclass=Meta2):
3330 pass
3331 for cls in C, D, E:
3332 verify_dict_readonly(cls)
3333 class_dict = cls.__dict__
3334 try:
3335 class_dict["spam"] = "eggs"
3336 except TypeError:
3337 pass
3338 else:
3339 self.fail("%r's __dict__ can be modified" % cls)
3340
3341 # Modules also disallow __dict__ assignment
3342 class Module1(types.ModuleType, Base):
3343 pass
3344 class Module2(Base, types.ModuleType):
3345 pass
3346 for ModuleType in Module1, Module2:
3347 mod = ModuleType("spam")
3348 verify_dict_readonly(mod)
3349 mod.__dict__["spam"] = "eggs"
3350
3351 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003352 # (at least not any more than regular exception's __dict__ can
3353 # be deleted; on CPython it is not the case, whereas on PyPy they
3354 # can, just like any other new-style instance's __dict__.)
3355 def can_delete_dict(e):
3356 try:
3357 del e.__dict__
3358 except (TypeError, AttributeError):
3359 return False
3360 else:
3361 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003362 class Exception1(Exception, Base):
3363 pass
3364 class Exception2(Base, Exception):
3365 pass
3366 for ExceptionType in Exception, Exception1, Exception2:
3367 e = ExceptionType()
3368 e.__dict__ = {"a": 1}
3369 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003370 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003371
Georg Brandl479a7e72008-02-05 18:13:15 +00003372 def test_binary_operator_override(self):
3373 # Testing overrides of binary operations...
3374 class I(int):
3375 def __repr__(self):
3376 return "I(%r)" % int(self)
3377 def __add__(self, other):
3378 return I(int(self) + int(other))
3379 __radd__ = __add__
3380 def __pow__(self, other, mod=None):
3381 if mod is None:
3382 return I(pow(int(self), int(other)))
3383 else:
3384 return I(pow(int(self), int(other), int(mod)))
3385 def __rpow__(self, other, mod=None):
3386 if mod is None:
3387 return I(pow(int(other), int(self), mod))
3388 else:
3389 return I(pow(int(other), int(self), int(mod)))
3390
3391 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3392 self.assertEqual(repr(I(1) + 2), "I(3)")
3393 self.assertEqual(repr(1 + I(2)), "I(3)")
3394 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3395 self.assertEqual(repr(2 ** I(3)), "I(8)")
3396 self.assertEqual(repr(I(2) ** 3), "I(8)")
3397 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3398 class S(str):
3399 def __eq__(self, other):
3400 return self.lower() == other.lower()
3401
3402 def test_subclass_propagation(self):
3403 # Testing propagation of slot functions to subclasses...
3404 class A(object):
3405 pass
3406 class B(A):
3407 pass
3408 class C(A):
3409 pass
3410 class D(B, C):
3411 pass
3412 d = D()
3413 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3414 A.__hash__ = lambda self: 42
3415 self.assertEqual(hash(d), 42)
3416 C.__hash__ = lambda self: 314
3417 self.assertEqual(hash(d), 314)
3418 B.__hash__ = lambda self: 144
3419 self.assertEqual(hash(d), 144)
3420 D.__hash__ = lambda self: 100
3421 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003422 D.__hash__ = None
3423 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003424 del D.__hash__
3425 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003426 B.__hash__ = None
3427 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003428 del B.__hash__
3429 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003430 C.__hash__ = None
3431 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003432 del C.__hash__
3433 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003434 A.__hash__ = None
3435 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003436 del A.__hash__
3437 self.assertEqual(hash(d), orig_hash)
3438 d.foo = 42
3439 d.bar = 42
3440 self.assertEqual(d.foo, 42)
3441 self.assertEqual(d.bar, 42)
3442 def __getattribute__(self, name):
3443 if name == "foo":
3444 return 24
3445 return object.__getattribute__(self, name)
3446 A.__getattribute__ = __getattribute__
3447 self.assertEqual(d.foo, 24)
3448 self.assertEqual(d.bar, 42)
3449 def __getattr__(self, name):
3450 if name in ("spam", "foo", "bar"):
3451 return "hello"
3452 raise AttributeError(name)
3453 B.__getattr__ = __getattr__
3454 self.assertEqual(d.spam, "hello")
3455 self.assertEqual(d.foo, 24)
3456 self.assertEqual(d.bar, 42)
3457 del A.__getattribute__
3458 self.assertEqual(d.foo, 42)
3459 del d.foo
3460 self.assertEqual(d.foo, "hello")
3461 self.assertEqual(d.bar, 42)
3462 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003463 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003464 d.foo
3465 except AttributeError:
3466 pass
3467 else:
3468 self.fail("d.foo should be undefined now")
3469
3470 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003471 class A(object):
3472 pass
3473 class B(A):
3474 pass
3475 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003476 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003477 A.__setitem__ = lambda *a: None # crash
3478
3479 def test_buffer_inheritance(self):
3480 # Testing that buffer interface is inherited ...
3481
3482 import binascii
3483 # SF bug [#470040] ParseTuple t# vs subclasses.
3484
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003485 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003486 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003487 base = b'abc'
3488 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003489 # b2a_hex uses the buffer interface to get its argument's value, via
3490 # PyArg_ParseTuple 't#' code.
3491 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3492
Georg Brandl479a7e72008-02-05 18:13:15 +00003493 class MyInt(int):
3494 pass
3495 m = MyInt(42)
3496 try:
3497 binascii.b2a_hex(m)
3498 self.fail('subclass of int should not have a buffer interface')
3499 except TypeError:
3500 pass
3501
3502 def test_str_of_str_subclass(self):
3503 # Testing __str__ defined in subclass of str ...
3504 import binascii
3505 import io
3506
3507 class octetstring(str):
3508 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003509 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003510 def __repr__(self):
3511 return self + " repr"
3512
3513 o = octetstring('A')
3514 self.assertEqual(type(o), octetstring)
3515 self.assertEqual(type(str(o)), str)
3516 self.assertEqual(type(repr(o)), str)
3517 self.assertEqual(ord(o), 0x41)
3518 self.assertEqual(str(o), '41')
3519 self.assertEqual(repr(o), 'A repr')
3520 self.assertEqual(o.__str__(), '41')
3521 self.assertEqual(o.__repr__(), 'A repr')
3522
3523 capture = io.StringIO()
3524 # Calling str() or not exercises different internal paths.
3525 print(o, file=capture)
3526 print(str(o), file=capture)
3527 self.assertEqual(capture.getvalue(), '41\n41\n')
3528 capture.close()
3529
3530 def test_keyword_arguments(self):
3531 # Testing keyword arguments to __init__, __call__...
3532 def f(a): return a
3533 self.assertEqual(f.__call__(a=42), 42)
Serhiy Storchakad908fd92017-03-06 21:08:59 +02003534 ba = bytearray()
3535 bytearray.__init__(ba, 'abc\xbd\u20ac',
3536 encoding='latin1', errors='replace')
3537 self.assertEqual(ba, b'abc\xbd?')
Georg Brandl479a7e72008-02-05 18:13:15 +00003538
3539 def test_recursive_call(self):
3540 # Testing recursive __call__() by setting to instance of class...
3541 class A(object):
3542 pass
3543
3544 A.__call__ = A()
3545 try:
3546 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003547 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003548 pass
3549 else:
3550 self.fail("Recursion limit should have been reached for __call__()")
3551
3552 def test_delete_hook(self):
3553 # Testing __del__ hook...
3554 log = []
3555 class C(object):
3556 def __del__(self):
3557 log.append(1)
3558 c = C()
3559 self.assertEqual(log, [])
3560 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003561 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003562 self.assertEqual(log, [1])
3563
3564 class D(object): pass
3565 d = D()
3566 try: del d[0]
3567 except TypeError: pass
3568 else: self.fail("invalid del() didn't raise TypeError")
3569
3570 def test_hash_inheritance(self):
3571 # Testing hash of mutable subclasses...
3572
3573 class mydict(dict):
3574 pass
3575 d = mydict()
3576 try:
3577 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003578 except TypeError:
3579 pass
3580 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003581 self.fail("hash() of dict subclass should fail")
3582
3583 class mylist(list):
3584 pass
3585 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003586 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003587 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003588 except TypeError:
3589 pass
3590 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003591 self.fail("hash() of list subclass should fail")
3592
3593 def test_str_operations(self):
3594 try: 'a' + 5
3595 except TypeError: pass
3596 else: self.fail("'' + 5 doesn't raise TypeError")
3597
3598 try: ''.split('')
3599 except ValueError: pass
3600 else: self.fail("''.split('') doesn't raise ValueError")
3601
3602 try: ''.join([0])
3603 except TypeError: pass
3604 else: self.fail("''.join([0]) doesn't raise TypeError")
3605
3606 try: ''.rindex('5')
3607 except ValueError: pass
3608 else: self.fail("''.rindex('5') doesn't raise ValueError")
3609
3610 try: '%(n)s' % None
3611 except TypeError: pass
3612 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3613
3614 try: '%(n' % {}
3615 except ValueError: pass
3616 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3617
3618 try: '%*s' % ('abc')
3619 except TypeError: pass
3620 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3621
3622 try: '%*.*s' % ('abc', 5)
3623 except TypeError: pass
3624 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3625
3626 try: '%s' % (1, 2)
3627 except TypeError: pass
3628 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3629
3630 try: '%' % None
3631 except ValueError: pass
3632 else: self.fail("'%' % None doesn't raise ValueError")
3633
3634 self.assertEqual('534253'.isdigit(), 1)
3635 self.assertEqual('534253x'.isdigit(), 0)
3636 self.assertEqual('%c' % 5, '\x05')
3637 self.assertEqual('%c' % '5', '5')
3638
3639 def test_deepcopy_recursive(self):
3640 # Testing deepcopy of recursive objects...
3641 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003642 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003643 a = Node()
3644 b = Node()
3645 a.b = b
3646 b.a = a
3647 z = deepcopy(a) # This blew up before
3648
Martin Panterf05641642016-05-08 13:48:10 +00003649 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003650 # Testing uninitialized module objects...
3651 from types import ModuleType as M
3652 m = M.__new__(M)
3653 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003654 self.assertNotHasAttr(m, "__name__")
3655 self.assertNotHasAttr(m, "__file__")
3656 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003657 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003658 m.foo = 1
3659 self.assertEqual(m.__dict__, {"foo": 1})
3660
3661 def test_funny_new(self):
3662 # Testing __new__ returning something unexpected...
3663 class C(object):
3664 def __new__(cls, arg):
3665 if isinstance(arg, str): return [1, 2, 3]
3666 elif isinstance(arg, int): return object.__new__(D)
3667 else: return object.__new__(cls)
3668 class D(C):
3669 def __init__(self, arg):
3670 self.foo = arg
3671 self.assertEqual(C("1"), [1, 2, 3])
3672 self.assertEqual(D("1"), [1, 2, 3])
3673 d = D(None)
3674 self.assertEqual(d.foo, None)
3675 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003676 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003677 self.assertEqual(d.foo, 1)
3678 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003679 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003680 self.assertEqual(d.foo, 1)
3681
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003682 class C(object):
3683 @staticmethod
3684 def __new__(*args):
3685 return args
3686 self.assertEqual(C(1, 2), (C, 1, 2))
3687 class D(C):
3688 pass
3689 self.assertEqual(D(1, 2), (D, 1, 2))
3690
3691 class C(object):
3692 @classmethod
3693 def __new__(*args):
3694 return args
3695 self.assertEqual(C(1, 2), (C, C, 1, 2))
3696 class D(C):
3697 pass
3698 self.assertEqual(D(1, 2), (D, D, 1, 2))
3699
Georg Brandl479a7e72008-02-05 18:13:15 +00003700 def test_imul_bug(self):
3701 # Testing for __imul__ problems...
3702 # SF bug 544647
3703 class C(object):
3704 def __imul__(self, other):
3705 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003706 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003707 y = x
3708 y *= 1.0
3709 self.assertEqual(y, (x, 1.0))
3710 y = x
3711 y *= 2
3712 self.assertEqual(y, (x, 2))
3713 y = x
3714 y *= 3
3715 self.assertEqual(y, (x, 3))
3716 y = x
3717 y *= 1<<100
3718 self.assertEqual(y, (x, 1<<100))
3719 y = x
3720 y *= None
3721 self.assertEqual(y, (x, None))
3722 y = x
3723 y *= "foo"
3724 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003725
Georg Brandl479a7e72008-02-05 18:13:15 +00003726 def test_copy_setstate(self):
3727 # Testing that copy.*copy() correctly uses __setstate__...
3728 import copy
3729 class C(object):
3730 def __init__(self, foo=None):
3731 self.foo = foo
3732 self.__foo = foo
3733 def setfoo(self, foo=None):
3734 self.foo = foo
3735 def getfoo(self):
3736 return self.__foo
3737 def __getstate__(self):
3738 return [self.foo]
3739 def __setstate__(self_, lst):
3740 self.assertEqual(len(lst), 1)
3741 self_.__foo = self_.foo = lst[0]
3742 a = C(42)
3743 a.setfoo(24)
3744 self.assertEqual(a.foo, 24)
3745 self.assertEqual(a.getfoo(), 42)
3746 b = copy.copy(a)
3747 self.assertEqual(b.foo, 24)
3748 self.assertEqual(b.getfoo(), 24)
3749 b = copy.deepcopy(a)
3750 self.assertEqual(b.foo, 24)
3751 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003752
Georg Brandl479a7e72008-02-05 18:13:15 +00003753 def test_slices(self):
3754 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003755
Georg Brandl479a7e72008-02-05 18:13:15 +00003756 # Strings
3757 self.assertEqual("hello"[:4], "hell")
3758 self.assertEqual("hello"[slice(4)], "hell")
3759 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3760 class S(str):
3761 def __getitem__(self, x):
3762 return str.__getitem__(self, x)
3763 self.assertEqual(S("hello")[:4], "hell")
3764 self.assertEqual(S("hello")[slice(4)], "hell")
3765 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3766 # Tuples
3767 self.assertEqual((1,2,3)[:2], (1,2))
3768 self.assertEqual((1,2,3)[slice(2)], (1,2))
3769 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3770 class T(tuple):
3771 def __getitem__(self, x):
3772 return tuple.__getitem__(self, x)
3773 self.assertEqual(T((1,2,3))[:2], (1,2))
3774 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3775 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3776 # Lists
3777 self.assertEqual([1,2,3][:2], [1,2])
3778 self.assertEqual([1,2,3][slice(2)], [1,2])
3779 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3780 class L(list):
3781 def __getitem__(self, x):
3782 return list.__getitem__(self, x)
3783 self.assertEqual(L([1,2,3])[:2], [1,2])
3784 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3785 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3786 # Now do lists and __setitem__
3787 a = L([1,2,3])
3788 a[slice(1, 3)] = [3,2]
3789 self.assertEqual(a, [1,3,2])
3790 a[slice(0, 2, 1)] = [3,1]
3791 self.assertEqual(a, [3,1,2])
3792 a.__setitem__(slice(1, 3), [2,1])
3793 self.assertEqual(a, [3,2,1])
3794 a.__setitem__(slice(0, 2, 1), [2,3])
3795 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003796
Georg Brandl479a7e72008-02-05 18:13:15 +00003797 def test_subtype_resurrection(self):
3798 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003799
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 class C(object):
3801 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003802
Georg Brandl479a7e72008-02-05 18:13:15 +00003803 def __del__(self):
3804 # resurrect the instance
3805 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003806
Georg Brandl479a7e72008-02-05 18:13:15 +00003807 c = C()
3808 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003809
Benjamin Petersone549ead2009-03-28 21:42:05 +00003810 # The most interesting thing here is whether this blows up, due to
3811 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3812 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003813 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003814
Benjamin Petersone549ead2009-03-28 21:42:05 +00003815 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003816 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003817
Georg Brandl479a7e72008-02-05 18:13:15 +00003818 # Make c mortal again, so that the test framework with -l doesn't report
3819 # it as a leak.
3820 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003821
Georg Brandl479a7e72008-02-05 18:13:15 +00003822 def test_slots_trash(self):
3823 # Testing slot trash...
3824 # Deallocating deeply nested slotted trash caused stack overflows
3825 class trash(object):
3826 __slots__ = ['x']
3827 def __init__(self, x):
3828 self.x = x
3829 o = None
3830 for i in range(50000):
3831 o = trash(o)
3832 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003833
Georg Brandl479a7e72008-02-05 18:13:15 +00003834 def test_slots_multiple_inheritance(self):
3835 # SF bug 575229, multiple inheritance w/ slots dumps core
3836 class A(object):
3837 __slots__=()
3838 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003839 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003840 class C(A,B) :
3841 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003842 if support.check_impl_detail():
3843 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003844 self.assertHasAttr(C, '__dict__')
3845 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003846 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003847
Georg Brandl479a7e72008-02-05 18:13:15 +00003848 def test_rmul(self):
3849 # Testing correct invocation of __rmul__...
3850 # SF patch 592646
3851 class C(object):
3852 def __mul__(self, other):
3853 return "mul"
3854 def __rmul__(self, other):
3855 return "rmul"
3856 a = C()
3857 self.assertEqual(a*2, "mul")
3858 self.assertEqual(a*2.2, "mul")
3859 self.assertEqual(2*a, "rmul")
3860 self.assertEqual(2.2*a, "rmul")
3861
3862 def test_ipow(self):
3863 # Testing correct invocation of __ipow__...
3864 # [SF bug 620179]
3865 class C(object):
3866 def __ipow__(self, other):
3867 pass
3868 a = C()
3869 a **= 2
3870
3871 def test_mutable_bases(self):
3872 # Testing mutable bases...
3873
3874 # stuff that should work:
3875 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003876 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003877 class C2(object):
3878 def __getattribute__(self, attr):
3879 if attr == 'a':
3880 return 2
3881 else:
3882 return super(C2, self).__getattribute__(attr)
3883 def meth(self):
3884 return 1
3885 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003886 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003887 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003888 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003889 d = D()
3890 e = E()
3891 D.__bases__ = (C,)
3892 D.__bases__ = (C2,)
3893 self.assertEqual(d.meth(), 1)
3894 self.assertEqual(e.meth(), 1)
3895 self.assertEqual(d.a, 2)
3896 self.assertEqual(e.a, 2)
3897 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003898
Georg Brandl479a7e72008-02-05 18:13:15 +00003899 try:
3900 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003901 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003902 pass
3903 else:
3904 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003905
Georg Brandl479a7e72008-02-05 18:13:15 +00003906 try:
3907 D.__bases__ = ()
3908 except TypeError as msg:
3909 if str(msg) == "a new-style class can't have only classic bases":
3910 self.fail("wrong error message for .__bases__ = ()")
3911 else:
3912 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003913
Georg Brandl479a7e72008-02-05 18:13:15 +00003914 try:
3915 D.__bases__ = (D,)
3916 except TypeError:
3917 pass
3918 else:
3919 # actually, we'll have crashed by here...
3920 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003921
Georg Brandl479a7e72008-02-05 18:13:15 +00003922 try:
3923 D.__bases__ = (C, C)
3924 except TypeError:
3925 pass
3926 else:
3927 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003928
Georg Brandl479a7e72008-02-05 18:13:15 +00003929 try:
3930 D.__bases__ = (E,)
3931 except TypeError:
3932 pass
3933 else:
3934 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003935
Benjamin Petersonae937c02009-04-18 20:54:08 +00003936 def test_builtin_bases(self):
3937 # Make sure all the builtin types can have their base queried without
3938 # segfaulting. See issue #5787.
3939 builtin_types = [tp for tp in builtins.__dict__.values()
3940 if isinstance(tp, type)]
3941 for tp in builtin_types:
3942 object.__getattribute__(tp, "__bases__")
3943 if tp is not object:
3944 self.assertEqual(len(tp.__bases__), 1, tp)
3945
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003946 class L(list):
3947 pass
3948
3949 class C(object):
3950 pass
3951
3952 class D(C):
3953 pass
3954
3955 try:
3956 L.__bases__ = (dict,)
3957 except TypeError:
3958 pass
3959 else:
3960 self.fail("shouldn't turn list subclass into dict subclass")
3961
3962 try:
3963 list.__bases__ = (dict,)
3964 except TypeError:
3965 pass
3966 else:
3967 self.fail("shouldn't be able to assign to list.__bases__")
3968
3969 try:
3970 D.__bases__ = (C, list)
3971 except TypeError:
3972 pass
3973 else:
3974 assert 0, "best_base calculation found wanting"
3975
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003976 def test_unsubclassable_types(self):
3977 with self.assertRaises(TypeError):
3978 class X(type(None)):
3979 pass
3980 with self.assertRaises(TypeError):
3981 class X(object, type(None)):
3982 pass
3983 with self.assertRaises(TypeError):
3984 class X(type(None), object):
3985 pass
3986 class O(object):
3987 pass
3988 with self.assertRaises(TypeError):
3989 class X(O, type(None)):
3990 pass
3991 with self.assertRaises(TypeError):
3992 class X(type(None), O):
3993 pass
3994
3995 class X(object):
3996 pass
3997 with self.assertRaises(TypeError):
3998 X.__bases__ = type(None),
3999 with self.assertRaises(TypeError):
4000 X.__bases__ = object, type(None)
4001 with self.assertRaises(TypeError):
4002 X.__bases__ = type(None), object
4003 with self.assertRaises(TypeError):
4004 X.__bases__ = O, type(None)
4005 with self.assertRaises(TypeError):
4006 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00004007
Georg Brandl479a7e72008-02-05 18:13:15 +00004008 def test_mutable_bases_with_failing_mro(self):
4009 # Testing mutable bases with failing mro...
4010 class WorkOnce(type):
4011 def __new__(self, name, bases, ns):
4012 self.flag = 0
4013 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4014 def mro(self):
4015 if self.flag > 0:
4016 raise RuntimeError("bozo")
4017 else:
4018 self.flag += 1
4019 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004020
Georg Brandl479a7e72008-02-05 18:13:15 +00004021 class WorkAlways(type):
4022 def mro(self):
4023 # this is here to make sure that .mro()s aren't called
4024 # with an exception set (which was possible at one point).
4025 # An error message will be printed in a debug build.
4026 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004027 return type.mro(self)
4028
Georg Brandl479a7e72008-02-05 18:13:15 +00004029 class C(object):
4030 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004031
Georg Brandl479a7e72008-02-05 18:13:15 +00004032 class C2(object):
4033 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004034
Georg Brandl479a7e72008-02-05 18:13:15 +00004035 class D(C):
4036 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004037
Georg Brandl479a7e72008-02-05 18:13:15 +00004038 class E(D):
4039 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004040
Georg Brandl479a7e72008-02-05 18:13:15 +00004041 class F(D, metaclass=WorkOnce):
4042 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004043
Georg Brandl479a7e72008-02-05 18:13:15 +00004044 class G(D, metaclass=WorkAlways):
4045 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004046
Georg Brandl479a7e72008-02-05 18:13:15 +00004047 # Immediate subclasses have their mro's adjusted in alphabetical
4048 # order, so E's will get adjusted before adjusting F's fails. We
4049 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004050
Georg Brandl479a7e72008-02-05 18:13:15 +00004051 E_mro_before = E.__mro__
4052 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004053
Armin Rigofd163f92005-12-29 15:59:19 +00004054 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00004055 D.__bases__ = (C2,)
4056 except RuntimeError:
4057 self.assertEqual(E.__mro__, E_mro_before)
4058 self.assertEqual(D.__mro__, D_mro_before)
4059 else:
4060 self.fail("exception not propagated")
4061
4062 def test_mutable_bases_catch_mro_conflict(self):
4063 # Testing mutable bases catch mro conflict...
4064 class A(object):
4065 pass
4066
4067 class B(object):
4068 pass
4069
4070 class C(A, B):
4071 pass
4072
4073 class D(A, B):
4074 pass
4075
4076 class E(C, D):
4077 pass
4078
4079 try:
4080 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004081 except TypeError:
4082 pass
4083 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00004084 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004085
Georg Brandl479a7e72008-02-05 18:13:15 +00004086 def test_mutable_names(self):
4087 # Testing mutable names...
4088 class C(object):
4089 pass
4090
4091 # C.__module__ could be 'test_descr' or '__main__'
4092 mod = C.__module__
4093
4094 C.__name__ = 'D'
4095 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4096
4097 C.__name__ = 'D.E'
4098 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4099
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004100 def test_evil_type_name(self):
4101 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4102 # execution while the type structure was not in a sane state, and a
4103 # possible segmentation fault as a result. See bug #16447.
4104 class Nasty(str):
4105 def __del__(self):
4106 C.__name__ = "other"
4107
4108 class C:
4109 pass
4110
4111 C.__name__ = Nasty("abc")
4112 C.__name__ = "normal"
4113
Georg Brandl479a7e72008-02-05 18:13:15 +00004114 def test_subclass_right_op(self):
4115 # Testing correct dispatch of subclass overloading __r<op>__...
4116
4117 # This code tests various cases where right-dispatch of a subclass
4118 # should be preferred over left-dispatch of a base class.
4119
4120 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4121
4122 class B(int):
4123 def __floordiv__(self, other):
4124 return "B.__floordiv__"
4125 def __rfloordiv__(self, other):
4126 return "B.__rfloordiv__"
4127
4128 self.assertEqual(B(1) // 1, "B.__floordiv__")
4129 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4130
4131 # Case 2: subclass of object; this is just the baseline for case 3
4132
4133 class C(object):
4134 def __floordiv__(self, other):
4135 return "C.__floordiv__"
4136 def __rfloordiv__(self, other):
4137 return "C.__rfloordiv__"
4138
4139 self.assertEqual(C() // 1, "C.__floordiv__")
4140 self.assertEqual(1 // C(), "C.__rfloordiv__")
4141
4142 # Case 3: subclass of new-style class; here it gets interesting
4143
4144 class D(C):
4145 def __floordiv__(self, other):
4146 return "D.__floordiv__"
4147 def __rfloordiv__(self, other):
4148 return "D.__rfloordiv__"
4149
4150 self.assertEqual(D() // C(), "D.__floordiv__")
4151 self.assertEqual(C() // D(), "D.__rfloordiv__")
4152
4153 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4154
4155 class E(C):
4156 pass
4157
4158 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4159
4160 self.assertEqual(E() // 1, "C.__floordiv__")
4161 self.assertEqual(1 // E(), "C.__rfloordiv__")
4162 self.assertEqual(E() // C(), "C.__floordiv__")
4163 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4164
Benjamin Petersone549ead2009-03-28 21:42:05 +00004165 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004166 def test_meth_class_get(self):
4167 # Testing __get__ method of METH_CLASS C methods...
4168 # Full coverage of descrobject.c::classmethod_get()
4169
4170 # Baseline
4171 arg = [1, 2, 3]
4172 res = {1: None, 2: None, 3: None}
4173 self.assertEqual(dict.fromkeys(arg), res)
4174 self.assertEqual({}.fromkeys(arg), res)
4175
4176 # Now get the descriptor
4177 descr = dict.__dict__["fromkeys"]
4178
4179 # More baseline using the descriptor directly
4180 self.assertEqual(descr.__get__(None, dict)(arg), res)
4181 self.assertEqual(descr.__get__({})(arg), res)
4182
4183 # Now check various error cases
4184 try:
4185 descr.__get__(None, None)
4186 except TypeError:
4187 pass
4188 else:
4189 self.fail("shouldn't have allowed descr.__get__(None, None)")
4190 try:
4191 descr.__get__(42)
4192 except TypeError:
4193 pass
4194 else:
4195 self.fail("shouldn't have allowed descr.__get__(42)")
4196 try:
4197 descr.__get__(None, 42)
4198 except TypeError:
4199 pass
4200 else:
4201 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4202 try:
4203 descr.__get__(None, int)
4204 except TypeError:
4205 pass
4206 else:
4207 self.fail("shouldn't have allowed descr.__get__(None, int)")
4208
4209 def test_isinst_isclass(self):
4210 # Testing proxy isinstance() and isclass()...
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 # Test with a classic class
4220 class C:
4221 pass
4222 a = C()
4223 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004224 self.assertIsInstance(a, C) # Baseline
4225 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004226 # Test with a classic subclass
4227 class D(C):
4228 pass
4229 a = D()
4230 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004231 self.assertIsInstance(a, C) # Baseline
4232 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004233 # Test with a new-style class
4234 class C(object):
4235 pass
4236 a = C()
4237 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004238 self.assertIsInstance(a, C) # Baseline
4239 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004240 # Test with a new-style subclass
4241 class D(C):
4242 pass
4243 a = D()
4244 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004245 self.assertIsInstance(a, C) # Baseline
4246 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004247
4248 def test_proxy_super(self):
4249 # Testing super() for a proxy object...
4250 class Proxy(object):
4251 def __init__(self, obj):
4252 self.__obj = obj
4253 def __getattribute__(self, name):
4254 if name.startswith("_Proxy__"):
4255 return object.__getattribute__(self, name)
4256 else:
4257 return getattr(self.__obj, name)
4258
4259 class B(object):
4260 def f(self):
4261 return "B.f"
4262
4263 class C(B):
4264 def f(self):
4265 return super(C, self).f() + "->C.f"
4266
4267 obj = C()
4268 p = Proxy(obj)
4269 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4270
4271 def test_carloverre(self):
4272 # Testing prohibition of Carlo Verre's hack...
4273 try:
4274 object.__setattr__(str, "foo", 42)
4275 except TypeError:
4276 pass
4277 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004278 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004279 try:
4280 object.__delattr__(str, "lower")
4281 except TypeError:
4282 pass
4283 else:
4284 self.fail("Carlo Verre __delattr__ succeeded!")
4285
4286 def test_weakref_segfault(self):
4287 # Testing weakref segfault...
4288 # SF 742911
4289 import weakref
4290
4291 class Provoker:
4292 def __init__(self, referrent):
4293 self.ref = weakref.ref(referrent)
4294
4295 def __del__(self):
4296 x = self.ref()
4297
4298 class Oops(object):
4299 pass
4300
4301 o = Oops()
4302 o.whatever = Provoker(o)
4303 del o
4304
4305 def test_wrapper_segfault(self):
4306 # SF 927248: deeply nested wrappers could cause stack overflow
4307 f = lambda:None
4308 for i in range(1000000):
4309 f = f.__call__
4310 f = None
4311
4312 def test_file_fault(self):
4313 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004314 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 class StdoutGuard:
4316 def __getattr__(self, attr):
4317 sys.stdout = sys.__stdout__
4318 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4319 sys.stdout = StdoutGuard()
4320 try:
4321 print("Oops!")
4322 except RuntimeError:
4323 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004324 finally:
4325 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004326
4327 def test_vicious_descriptor_nonsense(self):
4328 # Testing vicious_descriptor_nonsense...
4329
4330 # A potential segfault spotted by Thomas Wouters in mail to
4331 # python-dev 2003-04-17, turned into an example & fixed by Michael
4332 # Hudson just less than four months later...
4333
4334 class Evil(object):
4335 def __hash__(self):
4336 return hash('attr')
4337 def __eq__(self, other):
4338 del C.attr
4339 return 0
4340
4341 class Descr(object):
4342 def __get__(self, ob, type=None):
4343 return 1
4344
4345 class C(object):
4346 attr = Descr()
4347
4348 c = C()
4349 c.__dict__[Evil()] = 0
4350
4351 self.assertEqual(c.attr, 1)
4352 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004353 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004354 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004355
4356 def test_init(self):
4357 # SF 1155938
4358 class Foo(object):
4359 def __init__(self):
4360 return 10
4361 try:
4362 Foo()
4363 except TypeError:
4364 pass
4365 else:
4366 self.fail("did not test __init__() for None return")
4367
4368 def test_method_wrapper(self):
4369 # Testing method-wrapper objects...
4370 # <type 'method-wrapper'> did not support any reflection before 2.5
4371
Mark Dickinson211c6252009-02-01 10:28:51 +00004372 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004373
4374 l = []
4375 self.assertEqual(l.__add__, l.__add__)
4376 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004377 self.assertNotEqual(l.__add__, [5].__add__)
4378 self.assertNotEqual(l.__add__, l.__mul__)
4379 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004380 if hasattr(l.__add__, '__self__'):
4381 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004382 self.assertIs(l.__add__.__self__, l)
4383 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004384 else:
4385 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004386 self.assertIs(l.__add__.im_self, l)
4387 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004388 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4389 try:
4390 hash(l.__add__)
4391 except TypeError:
4392 pass
4393 else:
4394 self.fail("no TypeError from hash([].__add__)")
4395
4396 t = ()
4397 t += (7,)
4398 self.assertEqual(t.__add__, (7,).__add__)
4399 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4400
4401 def test_not_implemented(self):
4402 # Testing NotImplemented...
4403 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004404 import operator
4405
4406 def specialmethod(self, other):
4407 return NotImplemented
4408
4409 def check(expr, x, y):
4410 try:
4411 exec(expr, {'x': x, 'y': y, 'operator': operator})
4412 except TypeError:
4413 pass
4414 else:
4415 self.fail("no TypeError from %r" % (expr,))
4416
4417 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4418 # TypeErrors
4419 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4420 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004421 for name, expr, iexpr in [
4422 ('__add__', 'x + y', 'x += y'),
4423 ('__sub__', 'x - y', 'x -= y'),
4424 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004425 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004426 ('__truediv__', 'x / y', 'x /= y'),
4427 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004428 ('__mod__', 'x % y', 'x %= y'),
4429 ('__divmod__', 'divmod(x, y)', None),
4430 ('__pow__', 'x ** y', 'x **= y'),
4431 ('__lshift__', 'x << y', 'x <<= y'),
4432 ('__rshift__', 'x >> y', 'x >>= y'),
4433 ('__and__', 'x & y', 'x &= y'),
4434 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004435 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004436 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004437 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004438 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004439 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004440 check(expr, a, N1)
4441 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004442 if iexpr:
4443 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004444 check(iexpr, a, N1)
4445 check(iexpr, a, N2)
4446 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004447 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004448 c = C()
4449 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004450 check(iexpr, c, N1)
4451 check(iexpr, c, N2)
4452
Georg Brandl479a7e72008-02-05 18:13:15 +00004453 def test_assign_slice(self):
4454 # ceval.c's assign_slice used to check for
4455 # tp->tp_as_sequence->sq_slice instead of
4456 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004457
Georg Brandl479a7e72008-02-05 18:13:15 +00004458 class C(object):
4459 def __setitem__(self, idx, value):
4460 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004461
Georg Brandl479a7e72008-02-05 18:13:15 +00004462 c = C()
4463 c[1:2] = 3
4464 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004465
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004466 def test_set_and_no_get(self):
4467 # See
4468 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4469 class Descr(object):
4470
4471 def __init__(self, name):
4472 self.name = name
4473
4474 def __set__(self, obj, value):
4475 obj.__dict__[self.name] = value
4476 descr = Descr("a")
4477
4478 class X(object):
4479 a = descr
4480
4481 x = X()
4482 self.assertIs(x.a, descr)
4483 x.a = 42
4484 self.assertEqual(x.a, 42)
4485
Benjamin Peterson21896a32010-03-21 22:03:03 +00004486 # Also check type_getattro for correctness.
4487 class Meta(type):
4488 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004489 class X(metaclass=Meta):
4490 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004491 X.a = 42
4492 Meta.a = Descr("a")
4493 self.assertEqual(X.a, 42)
4494
Benjamin Peterson9262b842008-11-17 22:45:50 +00004495 def test_getattr_hooks(self):
4496 # issue 4230
4497
4498 class Descriptor(object):
4499 counter = 0
4500 def __get__(self, obj, objtype=None):
4501 def getter(name):
4502 self.counter += 1
4503 raise AttributeError(name)
4504 return getter
4505
4506 descr = Descriptor()
4507 class A(object):
4508 __getattribute__ = descr
4509 class B(object):
4510 __getattr__ = descr
4511 class C(object):
4512 __getattribute__ = descr
4513 __getattr__ = descr
4514
4515 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004516 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004517 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004518 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004519 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004520 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004521
Benjamin Peterson9262b842008-11-17 22:45:50 +00004522 class EvilGetattribute(object):
4523 # This used to segfault
4524 def __getattr__(self, name):
4525 raise AttributeError(name)
4526 def __getattribute__(self, name):
4527 del EvilGetattribute.__getattr__
4528 for i in range(5):
4529 gc.collect()
4530 raise AttributeError(name)
4531
4532 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4533
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004534 def test_type___getattribute__(self):
4535 self.assertRaises(TypeError, type.__getattribute__, list, type)
4536
Benjamin Peterson477ba912011-01-12 15:34:01 +00004537 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004538 # type pretends not to have __abstractmethods__.
4539 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4540 class meta(type):
4541 pass
4542 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004543 class X(object):
4544 pass
4545 with self.assertRaises(AttributeError):
4546 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004547
Victor Stinner3249dec2011-05-01 23:19:15 +02004548 def test_proxy_call(self):
4549 class FakeStr:
4550 __class__ = str
4551
4552 fake_str = FakeStr()
4553 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004554 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004555
4556 # call a method descriptor
4557 with self.assertRaises(TypeError):
4558 str.split(fake_str)
4559
4560 # call a slot wrapper descriptor
4561 with self.assertRaises(TypeError):
4562 str.__add__(fake_str, "abc")
4563
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004564 def test_repr_as_str(self):
4565 # Issue #11603: crash or infinite loop when rebinding __str__ as
4566 # __repr__.
4567 class Foo:
4568 pass
4569 Foo.__repr__ = Foo.__str__
4570 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004571 self.assertRaises(RecursionError, str, foo)
4572 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004573
4574 def test_mixing_slot_wrappers(self):
4575 class X(dict):
4576 __setattr__ = dict.__setitem__
4577 x = X()
4578 x.y = 42
4579 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004580
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004581 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004582 with self.assertRaises(ValueError) as cm:
4583 class X:
4584 __slots__ = ["foo"]
4585 foo = None
4586 m = str(cm.exception)
4587 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4588
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004589 def test_set_doc(self):
4590 class X:
4591 "elephant"
4592 X.__doc__ = "banana"
4593 self.assertEqual(X.__doc__, "banana")
4594 with self.assertRaises(TypeError) as cm:
4595 type(list).__dict__["__doc__"].__set__(list, "blah")
4596 self.assertIn("can't set list.__doc__", str(cm.exception))
4597 with self.assertRaises(TypeError) as cm:
4598 type(X).__dict__["__doc__"].__delete__(X)
4599 self.assertIn("can't delete X.__doc__", str(cm.exception))
4600 self.assertEqual(X.__doc__, "banana")
4601
Antoine Pitrou9d574812011-12-12 13:47:25 +01004602 def test_qualname(self):
4603 descriptors = [str.lower, complex.real, float.real, int.__add__]
4604 types = ['method', 'member', 'getset', 'wrapper']
4605
4606 # make sure we have an example of each type of descriptor
4607 for d, n in zip(descriptors, types):
4608 self.assertEqual(type(d).__name__, n + '_descriptor')
4609
4610 for d in descriptors:
4611 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4612 self.assertEqual(d.__qualname__, qualname)
4613
4614 self.assertEqual(str.lower.__qualname__, 'str.lower')
4615 self.assertEqual(complex.real.__qualname__, 'complex.real')
4616 self.assertEqual(float.real.__qualname__, 'float.real')
4617 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4618
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004619 class X:
4620 pass
4621 with self.assertRaises(TypeError):
4622 del X.__qualname__
4623
4624 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4625 str, 'Oink')
4626
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004627 global Y
4628 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004629 class Inside:
4630 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004631 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004632 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004633
Victor Stinner6f738742012-02-25 01:22:36 +01004634 def test_qualname_dict(self):
4635 ns = {'__qualname__': 'some.name'}
4636 tp = type('Foo', (), ns)
4637 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004638 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004639 self.assertEqual(ns, {'__qualname__': 'some.name'})
4640
4641 ns = {'__qualname__': 1}
4642 self.assertRaises(TypeError, type, 'Foo', (), ns)
4643
Benjamin Peterson52c42432012-03-07 18:41:11 -06004644 def test_cycle_through_dict(self):
4645 # See bug #1469629
4646 class X(dict):
4647 def __init__(self):
4648 dict.__init__(self)
4649 self.__dict__ = self
4650 x = X()
4651 x.attr = 42
4652 wr = weakref.ref(x)
4653 del x
4654 support.gc_collect()
4655 self.assertIsNone(wr())
4656 for o in gc.get_objects():
4657 self.assertIsNot(type(o), X)
4658
Benjamin Peterson96384b92012-03-17 00:05:44 -05004659 def test_object_new_and_init_with_parameters(self):
4660 # See issue #1683368
4661 class OverrideNeither:
4662 pass
4663 self.assertRaises(TypeError, OverrideNeither, 1)
4664 self.assertRaises(TypeError, OverrideNeither, kw=1)
4665 class OverrideNew:
4666 def __new__(cls, foo, kw=0, *args, **kwds):
4667 return object.__new__(cls, *args, **kwds)
4668 class OverrideInit:
4669 def __init__(self, foo, kw=0, *args, **kwargs):
4670 return object.__init__(self, *args, **kwargs)
4671 class OverrideBoth(OverrideNew, OverrideInit):
4672 pass
4673 for case in OverrideNew, OverrideInit, OverrideBoth:
4674 case(1)
4675 case(1, kw=2)
4676 self.assertRaises(TypeError, case, 1, 2, 3)
4677 self.assertRaises(TypeError, case, 1, 2, foo=3)
4678
Benjamin Petersondf813792014-03-17 15:57:17 -05004679 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4680 class Base:
4681 pass
4682 class Sub(Base):
4683 pass
4684 self.assertIn("__dict__", Base.__dict__)
4685 self.assertNotIn("__dict__", Sub.__dict__)
4686
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004687 def test_bound_method_repr(self):
4688 class Foo:
4689 def method(self):
4690 pass
4691 self.assertRegex(repr(Foo().method),
4692 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4693
4694
4695 class Base:
4696 def method(self):
4697 pass
4698 class Derived1(Base):
4699 pass
4700 class Derived2(Base):
4701 def method(self):
4702 pass
4703 base = Base()
4704 derived1 = Derived1()
4705 derived2 = Derived2()
4706 super_d2 = super(Derived2, derived2)
4707 self.assertRegex(repr(base.method),
4708 r"<bound method .*Base\.method of <.*Base object at .*>>")
4709 self.assertRegex(repr(derived1.method),
4710 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4711 self.assertRegex(repr(derived2.method),
4712 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4713 self.assertRegex(repr(super_d2.method),
4714 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4715
4716 class Foo:
4717 @classmethod
4718 def method(cls):
4719 pass
4720 foo = Foo()
4721 self.assertRegex(repr(foo.method), # access via instance
Benjamin Petersonab078e92016-07-13 21:13:29 -07004722 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004723 self.assertRegex(repr(Foo.method), # access via the class
Benjamin Petersonab078e92016-07-13 21:13:29 -07004724 r"<bound method .*Foo\.method of <class '.*Foo'>>")
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004725
4726
4727 class MyCallable:
4728 def __call__(self, arg):
4729 pass
4730 func = MyCallable() # func has no __name__ or __qualname__ attributes
4731 instance = object()
4732 method = types.MethodType(func, instance)
4733 self.assertRegex(repr(method),
4734 r"<bound method \? of <object object at .*>>")
4735 func.__name__ = "name"
4736 self.assertRegex(repr(method),
4737 r"<bound method name of <object object at .*>>")
4738 func.__qualname__ = "qualname"
4739 self.assertRegex(repr(method),
4740 r"<bound method qualname of <object object at .*>>")
4741
Antoine Pitrou9d574812011-12-12 13:47:25 +01004742
Georg Brandl479a7e72008-02-05 18:13:15 +00004743class DictProxyTests(unittest.TestCase):
4744 def setUp(self):
4745 class C(object):
4746 def meth(self):
4747 pass
4748 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004749
Brett Cannon7a540732011-02-22 03:04:06 +00004750 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4751 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004752 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004753 # Testing dict-proxy keys...
4754 it = self.C.__dict__.keys()
4755 self.assertNotIsInstance(it, list)
4756 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004757 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004758 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004759 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004760
Brett Cannon7a540732011-02-22 03:04:06 +00004761 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4762 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004763 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004764 # Testing dict-proxy values...
4765 it = self.C.__dict__.values()
4766 self.assertNotIsInstance(it, list)
4767 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004768 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004769
Brett Cannon7a540732011-02-22 03:04:06 +00004770 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4771 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004772 def test_iter_items(self):
4773 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004774 it = self.C.__dict__.items()
4775 self.assertNotIsInstance(it, list)
4776 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004777 keys.sort()
4778 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004779 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004780
Georg Brandl479a7e72008-02-05 18:13:15 +00004781 def test_dict_type_with_metaclass(self):
4782 # Testing type of __dict__ when metaclass set...
4783 class B(object):
4784 pass
4785 class M(type):
4786 pass
4787 class C(metaclass=M):
4788 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4789 pass
4790 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004791
Ezio Melottiac53ab62010-12-18 14:59:43 +00004792 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004793 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004794 # We can't blindly compare with the repr of another dict as ordering
4795 # of keys and values is arbitrary and may differ.
4796 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004797 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004798 self.assertTrue(r.endswith(')'), r)
4799 for k, v in self.C.__dict__.items():
4800 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004801
Christian Heimesbbffeb62008-01-24 09:42:52 +00004802
Georg Brandl479a7e72008-02-05 18:13:15 +00004803class PTypesLongInitTest(unittest.TestCase):
4804 # This is in its own TestCase so that it can be run before any other tests.
4805 def test_pytype_long_ready(self):
4806 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004807
Georg Brandl479a7e72008-02-05 18:13:15 +00004808 # This dumps core when SF bug 551412 isn't fixed --
4809 # but only when test_descr.py is run separately.
4810 # (That can't be helped -- as soon as PyType_Ready()
4811 # is called for PyLong_Type, the bug is gone.)
4812 class UserLong(object):
4813 def __pow__(self, *args):
4814 pass
4815 try:
4816 pow(0, UserLong(), 0)
4817 except:
4818 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004819
Georg Brandl479a7e72008-02-05 18:13:15 +00004820 # Another segfault only when run early
4821 # (before PyType_Ready(tuple) is called)
4822 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004823
4824
Victor Stinnerd74782b2012-03-09 00:39:08 +01004825class MiscTests(unittest.TestCase):
4826 def test_type_lookup_mro_reference(self):
4827 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4828 # the type MRO because it may be modified during the lookup, if
4829 # __bases__ is set during the lookup for example.
4830 class MyKey(object):
4831 def __hash__(self):
4832 return hash('mykey')
4833
4834 def __eq__(self, other):
4835 X.__bases__ = (Base2,)
4836
4837 class Base(object):
4838 mykey = 'from Base'
4839 mykey2 = 'from Base'
4840
4841 class Base2(object):
4842 mykey = 'from Base2'
4843 mykey2 = 'from Base2'
4844
4845 X = type('X', (Base,), {MyKey(): 5})
4846 # mykey is read from Base
4847 self.assertEqual(X.mykey, 'from Base')
4848 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4849 self.assertEqual(X.mykey2, 'from Base2')
4850
4851
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004852class PicklingTests(unittest.TestCase):
4853
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004854 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004855 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004856 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004857 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004858 if kwargs:
4859 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4860 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004861 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004862 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4863 self.assertEqual(reduce_value[1], (type(obj),) + args)
4864 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004865 if listitems is not None:
4866 self.assertListEqual(list(reduce_value[3]), listitems)
4867 else:
4868 self.assertIsNone(reduce_value[3])
4869 if dictitems is not None:
4870 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4871 else:
4872 self.assertIsNone(reduce_value[4])
4873 else:
4874 base_type = type(obj).__base__
4875 reduce_value = (copyreg._reconstructor,
4876 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004877 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004878 None if base_type is object else base_type(obj)))
4879 if state is not None:
4880 reduce_value += (state,)
4881 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4882 self.assertEqual(obj.__reduce__(), reduce_value)
4883
4884 def test_reduce(self):
4885 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4886 args = (-101, "spam")
4887 kwargs = {'bacon': -201, 'fish': -301}
4888 state = {'cheese': -401}
4889
4890 class C1:
4891 def __getnewargs__(self):
4892 return args
4893 obj = C1()
4894 for proto in protocols:
4895 self._check_reduce(proto, obj, args)
4896
4897 for name, value in state.items():
4898 setattr(obj, name, value)
4899 for proto in protocols:
4900 self._check_reduce(proto, obj, args, state=state)
4901
4902 class C2:
4903 def __getnewargs__(self):
4904 return "bad args"
4905 obj = C2()
4906 for proto in protocols:
4907 if proto >= 2:
4908 with self.assertRaises(TypeError):
4909 obj.__reduce_ex__(proto)
4910
4911 class C3:
4912 def __getnewargs_ex__(self):
4913 return (args, kwargs)
4914 obj = C3()
4915 for proto in protocols:
Serhiy Storchaka20d15b52015-10-11 17:52:09 +03004916 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004917 self._check_reduce(proto, obj, args, kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004918
4919 class C4:
4920 def __getnewargs_ex__(self):
4921 return (args, "bad dict")
4922 class C5:
4923 def __getnewargs_ex__(self):
4924 return ("bad tuple", kwargs)
4925 class C6:
4926 def __getnewargs_ex__(self):
4927 return ()
4928 class C7:
4929 def __getnewargs_ex__(self):
4930 return "bad args"
4931 for proto in protocols:
4932 for cls in C4, C5, C6, C7:
4933 obj = cls()
4934 if proto >= 2:
4935 with self.assertRaises((TypeError, ValueError)):
4936 obj.__reduce_ex__(proto)
4937
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004938 class C9:
4939 def __getnewargs_ex__(self):
4940 return (args, {})
4941 obj = C9()
4942 for proto in protocols:
4943 self._check_reduce(proto, obj, args)
4944
4945 class C10:
4946 def __getnewargs_ex__(self):
4947 raise IndexError
4948 obj = C10()
4949 for proto in protocols:
4950 if proto >= 2:
4951 with self.assertRaises(IndexError):
4952 obj.__reduce_ex__(proto)
4953
4954 class C11:
4955 def __getstate__(self):
4956 return state
4957 obj = C11()
4958 for proto in protocols:
4959 self._check_reduce(proto, obj, state=state)
4960
4961 class C12:
4962 def __getstate__(self):
4963 return "not dict"
4964 obj = C12()
4965 for proto in protocols:
4966 self._check_reduce(proto, obj, state="not dict")
4967
4968 class C13:
4969 def __getstate__(self):
4970 raise IndexError
4971 obj = C13()
4972 for proto in protocols:
4973 with self.assertRaises(IndexError):
4974 obj.__reduce_ex__(proto)
4975 if proto < 2:
4976 with self.assertRaises(IndexError):
4977 obj.__reduce__()
4978
4979 class C14:
4980 __slots__ = tuple(state)
4981 def __init__(self):
4982 for name, value in state.items():
4983 setattr(self, name, value)
4984
4985 obj = C14()
4986 for proto in protocols:
4987 if proto >= 2:
4988 self._check_reduce(proto, obj, state=(None, state))
4989 else:
4990 with self.assertRaises(TypeError):
4991 obj.__reduce_ex__(proto)
4992 with self.assertRaises(TypeError):
4993 obj.__reduce__()
4994
4995 class C15(dict):
4996 pass
4997 obj = C15({"quebec": -601})
4998 for proto in protocols:
4999 self._check_reduce(proto, obj, dictitems=dict(obj))
5000
5001 class C16(list):
5002 pass
5003 obj = C16(["yukon"])
5004 for proto in protocols:
5005 self._check_reduce(proto, obj, listitems=list(obj))
5006
Benjamin Peterson2626fab2014-02-16 13:49:16 -05005007 def test_special_method_lookup(self):
5008 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5009 class Picky:
5010 def __getstate__(self):
5011 return {}
5012
5013 def __getattr__(self, attr):
5014 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5015 raise AssertionError(attr)
5016 return None
5017 for protocol in protocols:
5018 state = {} if protocol >= 2 else None
5019 self._check_reduce(protocol, Picky(), state=state)
5020
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005021 def _assert_is_copy(self, obj, objcopy, msg=None):
5022 """Utility method to verify if two objects are copies of each others.
5023 """
5024 if msg is None:
5025 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5026 if type(obj).__repr__ is object.__repr__:
5027 # We have this limitation for now because we use the object's repr
5028 # to help us verify that the two objects are copies. This allows
5029 # us to delegate the non-generic verification logic to the objects
5030 # themselves.
5031 raise ValueError("object passed to _assert_is_copy must " +
5032 "override the __repr__ method.")
5033 self.assertIsNot(obj, objcopy, msg=msg)
5034 self.assertIs(type(obj), type(objcopy), msg=msg)
5035 if hasattr(obj, '__dict__'):
5036 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5037 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5038 if hasattr(obj, '__slots__'):
5039 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5040 for slot in obj.__slots__:
5041 self.assertEqual(
5042 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5043 self.assertEqual(getattr(obj, slot, None),
5044 getattr(objcopy, slot, None), msg=msg)
5045 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5046
5047 @staticmethod
5048 def _generate_pickle_copiers():
5049 """Utility method to generate the many possible pickle configurations.
5050 """
5051 class PickleCopier:
5052 "This class copies object using pickle."
5053 def __init__(self, proto, dumps, loads):
5054 self.proto = proto
5055 self.dumps = dumps
5056 self.loads = loads
5057 def copy(self, obj):
5058 return self.loads(self.dumps(obj, self.proto))
5059 def __repr__(self):
5060 # We try to be as descriptive as possible here since this is
5061 # the string which we will allow us to tell the pickle
5062 # configuration we are using during debugging.
5063 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5064 .format(self.proto,
5065 self.dumps.__module__, self.dumps.__qualname__,
5066 self.loads.__module__, self.loads.__qualname__))
5067 return (PickleCopier(*args) for args in
5068 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5069 {pickle.dumps, pickle._dumps},
5070 {pickle.loads, pickle._loads}))
5071
5072 def test_pickle_slots(self):
5073 # Tests pickling of classes with __slots__.
5074
5075 # Pickling of classes with __slots__ but without __getstate__ should
5076 # fail (if using protocol 0 or 1)
5077 global C
5078 class C:
5079 __slots__ = ['a']
5080 with self.assertRaises(TypeError):
5081 pickle.dumps(C(), 0)
5082
5083 global D
5084 class D(C):
5085 pass
5086 with self.assertRaises(TypeError):
5087 pickle.dumps(D(), 0)
5088
5089 class C:
5090 "A class with __getstate__ and __setstate__ implemented."
5091 __slots__ = ['a']
5092 def __getstate__(self):
5093 state = getattr(self, '__dict__', {}).copy()
5094 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005095 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005096 try:
5097 state[slot] = getattr(self, slot)
5098 except AttributeError:
5099 pass
5100 return state
5101 def __setstate__(self, state):
5102 for k, v in state.items():
5103 setattr(self, k, v)
5104 def __repr__(self):
5105 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5106
5107 class D(C):
5108 "A subclass of a class with slots."
5109 pass
5110
5111 global E
5112 class E(C):
5113 "A subclass with an extra slot."
5114 __slots__ = ['b']
5115
5116 # Now it should work
5117 for pickle_copier in self._generate_pickle_copiers():
5118 with self.subTest(pickle_copier=pickle_copier):
5119 x = C()
5120 y = pickle_copier.copy(x)
5121 self._assert_is_copy(x, y)
5122
5123 x.a = 42
5124 y = pickle_copier.copy(x)
5125 self._assert_is_copy(x, y)
5126
5127 x = D()
5128 x.a = 42
5129 x.b = 100
5130 y = pickle_copier.copy(x)
5131 self._assert_is_copy(x, y)
5132
5133 x = E()
5134 x.a = 42
5135 x.b = "foo"
5136 y = pickle_copier.copy(x)
5137 self._assert_is_copy(x, y)
5138
5139 def test_reduce_copying(self):
5140 # Tests pickling and copying new-style classes and objects.
5141 global C1
5142 class C1:
5143 "The state of this class is copyable via its instance dict."
5144 ARGS = (1, 2)
5145 NEED_DICT_COPYING = True
5146 def __init__(self, a, b):
5147 super().__init__()
5148 self.a = a
5149 self.b = b
5150 def __repr__(self):
5151 return "C1(%r, %r)" % (self.a, self.b)
5152
5153 global C2
5154 class C2(list):
5155 "A list subclass copyable via __getnewargs__."
5156 ARGS = (1, 2)
5157 NEED_DICT_COPYING = False
5158 def __new__(cls, a, b):
5159 self = super().__new__(cls)
5160 self.a = a
5161 self.b = b
5162 return self
5163 def __init__(self, *args):
5164 super().__init__()
5165 # This helps testing that __init__ is not called during the
5166 # unpickling process, which would cause extra appends.
5167 self.append("cheese")
5168 @classmethod
5169 def __getnewargs__(cls):
5170 return cls.ARGS
5171 def __repr__(self):
5172 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5173
5174 global C3
5175 class C3(list):
5176 "A list subclass copyable via __getstate__."
5177 ARGS = (1, 2)
5178 NEED_DICT_COPYING = False
5179 def __init__(self, a, b):
5180 self.a = a
5181 self.b = b
5182 # This helps testing that __init__ is not called during the
5183 # unpickling process, which would cause extra appends.
5184 self.append("cheese")
5185 @classmethod
5186 def __getstate__(cls):
5187 return cls.ARGS
5188 def __setstate__(self, state):
5189 a, b = state
5190 self.a = a
5191 self.b = b
5192 def __repr__(self):
5193 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5194
5195 global C4
5196 class C4(int):
5197 "An int subclass copyable via __getnewargs__."
5198 ARGS = ("hello", "world", 1)
5199 NEED_DICT_COPYING = False
5200 def __new__(cls, a, b, value):
5201 self = super().__new__(cls, value)
5202 self.a = a
5203 self.b = b
5204 return self
5205 @classmethod
5206 def __getnewargs__(cls):
5207 return cls.ARGS
5208 def __repr__(self):
5209 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5210
5211 global C5
5212 class C5(int):
5213 "An int subclass copyable via __getnewargs_ex__."
5214 ARGS = (1, 2)
5215 KWARGS = {'value': 3}
5216 NEED_DICT_COPYING = False
5217 def __new__(cls, a, b, *, value=0):
5218 self = super().__new__(cls, value)
5219 self.a = a
5220 self.b = b
5221 return self
5222 @classmethod
5223 def __getnewargs_ex__(cls):
5224 return (cls.ARGS, cls.KWARGS)
5225 def __repr__(self):
5226 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5227
5228 test_classes = (C1, C2, C3, C4, C5)
5229 # Testing copying through pickle
5230 pickle_copiers = self._generate_pickle_copiers()
5231 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5232 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5233 kwargs = getattr(cls, 'KWARGS', {})
5234 obj = cls(*cls.ARGS, **kwargs)
5235 proto = pickle_copier.proto
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005236 objcopy = pickle_copier.copy(obj)
5237 self._assert_is_copy(obj, objcopy)
5238 # For test classes that supports this, make sure we didn't go
5239 # around the reduce protocol by simply copying the attribute
5240 # dictionary. We clear attributes using the previous copy to
5241 # not mutate the original argument.
5242 if proto >= 2 and not cls.NEED_DICT_COPYING:
5243 objcopy.__dict__.clear()
5244 objcopy2 = pickle_copier.copy(objcopy)
5245 self._assert_is_copy(obj, objcopy2)
5246
5247 # Testing copying through copy.deepcopy()
5248 for cls in test_classes:
5249 with self.subTest(cls=cls):
5250 kwargs = getattr(cls, 'KWARGS', {})
5251 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005252 objcopy = deepcopy(obj)
5253 self._assert_is_copy(obj, objcopy)
5254 # For test classes that supports this, make sure we didn't go
5255 # around the reduce protocol by simply copying the attribute
5256 # dictionary. We clear attributes using the previous copy to
5257 # not mutate the original argument.
5258 if not cls.NEED_DICT_COPYING:
5259 objcopy.__dict__.clear()
5260 objcopy2 = deepcopy(objcopy)
5261 self._assert_is_copy(obj, objcopy2)
5262
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005263 def test_issue24097(self):
5264 # Slot name is freed inside __getattr__ and is later used.
5265 class S(str): # Not interned
5266 pass
5267 class A:
5268 __slotnames__ = [S('spam')]
5269 def __getattr__(self, attr):
5270 if attr == 'spam':
5271 A.__slotnames__[:] = [S('spam')]
5272 return 42
5273 else:
5274 raise AttributeError
5275
5276 import copyreg
5277 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
Serhiy Storchaka205e00c2017-04-08 09:52:59 +03005278 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5279
5280 def test_object_reduce(self):
5281 # Issue #29914
5282 # __reduce__() takes no arguments
5283 object().__reduce__()
5284 with self.assertRaises(TypeError):
5285 object().__reduce__(0)
5286 # __reduce_ex__() takes one integer argument
5287 object().__reduce_ex__(0)
5288 with self.assertRaises(TypeError):
5289 object().__reduce_ex__()
5290 with self.assertRaises(TypeError):
5291 object().__reduce_ex__(None)
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005292
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005293
Benjamin Peterson2a605342014-03-17 16:20:12 -05005294class SharedKeyTests(unittest.TestCase):
5295
5296 @support.cpython_only
5297 def test_subclasses(self):
5298 # Verify that subclasses can share keys (per PEP 412)
5299 class A:
5300 pass
5301 class B(A):
5302 pass
5303
5304 a, b = A(), B()
5305 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5306 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005307 # Initial hash table can contain at most 5 elements.
5308 # Set 6 attributes to cause internal resizing.
5309 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005310 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5311 a2 = A()
5312 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5313 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
Victor Stinner742da042016-09-07 17:40:12 -07005314 b.u, b.v, b.w, b.t, b.s, b.r = range(6)
Benjamin Peterson2a605342014-03-17 16:20:12 -05005315 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5316
5317
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005318class DebugHelperMeta(type):
5319 """
5320 Sets default __doc__ and simplifies repr() output.
5321 """
5322 def __new__(mcls, name, bases, attrs):
5323 if attrs.get('__doc__') is None:
5324 attrs['__doc__'] = name # helps when debugging with gdb
5325 return type.__new__(mcls, name, bases, attrs)
5326 def __repr__(cls):
5327 return repr(cls.__name__)
5328
5329
5330class MroTest(unittest.TestCase):
5331 """
5332 Regressions for some bugs revealed through
5333 mcsl.mro() customization (typeobject.c: mro_internal()) and
5334 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5335 """
5336
5337 def setUp(self):
5338 self.step = 0
5339 self.ready = False
5340
5341 def step_until(self, limit):
5342 ret = (self.step < limit)
5343 if ret:
5344 self.step += 1
5345 return ret
5346
5347 def test_incomplete_set_bases_on_self(self):
5348 """
5349 type_set_bases must be aware that type->tp_mro can be NULL.
5350 """
5351 class M(DebugHelperMeta):
5352 def mro(cls):
5353 if self.step_until(1):
5354 assert cls.__mro__ is None
5355 cls.__bases__ += ()
5356
5357 return type.mro(cls)
5358
5359 class A(metaclass=M):
5360 pass
5361
5362 def test_reent_set_bases_on_base(self):
5363 """
5364 Deep reentrancy must not over-decref old_mro.
5365 """
5366 class M(DebugHelperMeta):
5367 def mro(cls):
5368 if cls.__mro__ is not None and cls.__name__ == 'B':
5369 # 4-5 steps are usually enough to make it crash somewhere
5370 if self.step_until(10):
5371 A.__bases__ += ()
5372
5373 return type.mro(cls)
5374
5375 class A(metaclass=M):
5376 pass
5377 class B(A):
5378 pass
5379 B.__bases__ += ()
5380
5381 def test_reent_set_bases_on_direct_base(self):
5382 """
5383 Similar to test_reent_set_bases_on_base, but may crash differently.
5384 """
5385 class M(DebugHelperMeta):
5386 def mro(cls):
5387 base = cls.__bases__[0]
5388 if base is not object:
5389 if self.step_until(5):
5390 base.__bases__ += ()
5391
5392 return type.mro(cls)
5393
5394 class A(metaclass=M):
5395 pass
5396 class B(A):
5397 pass
5398 class C(B):
5399 pass
5400
5401 def test_reent_set_bases_tp_base_cycle(self):
5402 """
5403 type_set_bases must check for an inheritance cycle not only through
5404 MRO of the type, which may be not yet updated in case of reentrance,
5405 but also through tp_base chain, which is assigned before diving into
5406 inner calls to mro().
5407
5408 Otherwise, the following snippet can loop forever:
5409 do {
5410 // ...
5411 type = type->tp_base;
5412 } while (type != NULL);
5413
5414 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5415 would not be happy in that case, causing a stack overflow.
5416 """
5417 class M(DebugHelperMeta):
5418 def mro(cls):
5419 if self.ready:
5420 if cls.__name__ == 'B1':
5421 B2.__bases__ = (B1,)
5422 if cls.__name__ == 'B2':
5423 B1.__bases__ = (B2,)
5424 return type.mro(cls)
5425
5426 class A(metaclass=M):
5427 pass
5428 class B1(A):
5429 pass
5430 class B2(A):
5431 pass
5432
5433 self.ready = True
5434 with self.assertRaises(TypeError):
5435 B1.__bases__ += ()
5436
5437 def test_tp_subclasses_cycle_in_update_slots(self):
5438 """
5439 type_set_bases must check for reentrancy upon finishing its job
5440 by updating tp_subclasses of old/new bases of the type.
5441 Otherwise, an implicit inheritance cycle through tp_subclasses
5442 can break functions that recurse on elements of that field
5443 (like recurse_down_subclasses and mro_hierarchy) eventually
5444 leading to a stack overflow.
5445 """
5446 class M(DebugHelperMeta):
5447 def mro(cls):
5448 if self.ready and cls.__name__ == 'C':
5449 self.ready = False
5450 C.__bases__ = (B2,)
5451 return type.mro(cls)
5452
5453 class A(metaclass=M):
5454 pass
5455 class B1(A):
5456 pass
5457 class B2(A):
5458 pass
5459 class C(A):
5460 pass
5461
5462 self.ready = True
5463 C.__bases__ = (B1,)
5464 B1.__bases__ = (C,)
5465
5466 self.assertEqual(C.__bases__, (B2,))
5467 self.assertEqual(B2.__subclasses__(), [C])
5468 self.assertEqual(B1.__subclasses__(), [])
5469
5470 self.assertEqual(B1.__bases__, (C,))
5471 self.assertEqual(C.__subclasses__(), [B1])
5472
5473 def test_tp_subclasses_cycle_error_return_path(self):
5474 """
5475 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5476 a code path executed on error (goto bail).
5477 """
5478 class E(Exception):
5479 pass
5480 class M(DebugHelperMeta):
5481 def mro(cls):
5482 if self.ready and cls.__name__ == 'C':
5483 if C.__bases__ == (B2,):
5484 self.ready = False
5485 else:
5486 C.__bases__ = (B2,)
5487 raise E
5488 return type.mro(cls)
5489
5490 class A(metaclass=M):
5491 pass
5492 class B1(A):
5493 pass
5494 class B2(A):
5495 pass
5496 class C(A):
5497 pass
5498
5499 self.ready = True
5500 with self.assertRaises(E):
5501 C.__bases__ = (B1,)
5502 B1.__bases__ = (C,)
5503
5504 self.assertEqual(C.__bases__, (B2,))
5505 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5506
5507 def test_incomplete_extend(self):
5508 """
5509 Extending an unitialized type with type->tp_mro == NULL must
5510 throw a reasonable TypeError exception, instead of failing
5511 with PyErr_BadInternalCall.
5512 """
5513 class M(DebugHelperMeta):
5514 def mro(cls):
5515 if cls.__mro__ is None and cls.__name__ != 'X':
5516 with self.assertRaises(TypeError):
5517 class X(cls):
5518 pass
5519
5520 return type.mro(cls)
5521
5522 class A(metaclass=M):
5523 pass
5524
5525 def test_incomplete_super(self):
5526 """
5527 Attrubute lookup on a super object must be aware that
5528 its target type can be uninitialized (type->tp_mro == NULL).
5529 """
5530 class M(DebugHelperMeta):
5531 def mro(cls):
5532 if cls.__mro__ is None:
5533 with self.assertRaises(AttributeError):
5534 super(cls, cls).xxx
5535
5536 return type.mro(cls)
5537
5538 class A(metaclass=M):
5539 pass
5540
5541
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005542def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005543 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005544 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005545 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005546 MiscTests, PicklingTests, SharedKeyTests,
5547 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005548
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005549if __name__ == "__main__":
5550 test_main()