blob: eda6fc1dac13053317b660bc5fd6679e2158df3f [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
Martin Panter0be894b2016-09-07 12:03:06 +0000880 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
Christian Heimesa156e092008-02-16 07:38:31 +00001325 def test_slots_descriptor(self):
1326 # Issue2115: slot descriptors did not correctly check
1327 # the type of the given object
1328 import abc
1329 class MyABC(metaclass=abc.ABCMeta):
1330 __slots__ = "a"
1331
1332 class Unrelated(object):
1333 pass
1334 MyABC.register(Unrelated)
1335
1336 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001337 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001338
1339 # This used to crash
1340 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1341
Georg Brandl479a7e72008-02-05 18:13:15 +00001342 def test_dynamics(self):
1343 # Testing class attribute propagation...
1344 class D(object):
1345 pass
1346 class E(D):
1347 pass
1348 class F(D):
1349 pass
1350 D.foo = 1
1351 self.assertEqual(D.foo, 1)
1352 # Test that dynamic attributes are inherited
1353 self.assertEqual(E.foo, 1)
1354 self.assertEqual(F.foo, 1)
1355 # Test dynamic instances
1356 class C(object):
1357 pass
1358 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001359 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001360 C.foobar = 2
1361 self.assertEqual(a.foobar, 2)
1362 C.method = lambda self: 42
1363 self.assertEqual(a.method(), 42)
1364 C.__repr__ = lambda self: "C()"
1365 self.assertEqual(repr(a), "C()")
1366 C.__int__ = lambda self: 100
1367 self.assertEqual(int(a), 100)
1368 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001369 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001370 def mygetattr(self, name):
1371 if name == "spam":
1372 return "spam"
1373 raise AttributeError
1374 C.__getattr__ = mygetattr
1375 self.assertEqual(a.spam, "spam")
1376 a.new = 12
1377 self.assertEqual(a.new, 12)
1378 def mysetattr(self, name, value):
1379 if name == "spam":
1380 raise AttributeError
1381 return object.__setattr__(self, name, value)
1382 C.__setattr__ = mysetattr
1383 try:
1384 a.spam = "not spam"
1385 except AttributeError:
1386 pass
1387 else:
1388 self.fail("expected AttributeError")
1389 self.assertEqual(a.spam, "spam")
1390 class D(C):
1391 pass
1392 d = D()
1393 d.foo = 1
1394 self.assertEqual(d.foo, 1)
1395
1396 # Test handling of int*seq and seq*int
1397 class I(int):
1398 pass
1399 self.assertEqual("a"*I(2), "aa")
1400 self.assertEqual(I(2)*"a", "aa")
1401 self.assertEqual(2*I(3), 6)
1402 self.assertEqual(I(3)*2, 6)
1403 self.assertEqual(I(3)*I(2), 6)
1404
Georg Brandl479a7e72008-02-05 18:13:15 +00001405 # Test comparison of classes with dynamic metaclasses
1406 class dynamicmetaclass(type):
1407 pass
1408 class someclass(metaclass=dynamicmetaclass):
1409 pass
1410 self.assertNotEqual(someclass, object)
1411
1412 def test_errors(self):
1413 # Testing errors...
1414 try:
1415 class C(list, dict):
1416 pass
1417 except TypeError:
1418 pass
1419 else:
1420 self.fail("inheritance from both list and dict should be illegal")
1421
1422 try:
1423 class C(object, None):
1424 pass
1425 except TypeError:
1426 pass
1427 else:
1428 self.fail("inheritance from non-type should be illegal")
1429 class Classic:
1430 pass
1431
1432 try:
1433 class C(type(len)):
1434 pass
1435 except TypeError:
1436 pass
1437 else:
1438 self.fail("inheritance from CFunction should be illegal")
1439
1440 try:
1441 class C(object):
1442 __slots__ = 1
1443 except TypeError:
1444 pass
1445 else:
1446 self.fail("__slots__ = 1 should be illegal")
1447
1448 try:
1449 class C(object):
1450 __slots__ = [1]
1451 except TypeError:
1452 pass
1453 else:
1454 self.fail("__slots__ = [1] should be illegal")
1455
1456 class M1(type):
1457 pass
1458 class M2(type):
1459 pass
1460 class A1(object, metaclass=M1):
1461 pass
1462 class A2(object, metaclass=M2):
1463 pass
1464 try:
1465 class B(A1, A2):
1466 pass
1467 except TypeError:
1468 pass
1469 else:
1470 self.fail("finding the most derived metaclass should have failed")
1471
1472 def test_classmethods(self):
1473 # Testing class methods...
1474 class C(object):
1475 def foo(*a): return a
1476 goo = classmethod(foo)
1477 c = C()
1478 self.assertEqual(C.goo(1), (C, 1))
1479 self.assertEqual(c.goo(1), (C, 1))
1480 self.assertEqual(c.foo(1), (c, 1))
1481 class D(C):
1482 pass
1483 d = D()
1484 self.assertEqual(D.goo(1), (D, 1))
1485 self.assertEqual(d.goo(1), (D, 1))
1486 self.assertEqual(d.foo(1), (d, 1))
1487 self.assertEqual(D.foo(d, 1), (d, 1))
1488 # Test for a specific crash (SF bug 528132)
1489 def f(cls, arg): return (cls, arg)
1490 ff = classmethod(f)
1491 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1492 self.assertEqual(ff.__get__(0)(42), (int, 42))
1493
1494 # Test super() with classmethods (SF bug 535444)
1495 self.assertEqual(C.goo.__self__, C)
1496 self.assertEqual(D.goo.__self__, D)
1497 self.assertEqual(super(D,D).goo.__self__, D)
1498 self.assertEqual(super(D,d).goo.__self__, D)
1499 self.assertEqual(super(D,D).goo(), (D,))
1500 self.assertEqual(super(D,d).goo(), (D,))
1501
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001502 # Verify that a non-callable will raise
1503 meth = classmethod(1).__get__(1)
1504 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001505
1506 # Verify that classmethod() doesn't allow keyword args
1507 try:
1508 classmethod(f, kw=1)
1509 except TypeError:
1510 pass
1511 else:
1512 self.fail("classmethod shouldn't accept keyword args")
1513
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001514 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001515 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001516 cm.x = 42
1517 self.assertEqual(cm.x, 42)
1518 self.assertEqual(cm.__dict__, {"x" : 42})
1519 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001520 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001521
Benjamin Petersone549ead2009-03-28 21:42:05 +00001522 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001523 def test_classmethods_in_c(self):
1524 # Testing C-based class methods...
1525 import xxsubtype as spam
1526 a = (1, 2, 3)
1527 d = {'abc': 123}
1528 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1529 self.assertEqual(x, spam.spamlist)
1530 self.assertEqual(a, a1)
1531 self.assertEqual(d, d1)
1532 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1533 self.assertEqual(x, spam.spamlist)
1534 self.assertEqual(a, a1)
1535 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001536 spam_cm = spam.spamlist.__dict__['classmeth']
1537 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1538 self.assertEqual(x2, spam.spamlist)
1539 self.assertEqual(a2, a1)
1540 self.assertEqual(d2, d1)
1541 class SubSpam(spam.spamlist): pass
1542 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1543 self.assertEqual(x2, SubSpam)
1544 self.assertEqual(a2, a1)
1545 self.assertEqual(d2, d1)
1546 with self.assertRaises(TypeError):
1547 spam_cm()
1548 with self.assertRaises(TypeError):
1549 spam_cm(spam.spamlist())
1550 with self.assertRaises(TypeError):
1551 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001552
1553 def test_staticmethods(self):
1554 # Testing static methods...
1555 class C(object):
1556 def foo(*a): return a
1557 goo = staticmethod(foo)
1558 c = C()
1559 self.assertEqual(C.goo(1), (1,))
1560 self.assertEqual(c.goo(1), (1,))
1561 self.assertEqual(c.foo(1), (c, 1,))
1562 class D(C):
1563 pass
1564 d = D()
1565 self.assertEqual(D.goo(1), (1,))
1566 self.assertEqual(d.goo(1), (1,))
1567 self.assertEqual(d.foo(1), (d, 1))
1568 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001569 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001570 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001571 sm.x = 42
1572 self.assertEqual(sm.x, 42)
1573 self.assertEqual(sm.__dict__, {"x" : 42})
1574 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001575 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001576
Benjamin Petersone549ead2009-03-28 21:42:05 +00001577 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001578 def test_staticmethods_in_c(self):
1579 # Testing C-based static methods...
1580 import xxsubtype as spam
1581 a = (1, 2, 3)
1582 d = {"abc": 123}
1583 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1584 self.assertEqual(x, None)
1585 self.assertEqual(a, a1)
1586 self.assertEqual(d, d1)
1587 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1588 self.assertEqual(x, None)
1589 self.assertEqual(a, a1)
1590 self.assertEqual(d, d1)
1591
1592 def test_classic(self):
1593 # Testing classic classes...
1594 class C:
1595 def foo(*a): return a
1596 goo = classmethod(foo)
1597 c = C()
1598 self.assertEqual(C.goo(1), (C, 1))
1599 self.assertEqual(c.goo(1), (C, 1))
1600 self.assertEqual(c.foo(1), (c, 1))
1601 class D(C):
1602 pass
1603 d = D()
1604 self.assertEqual(D.goo(1), (D, 1))
1605 self.assertEqual(d.goo(1), (D, 1))
1606 self.assertEqual(d.foo(1), (d, 1))
1607 self.assertEqual(D.foo(d, 1), (d, 1))
1608 class E: # *not* subclassing from C
1609 foo = C.foo
1610 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001611 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001612
1613 def test_compattr(self):
1614 # Testing computed attributes...
1615 class C(object):
1616 class computed_attribute(object):
1617 def __init__(self, get, set=None, delete=None):
1618 self.__get = get
1619 self.__set = set
1620 self.__delete = delete
1621 def __get__(self, obj, type=None):
1622 return self.__get(obj)
1623 def __set__(self, obj, value):
1624 return self.__set(obj, value)
1625 def __delete__(self, obj):
1626 return self.__delete(obj)
1627 def __init__(self):
1628 self.__x = 0
1629 def __get_x(self):
1630 x = self.__x
1631 self.__x = x+1
1632 return x
1633 def __set_x(self, x):
1634 self.__x = x
1635 def __delete_x(self):
1636 del self.__x
1637 x = computed_attribute(__get_x, __set_x, __delete_x)
1638 a = C()
1639 self.assertEqual(a.x, 0)
1640 self.assertEqual(a.x, 1)
1641 a.x = 10
1642 self.assertEqual(a.x, 10)
1643 self.assertEqual(a.x, 11)
1644 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001645 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001646
1647 def test_newslots(self):
1648 # Testing __new__ slot override...
1649 class C(list):
1650 def __new__(cls):
1651 self = list.__new__(cls)
1652 self.foo = 1
1653 return self
1654 def __init__(self):
1655 self.foo = self.foo + 2
1656 a = C()
1657 self.assertEqual(a.foo, 3)
1658 self.assertEqual(a.__class__, C)
1659 class D(C):
1660 pass
1661 b = D()
1662 self.assertEqual(b.foo, 3)
1663 self.assertEqual(b.__class__, D)
1664
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001665 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001666 def test_bad_new(self):
1667 self.assertRaises(TypeError, object.__new__)
1668 self.assertRaises(TypeError, object.__new__, '')
1669 self.assertRaises(TypeError, list.__new__, object)
1670 self.assertRaises(TypeError, object.__new__, list)
1671 class C(object):
1672 __new__ = list.__new__
1673 self.assertRaises(TypeError, C)
1674 class C(list):
1675 __new__ = object.__new__
1676 self.assertRaises(TypeError, C)
1677
1678 def test_object_new(self):
1679 class A(object):
1680 pass
1681 object.__new__(A)
1682 self.assertRaises(TypeError, object.__new__, A, 5)
1683 object.__init__(A())
1684 self.assertRaises(TypeError, object.__init__, A(), 5)
1685
1686 class A(object):
1687 def __init__(self, foo):
1688 self.foo = foo
1689 object.__new__(A)
1690 object.__new__(A, 5)
1691 object.__init__(A(3))
1692 self.assertRaises(TypeError, object.__init__, A(3), 5)
1693
1694 class A(object):
1695 def __new__(cls, foo):
1696 return object.__new__(cls)
1697 object.__new__(A)
1698 self.assertRaises(TypeError, object.__new__, A, 5)
1699 object.__init__(A(3))
1700 object.__init__(A(3), 5)
1701
1702 class A(object):
1703 def __new__(cls, foo):
1704 return object.__new__(cls)
1705 def __init__(self, foo):
1706 self.foo = foo
1707 object.__new__(A)
1708 self.assertRaises(TypeError, object.__new__, A, 5)
1709 object.__init__(A(3))
1710 self.assertRaises(TypeError, object.__init__, A(3), 5)
1711
Serhiy Storchaka49010ee2016-12-14 19:52:17 +02001712 @unittest.expectedFailure
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02001713 def test_restored_object_new(self):
1714 class A(object):
1715 def __new__(cls, *args, **kwargs):
1716 raise AssertionError
1717 self.assertRaises(AssertionError, A)
1718 class B(A):
1719 __new__ = object.__new__
1720 def __init__(self, foo):
1721 self.foo = foo
1722 with warnings.catch_warnings():
1723 warnings.simplefilter('error', DeprecationWarning)
1724 b = B(3)
1725 self.assertEqual(b.foo, 3)
1726 self.assertEqual(b.__class__, B)
1727 del B.__new__
1728 self.assertRaises(AssertionError, B)
1729 del A.__new__
1730 with warnings.catch_warnings():
1731 warnings.simplefilter('error', DeprecationWarning)
1732 b = B(3)
1733 self.assertEqual(b.foo, 3)
1734 self.assertEqual(b.__class__, B)
1735
Georg Brandl479a7e72008-02-05 18:13:15 +00001736 def test_altmro(self):
1737 # Testing mro() and overriding it...
1738 class A(object):
1739 def f(self): return "A"
1740 class B(A):
1741 pass
1742 class C(A):
1743 def f(self): return "C"
1744 class D(B, C):
1745 pass
1746 self.assertEqual(D.mro(), [D, B, C, A, object])
1747 self.assertEqual(D.__mro__, (D, B, C, A, object))
1748 self.assertEqual(D().f(), "C")
1749
1750 class PerverseMetaType(type):
1751 def mro(cls):
1752 L = type.mro(cls)
1753 L.reverse()
1754 return L
1755 class X(D,B,C,A, metaclass=PerverseMetaType):
1756 pass
1757 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1758 self.assertEqual(X().f(), "A")
1759
1760 try:
1761 class _metaclass(type):
1762 def mro(self):
1763 return [self, dict, object]
1764 class X(object, metaclass=_metaclass):
1765 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001766 # In CPython, the class creation above already raises
1767 # TypeError, as a protection against the fact that
1768 # instances of X would segfault it. In other Python
1769 # implementations it would be ok to let the class X
1770 # be created, but instead get a clean TypeError on the
1771 # __setitem__ below.
1772 x = object.__new__(X)
1773 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001774 except TypeError:
1775 pass
1776 else:
1777 self.fail("devious mro() return not caught")
1778
1779 try:
1780 class _metaclass(type):
1781 def mro(self):
1782 return [1]
1783 class X(object, metaclass=_metaclass):
1784 pass
1785 except TypeError:
1786 pass
1787 else:
1788 self.fail("non-class mro() return not caught")
1789
1790 try:
1791 class _metaclass(type):
1792 def mro(self):
1793 return 1
1794 class X(object, metaclass=_metaclass):
1795 pass
1796 except TypeError:
1797 pass
1798 else:
1799 self.fail("non-sequence mro() return not caught")
1800
1801 def test_overloading(self):
1802 # Testing operator overloading...
1803
1804 class B(object):
1805 "Intermediate class because object doesn't have a __setattr__"
1806
1807 class C(B):
1808 def __getattr__(self, name):
1809 if name == "foo":
1810 return ("getattr", name)
1811 else:
1812 raise AttributeError
1813 def __setattr__(self, name, value):
1814 if name == "foo":
1815 self.setattr = (name, value)
1816 else:
1817 return B.__setattr__(self, name, value)
1818 def __delattr__(self, name):
1819 if name == "foo":
1820 self.delattr = name
1821 else:
1822 return B.__delattr__(self, name)
1823
1824 def __getitem__(self, key):
1825 return ("getitem", key)
1826 def __setitem__(self, key, value):
1827 self.setitem = (key, value)
1828 def __delitem__(self, key):
1829 self.delitem = key
1830
1831 a = C()
1832 self.assertEqual(a.foo, ("getattr", "foo"))
1833 a.foo = 12
1834 self.assertEqual(a.setattr, ("foo", 12))
1835 del a.foo
1836 self.assertEqual(a.delattr, "foo")
1837
1838 self.assertEqual(a[12], ("getitem", 12))
1839 a[12] = 21
1840 self.assertEqual(a.setitem, (12, 21))
1841 del a[12]
1842 self.assertEqual(a.delitem, 12)
1843
1844 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1845 a[0:10] = "foo"
1846 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1847 del a[0:10]
1848 self.assertEqual(a.delitem, (slice(0, 10)))
1849
1850 def test_methods(self):
1851 # Testing methods...
1852 class C(object):
1853 def __init__(self, x):
1854 self.x = x
1855 def foo(self):
1856 return self.x
1857 c1 = C(1)
1858 self.assertEqual(c1.foo(), 1)
1859 class D(C):
1860 boo = C.foo
1861 goo = c1.foo
1862 d2 = D(2)
1863 self.assertEqual(d2.foo(), 2)
1864 self.assertEqual(d2.boo(), 2)
1865 self.assertEqual(d2.goo(), 1)
1866 class E(object):
1867 foo = C.foo
1868 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001869 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001870
Benjamin Peterson224205f2009-05-08 03:25:19 +00001871 def test_special_method_lookup(self):
1872 # The lookup of special methods bypasses __getattr__ and
1873 # __getattribute__, but they still can be descriptors.
1874
1875 def run_context(manager):
1876 with manager:
1877 pass
1878 def iden(self):
1879 return self
1880 def hello(self):
1881 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001882 def empty_seq(self):
1883 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001884 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001885 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001886 def complex_num(self):
1887 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001888 def stop(self):
1889 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001890 def return_true(self, thing=None):
1891 return True
1892 def do_isinstance(obj):
1893 return isinstance(int, obj)
1894 def do_issubclass(obj):
1895 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001896 def do_dict_missing(checker):
1897 class DictSub(checker.__class__, dict):
1898 pass
1899 self.assertEqual(DictSub()["hi"], 4)
1900 def some_number(self_, key):
1901 self.assertEqual(key, "hi")
1902 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001903 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001904 def format_impl(self, spec):
1905 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001906
1907 # It would be nice to have every special method tested here, but I'm
1908 # only listing the ones I can remember outside of typeobject.c, since it
1909 # does it right.
1910 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001911 ("__bytes__", bytes, hello, set(), {}),
1912 ("__reversed__", reversed, empty_seq, set(), {}),
1913 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001914 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001915 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1916 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001917 ("__missing__", do_dict_missing, some_number,
1918 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001919 ("__subclasscheck__", do_issubclass, return_true,
1920 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001921 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1922 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001923 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001924 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001925 ("__floor__", math.floor, zero, set(), {}),
1926 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001927 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001928 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001929 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001930 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001931 ]
1932
1933 class Checker(object):
1934 def __getattr__(self, attr, test=self):
1935 test.fail("__getattr__ called with {0}".format(attr))
1936 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001937 if attr not in ok:
1938 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001939 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001940 class SpecialDescr(object):
1941 def __init__(self, impl):
1942 self.impl = impl
1943 def __get__(self, obj, owner):
1944 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001945 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001946 class MyException(Exception):
1947 pass
1948 class ErrDescr(object):
1949 def __get__(self, obj, owner):
1950 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001951
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001952 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001953 class X(Checker):
1954 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001955 for attr, obj in env.items():
1956 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001957 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001958 runner(X())
1959
1960 record = []
1961 class X(Checker):
1962 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001963 for attr, obj in env.items():
1964 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001965 setattr(X, name, SpecialDescr(meth_impl))
1966 runner(X())
1967 self.assertEqual(record, [1], name)
1968
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001969 class X(Checker):
1970 pass
1971 for attr, obj in env.items():
1972 setattr(X, attr, obj)
1973 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001974 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001975
Georg Brandl479a7e72008-02-05 18:13:15 +00001976 def test_specials(self):
1977 # Testing special operators...
1978 # Test operators like __hash__ for which a built-in default exists
1979
1980 # Test the default behavior for static classes
1981 class C(object):
1982 def __getitem__(self, i):
1983 if 0 <= i < 10: return i
1984 raise IndexError
1985 c1 = C()
1986 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001987 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001988 self.assertNotEqual(id(c1), id(c2))
1989 hash(c1)
1990 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001991 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001992 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001993 self.assertFalse(c1 != c1)
1994 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001995 # Note that the module name appears in str/repr, and that varies
1996 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001997 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001998 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001999 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002000 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002001 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002002 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002003 # Test the default behavior for dynamic classes
2004 class D(object):
2005 def __getitem__(self, i):
2006 if 0 <= i < 10: return i
2007 raise IndexError
2008 d1 = D()
2009 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002010 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002011 self.assertNotEqual(id(d1), id(d2))
2012 hash(d1)
2013 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002014 self.assertEqual(d1, d1)
2015 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002016 self.assertFalse(d1 != d1)
2017 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002018 # Note that the module name appears in str/repr, and that varies
2019 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002020 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002021 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00002022 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002023 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002024 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002025 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00002026 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00002027 class Proxy(object):
2028 def __init__(self, x):
2029 self.x = x
2030 def __bool__(self):
2031 return not not self.x
2032 def __hash__(self):
2033 return hash(self.x)
2034 def __eq__(self, other):
2035 return self.x == other
2036 def __ne__(self, other):
2037 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00002038 def __ge__(self, other):
2039 return self.x >= other
2040 def __gt__(self, other):
2041 return self.x > other
2042 def __le__(self, other):
2043 return self.x <= other
2044 def __lt__(self, other):
2045 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00002046 def __str__(self):
2047 return "Proxy:%s" % self.x
2048 def __repr__(self):
2049 return "Proxy(%r)" % self.x
2050 def __contains__(self, value):
2051 return value in self.x
2052 p0 = Proxy(0)
2053 p1 = Proxy(1)
2054 p_1 = Proxy(-1)
2055 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002056 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00002057 self.assertEqual(hash(p0), hash(0))
2058 self.assertEqual(p0, p0)
2059 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002060 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002061 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002062 self.assertTrue(p0 < p1)
2063 self.assertTrue(p0 <= p1)
2064 self.assertTrue(p1 > p0)
2065 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00002066 self.assertEqual(str(p0), "Proxy:0")
2067 self.assertEqual(repr(p0), "Proxy(0)")
2068 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002069 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002070 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00002071 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002072 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002073
Georg Brandl479a7e72008-02-05 18:13:15 +00002074 def test_weakrefs(self):
2075 # Testing weak references...
2076 import weakref
2077 class C(object):
2078 pass
2079 c = C()
2080 r = weakref.ref(c)
2081 self.assertEqual(r(), c)
2082 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002083 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002084 self.assertEqual(r(), None)
2085 del r
2086 class NoWeak(object):
2087 __slots__ = ['foo']
2088 no = NoWeak()
2089 try:
2090 weakref.ref(no)
2091 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002092 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002093 else:
2094 self.fail("weakref.ref(no) should be illegal")
2095 class Weak(object):
2096 __slots__ = ['foo', '__weakref__']
2097 yes = Weak()
2098 r = weakref.ref(yes)
2099 self.assertEqual(r(), yes)
2100 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002101 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002102 self.assertEqual(r(), None)
2103 del r
2104
2105 def test_properties(self):
2106 # Testing property...
2107 class C(object):
2108 def getx(self):
2109 return self.__x
2110 def setx(self, value):
2111 self.__x = value
2112 def delx(self):
2113 del self.__x
2114 x = property(getx, setx, delx, doc="I'm the x property.")
2115 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002116 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002117 a.x = 42
2118 self.assertEqual(a._C__x, 42)
2119 self.assertEqual(a.x, 42)
2120 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002121 self.assertNotHasAttr(a, "x")
2122 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002123 C.x.__set__(a, 100)
2124 self.assertEqual(C.x.__get__(a), 100)
2125 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002126 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002127
2128 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002129 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002130
2131 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002132 self.assertIn("__doc__", attrs)
2133 self.assertIn("fget", attrs)
2134 self.assertIn("fset", attrs)
2135 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002136
2137 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002138 self.assertIs(raw.fget, C.__dict__['getx'])
2139 self.assertIs(raw.fset, C.__dict__['setx'])
2140 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002141
Raymond Hettingereac503a2015-05-13 01:09:59 -07002142 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002143 try:
2144 setattr(raw, attr, 42)
2145 except AttributeError as msg:
2146 if str(msg).find('readonly') < 0:
2147 self.fail("when setting readonly attr %r on a property, "
2148 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2149 else:
2150 self.fail("expected AttributeError from trying to set readonly %r "
2151 "attr on a property" % attr)
2152
Raymond Hettingereac503a2015-05-13 01:09:59 -07002153 raw.__doc__ = 42
2154 self.assertEqual(raw.__doc__, 42)
2155
Georg Brandl479a7e72008-02-05 18:13:15 +00002156 class D(object):
2157 __getitem__ = property(lambda s: 1/0)
2158
2159 d = D()
2160 try:
2161 for i in d:
2162 str(i)
2163 except ZeroDivisionError:
2164 pass
2165 else:
2166 self.fail("expected ZeroDivisionError from bad property")
2167
R. David Murray378c0cf2010-02-24 01:46:21 +00002168 @unittest.skipIf(sys.flags.optimize >= 2,
2169 "Docstrings are omitted with -O2 and above")
2170 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002171 class E(object):
2172 def getter(self):
2173 "getter method"
2174 return 0
2175 def setter(self_, value):
2176 "setter method"
2177 pass
2178 prop = property(getter)
2179 self.assertEqual(prop.__doc__, "getter method")
2180 prop2 = property(fset=setter)
2181 self.assertEqual(prop2.__doc__, None)
2182
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002183 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002184 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002185 # this segfaulted in 2.5b2
2186 try:
2187 import _testcapi
2188 except ImportError:
2189 pass
2190 else:
2191 class X(object):
2192 p = property(_testcapi.test_with_docstring)
2193
2194 def test_properties_plus(self):
2195 class C(object):
2196 foo = property(doc="hello")
2197 @foo.getter
2198 def foo(self):
2199 return self._foo
2200 @foo.setter
2201 def foo(self, value):
2202 self._foo = abs(value)
2203 @foo.deleter
2204 def foo(self):
2205 del self._foo
2206 c = C()
2207 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002208 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002209 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002210 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002211 self.assertEqual(c._foo, 42)
2212 self.assertEqual(c.foo, 42)
2213 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002214 self.assertNotHasAttr(c, '_foo')
2215 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002216
2217 class D(C):
2218 @C.foo.deleter
2219 def foo(self):
2220 try:
2221 del self._foo
2222 except AttributeError:
2223 pass
2224 d = D()
2225 d.foo = 24
2226 self.assertEqual(d.foo, 24)
2227 del d.foo
2228 del d.foo
2229
2230 class E(object):
2231 @property
2232 def foo(self):
2233 return self._foo
2234 @foo.setter
2235 def foo(self, value):
2236 raise RuntimeError
2237 @foo.setter
2238 def foo(self, value):
2239 self._foo = abs(value)
2240 @foo.deleter
2241 def foo(self, value=None):
2242 del self._foo
2243
2244 e = E()
2245 e.foo = -42
2246 self.assertEqual(e.foo, 42)
2247 del e.foo
2248
2249 class F(E):
2250 @E.foo.deleter
2251 def foo(self):
2252 del self._foo
2253 @foo.setter
2254 def foo(self, value):
2255 self._foo = max(0, value)
2256 f = F()
2257 f.foo = -10
2258 self.assertEqual(f.foo, 0)
2259 del f.foo
2260
2261 def test_dict_constructors(self):
2262 # Testing dict constructor ...
2263 d = dict()
2264 self.assertEqual(d, {})
2265 d = dict({})
2266 self.assertEqual(d, {})
2267 d = dict({1: 2, 'a': 'b'})
2268 self.assertEqual(d, {1: 2, 'a': 'b'})
2269 self.assertEqual(d, dict(list(d.items())))
2270 self.assertEqual(d, dict(iter(d.items())))
2271 d = dict({'one':1, 'two':2})
2272 self.assertEqual(d, dict(one=1, two=2))
2273 self.assertEqual(d, dict(**d))
2274 self.assertEqual(d, dict({"one": 1}, two=2))
2275 self.assertEqual(d, dict([("two", 2)], one=1))
2276 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2277 self.assertEqual(d, dict(**d))
2278
2279 for badarg in 0, 0, 0j, "0", [0], (0,):
2280 try:
2281 dict(badarg)
2282 except TypeError:
2283 pass
2284 except ValueError:
2285 if badarg == "0":
2286 # It's a sequence, and its elements are also sequences (gotta
2287 # love strings <wink>), but they aren't of length 2, so this
2288 # one seemed better as a ValueError than a TypeError.
2289 pass
2290 else:
2291 self.fail("no TypeError from dict(%r)" % badarg)
2292 else:
2293 self.fail("no TypeError from dict(%r)" % badarg)
2294
2295 try:
2296 dict({}, {})
2297 except TypeError:
2298 pass
2299 else:
2300 self.fail("no TypeError from dict({}, {})")
2301
2302 class Mapping:
2303 # Lacks a .keys() method; will be added later.
2304 dict = {1:2, 3:4, 'a':1j}
2305
2306 try:
2307 dict(Mapping())
2308 except TypeError:
2309 pass
2310 else:
2311 self.fail("no TypeError from dict(incomplete mapping)")
2312
2313 Mapping.keys = lambda self: list(self.dict.keys())
2314 Mapping.__getitem__ = lambda self, i: self.dict[i]
2315 d = dict(Mapping())
2316 self.assertEqual(d, Mapping.dict)
2317
2318 # Init from sequence of iterable objects, each producing a 2-sequence.
2319 class AddressBookEntry:
2320 def __init__(self, first, last):
2321 self.first = first
2322 self.last = last
2323 def __iter__(self):
2324 return iter([self.first, self.last])
2325
2326 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2327 AddressBookEntry('Barry', 'Peters'),
2328 AddressBookEntry('Tim', 'Peters'),
2329 AddressBookEntry('Barry', 'Warsaw')])
2330 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2331
2332 d = dict(zip(range(4), range(1, 5)))
2333 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2334
2335 # Bad sequence lengths.
2336 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2337 try:
2338 dict(bad)
2339 except ValueError:
2340 pass
2341 else:
2342 self.fail("no ValueError from dict(%r)" % bad)
2343
2344 def test_dir(self):
2345 # Testing dir() ...
2346 junk = 12
2347 self.assertEqual(dir(), ['junk', 'self'])
2348 del junk
2349
2350 # Just make sure these don't blow up!
2351 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2352 dir(arg)
2353
2354 # Test dir on new-style classes. Since these have object as a
2355 # base class, a lot more gets sucked in.
2356 def interesting(strings):
2357 return [s for s in strings if not s.startswith('_')]
2358
2359 class C(object):
2360 Cdata = 1
2361 def Cmethod(self): pass
2362
2363 cstuff = ['Cdata', 'Cmethod']
2364 self.assertEqual(interesting(dir(C)), cstuff)
2365
2366 c = C()
2367 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002368 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002369
2370 c.cdata = 2
2371 c.cmethod = lambda self: 0
2372 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002373 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002374
2375 class A(C):
2376 Adata = 1
2377 def Amethod(self): pass
2378
2379 astuff = ['Adata', 'Amethod'] + cstuff
2380 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002381 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002382 a = A()
2383 self.assertEqual(interesting(dir(a)), astuff)
2384 a.adata = 42
2385 a.amethod = lambda self: 3
2386 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002387 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002388
2389 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002390 class M(type(sys)):
2391 pass
2392 minstance = M("m")
2393 minstance.b = 2
2394 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002395 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002396 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002397 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002398 self.assertEqual(names, ['a', 'b'])
2399
2400 class M2(M):
2401 def getdict(self):
2402 return "Not a dict!"
2403 __dict__ = property(getdict)
2404
2405 m2instance = M2("m2")
2406 m2instance.b = 2
2407 m2instance.a = 1
2408 self.assertEqual(m2instance.__dict__, "Not a dict!")
2409 try:
2410 dir(m2instance)
2411 except TypeError:
2412 pass
2413
2414 # Two essentially featureless objects, just inheriting stuff from
2415 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002416 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002417
2418 # Nasty test case for proxied objects
2419 class Wrapper(object):
2420 def __init__(self, obj):
2421 self.__obj = obj
2422 def __repr__(self):
2423 return "Wrapper(%s)" % repr(self.__obj)
2424 def __getitem__(self, key):
2425 return Wrapper(self.__obj[key])
2426 def __len__(self):
2427 return len(self.__obj)
2428 def __getattr__(self, name):
2429 return Wrapper(getattr(self.__obj, name))
2430
2431 class C(object):
2432 def __getclass(self):
2433 return Wrapper(type(self))
2434 __class__ = property(__getclass)
2435
2436 dir(C()) # This used to segfault
2437
2438 def test_supers(self):
2439 # Testing super...
2440
2441 class A(object):
2442 def meth(self, a):
2443 return "A(%r)" % a
2444
2445 self.assertEqual(A().meth(1), "A(1)")
2446
2447 class B(A):
2448 def __init__(self):
2449 self.__super = super(B, self)
2450 def meth(self, a):
2451 return "B(%r)" % a + self.__super.meth(a)
2452
2453 self.assertEqual(B().meth(2), "B(2)A(2)")
2454
2455 class C(A):
2456 def meth(self, a):
2457 return "C(%r)" % a + self.__super.meth(a)
2458 C._C__super = super(C)
2459
2460 self.assertEqual(C().meth(3), "C(3)A(3)")
2461
2462 class D(C, B):
2463 def meth(self, a):
2464 return "D(%r)" % a + super(D, self).meth(a)
2465
2466 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2467
2468 # Test for subclassing super
2469
2470 class mysuper(super):
2471 def __init__(self, *args):
2472 return super(mysuper, self).__init__(*args)
2473
2474 class E(D):
2475 def meth(self, a):
2476 return "E(%r)" % a + mysuper(E, self).meth(a)
2477
2478 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2479
2480 class F(E):
2481 def meth(self, a):
2482 s = self.__super # == mysuper(F, self)
2483 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2484 F._F__super = mysuper(F)
2485
2486 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2487
2488 # Make sure certain errors are raised
2489
2490 try:
2491 super(D, 42)
2492 except TypeError:
2493 pass
2494 else:
2495 self.fail("shouldn't allow super(D, 42)")
2496
2497 try:
2498 super(D, C())
2499 except TypeError:
2500 pass
2501 else:
2502 self.fail("shouldn't allow super(D, C())")
2503
2504 try:
2505 super(D).__get__(12)
2506 except TypeError:
2507 pass
2508 else:
2509 self.fail("shouldn't allow super(D).__get__(12)")
2510
2511 try:
2512 super(D).__get__(C())
2513 except TypeError:
2514 pass
2515 else:
2516 self.fail("shouldn't allow super(D).__get__(C())")
2517
2518 # Make sure data descriptors can be overridden and accessed via super
2519 # (new feature in Python 2.3)
2520
2521 class DDbase(object):
2522 def getx(self): return 42
2523 x = property(getx)
2524
2525 class DDsub(DDbase):
2526 def getx(self): return "hello"
2527 x = property(getx)
2528
2529 dd = DDsub()
2530 self.assertEqual(dd.x, "hello")
2531 self.assertEqual(super(DDsub, dd).x, 42)
2532
2533 # Ensure that super() lookup of descriptor from classmethod
2534 # works (SF ID# 743627)
2535
2536 class Base(object):
2537 aProp = property(lambda self: "foo")
2538
2539 class Sub(Base):
2540 @classmethod
2541 def test(klass):
2542 return super(Sub,klass).aProp
2543
2544 self.assertEqual(Sub.test(), Base.aProp)
2545
2546 # Verify that super() doesn't allow keyword args
2547 try:
2548 super(Base, kw=1)
2549 except TypeError:
2550 pass
2551 else:
2552 self.assertEqual("super shouldn't accept keyword args")
2553
2554 def test_basic_inheritance(self):
2555 # Testing inheritance from basic types...
2556
2557 class hexint(int):
2558 def __repr__(self):
2559 return hex(self)
2560 def __add__(self, other):
2561 return hexint(int.__add__(self, other))
2562 # (Note that overriding __radd__ doesn't work,
2563 # because the int type gets first dibs.)
2564 self.assertEqual(repr(hexint(7) + 9), "0x10")
2565 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2566 a = hexint(12345)
2567 self.assertEqual(a, 12345)
2568 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002569 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002570 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002571 self.assertIs((+a).__class__, int)
2572 self.assertIs((a >> 0).__class__, int)
2573 self.assertIs((a << 0).__class__, int)
2574 self.assertIs((hexint(0) << 12).__class__, int)
2575 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002576
2577 class octlong(int):
2578 __slots__ = []
2579 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002580 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002581 def __add__(self, other):
2582 return self.__class__(super(octlong, self).__add__(other))
2583 __radd__ = __add__
2584 self.assertEqual(str(octlong(3) + 5), "0o10")
2585 # (Note that overriding __radd__ here only seems to work
2586 # because the example uses a short int left argument.)
2587 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2588 a = octlong(12345)
2589 self.assertEqual(a, 12345)
2590 self.assertEqual(int(a), 12345)
2591 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002592 self.assertIs(int(a).__class__, int)
2593 self.assertIs((+a).__class__, int)
2594 self.assertIs((-a).__class__, int)
2595 self.assertIs((-octlong(0)).__class__, int)
2596 self.assertIs((a >> 0).__class__, int)
2597 self.assertIs((a << 0).__class__, int)
2598 self.assertIs((a - 0).__class__, int)
2599 self.assertIs((a * 1).__class__, int)
2600 self.assertIs((a ** 1).__class__, int)
2601 self.assertIs((a // 1).__class__, int)
2602 self.assertIs((1 * a).__class__, int)
2603 self.assertIs((a | 0).__class__, int)
2604 self.assertIs((a ^ 0).__class__, int)
2605 self.assertIs((a & -1).__class__, int)
2606 self.assertIs((octlong(0) << 12).__class__, int)
2607 self.assertIs((octlong(0) >> 12).__class__, int)
2608 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002609
2610 # Because octlong overrides __add__, we can't check the absence of +0
2611 # optimizations using octlong.
2612 class longclone(int):
2613 pass
2614 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002615 self.assertIs((a + 0).__class__, int)
2616 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617
2618 # Check that negative clones don't segfault
2619 a = longclone(-1)
2620 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002621 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002622
2623 class precfloat(float):
2624 __slots__ = ['prec']
2625 def __init__(self, value=0.0, prec=12):
2626 self.prec = int(prec)
2627 def __repr__(self):
2628 return "%.*g" % (self.prec, self)
2629 self.assertEqual(repr(precfloat(1.1)), "1.1")
2630 a = precfloat(12345)
2631 self.assertEqual(a, 12345.0)
2632 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002633 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002634 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002635 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002636
2637 class madcomplex(complex):
2638 def __repr__(self):
2639 return "%.17gj%+.17g" % (self.imag, self.real)
2640 a = madcomplex(-3, 4)
2641 self.assertEqual(repr(a), "4j-3")
2642 base = complex(-3, 4)
2643 self.assertEqual(base.__class__, complex)
2644 self.assertEqual(a, base)
2645 self.assertEqual(complex(a), base)
2646 self.assertEqual(complex(a).__class__, complex)
2647 a = madcomplex(a) # just trying another form of the constructor
2648 self.assertEqual(repr(a), "4j-3")
2649 self.assertEqual(a, base)
2650 self.assertEqual(complex(a), base)
2651 self.assertEqual(complex(a).__class__, complex)
2652 self.assertEqual(hash(a), hash(base))
2653 self.assertEqual((+a).__class__, complex)
2654 self.assertEqual((a + 0).__class__, complex)
2655 self.assertEqual(a + 0, base)
2656 self.assertEqual((a - 0).__class__, complex)
2657 self.assertEqual(a - 0, base)
2658 self.assertEqual((a * 1).__class__, complex)
2659 self.assertEqual(a * 1, base)
2660 self.assertEqual((a / 1).__class__, complex)
2661 self.assertEqual(a / 1, base)
2662
2663 class madtuple(tuple):
2664 _rev = None
2665 def rev(self):
2666 if self._rev is not None:
2667 return self._rev
2668 L = list(self)
2669 L.reverse()
2670 self._rev = self.__class__(L)
2671 return self._rev
2672 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2673 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2674 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2675 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2676 for i in range(512):
2677 t = madtuple(range(i))
2678 u = t.rev()
2679 v = u.rev()
2680 self.assertEqual(v, t)
2681 a = madtuple((1,2,3,4,5))
2682 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002683 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002684 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002685 self.assertIs(a[:].__class__, tuple)
2686 self.assertIs((a * 1).__class__, tuple)
2687 self.assertIs((a * 0).__class__, tuple)
2688 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002689 a = madtuple(())
2690 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002691 self.assertIs(tuple(a).__class__, tuple)
2692 self.assertIs((a + a).__class__, tuple)
2693 self.assertIs((a * 0).__class__, tuple)
2694 self.assertIs((a * 1).__class__, tuple)
2695 self.assertIs((a * 2).__class__, tuple)
2696 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002697
2698 class madstring(str):
2699 _rev = None
2700 def rev(self):
2701 if self._rev is not None:
2702 return self._rev
2703 L = list(self)
2704 L.reverse()
2705 self._rev = self.__class__("".join(L))
2706 return self._rev
2707 s = madstring("abcdefghijklmnopqrstuvwxyz")
2708 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2709 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2710 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2711 for i in range(256):
2712 s = madstring("".join(map(chr, range(i))))
2713 t = s.rev()
2714 u = t.rev()
2715 self.assertEqual(u, s)
2716 s = madstring("12345")
2717 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002718 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002719
2720 base = "\x00" * 5
2721 s = madstring(base)
2722 self.assertEqual(s, base)
2723 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002724 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002725 self.assertEqual(hash(s), hash(base))
2726 self.assertEqual({s: 1}[base], 1)
2727 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002728 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002729 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002730 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002731 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002732 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002733 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002734 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002735 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002736 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002737 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002738 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002739 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002740 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002741 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002742 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002743 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002744 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002745 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002746 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002747 self.assertEqual(s.rstrip(), base)
2748 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002749 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002750 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002751 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002752 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002753 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002754 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002755 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002756 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002757 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002758 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002759 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002760 self.assertEqual(s.lower(), base)
2761
2762 class madunicode(str):
2763 _rev = None
2764 def rev(self):
2765 if self._rev is not None:
2766 return self._rev
2767 L = list(self)
2768 L.reverse()
2769 self._rev = self.__class__("".join(L))
2770 return self._rev
2771 u = madunicode("ABCDEF")
2772 self.assertEqual(u, "ABCDEF")
2773 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2774 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2775 base = "12345"
2776 u = madunicode(base)
2777 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002778 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002779 self.assertEqual(hash(u), hash(base))
2780 self.assertEqual({u: 1}[base], 1)
2781 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002782 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002783 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002784 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002785 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002786 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002787 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002788 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002789 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002790 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002791 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002792 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002793 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002794 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002795 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002796 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002797 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002798 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002799 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002800 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002801 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002802 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002803 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002804 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002805 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002806 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002807 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002808 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002809 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002810 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002811 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002812 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002813 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002814 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002815 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002816 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002817 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002818 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002819 self.assertEqual(u[0:0], "")
2820
2821 class sublist(list):
2822 pass
2823 a = sublist(range(5))
2824 self.assertEqual(a, list(range(5)))
2825 a.append("hello")
2826 self.assertEqual(a, list(range(5)) + ["hello"])
2827 a[5] = 5
2828 self.assertEqual(a, list(range(6)))
2829 a.extend(range(6, 20))
2830 self.assertEqual(a, list(range(20)))
2831 a[-5:] = []
2832 self.assertEqual(a, list(range(15)))
2833 del a[10:15]
2834 self.assertEqual(len(a), 10)
2835 self.assertEqual(a, list(range(10)))
2836 self.assertEqual(list(a), list(range(10)))
2837 self.assertEqual(a[0], 0)
2838 self.assertEqual(a[9], 9)
2839 self.assertEqual(a[-10], 0)
2840 self.assertEqual(a[-1], 9)
2841 self.assertEqual(a[:5], list(range(5)))
2842
2843 ## class CountedInput(file):
2844 ## """Counts lines read by self.readline().
2845 ##
2846 ## self.lineno is the 0-based ordinal of the last line read, up to
2847 ## a maximum of one greater than the number of lines in the file.
2848 ##
2849 ## self.ateof is true if and only if the final "" line has been read,
2850 ## at which point self.lineno stops incrementing, and further calls
2851 ## to readline() continue to return "".
2852 ## """
2853 ##
2854 ## lineno = 0
2855 ## ateof = 0
2856 ## def readline(self):
2857 ## if self.ateof:
2858 ## return ""
2859 ## s = file.readline(self)
2860 ## # Next line works too.
2861 ## # s = super(CountedInput, self).readline()
2862 ## self.lineno += 1
2863 ## if s == "":
2864 ## self.ateof = 1
2865 ## return s
2866 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002867 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002868 ## lines = ['a\n', 'b\n', 'c\n']
2869 ## try:
2870 ## f.writelines(lines)
2871 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002872 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002873 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2874 ## got = f.readline()
2875 ## self.assertEqual(expected, got)
2876 ## self.assertEqual(f.lineno, i)
2877 ## self.assertEqual(f.ateof, (i > len(lines)))
2878 ## f.close()
2879 ## finally:
2880 ## try:
2881 ## f.close()
2882 ## except:
2883 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002884 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002885
2886 def test_keywords(self):
2887 # Testing keyword args to basic type constructors ...
2888 self.assertEqual(int(x=1), 1)
2889 self.assertEqual(float(x=2), 2.0)
2890 self.assertEqual(int(x=3), 3)
2891 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2892 self.assertEqual(str(object=500), '500')
2893 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2894 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2895 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2896 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2897
2898 for constructor in (int, float, int, complex, str, str,
2899 tuple, list):
2900 try:
2901 constructor(bogus_keyword_arg=1)
2902 except TypeError:
2903 pass
2904 else:
2905 self.fail("expected TypeError from bogus keyword argument to %r"
2906 % constructor)
2907
2908 def test_str_subclass_as_dict_key(self):
2909 # Testing a str subclass used as dict key ..
2910
2911 class cistr(str):
2912 """Sublcass of str that computes __eq__ case-insensitively.
2913
2914 Also computes a hash code of the string in canonical form.
2915 """
2916
2917 def __init__(self, value):
2918 self.canonical = value.lower()
2919 self.hashcode = hash(self.canonical)
2920
2921 def __eq__(self, other):
2922 if not isinstance(other, cistr):
2923 other = cistr(other)
2924 return self.canonical == other.canonical
2925
2926 def __hash__(self):
2927 return self.hashcode
2928
2929 self.assertEqual(cistr('ABC'), 'abc')
2930 self.assertEqual('aBc', cistr('ABC'))
2931 self.assertEqual(str(cistr('ABC')), 'ABC')
2932
2933 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2934 self.assertEqual(d[cistr('one')], 1)
2935 self.assertEqual(d[cistr('tWo')], 2)
2936 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002937 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002938 self.assertEqual(d.get(cistr('thrEE')), 3)
2939
2940 def test_classic_comparisons(self):
2941 # Testing classic comparisons...
2942 class classic:
2943 pass
2944
2945 for base in (classic, int, object):
2946 class C(base):
2947 def __init__(self, value):
2948 self.value = int(value)
2949 def __eq__(self, other):
2950 if isinstance(other, C):
2951 return self.value == other.value
2952 if isinstance(other, int) or isinstance(other, int):
2953 return self.value == other
2954 return NotImplemented
2955 def __ne__(self, other):
2956 if isinstance(other, C):
2957 return self.value != other.value
2958 if isinstance(other, int) or isinstance(other, int):
2959 return self.value != other
2960 return NotImplemented
2961 def __lt__(self, other):
2962 if isinstance(other, C):
2963 return self.value < other.value
2964 if isinstance(other, int) or isinstance(other, int):
2965 return self.value < other
2966 return NotImplemented
2967 def __le__(self, other):
2968 if isinstance(other, C):
2969 return self.value <= other.value
2970 if isinstance(other, int) or isinstance(other, int):
2971 return self.value <= other
2972 return NotImplemented
2973 def __gt__(self, other):
2974 if isinstance(other, C):
2975 return self.value > other.value
2976 if isinstance(other, int) or isinstance(other, int):
2977 return self.value > other
2978 return NotImplemented
2979 def __ge__(self, other):
2980 if isinstance(other, C):
2981 return self.value >= other.value
2982 if isinstance(other, int) or isinstance(other, int):
2983 return self.value >= other
2984 return NotImplemented
2985
2986 c1 = C(1)
2987 c2 = C(2)
2988 c3 = C(3)
2989 self.assertEqual(c1, 1)
2990 c = {1: c1, 2: c2, 3: c3}
2991 for x in 1, 2, 3:
2992 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002993 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002994 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002995 eval("x %s y" % op),
2996 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002997 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002998 eval("x %s y" % op),
2999 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003000 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00003001 eval("x %s y" % op),
3002 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003003
3004 def test_rich_comparisons(self):
3005 # Testing rich comparisons...
3006 class Z(complex):
3007 pass
3008 z = Z(1)
3009 self.assertEqual(z, 1+0j)
3010 self.assertEqual(1+0j, z)
3011 class ZZ(complex):
3012 def __eq__(self, other):
3013 try:
3014 return abs(self - other) <= 1e-6
3015 except:
3016 return NotImplemented
3017 zz = ZZ(1.0000003)
3018 self.assertEqual(zz, 1+0j)
3019 self.assertEqual(1+0j, zz)
3020
3021 class classic:
3022 pass
3023 for base in (classic, int, object, list):
3024 class C(base):
3025 def __init__(self, value):
3026 self.value = int(value)
3027 def __cmp__(self_, other):
3028 self.fail("shouldn't call __cmp__")
3029 def __eq__(self, other):
3030 if isinstance(other, C):
3031 return self.value == other.value
3032 if isinstance(other, int) or isinstance(other, int):
3033 return self.value == other
3034 return NotImplemented
3035 def __ne__(self, other):
3036 if isinstance(other, C):
3037 return self.value != other.value
3038 if isinstance(other, int) or isinstance(other, int):
3039 return self.value != other
3040 return NotImplemented
3041 def __lt__(self, other):
3042 if isinstance(other, C):
3043 return self.value < other.value
3044 if isinstance(other, int) or isinstance(other, int):
3045 return self.value < other
3046 return NotImplemented
3047 def __le__(self, other):
3048 if isinstance(other, C):
3049 return self.value <= other.value
3050 if isinstance(other, int) or isinstance(other, int):
3051 return self.value <= other
3052 return NotImplemented
3053 def __gt__(self, other):
3054 if isinstance(other, C):
3055 return self.value > other.value
3056 if isinstance(other, int) or isinstance(other, int):
3057 return self.value > other
3058 return NotImplemented
3059 def __ge__(self, other):
3060 if isinstance(other, C):
3061 return self.value >= other.value
3062 if isinstance(other, int) or isinstance(other, int):
3063 return self.value >= other
3064 return NotImplemented
3065 c1 = C(1)
3066 c2 = C(2)
3067 c3 = C(3)
3068 self.assertEqual(c1, 1)
3069 c = {1: c1, 2: c2, 3: c3}
3070 for x in 1, 2, 3:
3071 for y in 1, 2, 3:
3072 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003073 self.assertEqual(eval("c[x] %s c[y]" % op),
3074 eval("x %s y" % op),
3075 "x=%d, y=%d" % (x, y))
3076 self.assertEqual(eval("c[x] %s y" % op),
3077 eval("x %s y" % op),
3078 "x=%d, y=%d" % (x, y))
3079 self.assertEqual(eval("x %s c[y]" % op),
3080 eval("x %s y" % op),
3081 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003082
3083 def test_descrdoc(self):
3084 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003085 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003086 def check(descr, what):
3087 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003088 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003089 check(complex.real, "the real part of a complex number") # member descriptor
3090
3091 def test_doc_descriptor(self):
3092 # Testing __doc__ descriptor...
3093 # SF bug 542984
3094 class DocDescr(object):
3095 def __get__(self, object, otype):
3096 if object:
3097 object = object.__class__.__name__ + ' instance'
3098 if otype:
3099 otype = otype.__name__
3100 return 'object=%s; type=%s' % (object, otype)
3101 class OldClass:
3102 __doc__ = DocDescr()
3103 class NewClass(object):
3104 __doc__ = DocDescr()
3105 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3106 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3107 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3108 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3109
3110 def test_set_class(self):
3111 # Testing __class__ assignment...
3112 class C(object): pass
3113 class D(object): pass
3114 class E(object): pass
3115 class F(D, E): pass
3116 for cls in C, D, E, F:
3117 for cls2 in C, D, E, F:
3118 x = cls()
3119 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003120 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003121 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003122 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003123 def cant(x, C):
3124 try:
3125 x.__class__ = C
3126 except TypeError:
3127 pass
3128 else:
3129 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3130 try:
3131 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003132 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003133 pass
3134 else:
3135 self.fail("shouldn't allow del %r.__class__" % x)
3136 cant(C(), list)
3137 cant(list(), C)
3138 cant(C(), 1)
3139 cant(C(), object)
3140 cant(object(), list)
3141 cant(list(), object)
3142 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003143 cant(True, int)
3144 cant(2, bool)
3145 o = object()
3146 cant(o, type(1))
3147 cant(o, type(None))
3148 del o
3149 class G(object):
3150 __slots__ = ["a", "b"]
3151 class H(object):
3152 __slots__ = ["b", "a"]
3153 class I(object):
3154 __slots__ = ["a", "b"]
3155 class J(object):
3156 __slots__ = ["c", "b"]
3157 class K(object):
3158 __slots__ = ["a", "b", "d"]
3159 class L(H):
3160 __slots__ = ["e"]
3161 class M(I):
3162 __slots__ = ["e"]
3163 class N(J):
3164 __slots__ = ["__weakref__"]
3165 class P(J):
3166 __slots__ = ["__dict__"]
3167 class Q(J):
3168 pass
3169 class R(J):
3170 __slots__ = ["__dict__", "__weakref__"]
3171
3172 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3173 x = cls()
3174 x.a = 1
3175 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003176 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003177 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3178 self.assertEqual(x.a, 1)
3179 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003180 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003181 "assigning %r as __class__ for %r silently failed" % (cls, x))
3182 self.assertEqual(x.a, 1)
3183 for cls in G, J, K, L, M, N, P, R, list, Int:
3184 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3185 if cls is cls2:
3186 continue
3187 cant(cls(), cls2)
3188
Benjamin Peterson193152c2009-04-25 01:08:45 +00003189 # Issue5283: when __class__ changes in __del__, the wrong
3190 # type gets DECREF'd.
3191 class O(object):
3192 pass
3193 class A(object):
3194 def __del__(self):
3195 self.__class__ = O
3196 l = [A() for x in range(100)]
3197 del l
3198
Georg Brandl479a7e72008-02-05 18:13:15 +00003199 def test_set_dict(self):
3200 # Testing __dict__ assignment...
3201 class C(object): pass
3202 a = C()
3203 a.__dict__ = {'b': 1}
3204 self.assertEqual(a.b, 1)
3205 def cant(x, dict):
3206 try:
3207 x.__dict__ = dict
3208 except (AttributeError, TypeError):
3209 pass
3210 else:
3211 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3212 cant(a, None)
3213 cant(a, [])
3214 cant(a, 1)
3215 del a.__dict__ # Deleting __dict__ is allowed
3216
3217 class Base(object):
3218 pass
3219 def verify_dict_readonly(x):
3220 """
3221 x has to be an instance of a class inheriting from Base.
3222 """
3223 cant(x, {})
3224 try:
3225 del x.__dict__
3226 except (AttributeError, TypeError):
3227 pass
3228 else:
3229 self.fail("shouldn't allow del %r.__dict__" % x)
3230 dict_descr = Base.__dict__["__dict__"]
3231 try:
3232 dict_descr.__set__(x, {})
3233 except (AttributeError, TypeError):
3234 pass
3235 else:
3236 self.fail("dict_descr allowed access to %r's dict" % x)
3237
3238 # Classes don't allow __dict__ assignment and have readonly dicts
3239 class Meta1(type, Base):
3240 pass
3241 class Meta2(Base, type):
3242 pass
3243 class D(object, metaclass=Meta1):
3244 pass
3245 class E(object, metaclass=Meta2):
3246 pass
3247 for cls in C, D, E:
3248 verify_dict_readonly(cls)
3249 class_dict = cls.__dict__
3250 try:
3251 class_dict["spam"] = "eggs"
3252 except TypeError:
3253 pass
3254 else:
3255 self.fail("%r's __dict__ can be modified" % cls)
3256
3257 # Modules also disallow __dict__ assignment
3258 class Module1(types.ModuleType, Base):
3259 pass
3260 class Module2(Base, types.ModuleType):
3261 pass
3262 for ModuleType in Module1, Module2:
3263 mod = ModuleType("spam")
3264 verify_dict_readonly(mod)
3265 mod.__dict__["spam"] = "eggs"
3266
3267 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003268 # (at least not any more than regular exception's __dict__ can
3269 # be deleted; on CPython it is not the case, whereas on PyPy they
3270 # can, just like any other new-style instance's __dict__.)
3271 def can_delete_dict(e):
3272 try:
3273 del e.__dict__
3274 except (TypeError, AttributeError):
3275 return False
3276 else:
3277 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003278 class Exception1(Exception, Base):
3279 pass
3280 class Exception2(Base, Exception):
3281 pass
3282 for ExceptionType in Exception, Exception1, Exception2:
3283 e = ExceptionType()
3284 e.__dict__ = {"a": 1}
3285 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003286 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003287
Georg Brandl479a7e72008-02-05 18:13:15 +00003288 def test_binary_operator_override(self):
3289 # Testing overrides of binary operations...
3290 class I(int):
3291 def __repr__(self):
3292 return "I(%r)" % int(self)
3293 def __add__(self, other):
3294 return I(int(self) + int(other))
3295 __radd__ = __add__
3296 def __pow__(self, other, mod=None):
3297 if mod is None:
3298 return I(pow(int(self), int(other)))
3299 else:
3300 return I(pow(int(self), int(other), int(mod)))
3301 def __rpow__(self, other, mod=None):
3302 if mod is None:
3303 return I(pow(int(other), int(self), mod))
3304 else:
3305 return I(pow(int(other), int(self), int(mod)))
3306
3307 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3308 self.assertEqual(repr(I(1) + 2), "I(3)")
3309 self.assertEqual(repr(1 + I(2)), "I(3)")
3310 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3311 self.assertEqual(repr(2 ** I(3)), "I(8)")
3312 self.assertEqual(repr(I(2) ** 3), "I(8)")
3313 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3314 class S(str):
3315 def __eq__(self, other):
3316 return self.lower() == other.lower()
3317
3318 def test_subclass_propagation(self):
3319 # Testing propagation of slot functions to subclasses...
3320 class A(object):
3321 pass
3322 class B(A):
3323 pass
3324 class C(A):
3325 pass
3326 class D(B, C):
3327 pass
3328 d = D()
3329 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3330 A.__hash__ = lambda self: 42
3331 self.assertEqual(hash(d), 42)
3332 C.__hash__ = lambda self: 314
3333 self.assertEqual(hash(d), 314)
3334 B.__hash__ = lambda self: 144
3335 self.assertEqual(hash(d), 144)
3336 D.__hash__ = lambda self: 100
3337 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003338 D.__hash__ = None
3339 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003340 del D.__hash__
3341 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003342 B.__hash__ = None
3343 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003344 del B.__hash__
3345 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003346 C.__hash__ = None
3347 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003348 del C.__hash__
3349 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003350 A.__hash__ = None
3351 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003352 del A.__hash__
3353 self.assertEqual(hash(d), orig_hash)
3354 d.foo = 42
3355 d.bar = 42
3356 self.assertEqual(d.foo, 42)
3357 self.assertEqual(d.bar, 42)
3358 def __getattribute__(self, name):
3359 if name == "foo":
3360 return 24
3361 return object.__getattribute__(self, name)
3362 A.__getattribute__ = __getattribute__
3363 self.assertEqual(d.foo, 24)
3364 self.assertEqual(d.bar, 42)
3365 def __getattr__(self, name):
3366 if name in ("spam", "foo", "bar"):
3367 return "hello"
3368 raise AttributeError(name)
3369 B.__getattr__ = __getattr__
3370 self.assertEqual(d.spam, "hello")
3371 self.assertEqual(d.foo, 24)
3372 self.assertEqual(d.bar, 42)
3373 del A.__getattribute__
3374 self.assertEqual(d.foo, 42)
3375 del d.foo
3376 self.assertEqual(d.foo, "hello")
3377 self.assertEqual(d.bar, 42)
3378 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003379 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003380 d.foo
3381 except AttributeError:
3382 pass
3383 else:
3384 self.fail("d.foo should be undefined now")
3385
3386 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003387 class A(object):
3388 pass
3389 class B(A):
3390 pass
3391 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003392 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003393 A.__setitem__ = lambda *a: None # crash
3394
3395 def test_buffer_inheritance(self):
3396 # Testing that buffer interface is inherited ...
3397
3398 import binascii
3399 # SF bug [#470040] ParseTuple t# vs subclasses.
3400
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003401 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003402 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003403 base = b'abc'
3404 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003405 # b2a_hex uses the buffer interface to get its argument's value, via
3406 # PyArg_ParseTuple 't#' code.
3407 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3408
Georg Brandl479a7e72008-02-05 18:13:15 +00003409 class MyInt(int):
3410 pass
3411 m = MyInt(42)
3412 try:
3413 binascii.b2a_hex(m)
3414 self.fail('subclass of int should not have a buffer interface')
3415 except TypeError:
3416 pass
3417
3418 def test_str_of_str_subclass(self):
3419 # Testing __str__ defined in subclass of str ...
3420 import binascii
3421 import io
3422
3423 class octetstring(str):
3424 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003425 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003426 def __repr__(self):
3427 return self + " repr"
3428
3429 o = octetstring('A')
3430 self.assertEqual(type(o), octetstring)
3431 self.assertEqual(type(str(o)), str)
3432 self.assertEqual(type(repr(o)), str)
3433 self.assertEqual(ord(o), 0x41)
3434 self.assertEqual(str(o), '41')
3435 self.assertEqual(repr(o), 'A repr')
3436 self.assertEqual(o.__str__(), '41')
3437 self.assertEqual(o.__repr__(), 'A repr')
3438
3439 capture = io.StringIO()
3440 # Calling str() or not exercises different internal paths.
3441 print(o, file=capture)
3442 print(str(o), file=capture)
3443 self.assertEqual(capture.getvalue(), '41\n41\n')
3444 capture.close()
3445
3446 def test_keyword_arguments(self):
3447 # Testing keyword arguments to __init__, __call__...
3448 def f(a): return a
3449 self.assertEqual(f.__call__(a=42), 42)
3450 a = []
3451 list.__init__(a, sequence=[0, 1, 2])
3452 self.assertEqual(a, [0, 1, 2])
3453
3454 def test_recursive_call(self):
3455 # Testing recursive __call__() by setting to instance of class...
3456 class A(object):
3457 pass
3458
3459 A.__call__ = A()
3460 try:
3461 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003462 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003463 pass
3464 else:
3465 self.fail("Recursion limit should have been reached for __call__()")
3466
3467 def test_delete_hook(self):
3468 # Testing __del__ hook...
3469 log = []
3470 class C(object):
3471 def __del__(self):
3472 log.append(1)
3473 c = C()
3474 self.assertEqual(log, [])
3475 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003476 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003477 self.assertEqual(log, [1])
3478
3479 class D(object): pass
3480 d = D()
3481 try: del d[0]
3482 except TypeError: pass
3483 else: self.fail("invalid del() didn't raise TypeError")
3484
3485 def test_hash_inheritance(self):
3486 # Testing hash of mutable subclasses...
3487
3488 class mydict(dict):
3489 pass
3490 d = mydict()
3491 try:
3492 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003493 except TypeError:
3494 pass
3495 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003496 self.fail("hash() of dict subclass should fail")
3497
3498 class mylist(list):
3499 pass
3500 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003501 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003502 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003503 except TypeError:
3504 pass
3505 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003506 self.fail("hash() of list subclass should fail")
3507
3508 def test_str_operations(self):
3509 try: 'a' + 5
3510 except TypeError: pass
3511 else: self.fail("'' + 5 doesn't raise TypeError")
3512
3513 try: ''.split('')
3514 except ValueError: pass
3515 else: self.fail("''.split('') doesn't raise ValueError")
3516
3517 try: ''.join([0])
3518 except TypeError: pass
3519 else: self.fail("''.join([0]) doesn't raise TypeError")
3520
3521 try: ''.rindex('5')
3522 except ValueError: pass
3523 else: self.fail("''.rindex('5') doesn't raise ValueError")
3524
3525 try: '%(n)s' % None
3526 except TypeError: pass
3527 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3528
3529 try: '%(n' % {}
3530 except ValueError: pass
3531 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3532
3533 try: '%*s' % ('abc')
3534 except TypeError: pass
3535 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3536
3537 try: '%*.*s' % ('abc', 5)
3538 except TypeError: pass
3539 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3540
3541 try: '%s' % (1, 2)
3542 except TypeError: pass
3543 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3544
3545 try: '%' % None
3546 except ValueError: pass
3547 else: self.fail("'%' % None doesn't raise ValueError")
3548
3549 self.assertEqual('534253'.isdigit(), 1)
3550 self.assertEqual('534253x'.isdigit(), 0)
3551 self.assertEqual('%c' % 5, '\x05')
3552 self.assertEqual('%c' % '5', '5')
3553
3554 def test_deepcopy_recursive(self):
3555 # Testing deepcopy of recursive objects...
3556 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003557 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003558 a = Node()
3559 b = Node()
3560 a.b = b
3561 b.a = a
3562 z = deepcopy(a) # This blew up before
3563
Martin Panterf05641642016-05-08 13:48:10 +00003564 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003565 # Testing uninitialized module objects...
3566 from types import ModuleType as M
3567 m = M.__new__(M)
3568 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003569 self.assertNotHasAttr(m, "__name__")
3570 self.assertNotHasAttr(m, "__file__")
3571 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003572 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003573 m.foo = 1
3574 self.assertEqual(m.__dict__, {"foo": 1})
3575
3576 def test_funny_new(self):
3577 # Testing __new__ returning something unexpected...
3578 class C(object):
3579 def __new__(cls, arg):
3580 if isinstance(arg, str): return [1, 2, 3]
3581 elif isinstance(arg, int): return object.__new__(D)
3582 else: return object.__new__(cls)
3583 class D(C):
3584 def __init__(self, arg):
3585 self.foo = arg
3586 self.assertEqual(C("1"), [1, 2, 3])
3587 self.assertEqual(D("1"), [1, 2, 3])
3588 d = D(None)
3589 self.assertEqual(d.foo, None)
3590 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003591 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003592 self.assertEqual(d.foo, 1)
3593 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003594 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003595 self.assertEqual(d.foo, 1)
3596
Serhiy Storchaka5adfac22016-12-02 08:42:43 +02003597 class C(object):
3598 @staticmethod
3599 def __new__(*args):
3600 return args
3601 self.assertEqual(C(1, 2), (C, 1, 2))
3602 class D(C):
3603 pass
3604 self.assertEqual(D(1, 2), (D, 1, 2))
3605
3606 class C(object):
3607 @classmethod
3608 def __new__(*args):
3609 return args
3610 self.assertEqual(C(1, 2), (C, C, 1, 2))
3611 class D(C):
3612 pass
3613 self.assertEqual(D(1, 2), (D, D, 1, 2))
3614
Georg Brandl479a7e72008-02-05 18:13:15 +00003615 def test_imul_bug(self):
3616 # Testing for __imul__ problems...
3617 # SF bug 544647
3618 class C(object):
3619 def __imul__(self, other):
3620 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003621 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003622 y = x
3623 y *= 1.0
3624 self.assertEqual(y, (x, 1.0))
3625 y = x
3626 y *= 2
3627 self.assertEqual(y, (x, 2))
3628 y = x
3629 y *= 3
3630 self.assertEqual(y, (x, 3))
3631 y = x
3632 y *= 1<<100
3633 self.assertEqual(y, (x, 1<<100))
3634 y = x
3635 y *= None
3636 self.assertEqual(y, (x, None))
3637 y = x
3638 y *= "foo"
3639 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003640
Georg Brandl479a7e72008-02-05 18:13:15 +00003641 def test_copy_setstate(self):
3642 # Testing that copy.*copy() correctly uses __setstate__...
3643 import copy
3644 class C(object):
3645 def __init__(self, foo=None):
3646 self.foo = foo
3647 self.__foo = foo
3648 def setfoo(self, foo=None):
3649 self.foo = foo
3650 def getfoo(self):
3651 return self.__foo
3652 def __getstate__(self):
3653 return [self.foo]
3654 def __setstate__(self_, lst):
3655 self.assertEqual(len(lst), 1)
3656 self_.__foo = self_.foo = lst[0]
3657 a = C(42)
3658 a.setfoo(24)
3659 self.assertEqual(a.foo, 24)
3660 self.assertEqual(a.getfoo(), 42)
3661 b = copy.copy(a)
3662 self.assertEqual(b.foo, 24)
3663 self.assertEqual(b.getfoo(), 24)
3664 b = copy.deepcopy(a)
3665 self.assertEqual(b.foo, 24)
3666 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003667
Georg Brandl479a7e72008-02-05 18:13:15 +00003668 def test_slices(self):
3669 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003670
Georg Brandl479a7e72008-02-05 18:13:15 +00003671 # Strings
3672 self.assertEqual("hello"[:4], "hell")
3673 self.assertEqual("hello"[slice(4)], "hell")
3674 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3675 class S(str):
3676 def __getitem__(self, x):
3677 return str.__getitem__(self, x)
3678 self.assertEqual(S("hello")[:4], "hell")
3679 self.assertEqual(S("hello")[slice(4)], "hell")
3680 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3681 # Tuples
3682 self.assertEqual((1,2,3)[:2], (1,2))
3683 self.assertEqual((1,2,3)[slice(2)], (1,2))
3684 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3685 class T(tuple):
3686 def __getitem__(self, x):
3687 return tuple.__getitem__(self, x)
3688 self.assertEqual(T((1,2,3))[:2], (1,2))
3689 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3690 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3691 # Lists
3692 self.assertEqual([1,2,3][:2], [1,2])
3693 self.assertEqual([1,2,3][slice(2)], [1,2])
3694 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3695 class L(list):
3696 def __getitem__(self, x):
3697 return list.__getitem__(self, x)
3698 self.assertEqual(L([1,2,3])[:2], [1,2])
3699 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3700 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3701 # Now do lists and __setitem__
3702 a = L([1,2,3])
3703 a[slice(1, 3)] = [3,2]
3704 self.assertEqual(a, [1,3,2])
3705 a[slice(0, 2, 1)] = [3,1]
3706 self.assertEqual(a, [3,1,2])
3707 a.__setitem__(slice(1, 3), [2,1])
3708 self.assertEqual(a, [3,2,1])
3709 a.__setitem__(slice(0, 2, 1), [2,3])
3710 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003711
Georg Brandl479a7e72008-02-05 18:13:15 +00003712 def test_subtype_resurrection(self):
3713 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003714
Georg Brandl479a7e72008-02-05 18:13:15 +00003715 class C(object):
3716 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003717
Georg Brandl479a7e72008-02-05 18:13:15 +00003718 def __del__(self):
3719 # resurrect the instance
3720 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003721
Georg Brandl479a7e72008-02-05 18:13:15 +00003722 c = C()
3723 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003724
Benjamin Petersone549ead2009-03-28 21:42:05 +00003725 # The most interesting thing here is whether this blows up, due to
3726 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3727 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003728 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003729
Benjamin Petersone549ead2009-03-28 21:42:05 +00003730 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003731 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003732
Georg Brandl479a7e72008-02-05 18:13:15 +00003733 # Make c mortal again, so that the test framework with -l doesn't report
3734 # it as a leak.
3735 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003736
Georg Brandl479a7e72008-02-05 18:13:15 +00003737 def test_slots_trash(self):
3738 # Testing slot trash...
3739 # Deallocating deeply nested slotted trash caused stack overflows
3740 class trash(object):
3741 __slots__ = ['x']
3742 def __init__(self, x):
3743 self.x = x
3744 o = None
3745 for i in range(50000):
3746 o = trash(o)
3747 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003748
Georg Brandl479a7e72008-02-05 18:13:15 +00003749 def test_slots_multiple_inheritance(self):
3750 # SF bug 575229, multiple inheritance w/ slots dumps core
3751 class A(object):
3752 __slots__=()
3753 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003754 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003755 class C(A,B) :
3756 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003757 if support.check_impl_detail():
3758 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003759 self.assertHasAttr(C, '__dict__')
3760 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003761 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003762
Georg Brandl479a7e72008-02-05 18:13:15 +00003763 def test_rmul(self):
3764 # Testing correct invocation of __rmul__...
3765 # SF patch 592646
3766 class C(object):
3767 def __mul__(self, other):
3768 return "mul"
3769 def __rmul__(self, other):
3770 return "rmul"
3771 a = C()
3772 self.assertEqual(a*2, "mul")
3773 self.assertEqual(a*2.2, "mul")
3774 self.assertEqual(2*a, "rmul")
3775 self.assertEqual(2.2*a, "rmul")
3776
3777 def test_ipow(self):
3778 # Testing correct invocation of __ipow__...
3779 # [SF bug 620179]
3780 class C(object):
3781 def __ipow__(self, other):
3782 pass
3783 a = C()
3784 a **= 2
3785
3786 def test_mutable_bases(self):
3787 # Testing mutable bases...
3788
3789 # stuff that should work:
3790 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003791 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003792 class C2(object):
3793 def __getattribute__(self, attr):
3794 if attr == 'a':
3795 return 2
3796 else:
3797 return super(C2, self).__getattribute__(attr)
3798 def meth(self):
3799 return 1
3800 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003801 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003802 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003803 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003804 d = D()
3805 e = E()
3806 D.__bases__ = (C,)
3807 D.__bases__ = (C2,)
3808 self.assertEqual(d.meth(), 1)
3809 self.assertEqual(e.meth(), 1)
3810 self.assertEqual(d.a, 2)
3811 self.assertEqual(e.a, 2)
3812 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003813
Georg Brandl479a7e72008-02-05 18:13:15 +00003814 try:
3815 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003816 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003817 pass
3818 else:
3819 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003820
Georg Brandl479a7e72008-02-05 18:13:15 +00003821 try:
3822 D.__bases__ = ()
3823 except TypeError as msg:
3824 if str(msg) == "a new-style class can't have only classic bases":
3825 self.fail("wrong error message for .__bases__ = ()")
3826 else:
3827 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003828
Georg Brandl479a7e72008-02-05 18:13:15 +00003829 try:
3830 D.__bases__ = (D,)
3831 except TypeError:
3832 pass
3833 else:
3834 # actually, we'll have crashed by here...
3835 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003836
Georg Brandl479a7e72008-02-05 18:13:15 +00003837 try:
3838 D.__bases__ = (C, C)
3839 except TypeError:
3840 pass
3841 else:
3842 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003843
Georg Brandl479a7e72008-02-05 18:13:15 +00003844 try:
3845 D.__bases__ = (E,)
3846 except TypeError:
3847 pass
3848 else:
3849 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003850
Benjamin Petersonae937c02009-04-18 20:54:08 +00003851 def test_builtin_bases(self):
3852 # Make sure all the builtin types can have their base queried without
3853 # segfaulting. See issue #5787.
3854 builtin_types = [tp for tp in builtins.__dict__.values()
3855 if isinstance(tp, type)]
3856 for tp in builtin_types:
3857 object.__getattribute__(tp, "__bases__")
3858 if tp is not object:
3859 self.assertEqual(len(tp.__bases__), 1, tp)
3860
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003861 class L(list):
3862 pass
3863
3864 class C(object):
3865 pass
3866
3867 class D(C):
3868 pass
3869
3870 try:
3871 L.__bases__ = (dict,)
3872 except TypeError:
3873 pass
3874 else:
3875 self.fail("shouldn't turn list subclass into dict subclass")
3876
3877 try:
3878 list.__bases__ = (dict,)
3879 except TypeError:
3880 pass
3881 else:
3882 self.fail("shouldn't be able to assign to list.__bases__")
3883
3884 try:
3885 D.__bases__ = (C, list)
3886 except TypeError:
3887 pass
3888 else:
3889 assert 0, "best_base calculation found wanting"
3890
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003891 def test_unsubclassable_types(self):
3892 with self.assertRaises(TypeError):
3893 class X(type(None)):
3894 pass
3895 with self.assertRaises(TypeError):
3896 class X(object, type(None)):
3897 pass
3898 with self.assertRaises(TypeError):
3899 class X(type(None), object):
3900 pass
3901 class O(object):
3902 pass
3903 with self.assertRaises(TypeError):
3904 class X(O, type(None)):
3905 pass
3906 with self.assertRaises(TypeError):
3907 class X(type(None), O):
3908 pass
3909
3910 class X(object):
3911 pass
3912 with self.assertRaises(TypeError):
3913 X.__bases__ = type(None),
3914 with self.assertRaises(TypeError):
3915 X.__bases__ = object, type(None)
3916 with self.assertRaises(TypeError):
3917 X.__bases__ = type(None), object
3918 with self.assertRaises(TypeError):
3919 X.__bases__ = O, type(None)
3920 with self.assertRaises(TypeError):
3921 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00003922
Georg Brandl479a7e72008-02-05 18:13:15 +00003923 def test_mutable_bases_with_failing_mro(self):
3924 # Testing mutable bases with failing mro...
3925 class WorkOnce(type):
3926 def __new__(self, name, bases, ns):
3927 self.flag = 0
3928 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3929 def mro(self):
3930 if self.flag > 0:
3931 raise RuntimeError("bozo")
3932 else:
3933 self.flag += 1
3934 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003935
Georg Brandl479a7e72008-02-05 18:13:15 +00003936 class WorkAlways(type):
3937 def mro(self):
3938 # this is here to make sure that .mro()s aren't called
3939 # with an exception set (which was possible at one point).
3940 # An error message will be printed in a debug build.
3941 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003942 return type.mro(self)
3943
Georg Brandl479a7e72008-02-05 18:13:15 +00003944 class C(object):
3945 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003946
Georg Brandl479a7e72008-02-05 18:13:15 +00003947 class C2(object):
3948 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003949
Georg Brandl479a7e72008-02-05 18:13:15 +00003950 class D(C):
3951 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003952
Georg Brandl479a7e72008-02-05 18:13:15 +00003953 class E(D):
3954 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003955
Georg Brandl479a7e72008-02-05 18:13:15 +00003956 class F(D, metaclass=WorkOnce):
3957 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003958
Georg Brandl479a7e72008-02-05 18:13:15 +00003959 class G(D, metaclass=WorkAlways):
3960 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003961
Georg Brandl479a7e72008-02-05 18:13:15 +00003962 # Immediate subclasses have their mro's adjusted in alphabetical
3963 # order, so E's will get adjusted before adjusting F's fails. We
3964 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003965
Georg Brandl479a7e72008-02-05 18:13:15 +00003966 E_mro_before = E.__mro__
3967 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003968
Armin Rigofd163f92005-12-29 15:59:19 +00003969 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003970 D.__bases__ = (C2,)
3971 except RuntimeError:
3972 self.assertEqual(E.__mro__, E_mro_before)
3973 self.assertEqual(D.__mro__, D_mro_before)
3974 else:
3975 self.fail("exception not propagated")
3976
3977 def test_mutable_bases_catch_mro_conflict(self):
3978 # Testing mutable bases catch mro conflict...
3979 class A(object):
3980 pass
3981
3982 class B(object):
3983 pass
3984
3985 class C(A, B):
3986 pass
3987
3988 class D(A, B):
3989 pass
3990
3991 class E(C, D):
3992 pass
3993
3994 try:
3995 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003996 except TypeError:
3997 pass
3998 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003999 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004000
Georg Brandl479a7e72008-02-05 18:13:15 +00004001 def test_mutable_names(self):
4002 # Testing mutable names...
4003 class C(object):
4004 pass
4005
4006 # C.__module__ could be 'test_descr' or '__main__'
4007 mod = C.__module__
4008
4009 C.__name__ = 'D'
4010 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4011
4012 C.__name__ = 'D.E'
4013 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4014
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004015 def test_evil_type_name(self):
4016 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4017 # execution while the type structure was not in a sane state, and a
4018 # possible segmentation fault as a result. See bug #16447.
4019 class Nasty(str):
4020 def __del__(self):
4021 C.__name__ = "other"
4022
4023 class C:
4024 pass
4025
4026 C.__name__ = Nasty("abc")
4027 C.__name__ = "normal"
4028
Georg Brandl479a7e72008-02-05 18:13:15 +00004029 def test_subclass_right_op(self):
4030 # Testing correct dispatch of subclass overloading __r<op>__...
4031
4032 # This code tests various cases where right-dispatch of a subclass
4033 # should be preferred over left-dispatch of a base class.
4034
4035 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4036
4037 class B(int):
4038 def __floordiv__(self, other):
4039 return "B.__floordiv__"
4040 def __rfloordiv__(self, other):
4041 return "B.__rfloordiv__"
4042
4043 self.assertEqual(B(1) // 1, "B.__floordiv__")
4044 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4045
4046 # Case 2: subclass of object; this is just the baseline for case 3
4047
4048 class C(object):
4049 def __floordiv__(self, other):
4050 return "C.__floordiv__"
4051 def __rfloordiv__(self, other):
4052 return "C.__rfloordiv__"
4053
4054 self.assertEqual(C() // 1, "C.__floordiv__")
4055 self.assertEqual(1 // C(), "C.__rfloordiv__")
4056
4057 # Case 3: subclass of new-style class; here it gets interesting
4058
4059 class D(C):
4060 def __floordiv__(self, other):
4061 return "D.__floordiv__"
4062 def __rfloordiv__(self, other):
4063 return "D.__rfloordiv__"
4064
4065 self.assertEqual(D() // C(), "D.__floordiv__")
4066 self.assertEqual(C() // D(), "D.__rfloordiv__")
4067
4068 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4069
4070 class E(C):
4071 pass
4072
4073 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4074
4075 self.assertEqual(E() // 1, "C.__floordiv__")
4076 self.assertEqual(1 // E(), "C.__rfloordiv__")
4077 self.assertEqual(E() // C(), "C.__floordiv__")
4078 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4079
Benjamin Petersone549ead2009-03-28 21:42:05 +00004080 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004081 def test_meth_class_get(self):
4082 # Testing __get__ method of METH_CLASS C methods...
4083 # Full coverage of descrobject.c::classmethod_get()
4084
4085 # Baseline
4086 arg = [1, 2, 3]
4087 res = {1: None, 2: None, 3: None}
4088 self.assertEqual(dict.fromkeys(arg), res)
4089 self.assertEqual({}.fromkeys(arg), res)
4090
4091 # Now get the descriptor
4092 descr = dict.__dict__["fromkeys"]
4093
4094 # More baseline using the descriptor directly
4095 self.assertEqual(descr.__get__(None, dict)(arg), res)
4096 self.assertEqual(descr.__get__({})(arg), res)
4097
4098 # Now check various error cases
4099 try:
4100 descr.__get__(None, None)
4101 except TypeError:
4102 pass
4103 else:
4104 self.fail("shouldn't have allowed descr.__get__(None, None)")
4105 try:
4106 descr.__get__(42)
4107 except TypeError:
4108 pass
4109 else:
4110 self.fail("shouldn't have allowed descr.__get__(42)")
4111 try:
4112 descr.__get__(None, 42)
4113 except TypeError:
4114 pass
4115 else:
4116 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4117 try:
4118 descr.__get__(None, int)
4119 except TypeError:
4120 pass
4121 else:
4122 self.fail("shouldn't have allowed descr.__get__(None, int)")
4123
4124 def test_isinst_isclass(self):
4125 # Testing proxy isinstance() and isclass()...
4126 class Proxy(object):
4127 def __init__(self, obj):
4128 self.__obj = obj
4129 def __getattribute__(self, name):
4130 if name.startswith("_Proxy__"):
4131 return object.__getattribute__(self, name)
4132 else:
4133 return getattr(self.__obj, name)
4134 # Test with a classic class
4135 class C:
4136 pass
4137 a = C()
4138 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004139 self.assertIsInstance(a, C) # Baseline
4140 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004141 # Test with a classic subclass
4142 class D(C):
4143 pass
4144 a = D()
4145 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004146 self.assertIsInstance(a, C) # Baseline
4147 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004148 # Test with a new-style class
4149 class C(object):
4150 pass
4151 a = C()
4152 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004153 self.assertIsInstance(a, C) # Baseline
4154 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004155 # Test with a new-style subclass
4156 class D(C):
4157 pass
4158 a = D()
4159 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004160 self.assertIsInstance(a, C) # Baseline
4161 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004162
4163 def test_proxy_super(self):
4164 # Testing super() for a proxy object...
4165 class Proxy(object):
4166 def __init__(self, obj):
4167 self.__obj = obj
4168 def __getattribute__(self, name):
4169 if name.startswith("_Proxy__"):
4170 return object.__getattribute__(self, name)
4171 else:
4172 return getattr(self.__obj, name)
4173
4174 class B(object):
4175 def f(self):
4176 return "B.f"
4177
4178 class C(B):
4179 def f(self):
4180 return super(C, self).f() + "->C.f"
4181
4182 obj = C()
4183 p = Proxy(obj)
4184 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4185
4186 def test_carloverre(self):
4187 # Testing prohibition of Carlo Verre's hack...
4188 try:
4189 object.__setattr__(str, "foo", 42)
4190 except TypeError:
4191 pass
4192 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004193 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004194 try:
4195 object.__delattr__(str, "lower")
4196 except TypeError:
4197 pass
4198 else:
4199 self.fail("Carlo Verre __delattr__ succeeded!")
4200
4201 def test_weakref_segfault(self):
4202 # Testing weakref segfault...
4203 # SF 742911
4204 import weakref
4205
4206 class Provoker:
4207 def __init__(self, referrent):
4208 self.ref = weakref.ref(referrent)
4209
4210 def __del__(self):
4211 x = self.ref()
4212
4213 class Oops(object):
4214 pass
4215
4216 o = Oops()
4217 o.whatever = Provoker(o)
4218 del o
4219
4220 def test_wrapper_segfault(self):
4221 # SF 927248: deeply nested wrappers could cause stack overflow
4222 f = lambda:None
4223 for i in range(1000000):
4224 f = f.__call__
4225 f = None
4226
4227 def test_file_fault(self):
4228 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004229 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004230 class StdoutGuard:
4231 def __getattr__(self, attr):
4232 sys.stdout = sys.__stdout__
4233 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4234 sys.stdout = StdoutGuard()
4235 try:
4236 print("Oops!")
4237 except RuntimeError:
4238 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004239 finally:
4240 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004241
4242 def test_vicious_descriptor_nonsense(self):
4243 # Testing vicious_descriptor_nonsense...
4244
4245 # A potential segfault spotted by Thomas Wouters in mail to
4246 # python-dev 2003-04-17, turned into an example & fixed by Michael
4247 # Hudson just less than four months later...
4248
4249 class Evil(object):
4250 def __hash__(self):
4251 return hash('attr')
4252 def __eq__(self, other):
4253 del C.attr
4254 return 0
4255
4256 class Descr(object):
4257 def __get__(self, ob, type=None):
4258 return 1
4259
4260 class C(object):
4261 attr = Descr()
4262
4263 c = C()
4264 c.__dict__[Evil()] = 0
4265
4266 self.assertEqual(c.attr, 1)
4267 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004268 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004269 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004270
4271 def test_init(self):
4272 # SF 1155938
4273 class Foo(object):
4274 def __init__(self):
4275 return 10
4276 try:
4277 Foo()
4278 except TypeError:
4279 pass
4280 else:
4281 self.fail("did not test __init__() for None return")
4282
4283 def test_method_wrapper(self):
4284 # Testing method-wrapper objects...
4285 # <type 'method-wrapper'> did not support any reflection before 2.5
4286
Mark Dickinson211c6252009-02-01 10:28:51 +00004287 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004288
4289 l = []
4290 self.assertEqual(l.__add__, l.__add__)
4291 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004292 self.assertNotEqual(l.__add__, [5].__add__)
4293 self.assertNotEqual(l.__add__, l.__mul__)
4294 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004295 if hasattr(l.__add__, '__self__'):
4296 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004297 self.assertIs(l.__add__.__self__, l)
4298 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004299 else:
4300 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004301 self.assertIs(l.__add__.im_self, l)
4302 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004303 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4304 try:
4305 hash(l.__add__)
4306 except TypeError:
4307 pass
4308 else:
4309 self.fail("no TypeError from hash([].__add__)")
4310
4311 t = ()
4312 t += (7,)
4313 self.assertEqual(t.__add__, (7,).__add__)
4314 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4315
4316 def test_not_implemented(self):
4317 # Testing NotImplemented...
4318 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004319 import operator
4320
4321 def specialmethod(self, other):
4322 return NotImplemented
4323
4324 def check(expr, x, y):
4325 try:
4326 exec(expr, {'x': x, 'y': y, 'operator': operator})
4327 except TypeError:
4328 pass
4329 else:
4330 self.fail("no TypeError from %r" % (expr,))
4331
4332 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4333 # TypeErrors
4334 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4335 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004336 for name, expr, iexpr in [
4337 ('__add__', 'x + y', 'x += y'),
4338 ('__sub__', 'x - y', 'x -= y'),
4339 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004340 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004341 ('__truediv__', 'x / y', 'x /= y'),
4342 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004343 ('__mod__', 'x % y', 'x %= y'),
4344 ('__divmod__', 'divmod(x, y)', None),
4345 ('__pow__', 'x ** y', 'x **= y'),
4346 ('__lshift__', 'x << y', 'x <<= y'),
4347 ('__rshift__', 'x >> y', 'x >>= y'),
4348 ('__and__', 'x & y', 'x &= y'),
4349 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004350 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004351 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004352 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004353 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004354 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004355 check(expr, a, N1)
4356 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004357 if iexpr:
4358 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004359 check(iexpr, a, N1)
4360 check(iexpr, a, N2)
4361 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004362 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004363 c = C()
4364 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004365 check(iexpr, c, N1)
4366 check(iexpr, c, N2)
4367
Georg Brandl479a7e72008-02-05 18:13:15 +00004368 def test_assign_slice(self):
4369 # ceval.c's assign_slice used to check for
4370 # tp->tp_as_sequence->sq_slice instead of
4371 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004372
Georg Brandl479a7e72008-02-05 18:13:15 +00004373 class C(object):
4374 def __setitem__(self, idx, value):
4375 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004376
Georg Brandl479a7e72008-02-05 18:13:15 +00004377 c = C()
4378 c[1:2] = 3
4379 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004380
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004381 def test_set_and_no_get(self):
4382 # See
4383 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4384 class Descr(object):
4385
4386 def __init__(self, name):
4387 self.name = name
4388
4389 def __set__(self, obj, value):
4390 obj.__dict__[self.name] = value
4391 descr = Descr("a")
4392
4393 class X(object):
4394 a = descr
4395
4396 x = X()
4397 self.assertIs(x.a, descr)
4398 x.a = 42
4399 self.assertEqual(x.a, 42)
4400
Benjamin Peterson21896a32010-03-21 22:03:03 +00004401 # Also check type_getattro for correctness.
4402 class Meta(type):
4403 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004404 class X(metaclass=Meta):
4405 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004406 X.a = 42
4407 Meta.a = Descr("a")
4408 self.assertEqual(X.a, 42)
4409
Benjamin Peterson9262b842008-11-17 22:45:50 +00004410 def test_getattr_hooks(self):
4411 # issue 4230
4412
4413 class Descriptor(object):
4414 counter = 0
4415 def __get__(self, obj, objtype=None):
4416 def getter(name):
4417 self.counter += 1
4418 raise AttributeError(name)
4419 return getter
4420
4421 descr = Descriptor()
4422 class A(object):
4423 __getattribute__ = descr
4424 class B(object):
4425 __getattr__ = descr
4426 class C(object):
4427 __getattribute__ = descr
4428 __getattr__ = descr
4429
4430 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004431 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004432 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004433 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004434 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004435 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004436
Benjamin Peterson9262b842008-11-17 22:45:50 +00004437 class EvilGetattribute(object):
4438 # This used to segfault
4439 def __getattr__(self, name):
4440 raise AttributeError(name)
4441 def __getattribute__(self, name):
4442 del EvilGetattribute.__getattr__
4443 for i in range(5):
4444 gc.collect()
4445 raise AttributeError(name)
4446
4447 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4448
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004449 def test_type___getattribute__(self):
4450 self.assertRaises(TypeError, type.__getattribute__, list, type)
4451
Benjamin Peterson477ba912011-01-12 15:34:01 +00004452 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004453 # type pretends not to have __abstractmethods__.
4454 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4455 class meta(type):
4456 pass
4457 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004458 class X(object):
4459 pass
4460 with self.assertRaises(AttributeError):
4461 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004462
Victor Stinner3249dec2011-05-01 23:19:15 +02004463 def test_proxy_call(self):
4464 class FakeStr:
4465 __class__ = str
4466
4467 fake_str = FakeStr()
4468 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004469 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004470
4471 # call a method descriptor
4472 with self.assertRaises(TypeError):
4473 str.split(fake_str)
4474
4475 # call a slot wrapper descriptor
4476 with self.assertRaises(TypeError):
4477 str.__add__(fake_str, "abc")
4478
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004479 def test_repr_as_str(self):
4480 # Issue #11603: crash or infinite loop when rebinding __str__ as
4481 # __repr__.
4482 class Foo:
4483 pass
4484 Foo.__repr__ = Foo.__str__
4485 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004486 self.assertRaises(RecursionError, str, foo)
4487 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004488
4489 def test_mixing_slot_wrappers(self):
4490 class X(dict):
4491 __setattr__ = dict.__setitem__
4492 x = X()
4493 x.y = 42
4494 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004495
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004496 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004497 with self.assertRaises(ValueError) as cm:
4498 class X:
4499 __slots__ = ["foo"]
4500 foo = None
4501 m = str(cm.exception)
4502 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4503
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004504 def test_set_doc(self):
4505 class X:
4506 "elephant"
4507 X.__doc__ = "banana"
4508 self.assertEqual(X.__doc__, "banana")
4509 with self.assertRaises(TypeError) as cm:
4510 type(list).__dict__["__doc__"].__set__(list, "blah")
4511 self.assertIn("can't set list.__doc__", str(cm.exception))
4512 with self.assertRaises(TypeError) as cm:
4513 type(X).__dict__["__doc__"].__delete__(X)
4514 self.assertIn("can't delete X.__doc__", str(cm.exception))
4515 self.assertEqual(X.__doc__, "banana")
4516
Antoine Pitrou9d574812011-12-12 13:47:25 +01004517 def test_qualname(self):
4518 descriptors = [str.lower, complex.real, float.real, int.__add__]
4519 types = ['method', 'member', 'getset', 'wrapper']
4520
4521 # make sure we have an example of each type of descriptor
4522 for d, n in zip(descriptors, types):
4523 self.assertEqual(type(d).__name__, n + '_descriptor')
4524
4525 for d in descriptors:
4526 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4527 self.assertEqual(d.__qualname__, qualname)
4528
4529 self.assertEqual(str.lower.__qualname__, 'str.lower')
4530 self.assertEqual(complex.real.__qualname__, 'complex.real')
4531 self.assertEqual(float.real.__qualname__, 'float.real')
4532 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4533
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004534 class X:
4535 pass
4536 with self.assertRaises(TypeError):
4537 del X.__qualname__
4538
4539 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4540 str, 'Oink')
4541
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004542 global Y
4543 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004544 class Inside:
4545 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004546 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004547 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004548
Victor Stinner6f738742012-02-25 01:22:36 +01004549 def test_qualname_dict(self):
4550 ns = {'__qualname__': 'some.name'}
4551 tp = type('Foo', (), ns)
4552 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004553 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004554 self.assertEqual(ns, {'__qualname__': 'some.name'})
4555
4556 ns = {'__qualname__': 1}
4557 self.assertRaises(TypeError, type, 'Foo', (), ns)
4558
Benjamin Peterson52c42432012-03-07 18:41:11 -06004559 def test_cycle_through_dict(self):
4560 # See bug #1469629
4561 class X(dict):
4562 def __init__(self):
4563 dict.__init__(self)
4564 self.__dict__ = self
4565 x = X()
4566 x.attr = 42
4567 wr = weakref.ref(x)
4568 del x
4569 support.gc_collect()
4570 self.assertIsNone(wr())
4571 for o in gc.get_objects():
4572 self.assertIsNot(type(o), X)
4573
Benjamin Peterson96384b92012-03-17 00:05:44 -05004574 def test_object_new_and_init_with_parameters(self):
4575 # See issue #1683368
4576 class OverrideNeither:
4577 pass
4578 self.assertRaises(TypeError, OverrideNeither, 1)
4579 self.assertRaises(TypeError, OverrideNeither, kw=1)
4580 class OverrideNew:
4581 def __new__(cls, foo, kw=0, *args, **kwds):
4582 return object.__new__(cls, *args, **kwds)
4583 class OverrideInit:
4584 def __init__(self, foo, kw=0, *args, **kwargs):
4585 return object.__init__(self, *args, **kwargs)
4586 class OverrideBoth(OverrideNew, OverrideInit):
4587 pass
4588 for case in OverrideNew, OverrideInit, OverrideBoth:
4589 case(1)
4590 case(1, kw=2)
4591 self.assertRaises(TypeError, case, 1, 2, 3)
4592 self.assertRaises(TypeError, case, 1, 2, foo=3)
4593
Benjamin Petersondf813792014-03-17 15:57:17 -05004594 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4595 class Base:
4596 pass
4597 class Sub(Base):
4598 pass
4599 self.assertIn("__dict__", Base.__dict__)
4600 self.assertNotIn("__dict__", Sub.__dict__)
4601
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004602 def test_bound_method_repr(self):
4603 class Foo:
4604 def method(self):
4605 pass
4606 self.assertRegex(repr(Foo().method),
4607 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4608
4609
4610 class Base:
4611 def method(self):
4612 pass
4613 class Derived1(Base):
4614 pass
4615 class Derived2(Base):
4616 def method(self):
4617 pass
4618 base = Base()
4619 derived1 = Derived1()
4620 derived2 = Derived2()
4621 super_d2 = super(Derived2, derived2)
4622 self.assertRegex(repr(base.method),
4623 r"<bound method .*Base\.method of <.*Base object at .*>>")
4624 self.assertRegex(repr(derived1.method),
4625 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4626 self.assertRegex(repr(derived2.method),
4627 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4628 self.assertRegex(repr(super_d2.method),
4629 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4630
4631 class Foo:
4632 @classmethod
4633 def method(cls):
4634 pass
4635 foo = Foo()
4636 self.assertRegex(repr(foo.method), # access via instance
4637 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4638 self.assertRegex(repr(Foo.method), # access via the class
4639 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4640
4641
4642 class MyCallable:
4643 def __call__(self, arg):
4644 pass
4645 func = MyCallable() # func has no __name__ or __qualname__ attributes
4646 instance = object()
4647 method = types.MethodType(func, instance)
4648 self.assertRegex(repr(method),
4649 r"<bound method \? of <object object at .*>>")
4650 func.__name__ = "name"
4651 self.assertRegex(repr(method),
4652 r"<bound method name of <object object at .*>>")
4653 func.__qualname__ = "qualname"
4654 self.assertRegex(repr(method),
4655 r"<bound method qualname of <object object at .*>>")
4656
Antoine Pitrou9d574812011-12-12 13:47:25 +01004657
Georg Brandl479a7e72008-02-05 18:13:15 +00004658class DictProxyTests(unittest.TestCase):
4659 def setUp(self):
4660 class C(object):
4661 def meth(self):
4662 pass
4663 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004664
Brett Cannon7a540732011-02-22 03:04:06 +00004665 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4666 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004667 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004668 # Testing dict-proxy keys...
4669 it = self.C.__dict__.keys()
4670 self.assertNotIsInstance(it, list)
4671 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004672 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004673 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004674 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004675
Brett Cannon7a540732011-02-22 03:04:06 +00004676 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4677 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004678 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004679 # Testing dict-proxy values...
4680 it = self.C.__dict__.values()
4681 self.assertNotIsInstance(it, list)
4682 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004683 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004684
Brett Cannon7a540732011-02-22 03:04:06 +00004685 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4686 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004687 def test_iter_items(self):
4688 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004689 it = self.C.__dict__.items()
4690 self.assertNotIsInstance(it, list)
4691 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004692 keys.sort()
4693 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004694 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004695
Georg Brandl479a7e72008-02-05 18:13:15 +00004696 def test_dict_type_with_metaclass(self):
4697 # Testing type of __dict__ when metaclass set...
4698 class B(object):
4699 pass
4700 class M(type):
4701 pass
4702 class C(metaclass=M):
4703 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4704 pass
4705 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004706
Ezio Melottiac53ab62010-12-18 14:59:43 +00004707 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004708 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004709 # We can't blindly compare with the repr of another dict as ordering
4710 # of keys and values is arbitrary and may differ.
4711 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004712 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004713 self.assertTrue(r.endswith(')'), r)
4714 for k, v in self.C.__dict__.items():
4715 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004716
Christian Heimesbbffeb62008-01-24 09:42:52 +00004717
Georg Brandl479a7e72008-02-05 18:13:15 +00004718class PTypesLongInitTest(unittest.TestCase):
4719 # This is in its own TestCase so that it can be run before any other tests.
4720 def test_pytype_long_ready(self):
4721 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004722
Georg Brandl479a7e72008-02-05 18:13:15 +00004723 # This dumps core when SF bug 551412 isn't fixed --
4724 # but only when test_descr.py is run separately.
4725 # (That can't be helped -- as soon as PyType_Ready()
4726 # is called for PyLong_Type, the bug is gone.)
4727 class UserLong(object):
4728 def __pow__(self, *args):
4729 pass
4730 try:
4731 pow(0, UserLong(), 0)
4732 except:
4733 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004734
Georg Brandl479a7e72008-02-05 18:13:15 +00004735 # Another segfault only when run early
4736 # (before PyType_Ready(tuple) is called)
4737 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004738
4739
Victor Stinnerd74782b2012-03-09 00:39:08 +01004740class MiscTests(unittest.TestCase):
4741 def test_type_lookup_mro_reference(self):
4742 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4743 # the type MRO because it may be modified during the lookup, if
4744 # __bases__ is set during the lookup for example.
4745 class MyKey(object):
4746 def __hash__(self):
4747 return hash('mykey')
4748
4749 def __eq__(self, other):
4750 X.__bases__ = (Base2,)
4751
4752 class Base(object):
4753 mykey = 'from Base'
4754 mykey2 = 'from Base'
4755
4756 class Base2(object):
4757 mykey = 'from Base2'
4758 mykey2 = 'from Base2'
4759
4760 X = type('X', (Base,), {MyKey(): 5})
4761 # mykey is read from Base
4762 self.assertEqual(X.mykey, 'from Base')
4763 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4764 self.assertEqual(X.mykey2, 'from Base2')
4765
4766
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004767class PicklingTests(unittest.TestCase):
4768
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004769 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004770 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004771 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004772 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004773 if kwargs:
4774 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4775 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004776 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004777 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4778 self.assertEqual(reduce_value[1], (type(obj),) + args)
4779 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004780 if listitems is not None:
4781 self.assertListEqual(list(reduce_value[3]), listitems)
4782 else:
4783 self.assertIsNone(reduce_value[3])
4784 if dictitems is not None:
4785 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4786 else:
4787 self.assertIsNone(reduce_value[4])
4788 else:
4789 base_type = type(obj).__base__
4790 reduce_value = (copyreg._reconstructor,
4791 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004792 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004793 None if base_type is object else base_type(obj)))
4794 if state is not None:
4795 reduce_value += (state,)
4796 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4797 self.assertEqual(obj.__reduce__(), reduce_value)
4798
4799 def test_reduce(self):
4800 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4801 args = (-101, "spam")
4802 kwargs = {'bacon': -201, 'fish': -301}
4803 state = {'cheese': -401}
4804
4805 class C1:
4806 def __getnewargs__(self):
4807 return args
4808 obj = C1()
4809 for proto in protocols:
4810 self._check_reduce(proto, obj, args)
4811
4812 for name, value in state.items():
4813 setattr(obj, name, value)
4814 for proto in protocols:
4815 self._check_reduce(proto, obj, args, state=state)
4816
4817 class C2:
4818 def __getnewargs__(self):
4819 return "bad args"
4820 obj = C2()
4821 for proto in protocols:
4822 if proto >= 2:
4823 with self.assertRaises(TypeError):
4824 obj.__reduce_ex__(proto)
4825
4826 class C3:
4827 def __getnewargs_ex__(self):
4828 return (args, kwargs)
4829 obj = C3()
4830 for proto in protocols:
4831 if proto >= 4:
4832 self._check_reduce(proto, obj, args, kwargs)
4833 elif proto >= 2:
4834 with self.assertRaises(ValueError):
4835 obj.__reduce_ex__(proto)
4836
4837 class C4:
4838 def __getnewargs_ex__(self):
4839 return (args, "bad dict")
4840 class C5:
4841 def __getnewargs_ex__(self):
4842 return ("bad tuple", kwargs)
4843 class C6:
4844 def __getnewargs_ex__(self):
4845 return ()
4846 class C7:
4847 def __getnewargs_ex__(self):
4848 return "bad args"
4849 for proto in protocols:
4850 for cls in C4, C5, C6, C7:
4851 obj = cls()
4852 if proto >= 2:
4853 with self.assertRaises((TypeError, ValueError)):
4854 obj.__reduce_ex__(proto)
4855
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004856 class C9:
4857 def __getnewargs_ex__(self):
4858 return (args, {})
4859 obj = C9()
4860 for proto in protocols:
4861 self._check_reduce(proto, obj, args)
4862
4863 class C10:
4864 def __getnewargs_ex__(self):
4865 raise IndexError
4866 obj = C10()
4867 for proto in protocols:
4868 if proto >= 2:
4869 with self.assertRaises(IndexError):
4870 obj.__reduce_ex__(proto)
4871
4872 class C11:
4873 def __getstate__(self):
4874 return state
4875 obj = C11()
4876 for proto in protocols:
4877 self._check_reduce(proto, obj, state=state)
4878
4879 class C12:
4880 def __getstate__(self):
4881 return "not dict"
4882 obj = C12()
4883 for proto in protocols:
4884 self._check_reduce(proto, obj, state="not dict")
4885
4886 class C13:
4887 def __getstate__(self):
4888 raise IndexError
4889 obj = C13()
4890 for proto in protocols:
4891 with self.assertRaises(IndexError):
4892 obj.__reduce_ex__(proto)
4893 if proto < 2:
4894 with self.assertRaises(IndexError):
4895 obj.__reduce__()
4896
4897 class C14:
4898 __slots__ = tuple(state)
4899 def __init__(self):
4900 for name, value in state.items():
4901 setattr(self, name, value)
4902
4903 obj = C14()
4904 for proto in protocols:
4905 if proto >= 2:
4906 self._check_reduce(proto, obj, state=(None, state))
4907 else:
4908 with self.assertRaises(TypeError):
4909 obj.__reduce_ex__(proto)
4910 with self.assertRaises(TypeError):
4911 obj.__reduce__()
4912
4913 class C15(dict):
4914 pass
4915 obj = C15({"quebec": -601})
4916 for proto in protocols:
4917 self._check_reduce(proto, obj, dictitems=dict(obj))
4918
4919 class C16(list):
4920 pass
4921 obj = C16(["yukon"])
4922 for proto in protocols:
4923 self._check_reduce(proto, obj, listitems=list(obj))
4924
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004925 def test_special_method_lookup(self):
4926 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4927 class Picky:
4928 def __getstate__(self):
4929 return {}
4930
4931 def __getattr__(self, attr):
4932 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4933 raise AssertionError(attr)
4934 return None
4935 for protocol in protocols:
4936 state = {} if protocol >= 2 else None
4937 self._check_reduce(protocol, Picky(), state=state)
4938
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004939 def _assert_is_copy(self, obj, objcopy, msg=None):
4940 """Utility method to verify if two objects are copies of each others.
4941 """
4942 if msg is None:
4943 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4944 if type(obj).__repr__ is object.__repr__:
4945 # We have this limitation for now because we use the object's repr
4946 # to help us verify that the two objects are copies. This allows
4947 # us to delegate the non-generic verification logic to the objects
4948 # themselves.
4949 raise ValueError("object passed to _assert_is_copy must " +
4950 "override the __repr__ method.")
4951 self.assertIsNot(obj, objcopy, msg=msg)
4952 self.assertIs(type(obj), type(objcopy), msg=msg)
4953 if hasattr(obj, '__dict__'):
4954 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4955 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4956 if hasattr(obj, '__slots__'):
4957 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4958 for slot in obj.__slots__:
4959 self.assertEqual(
4960 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4961 self.assertEqual(getattr(obj, slot, None),
4962 getattr(objcopy, slot, None), msg=msg)
4963 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4964
4965 @staticmethod
4966 def _generate_pickle_copiers():
4967 """Utility method to generate the many possible pickle configurations.
4968 """
4969 class PickleCopier:
4970 "This class copies object using pickle."
4971 def __init__(self, proto, dumps, loads):
4972 self.proto = proto
4973 self.dumps = dumps
4974 self.loads = loads
4975 def copy(self, obj):
4976 return self.loads(self.dumps(obj, self.proto))
4977 def __repr__(self):
4978 # We try to be as descriptive as possible here since this is
4979 # the string which we will allow us to tell the pickle
4980 # configuration we are using during debugging.
4981 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4982 .format(self.proto,
4983 self.dumps.__module__, self.dumps.__qualname__,
4984 self.loads.__module__, self.loads.__qualname__))
4985 return (PickleCopier(*args) for args in
4986 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4987 {pickle.dumps, pickle._dumps},
4988 {pickle.loads, pickle._loads}))
4989
4990 def test_pickle_slots(self):
4991 # Tests pickling of classes with __slots__.
4992
4993 # Pickling of classes with __slots__ but without __getstate__ should
4994 # fail (if using protocol 0 or 1)
4995 global C
4996 class C:
4997 __slots__ = ['a']
4998 with self.assertRaises(TypeError):
4999 pickle.dumps(C(), 0)
5000
5001 global D
5002 class D(C):
5003 pass
5004 with self.assertRaises(TypeError):
5005 pickle.dumps(D(), 0)
5006
5007 class C:
5008 "A class with __getstate__ and __setstate__ implemented."
5009 __slots__ = ['a']
5010 def __getstate__(self):
5011 state = getattr(self, '__dict__', {}).copy()
5012 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01005013 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005014 try:
5015 state[slot] = getattr(self, slot)
5016 except AttributeError:
5017 pass
5018 return state
5019 def __setstate__(self, state):
5020 for k, v in state.items():
5021 setattr(self, k, v)
5022 def __repr__(self):
5023 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5024
5025 class D(C):
5026 "A subclass of a class with slots."
5027 pass
5028
5029 global E
5030 class E(C):
5031 "A subclass with an extra slot."
5032 __slots__ = ['b']
5033
5034 # Now it should work
5035 for pickle_copier in self._generate_pickle_copiers():
5036 with self.subTest(pickle_copier=pickle_copier):
5037 x = C()
5038 y = pickle_copier.copy(x)
5039 self._assert_is_copy(x, y)
5040
5041 x.a = 42
5042 y = pickle_copier.copy(x)
5043 self._assert_is_copy(x, y)
5044
5045 x = D()
5046 x.a = 42
5047 x.b = 100
5048 y = pickle_copier.copy(x)
5049 self._assert_is_copy(x, y)
5050
5051 x = E()
5052 x.a = 42
5053 x.b = "foo"
5054 y = pickle_copier.copy(x)
5055 self._assert_is_copy(x, y)
5056
5057 def test_reduce_copying(self):
5058 # Tests pickling and copying new-style classes and objects.
5059 global C1
5060 class C1:
5061 "The state of this class is copyable via its instance dict."
5062 ARGS = (1, 2)
5063 NEED_DICT_COPYING = True
5064 def __init__(self, a, b):
5065 super().__init__()
5066 self.a = a
5067 self.b = b
5068 def __repr__(self):
5069 return "C1(%r, %r)" % (self.a, self.b)
5070
5071 global C2
5072 class C2(list):
5073 "A list subclass copyable via __getnewargs__."
5074 ARGS = (1, 2)
5075 NEED_DICT_COPYING = False
5076 def __new__(cls, a, b):
5077 self = super().__new__(cls)
5078 self.a = a
5079 self.b = b
5080 return self
5081 def __init__(self, *args):
5082 super().__init__()
5083 # This helps testing that __init__ is not called during the
5084 # unpickling process, which would cause extra appends.
5085 self.append("cheese")
5086 @classmethod
5087 def __getnewargs__(cls):
5088 return cls.ARGS
5089 def __repr__(self):
5090 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5091
5092 global C3
5093 class C3(list):
5094 "A list subclass copyable via __getstate__."
5095 ARGS = (1, 2)
5096 NEED_DICT_COPYING = False
5097 def __init__(self, a, b):
5098 self.a = a
5099 self.b = b
5100 # This helps testing that __init__ is not called during the
5101 # unpickling process, which would cause extra appends.
5102 self.append("cheese")
5103 @classmethod
5104 def __getstate__(cls):
5105 return cls.ARGS
5106 def __setstate__(self, state):
5107 a, b = state
5108 self.a = a
5109 self.b = b
5110 def __repr__(self):
5111 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5112
5113 global C4
5114 class C4(int):
5115 "An int subclass copyable via __getnewargs__."
5116 ARGS = ("hello", "world", 1)
5117 NEED_DICT_COPYING = False
5118 def __new__(cls, a, b, value):
5119 self = super().__new__(cls, value)
5120 self.a = a
5121 self.b = b
5122 return self
5123 @classmethod
5124 def __getnewargs__(cls):
5125 return cls.ARGS
5126 def __repr__(self):
5127 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5128
5129 global C5
5130 class C5(int):
5131 "An int subclass copyable via __getnewargs_ex__."
5132 ARGS = (1, 2)
5133 KWARGS = {'value': 3}
5134 NEED_DICT_COPYING = False
5135 def __new__(cls, a, b, *, value=0):
5136 self = super().__new__(cls, value)
5137 self.a = a
5138 self.b = b
5139 return self
5140 @classmethod
5141 def __getnewargs_ex__(cls):
5142 return (cls.ARGS, cls.KWARGS)
5143 def __repr__(self):
5144 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5145
5146 test_classes = (C1, C2, C3, C4, C5)
5147 # Testing copying through pickle
5148 pickle_copiers = self._generate_pickle_copiers()
5149 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5150 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5151 kwargs = getattr(cls, 'KWARGS', {})
5152 obj = cls(*cls.ARGS, **kwargs)
5153 proto = pickle_copier.proto
5154 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
5155 with self.assertRaises(ValueError):
5156 pickle_copier.dumps(obj, proto)
5157 continue
5158 objcopy = pickle_copier.copy(obj)
5159 self._assert_is_copy(obj, objcopy)
5160 # For test classes that supports this, make sure we didn't go
5161 # around the reduce protocol by simply copying the attribute
5162 # dictionary. We clear attributes using the previous copy to
5163 # not mutate the original argument.
5164 if proto >= 2 and not cls.NEED_DICT_COPYING:
5165 objcopy.__dict__.clear()
5166 objcopy2 = pickle_copier.copy(objcopy)
5167 self._assert_is_copy(obj, objcopy2)
5168
5169 # Testing copying through copy.deepcopy()
5170 for cls in test_classes:
5171 with self.subTest(cls=cls):
5172 kwargs = getattr(cls, 'KWARGS', {})
5173 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005174 objcopy = deepcopy(obj)
5175 self._assert_is_copy(obj, objcopy)
5176 # For test classes that supports this, make sure we didn't go
5177 # around the reduce protocol by simply copying the attribute
5178 # dictionary. We clear attributes using the previous copy to
5179 # not mutate the original argument.
5180 if not cls.NEED_DICT_COPYING:
5181 objcopy.__dict__.clear()
5182 objcopy2 = deepcopy(objcopy)
5183 self._assert_is_copy(obj, objcopy2)
5184
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005185 def test_issue24097(self):
5186 # Slot name is freed inside __getattr__ and is later used.
5187 class S(str): # Not interned
5188 pass
5189 class A:
5190 __slotnames__ = [S('spam')]
5191 def __getattr__(self, attr):
5192 if attr == 'spam':
5193 A.__slotnames__[:] = [S('spam')]
5194 return 42
5195 else:
5196 raise AttributeError
5197
5198 import copyreg
5199 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
5200 self.assertEqual(A().__reduce__(2), expected) # Shouldn't crash
5201
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005202
Benjamin Peterson2a605342014-03-17 16:20:12 -05005203class SharedKeyTests(unittest.TestCase):
5204
5205 @support.cpython_only
5206 def test_subclasses(self):
5207 # Verify that subclasses can share keys (per PEP 412)
5208 class A:
5209 pass
5210 class B(A):
5211 pass
5212
5213 a, b = A(), B()
5214 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5215 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5216 a.x, a.y, a.z, a.w = range(4)
5217 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5218 a2 = A()
5219 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5220 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5221 b.u, b.v, b.w, b.t = range(4)
5222 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5223
5224
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005225class DebugHelperMeta(type):
5226 """
5227 Sets default __doc__ and simplifies repr() output.
5228 """
5229 def __new__(mcls, name, bases, attrs):
5230 if attrs.get('__doc__') is None:
5231 attrs['__doc__'] = name # helps when debugging with gdb
5232 return type.__new__(mcls, name, bases, attrs)
5233 def __repr__(cls):
5234 return repr(cls.__name__)
5235
5236
5237class MroTest(unittest.TestCase):
5238 """
5239 Regressions for some bugs revealed through
5240 mcsl.mro() customization (typeobject.c: mro_internal()) and
5241 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5242 """
5243
5244 def setUp(self):
5245 self.step = 0
5246 self.ready = False
5247
5248 def step_until(self, limit):
5249 ret = (self.step < limit)
5250 if ret:
5251 self.step += 1
5252 return ret
5253
5254 def test_incomplete_set_bases_on_self(self):
5255 """
5256 type_set_bases must be aware that type->tp_mro can be NULL.
5257 """
5258 class M(DebugHelperMeta):
5259 def mro(cls):
5260 if self.step_until(1):
5261 assert cls.__mro__ is None
5262 cls.__bases__ += ()
5263
5264 return type.mro(cls)
5265
5266 class A(metaclass=M):
5267 pass
5268
5269 def test_reent_set_bases_on_base(self):
5270 """
5271 Deep reentrancy must not over-decref old_mro.
5272 """
5273 class M(DebugHelperMeta):
5274 def mro(cls):
5275 if cls.__mro__ is not None and cls.__name__ == 'B':
5276 # 4-5 steps are usually enough to make it crash somewhere
5277 if self.step_until(10):
5278 A.__bases__ += ()
5279
5280 return type.mro(cls)
5281
5282 class A(metaclass=M):
5283 pass
5284 class B(A):
5285 pass
5286 B.__bases__ += ()
5287
5288 def test_reent_set_bases_on_direct_base(self):
5289 """
5290 Similar to test_reent_set_bases_on_base, but may crash differently.
5291 """
5292 class M(DebugHelperMeta):
5293 def mro(cls):
5294 base = cls.__bases__[0]
5295 if base is not object:
5296 if self.step_until(5):
5297 base.__bases__ += ()
5298
5299 return type.mro(cls)
5300
5301 class A(metaclass=M):
5302 pass
5303 class B(A):
5304 pass
5305 class C(B):
5306 pass
5307
5308 def test_reent_set_bases_tp_base_cycle(self):
5309 """
5310 type_set_bases must check for an inheritance cycle not only through
5311 MRO of the type, which may be not yet updated in case of reentrance,
5312 but also through tp_base chain, which is assigned before diving into
5313 inner calls to mro().
5314
5315 Otherwise, the following snippet can loop forever:
5316 do {
5317 // ...
5318 type = type->tp_base;
5319 } while (type != NULL);
5320
5321 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5322 would not be happy in that case, causing a stack overflow.
5323 """
5324 class M(DebugHelperMeta):
5325 def mro(cls):
5326 if self.ready:
5327 if cls.__name__ == 'B1':
5328 B2.__bases__ = (B1,)
5329 if cls.__name__ == 'B2':
5330 B1.__bases__ = (B2,)
5331 return type.mro(cls)
5332
5333 class A(metaclass=M):
5334 pass
5335 class B1(A):
5336 pass
5337 class B2(A):
5338 pass
5339
5340 self.ready = True
5341 with self.assertRaises(TypeError):
5342 B1.__bases__ += ()
5343
5344 def test_tp_subclasses_cycle_in_update_slots(self):
5345 """
5346 type_set_bases must check for reentrancy upon finishing its job
5347 by updating tp_subclasses of old/new bases of the type.
5348 Otherwise, an implicit inheritance cycle through tp_subclasses
5349 can break functions that recurse on elements of that field
5350 (like recurse_down_subclasses and mro_hierarchy) eventually
5351 leading to a stack overflow.
5352 """
5353 class M(DebugHelperMeta):
5354 def mro(cls):
5355 if self.ready and cls.__name__ == 'C':
5356 self.ready = False
5357 C.__bases__ = (B2,)
5358 return type.mro(cls)
5359
5360 class A(metaclass=M):
5361 pass
5362 class B1(A):
5363 pass
5364 class B2(A):
5365 pass
5366 class C(A):
5367 pass
5368
5369 self.ready = True
5370 C.__bases__ = (B1,)
5371 B1.__bases__ = (C,)
5372
5373 self.assertEqual(C.__bases__, (B2,))
5374 self.assertEqual(B2.__subclasses__(), [C])
5375 self.assertEqual(B1.__subclasses__(), [])
5376
5377 self.assertEqual(B1.__bases__, (C,))
5378 self.assertEqual(C.__subclasses__(), [B1])
5379
5380 def test_tp_subclasses_cycle_error_return_path(self):
5381 """
5382 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5383 a code path executed on error (goto bail).
5384 """
5385 class E(Exception):
5386 pass
5387 class M(DebugHelperMeta):
5388 def mro(cls):
5389 if self.ready and cls.__name__ == 'C':
5390 if C.__bases__ == (B2,):
5391 self.ready = False
5392 else:
5393 C.__bases__ = (B2,)
5394 raise E
5395 return type.mro(cls)
5396
5397 class A(metaclass=M):
5398 pass
5399 class B1(A):
5400 pass
5401 class B2(A):
5402 pass
5403 class C(A):
5404 pass
5405
5406 self.ready = True
5407 with self.assertRaises(E):
5408 C.__bases__ = (B1,)
5409 B1.__bases__ = (C,)
5410
5411 self.assertEqual(C.__bases__, (B2,))
5412 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5413
5414 def test_incomplete_extend(self):
5415 """
5416 Extending an unitialized type with type->tp_mro == NULL must
5417 throw a reasonable TypeError exception, instead of failing
5418 with PyErr_BadInternalCall.
5419 """
5420 class M(DebugHelperMeta):
5421 def mro(cls):
5422 if cls.__mro__ is None and cls.__name__ != 'X':
5423 with self.assertRaises(TypeError):
5424 class X(cls):
5425 pass
5426
5427 return type.mro(cls)
5428
5429 class A(metaclass=M):
5430 pass
5431
5432 def test_incomplete_super(self):
5433 """
5434 Attrubute lookup on a super object must be aware that
5435 its target type can be uninitialized (type->tp_mro == NULL).
5436 """
5437 class M(DebugHelperMeta):
5438 def mro(cls):
5439 if cls.__mro__ is None:
5440 with self.assertRaises(AttributeError):
5441 super(cls, cls).xxx
5442
5443 return type.mro(cls)
5444
5445 class A(metaclass=M):
5446 pass
5447
5448
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005449def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005450 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005451 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005452 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005453 MiscTests, PicklingTests, SharedKeyTests,
5454 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005455
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005456if __name__ == "__main__":
5457 test_main()