blob: a130cecb89e34444953dc9acc6ed33864b837fb5 [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
Benjamin Peterson52c42432012-03-07 18:41:11 -060010import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +000011
Georg Brandl479a7e72008-02-05 18:13:15 +000012from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +000013from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +000014
Tim Peters6d6c1a32001-08-02 04:15:00 +000015
Georg Brandl479a7e72008-02-05 18:13:15 +000016class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000017
Georg Brandl479a7e72008-02-05 18:13:15 +000018 def __init__(self, *args, **kwargs):
19 unittest.TestCase.__init__(self, *args, **kwargs)
20 self.binops = {
21 'add': '+',
22 'sub': '-',
23 'mul': '*',
Serhiy Storchakac2ccce72015-03-12 22:01:30 +020024 'matmul': '@',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +020025 'truediv': '/',
26 'floordiv': '//',
Georg Brandl479a7e72008-02-05 18:13:15 +000027 'divmod': 'divmod',
28 'pow': '**',
29 'lshift': '<<',
30 'rshift': '>>',
31 'and': '&',
32 'xor': '^',
33 'or': '|',
34 'cmp': 'cmp',
35 'lt': '<',
36 'le': '<=',
37 'eq': '==',
38 'ne': '!=',
39 'gt': '>',
40 'ge': '>=',
41 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
Georg Brandl479a7e72008-02-05 18:13:15 +000043 for name, expr in list(self.binops.items()):
44 if expr.islower():
45 expr = expr + "(a, b)"
46 else:
47 expr = 'a %s b' % expr
48 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000049
Georg Brandl479a7e72008-02-05 18:13:15 +000050 self.unops = {
51 'pos': '+',
52 'neg': '-',
53 'abs': 'abs',
54 'invert': '~',
55 'int': 'int',
56 'float': 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +000057 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000058
Georg Brandl479a7e72008-02-05 18:13:15 +000059 for name, expr in list(self.unops.items()):
60 if expr.islower():
61 expr = expr + "(a)"
62 else:
63 expr = '%s a' % expr
64 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000065
Georg Brandl479a7e72008-02-05 18:13:15 +000066 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
67 d = {'a': a}
68 self.assertEqual(eval(expr, d), res)
69 t = type(a)
70 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000071
Georg Brandl479a7e72008-02-05 18:13:15 +000072 # Find method in parent class
73 while meth not in t.__dict__:
74 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000075 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
76 # method object; the getattr() below obtains its underlying function.
77 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000078 self.assertEqual(m(a), res)
79 bm = getattr(a, meth)
80 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000081
Georg Brandl479a7e72008-02-05 18:13:15 +000082 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
83 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000084
Georg Brandl479a7e72008-02-05 18:13:15 +000085 self.assertEqual(eval(expr, d), res)
86 t = type(a)
87 m = getattr(t, meth)
88 while meth not in t.__dict__:
89 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000090 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
91 # method object; the getattr() below obtains its underlying function.
92 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000093 self.assertEqual(m(a, b), res)
94 bm = getattr(a, meth)
95 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000096
Georg Brandl479a7e72008-02-05 18:13:15 +000097 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
98 d = {'a': a, 'b': b, 'c': c}
99 self.assertEqual(eval(expr, d), res)
100 t = type(a)
101 m = getattr(t, meth)
102 while meth not in t.__dict__:
103 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000104 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
105 # method object; the getattr() below obtains its underlying function.
106 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000107 self.assertEqual(m(a, slice(b, c)), res)
108 bm = getattr(a, meth)
109 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110
Georg Brandl479a7e72008-02-05 18:13:15 +0000111 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
112 d = {'a': deepcopy(a), 'b': b}
113 exec(stmt, d)
114 self.assertEqual(d['a'], res)
115 t = type(a)
116 m = getattr(t, meth)
117 while meth not in t.__dict__:
118 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000119 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
120 # method object; the getattr() below obtains its underlying function.
121 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000122 d['a'] = deepcopy(a)
123 m(d['a'], b)
124 self.assertEqual(d['a'], res)
125 d['a'] = deepcopy(a)
126 bm = getattr(d['a'], meth)
127 bm(b)
128 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000129
Georg Brandl479a7e72008-02-05 18:13:15 +0000130 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
131 d = {'a': deepcopy(a), 'b': b, 'c': c}
132 exec(stmt, d)
133 self.assertEqual(d['a'], res)
134 t = type(a)
135 m = getattr(t, meth)
136 while meth not in t.__dict__:
137 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000138 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
139 # method object; the getattr() below obtains its underlying function.
140 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000141 d['a'] = deepcopy(a)
142 m(d['a'], b, c)
143 self.assertEqual(d['a'], res)
144 d['a'] = deepcopy(a)
145 bm = getattr(d['a'], meth)
146 bm(b, c)
147 self.assertEqual(d['a'], res)
148
149 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
150 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
151 exec(stmt, dictionary)
152 self.assertEqual(dictionary['a'], res)
153 t = type(a)
154 while meth not in t.__dict__:
155 t = t.__bases__[0]
156 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000157 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
158 # method object; the getattr() below obtains its underlying function.
159 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000160 dictionary['a'] = deepcopy(a)
161 m(dictionary['a'], slice(b, c), d)
162 self.assertEqual(dictionary['a'], res)
163 dictionary['a'] = deepcopy(a)
164 bm = getattr(dictionary['a'], meth)
165 bm(slice(b, c), d)
166 self.assertEqual(dictionary['a'], res)
167
168 def test_lists(self):
169 # Testing list operations...
170 # Asserts are within individual test methods
171 self.binop_test([1], [2], [1,2], "a+b", "__add__")
172 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
173 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
174 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
175 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
176 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
177 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
178 self.unop_test([1,2,3], 3, "len(a)", "__len__")
179 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
181 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
182 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
183 "__setitem__")
184
185 def test_dicts(self):
186 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000187 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
188 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
190
191 d = {1:2, 3:4}
192 l1 = []
193 for i in list(d.keys()):
194 l1.append(i)
195 l = []
196 for i in iter(d):
197 l.append(i)
198 self.assertEqual(l, l1)
199 l = []
200 for i in d.__iter__():
201 l.append(i)
202 self.assertEqual(l, l1)
203 l = []
204 for i in dict.__iter__(d):
205 l.append(i)
206 self.assertEqual(l, l1)
207 d = {1:2, 3:4}
208 self.unop_test(d, 2, "len(a)", "__len__")
209 self.assertEqual(eval(repr(d), {}), d)
210 self.assertEqual(eval(d.__repr__(), {}), d)
211 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
212 "__setitem__")
213
214 # Tests for unary and binary operators
215 def number_operators(self, a, b, skip=[]):
216 dict = {'a': a, 'b': b}
217
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200218 for name, expr in self.binops.items():
Georg Brandl479a7e72008-02-05 18:13:15 +0000219 if name not in skip:
220 name = "__%s__" % name
221 if hasattr(a, name):
222 res = eval(expr, dict)
223 self.binop_test(a, b, res, expr, name)
224
225 for name, expr in list(self.unops.items()):
226 if name not in skip:
227 name = "__%s__" % name
228 if hasattr(a, name):
229 res = eval(expr, dict)
230 self.unop_test(a, res, expr, name)
231
232 def test_ints(self):
233 # Testing int operations...
234 self.number_operators(100, 3)
235 # The following crashes in Python 2.2
236 self.assertEqual((1).__bool__(), 1)
237 self.assertEqual((0).__bool__(), 0)
238 # This returns 'NotImplemented' in Python 2.2
239 class C(int):
240 def __add__(self, other):
241 return NotImplemented
242 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000243 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000244 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000245 except TypeError:
246 pass
247 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000248 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000249
Georg Brandl479a7e72008-02-05 18:13:15 +0000250 def test_floats(self):
251 # Testing float operations...
252 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000253
Georg Brandl479a7e72008-02-05 18:13:15 +0000254 def test_complexes(self):
255 # Testing complex operations...
256 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000257 'int', 'float',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200258 'floordiv', 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000259
Georg Brandl479a7e72008-02-05 18:13:15 +0000260 class Number(complex):
261 __slots__ = ['prec']
262 def __new__(cls, *args, **kwds):
263 result = complex.__new__(cls, *args)
264 result.prec = kwds.get('prec', 12)
265 return result
266 def __repr__(self):
267 prec = self.prec
268 if self.imag == 0.0:
269 return "%.*g" % (prec, self.real)
270 if self.real == 0.0:
271 return "%.*gj" % (prec, self.imag)
272 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
273 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000274
Georg Brandl479a7e72008-02-05 18:13:15 +0000275 a = Number(3.14, prec=6)
276 self.assertEqual(repr(a), "3.14")
277 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000278
Georg Brandl479a7e72008-02-05 18:13:15 +0000279 a = Number(a, prec=2)
280 self.assertEqual(repr(a), "3.1")
281 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000282
Georg Brandl479a7e72008-02-05 18:13:15 +0000283 a = Number(234.5)
284 self.assertEqual(repr(a), "234.5")
285 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000286
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000287 def test_explicit_reverse_methods(self):
288 # see issue 9930
289 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
290 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
291
Benjamin Petersone549ead2009-03-28 21:42:05 +0000292 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000293 def test_spam_lists(self):
294 # Testing spamlist operations...
295 import copy, xxsubtype as spam
296
297 def spamlist(l, memo=None):
298 import xxsubtype as spam
299 return spam.spamlist(l)
300
301 # This is an ugly hack:
302 copy._deepcopy_dispatch[spam.spamlist] = spamlist
303
304 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
305 "__add__")
306 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
307 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
308 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
309 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
310 "__getitem__")
311 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
312 "__iadd__")
313 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
314 "__imul__")
315 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
316 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
317 "__mul__")
318 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
319 "__rmul__")
320 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
321 "__setitem__")
322 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
323 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
324 # Test subclassing
325 class C(spam.spamlist):
326 def foo(self): return 1
327 a = C()
328 self.assertEqual(a, [])
329 self.assertEqual(a.foo(), 1)
330 a.append(100)
331 self.assertEqual(a, [100])
332 self.assertEqual(a.getstate(), 0)
333 a.setstate(42)
334 self.assertEqual(a.getstate(), 42)
335
Benjamin Petersone549ead2009-03-28 21:42:05 +0000336 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000337 def test_spam_dicts(self):
338 # Testing spamdict operations...
339 import copy, xxsubtype as spam
340 def spamdict(d, memo=None):
341 import xxsubtype as spam
342 sd = spam.spamdict()
343 for k, v in list(d.items()):
344 sd[k] = v
345 return sd
346 # This is an ugly hack:
347 copy._deepcopy_dispatch[spam.spamdict] = spamdict
348
Georg Brandl479a7e72008-02-05 18:13:15 +0000349 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
350 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
351 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
352 d = spamdict({1:2,3:4})
353 l1 = []
354 for i in list(d.keys()):
355 l1.append(i)
356 l = []
357 for i in iter(d):
358 l.append(i)
359 self.assertEqual(l, l1)
360 l = []
361 for i in d.__iter__():
362 l.append(i)
363 self.assertEqual(l, l1)
364 l = []
365 for i in type(spamdict({})).__iter__(d):
366 l.append(i)
367 self.assertEqual(l, l1)
368 straightd = {1:2, 3:4}
369 spamd = spamdict(straightd)
370 self.unop_test(spamd, 2, "len(a)", "__len__")
371 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
372 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
373 "a[b]=c", "__setitem__")
374 # Test subclassing
375 class C(spam.spamdict):
376 def foo(self): return 1
377 a = C()
378 self.assertEqual(list(a.items()), [])
379 self.assertEqual(a.foo(), 1)
380 a['foo'] = 'bar'
381 self.assertEqual(list(a.items()), [('foo', 'bar')])
382 self.assertEqual(a.getstate(), 0)
383 a.setstate(100)
384 self.assertEqual(a.getstate(), 100)
385
386class ClassPropertiesAndMethods(unittest.TestCase):
387
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200388 def assertHasAttr(self, obj, name):
389 self.assertTrue(hasattr(obj, name),
390 '%r has no attribute %r' % (obj, name))
391
392 def assertNotHasAttr(self, obj, name):
393 self.assertFalse(hasattr(obj, name),
394 '%r has unexpected attribute %r' % (obj, name))
395
Georg Brandl479a7e72008-02-05 18:13:15 +0000396 def test_python_dicts(self):
397 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000398 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000399 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000400 d = dict()
401 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200402 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000403 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000404 class C(dict):
405 state = -1
406 def __init__(self_local, *a, **kw):
407 if a:
408 self.assertEqual(len(a), 1)
409 self_local.state = a[0]
410 if kw:
411 for k, v in list(kw.items()):
412 self_local[v] = k
413 def __getitem__(self, key):
414 return self.get(key, 0)
415 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000416 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000417 dict.__setitem__(self_local, key, value)
418 def setstate(self, state):
419 self.state = state
420 def getstate(self):
421 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000422 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000423 a1 = C(12)
424 self.assertEqual(a1.state, 12)
425 a2 = C(foo=1, bar=2)
426 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
427 a = C()
428 self.assertEqual(a.state, -1)
429 self.assertEqual(a.getstate(), -1)
430 a.setstate(0)
431 self.assertEqual(a.state, 0)
432 self.assertEqual(a.getstate(), 0)
433 a.setstate(10)
434 self.assertEqual(a.state, 10)
435 self.assertEqual(a.getstate(), 10)
436 self.assertEqual(a[42], 0)
437 a[42] = 24
438 self.assertEqual(a[42], 24)
439 N = 50
440 for i in range(N):
441 a[i] = C()
442 for j in range(N):
443 a[i][j] = i*j
444 for i in range(N):
445 for j in range(N):
446 self.assertEqual(a[i][j], i*j)
447
448 def test_python_lists(self):
449 # Testing Python subclass of list...
450 class C(list):
451 def __getitem__(self, i):
452 if isinstance(i, slice):
453 return i.start, i.stop
454 return list.__getitem__(self, i) + 100
455 a = C()
456 a.extend([0,1,2])
457 self.assertEqual(a[0], 100)
458 self.assertEqual(a[1], 101)
459 self.assertEqual(a[2], 102)
460 self.assertEqual(a[100:200], (100,200))
461
462 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000463 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000464 class C(metaclass=type):
465 def __init__(self):
466 self.__state = 0
467 def getstate(self):
468 return self.__state
469 def setstate(self, state):
470 self.__state = state
471 a = C()
472 self.assertEqual(a.getstate(), 0)
473 a.setstate(10)
474 self.assertEqual(a.getstate(), 10)
475 class _metaclass(type):
476 def myself(cls): return cls
477 class D(metaclass=_metaclass):
478 pass
479 self.assertEqual(D.myself(), D)
480 d = D()
481 self.assertEqual(d.__class__, D)
482 class M1(type):
483 def __new__(cls, name, bases, dict):
484 dict['__spam__'] = 1
485 return type.__new__(cls, name, bases, dict)
486 class C(metaclass=M1):
487 pass
488 self.assertEqual(C.__spam__, 1)
489 c = C()
490 self.assertEqual(c.__spam__, 1)
491
492 class _instance(object):
493 pass
494 class M2(object):
495 @staticmethod
496 def __new__(cls, name, bases, dict):
497 self = object.__new__(cls)
498 self.name = name
499 self.bases = bases
500 self.dict = dict
501 return self
502 def __call__(self):
503 it = _instance()
504 # Early binding of methods
505 for key in self.dict:
506 if key.startswith("__"):
507 continue
508 setattr(it, key, self.dict[key].__get__(it, self))
509 return it
510 class C(metaclass=M2):
511 def spam(self):
512 return 42
513 self.assertEqual(C.name, 'C')
514 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000515 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000516 c = C()
517 self.assertEqual(c.spam(), 42)
518
519 # More metaclass examples
520
521 class autosuper(type):
522 # Automatically add __super to the class
523 # This trick only works for dynamic classes
524 def __new__(metaclass, name, bases, dict):
525 cls = super(autosuper, metaclass).__new__(metaclass,
526 name, bases, dict)
527 # Name mangling for __super removes leading underscores
528 while name[:1] == "_":
529 name = name[1:]
530 if name:
531 name = "_%s__super" % name
532 else:
533 name = "__super"
534 setattr(cls, name, super(cls))
535 return cls
536 class A(metaclass=autosuper):
537 def meth(self):
538 return "A"
539 class B(A):
540 def meth(self):
541 return "B" + self.__super.meth()
542 class C(A):
543 def meth(self):
544 return "C" + self.__super.meth()
545 class D(C, B):
546 def meth(self):
547 return "D" + self.__super.meth()
548 self.assertEqual(D().meth(), "DCBA")
549 class E(B, C):
550 def meth(self):
551 return "E" + self.__super.meth()
552 self.assertEqual(E().meth(), "EBCA")
553
554 class autoproperty(type):
555 # Automatically create property attributes when methods
556 # named _get_x and/or _set_x are found
557 def __new__(metaclass, name, bases, dict):
558 hits = {}
559 for key, val in dict.items():
560 if key.startswith("_get_"):
561 key = key[5:]
562 get, set = hits.get(key, (None, None))
563 get = val
564 hits[key] = get, set
565 elif key.startswith("_set_"):
566 key = key[5:]
567 get, set = hits.get(key, (None, None))
568 set = val
569 hits[key] = get, set
570 for key, (get, set) in hits.items():
571 dict[key] = property(get, set)
572 return super(autoproperty, metaclass).__new__(metaclass,
573 name, bases, dict)
574 class A(metaclass=autoproperty):
575 def _get_x(self):
576 return -self.__x
577 def _set_x(self, x):
578 self.__x = -x
579 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200580 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000581 a.x = 12
582 self.assertEqual(a.x, 12)
583 self.assertEqual(a._A__x, -12)
584
585 class multimetaclass(autoproperty, autosuper):
586 # Merge of multiple cooperating metaclasses
587 pass
588 class A(metaclass=multimetaclass):
589 def _get_x(self):
590 return "A"
591 class B(A):
592 def _get_x(self):
593 return "B" + self.__super._get_x()
594 class C(A):
595 def _get_x(self):
596 return "C" + self.__super._get_x()
597 class D(C, B):
598 def _get_x(self):
599 return "D" + self.__super._get_x()
600 self.assertEqual(D().x, "DCBA")
601
602 # Make sure type(x) doesn't call x.__class__.__init__
603 class T(type):
604 counter = 0
605 def __init__(self, *args):
606 T.counter += 1
607 class C(metaclass=T):
608 pass
609 self.assertEqual(T.counter, 1)
610 a = C()
611 self.assertEqual(type(a), C)
612 self.assertEqual(T.counter, 1)
613
614 class C(object): pass
615 c = C()
616 try: c()
617 except TypeError: pass
618 else: self.fail("calling object w/o call method should raise "
619 "TypeError")
620
621 # Testing code to find most derived baseclass
622 class A(type):
623 def __new__(*args, **kwargs):
624 return type.__new__(*args, **kwargs)
625
626 class B(object):
627 pass
628
629 class C(object, metaclass=A):
630 pass
631
632 # The most derived metaclass of D is A rather than type.
633 class D(B, C):
634 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000635 self.assertIs(A, type(D))
636
637 # issue1294232: correct metaclass calculation
638 new_calls = [] # to check the order of __new__ calls
639 class AMeta(type):
640 @staticmethod
641 def __new__(mcls, name, bases, ns):
642 new_calls.append('AMeta')
643 return super().__new__(mcls, name, bases, ns)
644 @classmethod
645 def __prepare__(mcls, name, bases):
646 return {}
647
648 class BMeta(AMeta):
649 @staticmethod
650 def __new__(mcls, name, bases, ns):
651 new_calls.append('BMeta')
652 return super().__new__(mcls, name, bases, ns)
653 @classmethod
654 def __prepare__(mcls, name, bases):
655 ns = super().__prepare__(name, bases)
656 ns['BMeta_was_here'] = True
657 return ns
658
659 class A(metaclass=AMeta):
660 pass
661 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000662 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000663
664 class B(metaclass=BMeta):
665 pass
666 # BMeta.__new__ calls AMeta.__new__ with super:
667 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000668 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000669
670 class C(A, B):
671 pass
672 # The most derived metaclass is BMeta:
673 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000674 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000675 # BMeta.__prepare__ should've been called:
676 self.assertIn('BMeta_was_here', C.__dict__)
677
678 # The order of the bases shouldn't matter:
679 class C2(B, A):
680 pass
681 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000682 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000683 self.assertIn('BMeta_was_here', C2.__dict__)
684
685 # Check correct metaclass calculation when a metaclass is declared:
686 class D(C, metaclass=type):
687 pass
688 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000689 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000690 self.assertIn('BMeta_was_here', D.__dict__)
691
692 class E(C, metaclass=AMeta):
693 pass
694 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000695 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000696 self.assertIn('BMeta_was_here', E.__dict__)
697
698 # Special case: the given metaclass isn't a class,
699 # so there is no metaclass calculation.
700 marker = object()
701 def func(*args, **kwargs):
702 return marker
703 class X(metaclass=func):
704 pass
705 class Y(object, metaclass=func):
706 pass
707 class Z(D, metaclass=func):
708 pass
709 self.assertIs(marker, X)
710 self.assertIs(marker, Y)
711 self.assertIs(marker, Z)
712
713 # The given metaclass is a class,
714 # but not a descendant of type.
715 prepare_calls = [] # to track __prepare__ calls
716 class ANotMeta:
717 def __new__(mcls, *args, **kwargs):
718 new_calls.append('ANotMeta')
719 return super().__new__(mcls)
720 @classmethod
721 def __prepare__(mcls, name, bases):
722 prepare_calls.append('ANotMeta')
723 return {}
724 class BNotMeta(ANotMeta):
725 def __new__(mcls, *args, **kwargs):
726 new_calls.append('BNotMeta')
727 return super().__new__(mcls)
728 @classmethod
729 def __prepare__(mcls, name, bases):
730 prepare_calls.append('BNotMeta')
731 return super().__prepare__(name, bases)
732
733 class A(metaclass=ANotMeta):
734 pass
735 self.assertIs(ANotMeta, type(A))
736 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000737 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000738 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000739 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000740
741 class B(metaclass=BNotMeta):
742 pass
743 self.assertIs(BNotMeta, type(B))
744 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000745 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000746 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000747 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000748
749 class C(A, B):
750 pass
751 self.assertIs(BNotMeta, type(C))
752 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000753 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000754 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000755 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000756
757 class C2(B, A):
758 pass
759 self.assertIs(BNotMeta, type(C2))
760 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000761 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000762 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000763 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000764
765 # This is a TypeError, because of a metaclass conflict:
766 # BNotMeta is neither a subclass, nor a superclass of type
767 with self.assertRaises(TypeError):
768 class D(C, metaclass=type):
769 pass
770
771 class E(C, metaclass=ANotMeta):
772 pass
773 self.assertIs(BNotMeta, type(E))
774 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000775 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000776 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000777 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000778
779 class F(object(), C):
780 pass
781 self.assertIs(BNotMeta, type(F))
782 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000783 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000784 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000785 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000786
787 class F2(C, object()):
788 pass
789 self.assertIs(BNotMeta, type(F2))
790 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000791 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000792 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000793 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000794
795 # TypeError: BNotMeta is neither a
796 # subclass, nor a superclass of int
797 with self.assertRaises(TypeError):
798 class X(C, int()):
799 pass
800 with self.assertRaises(TypeError):
801 class X(int(), C):
802 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000803
804 def test_module_subclasses(self):
805 # Testing Python subclass of module...
806 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000807 MT = type(sys)
808 class MM(MT):
809 def __init__(self, name):
810 MT.__init__(self, name)
811 def __getattribute__(self, name):
812 log.append(("getattr", name))
813 return MT.__getattribute__(self, name)
814 def __setattr__(self, name, value):
815 log.append(("setattr", name, value))
816 MT.__setattr__(self, name, value)
817 def __delattr__(self, name):
818 log.append(("delattr", name))
819 MT.__delattr__(self, name)
820 a = MM("a")
821 a.foo = 12
822 x = a.foo
823 del a.foo
824 self.assertEqual(log, [("setattr", "foo", 12),
825 ("getattr", "foo"),
826 ("delattr", "foo")])
827
828 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000829 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000830 class Module(types.ModuleType, str):
831 pass
832 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000833 pass
834 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000835 self.fail("inheriting from ModuleType and str at the same time "
836 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000837
Georg Brandl479a7e72008-02-05 18:13:15 +0000838 def test_multiple_inheritance(self):
839 # Testing multiple inheritance...
840 class C(object):
841 def __init__(self):
842 self.__state = 0
843 def getstate(self):
844 return self.__state
845 def setstate(self, state):
846 self.__state = state
847 a = C()
848 self.assertEqual(a.getstate(), 0)
849 a.setstate(10)
850 self.assertEqual(a.getstate(), 10)
851 class D(dict, C):
852 def __init__(self):
853 type({}).__init__(self)
854 C.__init__(self)
855 d = D()
856 self.assertEqual(list(d.keys()), [])
857 d["hello"] = "world"
858 self.assertEqual(list(d.items()), [("hello", "world")])
859 self.assertEqual(d["hello"], "world")
860 self.assertEqual(d.getstate(), 0)
861 d.setstate(10)
862 self.assertEqual(d.getstate(), 10)
863 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000864
Georg Brandl479a7e72008-02-05 18:13:15 +0000865 # SF bug #442833
866 class Node(object):
867 def __int__(self):
868 return int(self.foo())
869 def foo(self):
870 return "23"
871 class Frag(Node, list):
872 def foo(self):
873 return "42"
874 self.assertEqual(Node().__int__(), 23)
875 self.assertEqual(int(Node()), 23)
876 self.assertEqual(Frag().__int__(), 42)
877 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000878
Georg Brandl479a7e72008-02-05 18:13:15 +0000879 def test_diamond_inheritence(self):
880 # Testing multiple inheritance special cases...
881 class A(object):
882 def spam(self): return "A"
883 self.assertEqual(A().spam(), "A")
884 class B(A):
885 def boo(self): return "B"
886 def spam(self): return "B"
887 self.assertEqual(B().spam(), "B")
888 self.assertEqual(B().boo(), "B")
889 class C(A):
890 def boo(self): return "C"
891 self.assertEqual(C().spam(), "A")
892 self.assertEqual(C().boo(), "C")
893 class D(B, C): pass
894 self.assertEqual(D().spam(), "B")
895 self.assertEqual(D().boo(), "B")
896 self.assertEqual(D.__mro__, (D, B, C, A, object))
897 class E(C, B): pass
898 self.assertEqual(E().spam(), "B")
899 self.assertEqual(E().boo(), "C")
900 self.assertEqual(E.__mro__, (E, C, B, A, object))
901 # MRO order disagreement
902 try:
903 class F(D, E): pass
904 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000905 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000906 else:
907 self.fail("expected MRO order disagreement (F)")
908 try:
909 class G(E, D): pass
910 except TypeError:
911 pass
912 else:
913 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000914
Georg Brandl479a7e72008-02-05 18:13:15 +0000915 # see thread python-dev/2002-October/029035.html
916 def test_ex5_from_c3_switch(self):
917 # Testing ex5 from C3 switch discussion...
918 class A(object): pass
919 class B(object): pass
920 class C(object): pass
921 class X(A): pass
922 class Y(A): pass
923 class Z(X,B,Y,C): pass
924 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000925
Georg Brandl479a7e72008-02-05 18:13:15 +0000926 # see "A Monotonic Superclass Linearization for Dylan",
927 # by Kim Barrett et al. (OOPSLA 1996)
928 def test_monotonicity(self):
929 # Testing MRO monotonicity...
930 class Boat(object): pass
931 class DayBoat(Boat): pass
932 class WheelBoat(Boat): pass
933 class EngineLess(DayBoat): pass
934 class SmallMultihull(DayBoat): pass
935 class PedalWheelBoat(EngineLess,WheelBoat): pass
936 class SmallCatamaran(SmallMultihull): pass
937 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000938
Georg Brandl479a7e72008-02-05 18:13:15 +0000939 self.assertEqual(PedalWheelBoat.__mro__,
940 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
941 self.assertEqual(SmallCatamaran.__mro__,
942 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
943 self.assertEqual(Pedalo.__mro__,
944 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
945 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000946
Georg Brandl479a7e72008-02-05 18:13:15 +0000947 # see "A Monotonic Superclass Linearization for Dylan",
948 # by Kim Barrett et al. (OOPSLA 1996)
949 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200950 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000951 class Pane(object): pass
952 class ScrollingMixin(object): pass
953 class EditingMixin(object): pass
954 class ScrollablePane(Pane,ScrollingMixin): pass
955 class EditablePane(Pane,EditingMixin): pass
956 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000957
Georg Brandl479a7e72008-02-05 18:13:15 +0000958 self.assertEqual(EditableScrollablePane.__mro__,
959 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
960 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000961
Georg Brandl479a7e72008-02-05 18:13:15 +0000962 def test_mro_disagreement(self):
963 # Testing error messages for MRO disagreement...
964 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000965order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000966
Georg Brandl479a7e72008-02-05 18:13:15 +0000967 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000968 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000969 callable(*args)
970 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000971 # the exact msg is generally considered an impl detail
972 if support.check_impl_detail():
973 if not str(msg).startswith(expected):
974 self.fail("Message %r, expected %r" %
975 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000976 else:
977 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000978
Georg Brandl479a7e72008-02-05 18:13:15 +0000979 class A(object): pass
980 class B(A): pass
981 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000982
Georg Brandl479a7e72008-02-05 18:13:15 +0000983 # Test some very simple errors
984 raises(TypeError, "duplicate base class A",
985 type, "X", (A, A), {})
986 raises(TypeError, mro_err_msg,
987 type, "X", (A, B), {})
988 raises(TypeError, mro_err_msg,
989 type, "X", (A, C, B), {})
990 # Test a slightly more complex error
991 class GridLayout(object): pass
992 class HorizontalGrid(GridLayout): pass
993 class VerticalGrid(GridLayout): pass
994 class HVGrid(HorizontalGrid, VerticalGrid): pass
995 class VHGrid(VerticalGrid, HorizontalGrid): pass
996 raises(TypeError, mro_err_msg,
997 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000998
Georg Brandl479a7e72008-02-05 18:13:15 +0000999 def test_object_class(self):
1000 # Testing object class...
1001 a = object()
1002 self.assertEqual(a.__class__, object)
1003 self.assertEqual(type(a), object)
1004 b = object()
1005 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001006 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001007 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001008 a.foo = 12
1009 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001010 pass
1011 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001012 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001013 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001014
Georg Brandl479a7e72008-02-05 18:13:15 +00001015 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001016 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001017 x = Cdict()
1018 self.assertEqual(x.__dict__, {})
1019 x.foo = 1
1020 self.assertEqual(x.foo, 1)
1021 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001022
Benjamin Peterson9d4cbcc2015-01-30 13:33:42 -05001023 def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1024 class SubType(types.ModuleType):
1025 a = 1
1026
1027 m = types.ModuleType("m")
1028 self.assertTrue(m.__class__ is types.ModuleType)
1029 self.assertFalse(hasattr(m, "a"))
1030
1031 m.__class__ = SubType
1032 self.assertTrue(m.__class__ is SubType)
1033 self.assertTrue(hasattr(m, "a"))
1034
1035 m.__class__ = types.ModuleType
1036 self.assertTrue(m.__class__ is types.ModuleType)
1037 self.assertFalse(hasattr(m, "a"))
1038
Guido van Rossum7d293ee2015-09-04 20:54:07 -07001039 # Make sure that builtin immutable objects don't support __class__
1040 # assignment, because the object instances may be interned.
1041 # We set __slots__ = () to ensure that the subclasses are
1042 # memory-layout compatible, and thus otherwise reasonable candidates
1043 # for __class__ assignment.
1044
1045 # The following types have immutable instances, but are not
1046 # subclassable and thus don't need to be checked:
1047 # NoneType, bool
1048
1049 class MyInt(int):
1050 __slots__ = ()
1051 with self.assertRaises(TypeError):
1052 (1).__class__ = MyInt
1053
1054 class MyFloat(float):
1055 __slots__ = ()
1056 with self.assertRaises(TypeError):
1057 (1.0).__class__ = MyFloat
1058
1059 class MyComplex(complex):
1060 __slots__ = ()
1061 with self.assertRaises(TypeError):
1062 (1 + 2j).__class__ = MyComplex
1063
1064 class MyStr(str):
1065 __slots__ = ()
1066 with self.assertRaises(TypeError):
1067 "a".__class__ = MyStr
1068
1069 class MyBytes(bytes):
1070 __slots__ = ()
1071 with self.assertRaises(TypeError):
1072 b"a".__class__ = MyBytes
1073
1074 class MyTuple(tuple):
1075 __slots__ = ()
1076 with self.assertRaises(TypeError):
1077 ().__class__ = MyTuple
1078
1079 class MyFrozenSet(frozenset):
1080 __slots__ = ()
1081 with self.assertRaises(TypeError):
1082 frozenset().__class__ = MyFrozenSet
1083
Georg Brandl479a7e72008-02-05 18:13:15 +00001084 def test_slots(self):
1085 # Testing __slots__...
1086 class C0(object):
1087 __slots__ = []
1088 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001089 self.assertNotHasAttr(x, "__dict__")
1090 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001091
1092 class C1(object):
1093 __slots__ = ['a']
1094 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001095 self.assertNotHasAttr(x, "__dict__")
1096 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001097 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001098 self.assertEqual(x.a, 1)
1099 x.a = None
1100 self.assertEqual(x.a, None)
1101 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001102 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001103
Georg Brandl479a7e72008-02-05 18:13:15 +00001104 class C3(object):
1105 __slots__ = ['a', 'b', 'c']
1106 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001107 self.assertNotHasAttr(x, "__dict__")
1108 self.assertNotHasAttr(x, 'a')
1109 self.assertNotHasAttr(x, 'b')
1110 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001111 x.a = 1
1112 x.b = 2
1113 x.c = 3
1114 self.assertEqual(x.a, 1)
1115 self.assertEqual(x.b, 2)
1116 self.assertEqual(x.c, 3)
1117
1118 class C4(object):
1119 """Validate name mangling"""
1120 __slots__ = ['__a']
1121 def __init__(self, value):
1122 self.__a = value
1123 def get(self):
1124 return self.__a
1125 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001126 self.assertNotHasAttr(x, '__dict__')
1127 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001128 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001129 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001130 x.__a = 6
1131 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001132 pass
1133 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001134 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001135
Georg Brandl479a7e72008-02-05 18:13:15 +00001136 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001137 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001138 class C(object):
1139 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001140 except TypeError:
1141 pass
1142 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001143 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001144 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001145 class C(object):
1146 __slots__ = ["foo bar"]
1147 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001148 pass
1149 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001150 self.fail("['foo bar'] slots not caught")
1151 try:
1152 class C(object):
1153 __slots__ = ["foo\0bar"]
1154 except TypeError:
1155 pass
1156 else:
1157 self.fail("['foo\\0bar'] slots not caught")
1158 try:
1159 class C(object):
1160 __slots__ = ["1"]
1161 except TypeError:
1162 pass
1163 else:
1164 self.fail("['1'] slots not caught")
1165 try:
1166 class C(object):
1167 __slots__ = [""]
1168 except TypeError:
1169 pass
1170 else:
1171 self.fail("[''] slots not caught")
1172 class C(object):
1173 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1174 # XXX(nnorwitz): was there supposed to be something tested
1175 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001176
Georg Brandl479a7e72008-02-05 18:13:15 +00001177 # Test a single string is not expanded as a sequence.
1178 class C(object):
1179 __slots__ = "abc"
1180 c = C()
1181 c.abc = 5
1182 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001183
Georg Brandl479a7e72008-02-05 18:13:15 +00001184 # Test unicode slot names
1185 # Test a single unicode string is not expanded as a sequence.
1186 class C(object):
1187 __slots__ = "abc"
1188 c = C()
1189 c.abc = 5
1190 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001191
Georg Brandl479a7e72008-02-05 18:13:15 +00001192 # _unicode_to_string used to modify slots in certain circumstances
1193 slots = ("foo", "bar")
1194 class C(object):
1195 __slots__ = slots
1196 x = C()
1197 x.foo = 5
1198 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001199 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001200 # this used to leak references
1201 try:
1202 class C(object):
1203 __slots__ = [chr(128)]
1204 except (TypeError, UnicodeEncodeError):
1205 pass
1206 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001207 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001208
Georg Brandl479a7e72008-02-05 18:13:15 +00001209 # Test leaks
1210 class Counted(object):
1211 counter = 0 # counts the number of instances alive
1212 def __init__(self):
1213 Counted.counter += 1
1214 def __del__(self):
1215 Counted.counter -= 1
1216 class C(object):
1217 __slots__ = ['a', 'b', 'c']
1218 x = C()
1219 x.a = Counted()
1220 x.b = Counted()
1221 x.c = Counted()
1222 self.assertEqual(Counted.counter, 3)
1223 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001224 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001225 self.assertEqual(Counted.counter, 0)
1226 class D(C):
1227 pass
1228 x = D()
1229 x.a = Counted()
1230 x.z = Counted()
1231 self.assertEqual(Counted.counter, 2)
1232 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001233 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001234 self.assertEqual(Counted.counter, 0)
1235 class E(D):
1236 __slots__ = ['e']
1237 x = E()
1238 x.a = Counted()
1239 x.z = Counted()
1240 x.e = Counted()
1241 self.assertEqual(Counted.counter, 3)
1242 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001243 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001244 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001245
Georg Brandl479a7e72008-02-05 18:13:15 +00001246 # Test cyclical leaks [SF bug 519621]
1247 class F(object):
1248 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001249 s = F()
1250 s.a = [Counted(), s]
1251 self.assertEqual(Counted.counter, 1)
1252 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001253 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001254 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001255
Georg Brandl479a7e72008-02-05 18:13:15 +00001256 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001257 if hasattr(gc, 'get_objects'):
1258 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001259 def __eq__(self, other):
1260 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001261 g = G()
1262 orig_objects = len(gc.get_objects())
1263 for i in range(10):
1264 g==g
1265 new_objects = len(gc.get_objects())
1266 self.assertEqual(orig_objects, new_objects)
1267
Georg Brandl479a7e72008-02-05 18:13:15 +00001268 class H(object):
1269 __slots__ = ['a', 'b']
1270 def __init__(self):
1271 self.a = 1
1272 self.b = 2
1273 def __del__(self_):
1274 self.assertEqual(self_.a, 1)
1275 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001276 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001277 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001278 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001279 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001280
Benjamin Petersond12362a2009-12-30 19:44:54 +00001281 class X(object):
1282 __slots__ = "a"
1283 with self.assertRaises(AttributeError):
1284 del X().a
1285
Georg Brandl479a7e72008-02-05 18:13:15 +00001286 def test_slots_special(self):
1287 # Testing __dict__ and __weakref__ in __slots__...
1288 class D(object):
1289 __slots__ = ["__dict__"]
1290 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001291 self.assertHasAttr(a, "__dict__")
1292 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001293 a.foo = 42
1294 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001295
Georg Brandl479a7e72008-02-05 18:13:15 +00001296 class W(object):
1297 __slots__ = ["__weakref__"]
1298 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001299 self.assertHasAttr(a, "__weakref__")
1300 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001301 try:
1302 a.foo = 42
1303 except AttributeError:
1304 pass
1305 else:
1306 self.fail("shouldn't be allowed to set a.foo")
1307
1308 class C1(W, D):
1309 __slots__ = []
1310 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001311 self.assertHasAttr(a, "__dict__")
1312 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001313 a.foo = 42
1314 self.assertEqual(a.__dict__, {"foo": 42})
1315
1316 class C2(D, W):
1317 __slots__ = []
1318 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001319 self.assertHasAttr(a, "__dict__")
1320 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001321 a.foo = 42
1322 self.assertEqual(a.__dict__, {"foo": 42})
1323
Christian Heimesa156e092008-02-16 07:38:31 +00001324 def test_slots_descriptor(self):
1325 # Issue2115: slot descriptors did not correctly check
1326 # the type of the given object
1327 import abc
1328 class MyABC(metaclass=abc.ABCMeta):
1329 __slots__ = "a"
1330
1331 class Unrelated(object):
1332 pass
1333 MyABC.register(Unrelated)
1334
1335 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001336 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001337
1338 # This used to crash
1339 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1340
Georg Brandl479a7e72008-02-05 18:13:15 +00001341 def test_dynamics(self):
1342 # Testing class attribute propagation...
1343 class D(object):
1344 pass
1345 class E(D):
1346 pass
1347 class F(D):
1348 pass
1349 D.foo = 1
1350 self.assertEqual(D.foo, 1)
1351 # Test that dynamic attributes are inherited
1352 self.assertEqual(E.foo, 1)
1353 self.assertEqual(F.foo, 1)
1354 # Test dynamic instances
1355 class C(object):
1356 pass
1357 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001358 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001359 C.foobar = 2
1360 self.assertEqual(a.foobar, 2)
1361 C.method = lambda self: 42
1362 self.assertEqual(a.method(), 42)
1363 C.__repr__ = lambda self: "C()"
1364 self.assertEqual(repr(a), "C()")
1365 C.__int__ = lambda self: 100
1366 self.assertEqual(int(a), 100)
1367 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001368 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001369 def mygetattr(self, name):
1370 if name == "spam":
1371 return "spam"
1372 raise AttributeError
1373 C.__getattr__ = mygetattr
1374 self.assertEqual(a.spam, "spam")
1375 a.new = 12
1376 self.assertEqual(a.new, 12)
1377 def mysetattr(self, name, value):
1378 if name == "spam":
1379 raise AttributeError
1380 return object.__setattr__(self, name, value)
1381 C.__setattr__ = mysetattr
1382 try:
1383 a.spam = "not spam"
1384 except AttributeError:
1385 pass
1386 else:
1387 self.fail("expected AttributeError")
1388 self.assertEqual(a.spam, "spam")
1389 class D(C):
1390 pass
1391 d = D()
1392 d.foo = 1
1393 self.assertEqual(d.foo, 1)
1394
1395 # Test handling of int*seq and seq*int
1396 class I(int):
1397 pass
1398 self.assertEqual("a"*I(2), "aa")
1399 self.assertEqual(I(2)*"a", "aa")
1400 self.assertEqual(2*I(3), 6)
1401 self.assertEqual(I(3)*2, 6)
1402 self.assertEqual(I(3)*I(2), 6)
1403
Georg Brandl479a7e72008-02-05 18:13:15 +00001404 # Test comparison of classes with dynamic metaclasses
1405 class dynamicmetaclass(type):
1406 pass
1407 class someclass(metaclass=dynamicmetaclass):
1408 pass
1409 self.assertNotEqual(someclass, object)
1410
1411 def test_errors(self):
1412 # Testing errors...
1413 try:
1414 class C(list, dict):
1415 pass
1416 except TypeError:
1417 pass
1418 else:
1419 self.fail("inheritance from both list and dict should be illegal")
1420
1421 try:
1422 class C(object, None):
1423 pass
1424 except TypeError:
1425 pass
1426 else:
1427 self.fail("inheritance from non-type should be illegal")
1428 class Classic:
1429 pass
1430
1431 try:
1432 class C(type(len)):
1433 pass
1434 except TypeError:
1435 pass
1436 else:
1437 self.fail("inheritance from CFunction should be illegal")
1438
1439 try:
1440 class C(object):
1441 __slots__ = 1
1442 except TypeError:
1443 pass
1444 else:
1445 self.fail("__slots__ = 1 should be illegal")
1446
1447 try:
1448 class C(object):
1449 __slots__ = [1]
1450 except TypeError:
1451 pass
1452 else:
1453 self.fail("__slots__ = [1] should be illegal")
1454
1455 class M1(type):
1456 pass
1457 class M2(type):
1458 pass
1459 class A1(object, metaclass=M1):
1460 pass
1461 class A2(object, metaclass=M2):
1462 pass
1463 try:
1464 class B(A1, A2):
1465 pass
1466 except TypeError:
1467 pass
1468 else:
1469 self.fail("finding the most derived metaclass should have failed")
1470
1471 def test_classmethods(self):
1472 # Testing class methods...
1473 class C(object):
1474 def foo(*a): return a
1475 goo = classmethod(foo)
1476 c = C()
1477 self.assertEqual(C.goo(1), (C, 1))
1478 self.assertEqual(c.goo(1), (C, 1))
1479 self.assertEqual(c.foo(1), (c, 1))
1480 class D(C):
1481 pass
1482 d = D()
1483 self.assertEqual(D.goo(1), (D, 1))
1484 self.assertEqual(d.goo(1), (D, 1))
1485 self.assertEqual(d.foo(1), (d, 1))
1486 self.assertEqual(D.foo(d, 1), (d, 1))
1487 # Test for a specific crash (SF bug 528132)
1488 def f(cls, arg): return (cls, arg)
1489 ff = classmethod(f)
1490 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1491 self.assertEqual(ff.__get__(0)(42), (int, 42))
1492
1493 # Test super() with classmethods (SF bug 535444)
1494 self.assertEqual(C.goo.__self__, C)
1495 self.assertEqual(D.goo.__self__, D)
1496 self.assertEqual(super(D,D).goo.__self__, D)
1497 self.assertEqual(super(D,d).goo.__self__, D)
1498 self.assertEqual(super(D,D).goo(), (D,))
1499 self.assertEqual(super(D,d).goo(), (D,))
1500
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001501 # Verify that a non-callable will raise
1502 meth = classmethod(1).__get__(1)
1503 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001504
1505 # Verify that classmethod() doesn't allow keyword args
1506 try:
1507 classmethod(f, kw=1)
1508 except TypeError:
1509 pass
1510 else:
1511 self.fail("classmethod shouldn't accept keyword args")
1512
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001513 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001514 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001515 cm.x = 42
1516 self.assertEqual(cm.x, 42)
1517 self.assertEqual(cm.__dict__, {"x" : 42})
1518 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001519 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001520
Benjamin Petersone549ead2009-03-28 21:42:05 +00001521 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001522 def test_classmethods_in_c(self):
1523 # Testing C-based class methods...
1524 import xxsubtype as spam
1525 a = (1, 2, 3)
1526 d = {'abc': 123}
1527 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1528 self.assertEqual(x, spam.spamlist)
1529 self.assertEqual(a, a1)
1530 self.assertEqual(d, d1)
1531 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1532 self.assertEqual(x, spam.spamlist)
1533 self.assertEqual(a, a1)
1534 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001535 spam_cm = spam.spamlist.__dict__['classmeth']
1536 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1537 self.assertEqual(x2, spam.spamlist)
1538 self.assertEqual(a2, a1)
1539 self.assertEqual(d2, d1)
1540 class SubSpam(spam.spamlist): pass
1541 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1542 self.assertEqual(x2, SubSpam)
1543 self.assertEqual(a2, a1)
1544 self.assertEqual(d2, d1)
1545 with self.assertRaises(TypeError):
1546 spam_cm()
1547 with self.assertRaises(TypeError):
1548 spam_cm(spam.spamlist())
1549 with self.assertRaises(TypeError):
1550 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001551
1552 def test_staticmethods(self):
1553 # Testing static methods...
1554 class C(object):
1555 def foo(*a): return a
1556 goo = staticmethod(foo)
1557 c = C()
1558 self.assertEqual(C.goo(1), (1,))
1559 self.assertEqual(c.goo(1), (1,))
1560 self.assertEqual(c.foo(1), (c, 1,))
1561 class D(C):
1562 pass
1563 d = D()
1564 self.assertEqual(D.goo(1), (1,))
1565 self.assertEqual(d.goo(1), (1,))
1566 self.assertEqual(d.foo(1), (d, 1))
1567 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001568 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001569 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001570 sm.x = 42
1571 self.assertEqual(sm.x, 42)
1572 self.assertEqual(sm.__dict__, {"x" : 42})
1573 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001574 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001575
Benjamin Petersone549ead2009-03-28 21:42:05 +00001576 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001577 def test_staticmethods_in_c(self):
1578 # Testing C-based static methods...
1579 import xxsubtype as spam
1580 a = (1, 2, 3)
1581 d = {"abc": 123}
1582 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1583 self.assertEqual(x, None)
1584 self.assertEqual(a, a1)
1585 self.assertEqual(d, d1)
1586 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1587 self.assertEqual(x, None)
1588 self.assertEqual(a, a1)
1589 self.assertEqual(d, d1)
1590
1591 def test_classic(self):
1592 # Testing classic classes...
1593 class C:
1594 def foo(*a): return a
1595 goo = classmethod(foo)
1596 c = C()
1597 self.assertEqual(C.goo(1), (C, 1))
1598 self.assertEqual(c.goo(1), (C, 1))
1599 self.assertEqual(c.foo(1), (c, 1))
1600 class D(C):
1601 pass
1602 d = D()
1603 self.assertEqual(D.goo(1), (D, 1))
1604 self.assertEqual(d.goo(1), (D, 1))
1605 self.assertEqual(d.foo(1), (d, 1))
1606 self.assertEqual(D.foo(d, 1), (d, 1))
1607 class E: # *not* subclassing from C
1608 foo = C.foo
1609 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001610 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001611
1612 def test_compattr(self):
1613 # Testing computed attributes...
1614 class C(object):
1615 class computed_attribute(object):
1616 def __init__(self, get, set=None, delete=None):
1617 self.__get = get
1618 self.__set = set
1619 self.__delete = delete
1620 def __get__(self, obj, type=None):
1621 return self.__get(obj)
1622 def __set__(self, obj, value):
1623 return self.__set(obj, value)
1624 def __delete__(self, obj):
1625 return self.__delete(obj)
1626 def __init__(self):
1627 self.__x = 0
1628 def __get_x(self):
1629 x = self.__x
1630 self.__x = x+1
1631 return x
1632 def __set_x(self, x):
1633 self.__x = x
1634 def __delete_x(self):
1635 del self.__x
1636 x = computed_attribute(__get_x, __set_x, __delete_x)
1637 a = C()
1638 self.assertEqual(a.x, 0)
1639 self.assertEqual(a.x, 1)
1640 a.x = 10
1641 self.assertEqual(a.x, 10)
1642 self.assertEqual(a.x, 11)
1643 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001644 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001645
1646 def test_newslots(self):
1647 # Testing __new__ slot override...
1648 class C(list):
1649 def __new__(cls):
1650 self = list.__new__(cls)
1651 self.foo = 1
1652 return self
1653 def __init__(self):
1654 self.foo = self.foo + 2
1655 a = C()
1656 self.assertEqual(a.foo, 3)
1657 self.assertEqual(a.__class__, C)
1658 class D(C):
1659 pass
1660 b = D()
1661 self.assertEqual(b.foo, 3)
1662 self.assertEqual(b.__class__, D)
1663
1664 def test_altmro(self):
1665 # Testing mro() and overriding it...
1666 class A(object):
1667 def f(self): return "A"
1668 class B(A):
1669 pass
1670 class C(A):
1671 def f(self): return "C"
1672 class D(B, C):
1673 pass
1674 self.assertEqual(D.mro(), [D, B, C, A, object])
1675 self.assertEqual(D.__mro__, (D, B, C, A, object))
1676 self.assertEqual(D().f(), "C")
1677
1678 class PerverseMetaType(type):
1679 def mro(cls):
1680 L = type.mro(cls)
1681 L.reverse()
1682 return L
1683 class X(D,B,C,A, metaclass=PerverseMetaType):
1684 pass
1685 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1686 self.assertEqual(X().f(), "A")
1687
1688 try:
1689 class _metaclass(type):
1690 def mro(self):
1691 return [self, dict, object]
1692 class X(object, metaclass=_metaclass):
1693 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001694 # In CPython, the class creation above already raises
1695 # TypeError, as a protection against the fact that
1696 # instances of X would segfault it. In other Python
1697 # implementations it would be ok to let the class X
1698 # be created, but instead get a clean TypeError on the
1699 # __setitem__ below.
1700 x = object.__new__(X)
1701 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001702 except TypeError:
1703 pass
1704 else:
1705 self.fail("devious mro() return not caught")
1706
1707 try:
1708 class _metaclass(type):
1709 def mro(self):
1710 return [1]
1711 class X(object, metaclass=_metaclass):
1712 pass
1713 except TypeError:
1714 pass
1715 else:
1716 self.fail("non-class mro() return not caught")
1717
1718 try:
1719 class _metaclass(type):
1720 def mro(self):
1721 return 1
1722 class X(object, metaclass=_metaclass):
1723 pass
1724 except TypeError:
1725 pass
1726 else:
1727 self.fail("non-sequence mro() return not caught")
1728
1729 def test_overloading(self):
1730 # Testing operator overloading...
1731
1732 class B(object):
1733 "Intermediate class because object doesn't have a __setattr__"
1734
1735 class C(B):
1736 def __getattr__(self, name):
1737 if name == "foo":
1738 return ("getattr", name)
1739 else:
1740 raise AttributeError
1741 def __setattr__(self, name, value):
1742 if name == "foo":
1743 self.setattr = (name, value)
1744 else:
1745 return B.__setattr__(self, name, value)
1746 def __delattr__(self, name):
1747 if name == "foo":
1748 self.delattr = name
1749 else:
1750 return B.__delattr__(self, name)
1751
1752 def __getitem__(self, key):
1753 return ("getitem", key)
1754 def __setitem__(self, key, value):
1755 self.setitem = (key, value)
1756 def __delitem__(self, key):
1757 self.delitem = key
1758
1759 a = C()
1760 self.assertEqual(a.foo, ("getattr", "foo"))
1761 a.foo = 12
1762 self.assertEqual(a.setattr, ("foo", 12))
1763 del a.foo
1764 self.assertEqual(a.delattr, "foo")
1765
1766 self.assertEqual(a[12], ("getitem", 12))
1767 a[12] = 21
1768 self.assertEqual(a.setitem, (12, 21))
1769 del a[12]
1770 self.assertEqual(a.delitem, 12)
1771
1772 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1773 a[0:10] = "foo"
1774 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1775 del a[0:10]
1776 self.assertEqual(a.delitem, (slice(0, 10)))
1777
1778 def test_methods(self):
1779 # Testing methods...
1780 class C(object):
1781 def __init__(self, x):
1782 self.x = x
1783 def foo(self):
1784 return self.x
1785 c1 = C(1)
1786 self.assertEqual(c1.foo(), 1)
1787 class D(C):
1788 boo = C.foo
1789 goo = c1.foo
1790 d2 = D(2)
1791 self.assertEqual(d2.foo(), 2)
1792 self.assertEqual(d2.boo(), 2)
1793 self.assertEqual(d2.goo(), 1)
1794 class E(object):
1795 foo = C.foo
1796 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001797 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001798
Benjamin Peterson224205f2009-05-08 03:25:19 +00001799 def test_special_method_lookup(self):
1800 # The lookup of special methods bypasses __getattr__ and
1801 # __getattribute__, but they still can be descriptors.
1802
1803 def run_context(manager):
1804 with manager:
1805 pass
1806 def iden(self):
1807 return self
1808 def hello(self):
1809 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001810 def empty_seq(self):
1811 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001812 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001813 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001814 def complex_num(self):
1815 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001816 def stop(self):
1817 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001818 def return_true(self, thing=None):
1819 return True
1820 def do_isinstance(obj):
1821 return isinstance(int, obj)
1822 def do_issubclass(obj):
1823 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001824 def do_dict_missing(checker):
1825 class DictSub(checker.__class__, dict):
1826 pass
1827 self.assertEqual(DictSub()["hi"], 4)
1828 def some_number(self_, key):
1829 self.assertEqual(key, "hi")
1830 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001831 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001832 def format_impl(self, spec):
1833 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001834
1835 # It would be nice to have every special method tested here, but I'm
1836 # only listing the ones I can remember outside of typeobject.c, since it
1837 # does it right.
1838 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001839 ("__bytes__", bytes, hello, set(), {}),
1840 ("__reversed__", reversed, empty_seq, set(), {}),
1841 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001842 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001843 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1844 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001845 ("__missing__", do_dict_missing, some_number,
1846 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001847 ("__subclasscheck__", do_issubclass, return_true,
1848 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001849 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1850 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001851 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001852 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001853 ("__floor__", math.floor, zero, set(), {}),
1854 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001855 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001856 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001857 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001858 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001859 ]
1860
1861 class Checker(object):
1862 def __getattr__(self, attr, test=self):
1863 test.fail("__getattr__ called with {0}".format(attr))
1864 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001865 if attr not in ok:
1866 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001867 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001868 class SpecialDescr(object):
1869 def __init__(self, impl):
1870 self.impl = impl
1871 def __get__(self, obj, owner):
1872 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001873 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001874 class MyException(Exception):
1875 pass
1876 class ErrDescr(object):
1877 def __get__(self, obj, owner):
1878 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001879
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001880 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001881 class X(Checker):
1882 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001883 for attr, obj in env.items():
1884 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001885 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001886 runner(X())
1887
1888 record = []
1889 class X(Checker):
1890 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001891 for attr, obj in env.items():
1892 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001893 setattr(X, name, SpecialDescr(meth_impl))
1894 runner(X())
1895 self.assertEqual(record, [1], name)
1896
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001897 class X(Checker):
1898 pass
1899 for attr, obj in env.items():
1900 setattr(X, attr, obj)
1901 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001902 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001903
Georg Brandl479a7e72008-02-05 18:13:15 +00001904 def test_specials(self):
1905 # Testing special operators...
1906 # Test operators like __hash__ for which a built-in default exists
1907
1908 # Test the default behavior for static classes
1909 class C(object):
1910 def __getitem__(self, i):
1911 if 0 <= i < 10: return i
1912 raise IndexError
1913 c1 = C()
1914 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001915 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001916 self.assertNotEqual(id(c1), id(c2))
1917 hash(c1)
1918 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001919 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001920 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001921 self.assertFalse(c1 != c1)
1922 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001923 # Note that the module name appears in str/repr, and that varies
1924 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001925 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001926 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001927 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001928 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001929 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001930 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001931 # Test the default behavior for dynamic classes
1932 class D(object):
1933 def __getitem__(self, i):
1934 if 0 <= i < 10: return i
1935 raise IndexError
1936 d1 = D()
1937 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001938 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001939 self.assertNotEqual(id(d1), id(d2))
1940 hash(d1)
1941 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001942 self.assertEqual(d1, d1)
1943 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001944 self.assertFalse(d1 != d1)
1945 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001946 # Note that the module name appears in str/repr, and that varies
1947 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001948 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001949 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001950 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001951 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001952 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001953 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001954 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001955 class Proxy(object):
1956 def __init__(self, x):
1957 self.x = x
1958 def __bool__(self):
1959 return not not self.x
1960 def __hash__(self):
1961 return hash(self.x)
1962 def __eq__(self, other):
1963 return self.x == other
1964 def __ne__(self, other):
1965 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001966 def __ge__(self, other):
1967 return self.x >= other
1968 def __gt__(self, other):
1969 return self.x > other
1970 def __le__(self, other):
1971 return self.x <= other
1972 def __lt__(self, other):
1973 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001974 def __str__(self):
1975 return "Proxy:%s" % self.x
1976 def __repr__(self):
1977 return "Proxy(%r)" % self.x
1978 def __contains__(self, value):
1979 return value in self.x
1980 p0 = Proxy(0)
1981 p1 = Proxy(1)
1982 p_1 = Proxy(-1)
1983 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001984 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001985 self.assertEqual(hash(p0), hash(0))
1986 self.assertEqual(p0, p0)
1987 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001988 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001989 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001990 self.assertTrue(p0 < p1)
1991 self.assertTrue(p0 <= p1)
1992 self.assertTrue(p1 > p0)
1993 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001994 self.assertEqual(str(p0), "Proxy:0")
1995 self.assertEqual(repr(p0), "Proxy(0)")
1996 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001997 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001998 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001999 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00002000 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00002001
Georg Brandl479a7e72008-02-05 18:13:15 +00002002 def test_weakrefs(self):
2003 # Testing weak references...
2004 import weakref
2005 class C(object):
2006 pass
2007 c = C()
2008 r = weakref.ref(c)
2009 self.assertEqual(r(), c)
2010 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00002011 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002012 self.assertEqual(r(), None)
2013 del r
2014 class NoWeak(object):
2015 __slots__ = ['foo']
2016 no = NoWeak()
2017 try:
2018 weakref.ref(no)
2019 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002020 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00002021 else:
2022 self.fail("weakref.ref(no) should be illegal")
2023 class Weak(object):
2024 __slots__ = ['foo', '__weakref__']
2025 yes = Weak()
2026 r = weakref.ref(yes)
2027 self.assertEqual(r(), yes)
2028 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00002029 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00002030 self.assertEqual(r(), None)
2031 del r
2032
2033 def test_properties(self):
2034 # Testing property...
2035 class C(object):
2036 def getx(self):
2037 return self.__x
2038 def setx(self, value):
2039 self.__x = value
2040 def delx(self):
2041 del self.__x
2042 x = property(getx, setx, delx, doc="I'm the x property.")
2043 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002044 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002045 a.x = 42
2046 self.assertEqual(a._C__x, 42)
2047 self.assertEqual(a.x, 42)
2048 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002049 self.assertNotHasAttr(a, "x")
2050 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002051 C.x.__set__(a, 100)
2052 self.assertEqual(C.x.__get__(a), 100)
2053 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002054 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002055
2056 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002057 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002058
2059 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002060 self.assertIn("__doc__", attrs)
2061 self.assertIn("fget", attrs)
2062 self.assertIn("fset", attrs)
2063 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002064
2065 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002066 self.assertIs(raw.fget, C.__dict__['getx'])
2067 self.assertIs(raw.fset, C.__dict__['setx'])
2068 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002069
Raymond Hettingereac503a2015-05-13 01:09:59 -07002070 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002071 try:
2072 setattr(raw, attr, 42)
2073 except AttributeError as msg:
2074 if str(msg).find('readonly') < 0:
2075 self.fail("when setting readonly attr %r on a property, "
2076 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2077 else:
2078 self.fail("expected AttributeError from trying to set readonly %r "
2079 "attr on a property" % attr)
2080
Raymond Hettingereac503a2015-05-13 01:09:59 -07002081 raw.__doc__ = 42
2082 self.assertEqual(raw.__doc__, 42)
2083
Georg Brandl479a7e72008-02-05 18:13:15 +00002084 class D(object):
2085 __getitem__ = property(lambda s: 1/0)
2086
2087 d = D()
2088 try:
2089 for i in d:
2090 str(i)
2091 except ZeroDivisionError:
2092 pass
2093 else:
2094 self.fail("expected ZeroDivisionError from bad property")
2095
R. David Murray378c0cf2010-02-24 01:46:21 +00002096 @unittest.skipIf(sys.flags.optimize >= 2,
2097 "Docstrings are omitted with -O2 and above")
2098 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002099 class E(object):
2100 def getter(self):
2101 "getter method"
2102 return 0
2103 def setter(self_, value):
2104 "setter method"
2105 pass
2106 prop = property(getter)
2107 self.assertEqual(prop.__doc__, "getter method")
2108 prop2 = property(fset=setter)
2109 self.assertEqual(prop2.__doc__, None)
2110
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002111 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002112 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002113 # this segfaulted in 2.5b2
2114 try:
2115 import _testcapi
2116 except ImportError:
2117 pass
2118 else:
2119 class X(object):
2120 p = property(_testcapi.test_with_docstring)
2121
2122 def test_properties_plus(self):
2123 class C(object):
2124 foo = property(doc="hello")
2125 @foo.getter
2126 def foo(self):
2127 return self._foo
2128 @foo.setter
2129 def foo(self, value):
2130 self._foo = abs(value)
2131 @foo.deleter
2132 def foo(self):
2133 del self._foo
2134 c = C()
2135 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002136 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002137 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002138 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002139 self.assertEqual(c._foo, 42)
2140 self.assertEqual(c.foo, 42)
2141 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002142 self.assertNotHasAttr(c, '_foo')
2143 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002144
2145 class D(C):
2146 @C.foo.deleter
2147 def foo(self):
2148 try:
2149 del self._foo
2150 except AttributeError:
2151 pass
2152 d = D()
2153 d.foo = 24
2154 self.assertEqual(d.foo, 24)
2155 del d.foo
2156 del d.foo
2157
2158 class E(object):
2159 @property
2160 def foo(self):
2161 return self._foo
2162 @foo.setter
2163 def foo(self, value):
2164 raise RuntimeError
2165 @foo.setter
2166 def foo(self, value):
2167 self._foo = abs(value)
2168 @foo.deleter
2169 def foo(self, value=None):
2170 del self._foo
2171
2172 e = E()
2173 e.foo = -42
2174 self.assertEqual(e.foo, 42)
2175 del e.foo
2176
2177 class F(E):
2178 @E.foo.deleter
2179 def foo(self):
2180 del self._foo
2181 @foo.setter
2182 def foo(self, value):
2183 self._foo = max(0, value)
2184 f = F()
2185 f.foo = -10
2186 self.assertEqual(f.foo, 0)
2187 del f.foo
2188
2189 def test_dict_constructors(self):
2190 # Testing dict constructor ...
2191 d = dict()
2192 self.assertEqual(d, {})
2193 d = dict({})
2194 self.assertEqual(d, {})
2195 d = dict({1: 2, 'a': 'b'})
2196 self.assertEqual(d, {1: 2, 'a': 'b'})
2197 self.assertEqual(d, dict(list(d.items())))
2198 self.assertEqual(d, dict(iter(d.items())))
2199 d = dict({'one':1, 'two':2})
2200 self.assertEqual(d, dict(one=1, two=2))
2201 self.assertEqual(d, dict(**d))
2202 self.assertEqual(d, dict({"one": 1}, two=2))
2203 self.assertEqual(d, dict([("two", 2)], one=1))
2204 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2205 self.assertEqual(d, dict(**d))
2206
2207 for badarg in 0, 0, 0j, "0", [0], (0,):
2208 try:
2209 dict(badarg)
2210 except TypeError:
2211 pass
2212 except ValueError:
2213 if badarg == "0":
2214 # It's a sequence, and its elements are also sequences (gotta
2215 # love strings <wink>), but they aren't of length 2, so this
2216 # one seemed better as a ValueError than a TypeError.
2217 pass
2218 else:
2219 self.fail("no TypeError from dict(%r)" % badarg)
2220 else:
2221 self.fail("no TypeError from dict(%r)" % badarg)
2222
2223 try:
2224 dict({}, {})
2225 except TypeError:
2226 pass
2227 else:
2228 self.fail("no TypeError from dict({}, {})")
2229
2230 class Mapping:
2231 # Lacks a .keys() method; will be added later.
2232 dict = {1:2, 3:4, 'a':1j}
2233
2234 try:
2235 dict(Mapping())
2236 except TypeError:
2237 pass
2238 else:
2239 self.fail("no TypeError from dict(incomplete mapping)")
2240
2241 Mapping.keys = lambda self: list(self.dict.keys())
2242 Mapping.__getitem__ = lambda self, i: self.dict[i]
2243 d = dict(Mapping())
2244 self.assertEqual(d, Mapping.dict)
2245
2246 # Init from sequence of iterable objects, each producing a 2-sequence.
2247 class AddressBookEntry:
2248 def __init__(self, first, last):
2249 self.first = first
2250 self.last = last
2251 def __iter__(self):
2252 return iter([self.first, self.last])
2253
2254 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2255 AddressBookEntry('Barry', 'Peters'),
2256 AddressBookEntry('Tim', 'Peters'),
2257 AddressBookEntry('Barry', 'Warsaw')])
2258 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2259
2260 d = dict(zip(range(4), range(1, 5)))
2261 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2262
2263 # Bad sequence lengths.
2264 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2265 try:
2266 dict(bad)
2267 except ValueError:
2268 pass
2269 else:
2270 self.fail("no ValueError from dict(%r)" % bad)
2271
2272 def test_dir(self):
2273 # Testing dir() ...
2274 junk = 12
2275 self.assertEqual(dir(), ['junk', 'self'])
2276 del junk
2277
2278 # Just make sure these don't blow up!
2279 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2280 dir(arg)
2281
2282 # Test dir on new-style classes. Since these have object as a
2283 # base class, a lot more gets sucked in.
2284 def interesting(strings):
2285 return [s for s in strings if not s.startswith('_')]
2286
2287 class C(object):
2288 Cdata = 1
2289 def Cmethod(self): pass
2290
2291 cstuff = ['Cdata', 'Cmethod']
2292 self.assertEqual(interesting(dir(C)), cstuff)
2293
2294 c = C()
2295 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002296 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002297
2298 c.cdata = 2
2299 c.cmethod = lambda self: 0
2300 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002301 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002302
2303 class A(C):
2304 Adata = 1
2305 def Amethod(self): pass
2306
2307 astuff = ['Adata', 'Amethod'] + cstuff
2308 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002309 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002310 a = A()
2311 self.assertEqual(interesting(dir(a)), astuff)
2312 a.adata = 42
2313 a.amethod = lambda self: 3
2314 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002315 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002316
2317 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002318 class M(type(sys)):
2319 pass
2320 minstance = M("m")
2321 minstance.b = 2
2322 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002323 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002324 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002325 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002326 self.assertEqual(names, ['a', 'b'])
2327
2328 class M2(M):
2329 def getdict(self):
2330 return "Not a dict!"
2331 __dict__ = property(getdict)
2332
2333 m2instance = M2("m2")
2334 m2instance.b = 2
2335 m2instance.a = 1
2336 self.assertEqual(m2instance.__dict__, "Not a dict!")
2337 try:
2338 dir(m2instance)
2339 except TypeError:
2340 pass
2341
2342 # Two essentially featureless objects, just inheriting stuff from
2343 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002344 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002345
2346 # Nasty test case for proxied objects
2347 class Wrapper(object):
2348 def __init__(self, obj):
2349 self.__obj = obj
2350 def __repr__(self):
2351 return "Wrapper(%s)" % repr(self.__obj)
2352 def __getitem__(self, key):
2353 return Wrapper(self.__obj[key])
2354 def __len__(self):
2355 return len(self.__obj)
2356 def __getattr__(self, name):
2357 return Wrapper(getattr(self.__obj, name))
2358
2359 class C(object):
2360 def __getclass(self):
2361 return Wrapper(type(self))
2362 __class__ = property(__getclass)
2363
2364 dir(C()) # This used to segfault
2365
2366 def test_supers(self):
2367 # Testing super...
2368
2369 class A(object):
2370 def meth(self, a):
2371 return "A(%r)" % a
2372
2373 self.assertEqual(A().meth(1), "A(1)")
2374
2375 class B(A):
2376 def __init__(self):
2377 self.__super = super(B, self)
2378 def meth(self, a):
2379 return "B(%r)" % a + self.__super.meth(a)
2380
2381 self.assertEqual(B().meth(2), "B(2)A(2)")
2382
2383 class C(A):
2384 def meth(self, a):
2385 return "C(%r)" % a + self.__super.meth(a)
2386 C._C__super = super(C)
2387
2388 self.assertEqual(C().meth(3), "C(3)A(3)")
2389
2390 class D(C, B):
2391 def meth(self, a):
2392 return "D(%r)" % a + super(D, self).meth(a)
2393
2394 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2395
2396 # Test for subclassing super
2397
2398 class mysuper(super):
2399 def __init__(self, *args):
2400 return super(mysuper, self).__init__(*args)
2401
2402 class E(D):
2403 def meth(self, a):
2404 return "E(%r)" % a + mysuper(E, self).meth(a)
2405
2406 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2407
2408 class F(E):
2409 def meth(self, a):
2410 s = self.__super # == mysuper(F, self)
2411 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2412 F._F__super = mysuper(F)
2413
2414 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2415
2416 # Make sure certain errors are raised
2417
2418 try:
2419 super(D, 42)
2420 except TypeError:
2421 pass
2422 else:
2423 self.fail("shouldn't allow super(D, 42)")
2424
2425 try:
2426 super(D, C())
2427 except TypeError:
2428 pass
2429 else:
2430 self.fail("shouldn't allow super(D, C())")
2431
2432 try:
2433 super(D).__get__(12)
2434 except TypeError:
2435 pass
2436 else:
2437 self.fail("shouldn't allow super(D).__get__(12)")
2438
2439 try:
2440 super(D).__get__(C())
2441 except TypeError:
2442 pass
2443 else:
2444 self.fail("shouldn't allow super(D).__get__(C())")
2445
2446 # Make sure data descriptors can be overridden and accessed via super
2447 # (new feature in Python 2.3)
2448
2449 class DDbase(object):
2450 def getx(self): return 42
2451 x = property(getx)
2452
2453 class DDsub(DDbase):
2454 def getx(self): return "hello"
2455 x = property(getx)
2456
2457 dd = DDsub()
2458 self.assertEqual(dd.x, "hello")
2459 self.assertEqual(super(DDsub, dd).x, 42)
2460
2461 # Ensure that super() lookup of descriptor from classmethod
2462 # works (SF ID# 743627)
2463
2464 class Base(object):
2465 aProp = property(lambda self: "foo")
2466
2467 class Sub(Base):
2468 @classmethod
2469 def test(klass):
2470 return super(Sub,klass).aProp
2471
2472 self.assertEqual(Sub.test(), Base.aProp)
2473
2474 # Verify that super() doesn't allow keyword args
2475 try:
2476 super(Base, kw=1)
2477 except TypeError:
2478 pass
2479 else:
2480 self.assertEqual("super shouldn't accept keyword args")
2481
2482 def test_basic_inheritance(self):
2483 # Testing inheritance from basic types...
2484
2485 class hexint(int):
2486 def __repr__(self):
2487 return hex(self)
2488 def __add__(self, other):
2489 return hexint(int.__add__(self, other))
2490 # (Note that overriding __radd__ doesn't work,
2491 # because the int type gets first dibs.)
2492 self.assertEqual(repr(hexint(7) + 9), "0x10")
2493 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2494 a = hexint(12345)
2495 self.assertEqual(a, 12345)
2496 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002497 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002498 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002499 self.assertIs((+a).__class__, int)
2500 self.assertIs((a >> 0).__class__, int)
2501 self.assertIs((a << 0).__class__, int)
2502 self.assertIs((hexint(0) << 12).__class__, int)
2503 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002504
2505 class octlong(int):
2506 __slots__ = []
2507 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002508 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002509 def __add__(self, other):
2510 return self.__class__(super(octlong, self).__add__(other))
2511 __radd__ = __add__
2512 self.assertEqual(str(octlong(3) + 5), "0o10")
2513 # (Note that overriding __radd__ here only seems to work
2514 # because the example uses a short int left argument.)
2515 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2516 a = octlong(12345)
2517 self.assertEqual(a, 12345)
2518 self.assertEqual(int(a), 12345)
2519 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002520 self.assertIs(int(a).__class__, int)
2521 self.assertIs((+a).__class__, int)
2522 self.assertIs((-a).__class__, int)
2523 self.assertIs((-octlong(0)).__class__, int)
2524 self.assertIs((a >> 0).__class__, int)
2525 self.assertIs((a << 0).__class__, int)
2526 self.assertIs((a - 0).__class__, int)
2527 self.assertIs((a * 1).__class__, int)
2528 self.assertIs((a ** 1).__class__, int)
2529 self.assertIs((a // 1).__class__, int)
2530 self.assertIs((1 * a).__class__, int)
2531 self.assertIs((a | 0).__class__, int)
2532 self.assertIs((a ^ 0).__class__, int)
2533 self.assertIs((a & -1).__class__, int)
2534 self.assertIs((octlong(0) << 12).__class__, int)
2535 self.assertIs((octlong(0) >> 12).__class__, int)
2536 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002537
2538 # Because octlong overrides __add__, we can't check the absence of +0
2539 # optimizations using octlong.
2540 class longclone(int):
2541 pass
2542 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002543 self.assertIs((a + 0).__class__, int)
2544 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002545
2546 # Check that negative clones don't segfault
2547 a = longclone(-1)
2548 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002549 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002550
2551 class precfloat(float):
2552 __slots__ = ['prec']
2553 def __init__(self, value=0.0, prec=12):
2554 self.prec = int(prec)
2555 def __repr__(self):
2556 return "%.*g" % (self.prec, self)
2557 self.assertEqual(repr(precfloat(1.1)), "1.1")
2558 a = precfloat(12345)
2559 self.assertEqual(a, 12345.0)
2560 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002561 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002562 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002563 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002564
2565 class madcomplex(complex):
2566 def __repr__(self):
2567 return "%.17gj%+.17g" % (self.imag, self.real)
2568 a = madcomplex(-3, 4)
2569 self.assertEqual(repr(a), "4j-3")
2570 base = complex(-3, 4)
2571 self.assertEqual(base.__class__, complex)
2572 self.assertEqual(a, base)
2573 self.assertEqual(complex(a), base)
2574 self.assertEqual(complex(a).__class__, complex)
2575 a = madcomplex(a) # just trying another form of the constructor
2576 self.assertEqual(repr(a), "4j-3")
2577 self.assertEqual(a, base)
2578 self.assertEqual(complex(a), base)
2579 self.assertEqual(complex(a).__class__, complex)
2580 self.assertEqual(hash(a), hash(base))
2581 self.assertEqual((+a).__class__, complex)
2582 self.assertEqual((a + 0).__class__, complex)
2583 self.assertEqual(a + 0, base)
2584 self.assertEqual((a - 0).__class__, complex)
2585 self.assertEqual(a - 0, base)
2586 self.assertEqual((a * 1).__class__, complex)
2587 self.assertEqual(a * 1, base)
2588 self.assertEqual((a / 1).__class__, complex)
2589 self.assertEqual(a / 1, base)
2590
2591 class madtuple(tuple):
2592 _rev = None
2593 def rev(self):
2594 if self._rev is not None:
2595 return self._rev
2596 L = list(self)
2597 L.reverse()
2598 self._rev = self.__class__(L)
2599 return self._rev
2600 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2601 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2602 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2603 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2604 for i in range(512):
2605 t = madtuple(range(i))
2606 u = t.rev()
2607 v = u.rev()
2608 self.assertEqual(v, t)
2609 a = madtuple((1,2,3,4,5))
2610 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002611 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002612 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002613 self.assertIs(a[:].__class__, tuple)
2614 self.assertIs((a * 1).__class__, tuple)
2615 self.assertIs((a * 0).__class__, tuple)
2616 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 a = madtuple(())
2618 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002619 self.assertIs(tuple(a).__class__, tuple)
2620 self.assertIs((a + a).__class__, tuple)
2621 self.assertIs((a * 0).__class__, tuple)
2622 self.assertIs((a * 1).__class__, tuple)
2623 self.assertIs((a * 2).__class__, tuple)
2624 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002625
2626 class madstring(str):
2627 _rev = None
2628 def rev(self):
2629 if self._rev is not None:
2630 return self._rev
2631 L = list(self)
2632 L.reverse()
2633 self._rev = self.__class__("".join(L))
2634 return self._rev
2635 s = madstring("abcdefghijklmnopqrstuvwxyz")
2636 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2637 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2638 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2639 for i in range(256):
2640 s = madstring("".join(map(chr, range(i))))
2641 t = s.rev()
2642 u = t.rev()
2643 self.assertEqual(u, s)
2644 s = madstring("12345")
2645 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002646 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002647
2648 base = "\x00" * 5
2649 s = madstring(base)
2650 self.assertEqual(s, base)
2651 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002652 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002653 self.assertEqual(hash(s), hash(base))
2654 self.assertEqual({s: 1}[base], 1)
2655 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002656 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002657 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002658 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002659 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002660 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002661 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002662 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002663 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002664 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002665 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002666 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002667 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002668 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002669 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002670 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002671 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002672 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002673 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002674 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002675 self.assertEqual(s.rstrip(), base)
2676 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002677 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002678 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002679 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002680 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002681 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002683 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002684 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002685 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002686 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002687 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002688 self.assertEqual(s.lower(), base)
2689
2690 class madunicode(str):
2691 _rev = None
2692 def rev(self):
2693 if self._rev is not None:
2694 return self._rev
2695 L = list(self)
2696 L.reverse()
2697 self._rev = self.__class__("".join(L))
2698 return self._rev
2699 u = madunicode("ABCDEF")
2700 self.assertEqual(u, "ABCDEF")
2701 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2702 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2703 base = "12345"
2704 u = madunicode(base)
2705 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002706 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002707 self.assertEqual(hash(u), hash(base))
2708 self.assertEqual({u: 1}[base], 1)
2709 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002710 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002711 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002712 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002713 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002714 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002715 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002716 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002717 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002718 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002719 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002720 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002721 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002722 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002723 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002724 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002725 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002726 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002727 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002728 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002729 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002730 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002731 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002732 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002733 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002734 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002735 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002736 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002737 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002738 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002739 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002740 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002741 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002742 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002743 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002744 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002745 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002746 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002747 self.assertEqual(u[0:0], "")
2748
2749 class sublist(list):
2750 pass
2751 a = sublist(range(5))
2752 self.assertEqual(a, list(range(5)))
2753 a.append("hello")
2754 self.assertEqual(a, list(range(5)) + ["hello"])
2755 a[5] = 5
2756 self.assertEqual(a, list(range(6)))
2757 a.extend(range(6, 20))
2758 self.assertEqual(a, list(range(20)))
2759 a[-5:] = []
2760 self.assertEqual(a, list(range(15)))
2761 del a[10:15]
2762 self.assertEqual(len(a), 10)
2763 self.assertEqual(a, list(range(10)))
2764 self.assertEqual(list(a), list(range(10)))
2765 self.assertEqual(a[0], 0)
2766 self.assertEqual(a[9], 9)
2767 self.assertEqual(a[-10], 0)
2768 self.assertEqual(a[-1], 9)
2769 self.assertEqual(a[:5], list(range(5)))
2770
2771 ## class CountedInput(file):
2772 ## """Counts lines read by self.readline().
2773 ##
2774 ## self.lineno is the 0-based ordinal of the last line read, up to
2775 ## a maximum of one greater than the number of lines in the file.
2776 ##
2777 ## self.ateof is true if and only if the final "" line has been read,
2778 ## at which point self.lineno stops incrementing, and further calls
2779 ## to readline() continue to return "".
2780 ## """
2781 ##
2782 ## lineno = 0
2783 ## ateof = 0
2784 ## def readline(self):
2785 ## if self.ateof:
2786 ## return ""
2787 ## s = file.readline(self)
2788 ## # Next line works too.
2789 ## # s = super(CountedInput, self).readline()
2790 ## self.lineno += 1
2791 ## if s == "":
2792 ## self.ateof = 1
2793 ## return s
2794 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002795 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002796 ## lines = ['a\n', 'b\n', 'c\n']
2797 ## try:
2798 ## f.writelines(lines)
2799 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002800 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002801 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2802 ## got = f.readline()
2803 ## self.assertEqual(expected, got)
2804 ## self.assertEqual(f.lineno, i)
2805 ## self.assertEqual(f.ateof, (i > len(lines)))
2806 ## f.close()
2807 ## finally:
2808 ## try:
2809 ## f.close()
2810 ## except:
2811 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002812 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002813
2814 def test_keywords(self):
2815 # Testing keyword args to basic type constructors ...
2816 self.assertEqual(int(x=1), 1)
2817 self.assertEqual(float(x=2), 2.0)
2818 self.assertEqual(int(x=3), 3)
2819 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2820 self.assertEqual(str(object=500), '500')
2821 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2822 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2823 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2824 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2825
2826 for constructor in (int, float, int, complex, str, str,
2827 tuple, list):
2828 try:
2829 constructor(bogus_keyword_arg=1)
2830 except TypeError:
2831 pass
2832 else:
2833 self.fail("expected TypeError from bogus keyword argument to %r"
2834 % constructor)
2835
2836 def test_str_subclass_as_dict_key(self):
2837 # Testing a str subclass used as dict key ..
2838
2839 class cistr(str):
2840 """Sublcass of str that computes __eq__ case-insensitively.
2841
2842 Also computes a hash code of the string in canonical form.
2843 """
2844
2845 def __init__(self, value):
2846 self.canonical = value.lower()
2847 self.hashcode = hash(self.canonical)
2848
2849 def __eq__(self, other):
2850 if not isinstance(other, cistr):
2851 other = cistr(other)
2852 return self.canonical == other.canonical
2853
2854 def __hash__(self):
2855 return self.hashcode
2856
2857 self.assertEqual(cistr('ABC'), 'abc')
2858 self.assertEqual('aBc', cistr('ABC'))
2859 self.assertEqual(str(cistr('ABC')), 'ABC')
2860
2861 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2862 self.assertEqual(d[cistr('one')], 1)
2863 self.assertEqual(d[cistr('tWo')], 2)
2864 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002865 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002866 self.assertEqual(d.get(cistr('thrEE')), 3)
2867
2868 def test_classic_comparisons(self):
2869 # Testing classic comparisons...
2870 class classic:
2871 pass
2872
2873 for base in (classic, int, object):
2874 class C(base):
2875 def __init__(self, value):
2876 self.value = int(value)
2877 def __eq__(self, other):
2878 if isinstance(other, C):
2879 return self.value == other.value
2880 if isinstance(other, int) or isinstance(other, int):
2881 return self.value == other
2882 return NotImplemented
2883 def __ne__(self, other):
2884 if isinstance(other, C):
2885 return self.value != other.value
2886 if isinstance(other, int) or isinstance(other, int):
2887 return self.value != other
2888 return NotImplemented
2889 def __lt__(self, other):
2890 if isinstance(other, C):
2891 return self.value < other.value
2892 if isinstance(other, int) or isinstance(other, int):
2893 return self.value < other
2894 return NotImplemented
2895 def __le__(self, other):
2896 if isinstance(other, C):
2897 return self.value <= other.value
2898 if isinstance(other, int) or isinstance(other, int):
2899 return self.value <= other
2900 return NotImplemented
2901 def __gt__(self, other):
2902 if isinstance(other, C):
2903 return self.value > other.value
2904 if isinstance(other, int) or isinstance(other, int):
2905 return self.value > other
2906 return NotImplemented
2907 def __ge__(self, other):
2908 if isinstance(other, C):
2909 return self.value >= other.value
2910 if isinstance(other, int) or isinstance(other, int):
2911 return self.value >= other
2912 return NotImplemented
2913
2914 c1 = C(1)
2915 c2 = C(2)
2916 c3 = C(3)
2917 self.assertEqual(c1, 1)
2918 c = {1: c1, 2: c2, 3: c3}
2919 for x in 1, 2, 3:
2920 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002921 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002922 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002923 eval("x %s y" % op),
2924 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002925 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002926 eval("x %s y" % op),
2927 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002928 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002929 eval("x %s y" % op),
2930 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002931
2932 def test_rich_comparisons(self):
2933 # Testing rich comparisons...
2934 class Z(complex):
2935 pass
2936 z = Z(1)
2937 self.assertEqual(z, 1+0j)
2938 self.assertEqual(1+0j, z)
2939 class ZZ(complex):
2940 def __eq__(self, other):
2941 try:
2942 return abs(self - other) <= 1e-6
2943 except:
2944 return NotImplemented
2945 zz = ZZ(1.0000003)
2946 self.assertEqual(zz, 1+0j)
2947 self.assertEqual(1+0j, zz)
2948
2949 class classic:
2950 pass
2951 for base in (classic, int, object, list):
2952 class C(base):
2953 def __init__(self, value):
2954 self.value = int(value)
2955 def __cmp__(self_, other):
2956 self.fail("shouldn't call __cmp__")
2957 def __eq__(self, other):
2958 if isinstance(other, C):
2959 return self.value == other.value
2960 if isinstance(other, int) or isinstance(other, int):
2961 return self.value == other
2962 return NotImplemented
2963 def __ne__(self, other):
2964 if isinstance(other, C):
2965 return self.value != other.value
2966 if isinstance(other, int) or isinstance(other, int):
2967 return self.value != other
2968 return NotImplemented
2969 def __lt__(self, other):
2970 if isinstance(other, C):
2971 return self.value < other.value
2972 if isinstance(other, int) or isinstance(other, int):
2973 return self.value < other
2974 return NotImplemented
2975 def __le__(self, other):
2976 if isinstance(other, C):
2977 return self.value <= other.value
2978 if isinstance(other, int) or isinstance(other, int):
2979 return self.value <= other
2980 return NotImplemented
2981 def __gt__(self, other):
2982 if isinstance(other, C):
2983 return self.value > other.value
2984 if isinstance(other, int) or isinstance(other, int):
2985 return self.value > other
2986 return NotImplemented
2987 def __ge__(self, other):
2988 if isinstance(other, C):
2989 return self.value >= other.value
2990 if isinstance(other, int) or isinstance(other, int):
2991 return self.value >= other
2992 return NotImplemented
2993 c1 = C(1)
2994 c2 = C(2)
2995 c3 = C(3)
2996 self.assertEqual(c1, 1)
2997 c = {1: c1, 2: c2, 3: c3}
2998 for x in 1, 2, 3:
2999 for y in 1, 2, 3:
3000 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003001 self.assertEqual(eval("c[x] %s c[y]" % op),
3002 eval("x %s y" % op),
3003 "x=%d, y=%d" % (x, y))
3004 self.assertEqual(eval("c[x] %s y" % op),
3005 eval("x %s y" % op),
3006 "x=%d, y=%d" % (x, y))
3007 self.assertEqual(eval("x %s c[y]" % op),
3008 eval("x %s y" % op),
3009 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00003010
3011 def test_descrdoc(self):
3012 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003013 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00003014 def check(descr, what):
3015 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003016 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00003017 check(complex.real, "the real part of a complex number") # member descriptor
3018
3019 def test_doc_descriptor(self):
3020 # Testing __doc__ descriptor...
3021 # SF bug 542984
3022 class DocDescr(object):
3023 def __get__(self, object, otype):
3024 if object:
3025 object = object.__class__.__name__ + ' instance'
3026 if otype:
3027 otype = otype.__name__
3028 return 'object=%s; type=%s' % (object, otype)
3029 class OldClass:
3030 __doc__ = DocDescr()
3031 class NewClass(object):
3032 __doc__ = DocDescr()
3033 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3034 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3035 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3036 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3037
3038 def test_set_class(self):
3039 # Testing __class__ assignment...
3040 class C(object): pass
3041 class D(object): pass
3042 class E(object): pass
3043 class F(D, E): pass
3044 for cls in C, D, E, F:
3045 for cls2 in C, D, E, F:
3046 x = cls()
3047 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003048 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003049 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003050 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003051 def cant(x, C):
3052 try:
3053 x.__class__ = C
3054 except TypeError:
3055 pass
3056 else:
3057 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3058 try:
3059 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003060 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003061 pass
3062 else:
3063 self.fail("shouldn't allow del %r.__class__" % x)
3064 cant(C(), list)
3065 cant(list(), C)
3066 cant(C(), 1)
3067 cant(C(), object)
3068 cant(object(), list)
3069 cant(list(), object)
3070 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003071 cant(True, int)
3072 cant(2, bool)
3073 o = object()
3074 cant(o, type(1))
3075 cant(o, type(None))
3076 del o
3077 class G(object):
3078 __slots__ = ["a", "b"]
3079 class H(object):
3080 __slots__ = ["b", "a"]
3081 class I(object):
3082 __slots__ = ["a", "b"]
3083 class J(object):
3084 __slots__ = ["c", "b"]
3085 class K(object):
3086 __slots__ = ["a", "b", "d"]
3087 class L(H):
3088 __slots__ = ["e"]
3089 class M(I):
3090 __slots__ = ["e"]
3091 class N(J):
3092 __slots__ = ["__weakref__"]
3093 class P(J):
3094 __slots__ = ["__dict__"]
3095 class Q(J):
3096 pass
3097 class R(J):
3098 __slots__ = ["__dict__", "__weakref__"]
3099
3100 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3101 x = cls()
3102 x.a = 1
3103 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003104 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003105 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3106 self.assertEqual(x.a, 1)
3107 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003108 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003109 "assigning %r as __class__ for %r silently failed" % (cls, x))
3110 self.assertEqual(x.a, 1)
3111 for cls in G, J, K, L, M, N, P, R, list, Int:
3112 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3113 if cls is cls2:
3114 continue
3115 cant(cls(), cls2)
3116
Benjamin Peterson193152c2009-04-25 01:08:45 +00003117 # Issue5283: when __class__ changes in __del__, the wrong
3118 # type gets DECREF'd.
3119 class O(object):
3120 pass
3121 class A(object):
3122 def __del__(self):
3123 self.__class__ = O
3124 l = [A() for x in range(100)]
3125 del l
3126
Georg Brandl479a7e72008-02-05 18:13:15 +00003127 def test_set_dict(self):
3128 # Testing __dict__ assignment...
3129 class C(object): pass
3130 a = C()
3131 a.__dict__ = {'b': 1}
3132 self.assertEqual(a.b, 1)
3133 def cant(x, dict):
3134 try:
3135 x.__dict__ = dict
3136 except (AttributeError, TypeError):
3137 pass
3138 else:
3139 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3140 cant(a, None)
3141 cant(a, [])
3142 cant(a, 1)
3143 del a.__dict__ # Deleting __dict__ is allowed
3144
3145 class Base(object):
3146 pass
3147 def verify_dict_readonly(x):
3148 """
3149 x has to be an instance of a class inheriting from Base.
3150 """
3151 cant(x, {})
3152 try:
3153 del x.__dict__
3154 except (AttributeError, TypeError):
3155 pass
3156 else:
3157 self.fail("shouldn't allow del %r.__dict__" % x)
3158 dict_descr = Base.__dict__["__dict__"]
3159 try:
3160 dict_descr.__set__(x, {})
3161 except (AttributeError, TypeError):
3162 pass
3163 else:
3164 self.fail("dict_descr allowed access to %r's dict" % x)
3165
3166 # Classes don't allow __dict__ assignment and have readonly dicts
3167 class Meta1(type, Base):
3168 pass
3169 class Meta2(Base, type):
3170 pass
3171 class D(object, metaclass=Meta1):
3172 pass
3173 class E(object, metaclass=Meta2):
3174 pass
3175 for cls in C, D, E:
3176 verify_dict_readonly(cls)
3177 class_dict = cls.__dict__
3178 try:
3179 class_dict["spam"] = "eggs"
3180 except TypeError:
3181 pass
3182 else:
3183 self.fail("%r's __dict__ can be modified" % cls)
3184
3185 # Modules also disallow __dict__ assignment
3186 class Module1(types.ModuleType, Base):
3187 pass
3188 class Module2(Base, types.ModuleType):
3189 pass
3190 for ModuleType in Module1, Module2:
3191 mod = ModuleType("spam")
3192 verify_dict_readonly(mod)
3193 mod.__dict__["spam"] = "eggs"
3194
3195 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003196 # (at least not any more than regular exception's __dict__ can
3197 # be deleted; on CPython it is not the case, whereas on PyPy they
3198 # can, just like any other new-style instance's __dict__.)
3199 def can_delete_dict(e):
3200 try:
3201 del e.__dict__
3202 except (TypeError, AttributeError):
3203 return False
3204 else:
3205 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003206 class Exception1(Exception, Base):
3207 pass
3208 class Exception2(Base, Exception):
3209 pass
3210 for ExceptionType in Exception, Exception1, Exception2:
3211 e = ExceptionType()
3212 e.__dict__ = {"a": 1}
3213 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003214 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003215
Georg Brandl479a7e72008-02-05 18:13:15 +00003216 def test_binary_operator_override(self):
3217 # Testing overrides of binary operations...
3218 class I(int):
3219 def __repr__(self):
3220 return "I(%r)" % int(self)
3221 def __add__(self, other):
3222 return I(int(self) + int(other))
3223 __radd__ = __add__
3224 def __pow__(self, other, mod=None):
3225 if mod is None:
3226 return I(pow(int(self), int(other)))
3227 else:
3228 return I(pow(int(self), int(other), int(mod)))
3229 def __rpow__(self, other, mod=None):
3230 if mod is None:
3231 return I(pow(int(other), int(self), mod))
3232 else:
3233 return I(pow(int(other), int(self), int(mod)))
3234
3235 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3236 self.assertEqual(repr(I(1) + 2), "I(3)")
3237 self.assertEqual(repr(1 + I(2)), "I(3)")
3238 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3239 self.assertEqual(repr(2 ** I(3)), "I(8)")
3240 self.assertEqual(repr(I(2) ** 3), "I(8)")
3241 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3242 class S(str):
3243 def __eq__(self, other):
3244 return self.lower() == other.lower()
3245
3246 def test_subclass_propagation(self):
3247 # Testing propagation of slot functions to subclasses...
3248 class A(object):
3249 pass
3250 class B(A):
3251 pass
3252 class C(A):
3253 pass
3254 class D(B, C):
3255 pass
3256 d = D()
3257 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3258 A.__hash__ = lambda self: 42
3259 self.assertEqual(hash(d), 42)
3260 C.__hash__ = lambda self: 314
3261 self.assertEqual(hash(d), 314)
3262 B.__hash__ = lambda self: 144
3263 self.assertEqual(hash(d), 144)
3264 D.__hash__ = lambda self: 100
3265 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003266 D.__hash__ = None
3267 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003268 del D.__hash__
3269 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003270 B.__hash__ = None
3271 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003272 del B.__hash__
3273 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003274 C.__hash__ = None
3275 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003276 del C.__hash__
3277 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003278 A.__hash__ = None
3279 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003280 del A.__hash__
3281 self.assertEqual(hash(d), orig_hash)
3282 d.foo = 42
3283 d.bar = 42
3284 self.assertEqual(d.foo, 42)
3285 self.assertEqual(d.bar, 42)
3286 def __getattribute__(self, name):
3287 if name == "foo":
3288 return 24
3289 return object.__getattribute__(self, name)
3290 A.__getattribute__ = __getattribute__
3291 self.assertEqual(d.foo, 24)
3292 self.assertEqual(d.bar, 42)
3293 def __getattr__(self, name):
3294 if name in ("spam", "foo", "bar"):
3295 return "hello"
3296 raise AttributeError(name)
3297 B.__getattr__ = __getattr__
3298 self.assertEqual(d.spam, "hello")
3299 self.assertEqual(d.foo, 24)
3300 self.assertEqual(d.bar, 42)
3301 del A.__getattribute__
3302 self.assertEqual(d.foo, 42)
3303 del d.foo
3304 self.assertEqual(d.foo, "hello")
3305 self.assertEqual(d.bar, 42)
3306 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003307 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003308 d.foo
3309 except AttributeError:
3310 pass
3311 else:
3312 self.fail("d.foo should be undefined now")
3313
3314 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003315 class A(object):
3316 pass
3317 class B(A):
3318 pass
3319 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003320 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003321 A.__setitem__ = lambda *a: None # crash
3322
3323 def test_buffer_inheritance(self):
3324 # Testing that buffer interface is inherited ...
3325
3326 import binascii
3327 # SF bug [#470040] ParseTuple t# vs subclasses.
3328
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003329 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003330 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003331 base = b'abc'
3332 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003333 # b2a_hex uses the buffer interface to get its argument's value, via
3334 # PyArg_ParseTuple 't#' code.
3335 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3336
Georg Brandl479a7e72008-02-05 18:13:15 +00003337 class MyInt(int):
3338 pass
3339 m = MyInt(42)
3340 try:
3341 binascii.b2a_hex(m)
3342 self.fail('subclass of int should not have a buffer interface')
3343 except TypeError:
3344 pass
3345
3346 def test_str_of_str_subclass(self):
3347 # Testing __str__ defined in subclass of str ...
3348 import binascii
3349 import io
3350
3351 class octetstring(str):
3352 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003353 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003354 def __repr__(self):
3355 return self + " repr"
3356
3357 o = octetstring('A')
3358 self.assertEqual(type(o), octetstring)
3359 self.assertEqual(type(str(o)), str)
3360 self.assertEqual(type(repr(o)), str)
3361 self.assertEqual(ord(o), 0x41)
3362 self.assertEqual(str(o), '41')
3363 self.assertEqual(repr(o), 'A repr')
3364 self.assertEqual(o.__str__(), '41')
3365 self.assertEqual(o.__repr__(), 'A repr')
3366
3367 capture = io.StringIO()
3368 # Calling str() or not exercises different internal paths.
3369 print(o, file=capture)
3370 print(str(o), file=capture)
3371 self.assertEqual(capture.getvalue(), '41\n41\n')
3372 capture.close()
3373
3374 def test_keyword_arguments(self):
3375 # Testing keyword arguments to __init__, __call__...
3376 def f(a): return a
3377 self.assertEqual(f.__call__(a=42), 42)
3378 a = []
3379 list.__init__(a, sequence=[0, 1, 2])
3380 self.assertEqual(a, [0, 1, 2])
3381
3382 def test_recursive_call(self):
3383 # Testing recursive __call__() by setting to instance of class...
3384 class A(object):
3385 pass
3386
3387 A.__call__ = A()
3388 try:
3389 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003390 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003391 pass
3392 else:
3393 self.fail("Recursion limit should have been reached for __call__()")
3394
3395 def test_delete_hook(self):
3396 # Testing __del__ hook...
3397 log = []
3398 class C(object):
3399 def __del__(self):
3400 log.append(1)
3401 c = C()
3402 self.assertEqual(log, [])
3403 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003404 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003405 self.assertEqual(log, [1])
3406
3407 class D(object): pass
3408 d = D()
3409 try: del d[0]
3410 except TypeError: pass
3411 else: self.fail("invalid del() didn't raise TypeError")
3412
3413 def test_hash_inheritance(self):
3414 # Testing hash of mutable subclasses...
3415
3416 class mydict(dict):
3417 pass
3418 d = mydict()
3419 try:
3420 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003421 except TypeError:
3422 pass
3423 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003424 self.fail("hash() of dict subclass should fail")
3425
3426 class mylist(list):
3427 pass
3428 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003429 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003430 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003431 except TypeError:
3432 pass
3433 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003434 self.fail("hash() of list subclass should fail")
3435
3436 def test_str_operations(self):
3437 try: 'a' + 5
3438 except TypeError: pass
3439 else: self.fail("'' + 5 doesn't raise TypeError")
3440
3441 try: ''.split('')
3442 except ValueError: pass
3443 else: self.fail("''.split('') doesn't raise ValueError")
3444
3445 try: ''.join([0])
3446 except TypeError: pass
3447 else: self.fail("''.join([0]) doesn't raise TypeError")
3448
3449 try: ''.rindex('5')
3450 except ValueError: pass
3451 else: self.fail("''.rindex('5') doesn't raise ValueError")
3452
3453 try: '%(n)s' % None
3454 except TypeError: pass
3455 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3456
3457 try: '%(n' % {}
3458 except ValueError: pass
3459 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3460
3461 try: '%*s' % ('abc')
3462 except TypeError: pass
3463 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3464
3465 try: '%*.*s' % ('abc', 5)
3466 except TypeError: pass
3467 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3468
3469 try: '%s' % (1, 2)
3470 except TypeError: pass
3471 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3472
3473 try: '%' % None
3474 except ValueError: pass
3475 else: self.fail("'%' % None doesn't raise ValueError")
3476
3477 self.assertEqual('534253'.isdigit(), 1)
3478 self.assertEqual('534253x'.isdigit(), 0)
3479 self.assertEqual('%c' % 5, '\x05')
3480 self.assertEqual('%c' % '5', '5')
3481
3482 def test_deepcopy_recursive(self):
3483 # Testing deepcopy of recursive objects...
3484 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003485 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003486 a = Node()
3487 b = Node()
3488 a.b = b
3489 b.a = a
3490 z = deepcopy(a) # This blew up before
3491
Martin Panterf05641642016-05-08 13:48:10 +00003492 def test_uninitialized_modules(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00003493 # Testing uninitialized module objects...
3494 from types import ModuleType as M
3495 m = M.__new__(M)
3496 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003497 self.assertNotHasAttr(m, "__name__")
3498 self.assertNotHasAttr(m, "__file__")
3499 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003500 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003501 m.foo = 1
3502 self.assertEqual(m.__dict__, {"foo": 1})
3503
3504 def test_funny_new(self):
3505 # Testing __new__ returning something unexpected...
3506 class C(object):
3507 def __new__(cls, arg):
3508 if isinstance(arg, str): return [1, 2, 3]
3509 elif isinstance(arg, int): return object.__new__(D)
3510 else: return object.__new__(cls)
3511 class D(C):
3512 def __init__(self, arg):
3513 self.foo = arg
3514 self.assertEqual(C("1"), [1, 2, 3])
3515 self.assertEqual(D("1"), [1, 2, 3])
3516 d = D(None)
3517 self.assertEqual(d.foo, None)
3518 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003519 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003520 self.assertEqual(d.foo, 1)
3521 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003522 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003523 self.assertEqual(d.foo, 1)
3524
3525 def test_imul_bug(self):
3526 # Testing for __imul__ problems...
3527 # SF bug 544647
3528 class C(object):
3529 def __imul__(self, other):
3530 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003531 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003532 y = x
3533 y *= 1.0
3534 self.assertEqual(y, (x, 1.0))
3535 y = x
3536 y *= 2
3537 self.assertEqual(y, (x, 2))
3538 y = x
3539 y *= 3
3540 self.assertEqual(y, (x, 3))
3541 y = x
3542 y *= 1<<100
3543 self.assertEqual(y, (x, 1<<100))
3544 y = x
3545 y *= None
3546 self.assertEqual(y, (x, None))
3547 y = x
3548 y *= "foo"
3549 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003550
Georg Brandl479a7e72008-02-05 18:13:15 +00003551 def test_copy_setstate(self):
3552 # Testing that copy.*copy() correctly uses __setstate__...
3553 import copy
3554 class C(object):
3555 def __init__(self, foo=None):
3556 self.foo = foo
3557 self.__foo = foo
3558 def setfoo(self, foo=None):
3559 self.foo = foo
3560 def getfoo(self):
3561 return self.__foo
3562 def __getstate__(self):
3563 return [self.foo]
3564 def __setstate__(self_, lst):
3565 self.assertEqual(len(lst), 1)
3566 self_.__foo = self_.foo = lst[0]
3567 a = C(42)
3568 a.setfoo(24)
3569 self.assertEqual(a.foo, 24)
3570 self.assertEqual(a.getfoo(), 42)
3571 b = copy.copy(a)
3572 self.assertEqual(b.foo, 24)
3573 self.assertEqual(b.getfoo(), 24)
3574 b = copy.deepcopy(a)
3575 self.assertEqual(b.foo, 24)
3576 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003577
Georg Brandl479a7e72008-02-05 18:13:15 +00003578 def test_slices(self):
3579 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003580
Georg Brandl479a7e72008-02-05 18:13:15 +00003581 # Strings
3582 self.assertEqual("hello"[:4], "hell")
3583 self.assertEqual("hello"[slice(4)], "hell")
3584 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3585 class S(str):
3586 def __getitem__(self, x):
3587 return str.__getitem__(self, x)
3588 self.assertEqual(S("hello")[:4], "hell")
3589 self.assertEqual(S("hello")[slice(4)], "hell")
3590 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3591 # Tuples
3592 self.assertEqual((1,2,3)[:2], (1,2))
3593 self.assertEqual((1,2,3)[slice(2)], (1,2))
3594 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3595 class T(tuple):
3596 def __getitem__(self, x):
3597 return tuple.__getitem__(self, x)
3598 self.assertEqual(T((1,2,3))[:2], (1,2))
3599 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3600 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3601 # Lists
3602 self.assertEqual([1,2,3][:2], [1,2])
3603 self.assertEqual([1,2,3][slice(2)], [1,2])
3604 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3605 class L(list):
3606 def __getitem__(self, x):
3607 return list.__getitem__(self, x)
3608 self.assertEqual(L([1,2,3])[:2], [1,2])
3609 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3610 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3611 # Now do lists and __setitem__
3612 a = L([1,2,3])
3613 a[slice(1, 3)] = [3,2]
3614 self.assertEqual(a, [1,3,2])
3615 a[slice(0, 2, 1)] = [3,1]
3616 self.assertEqual(a, [3,1,2])
3617 a.__setitem__(slice(1, 3), [2,1])
3618 self.assertEqual(a, [3,2,1])
3619 a.__setitem__(slice(0, 2, 1), [2,3])
3620 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003621
Georg Brandl479a7e72008-02-05 18:13:15 +00003622 def test_subtype_resurrection(self):
3623 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003624
Georg Brandl479a7e72008-02-05 18:13:15 +00003625 class C(object):
3626 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003627
Georg Brandl479a7e72008-02-05 18:13:15 +00003628 def __del__(self):
3629 # resurrect the instance
3630 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003631
Georg Brandl479a7e72008-02-05 18:13:15 +00003632 c = C()
3633 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003634
Benjamin Petersone549ead2009-03-28 21:42:05 +00003635 # The most interesting thing here is whether this blows up, due to
3636 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3637 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003638 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003639
Benjamin Petersone549ead2009-03-28 21:42:05 +00003640 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003641 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003642
Georg Brandl479a7e72008-02-05 18:13:15 +00003643 # Make c mortal again, so that the test framework with -l doesn't report
3644 # it as a leak.
3645 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003646
Georg Brandl479a7e72008-02-05 18:13:15 +00003647 def test_slots_trash(self):
3648 # Testing slot trash...
3649 # Deallocating deeply nested slotted trash caused stack overflows
3650 class trash(object):
3651 __slots__ = ['x']
3652 def __init__(self, x):
3653 self.x = x
3654 o = None
3655 for i in range(50000):
3656 o = trash(o)
3657 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003658
Georg Brandl479a7e72008-02-05 18:13:15 +00003659 def test_slots_multiple_inheritance(self):
3660 # SF bug 575229, multiple inheritance w/ slots dumps core
3661 class A(object):
3662 __slots__=()
3663 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003664 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003665 class C(A,B) :
3666 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003667 if support.check_impl_detail():
3668 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003669 self.assertHasAttr(C, '__dict__')
3670 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003671 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003672
Georg Brandl479a7e72008-02-05 18:13:15 +00003673 def test_rmul(self):
3674 # Testing correct invocation of __rmul__...
3675 # SF patch 592646
3676 class C(object):
3677 def __mul__(self, other):
3678 return "mul"
3679 def __rmul__(self, other):
3680 return "rmul"
3681 a = C()
3682 self.assertEqual(a*2, "mul")
3683 self.assertEqual(a*2.2, "mul")
3684 self.assertEqual(2*a, "rmul")
3685 self.assertEqual(2.2*a, "rmul")
3686
3687 def test_ipow(self):
3688 # Testing correct invocation of __ipow__...
3689 # [SF bug 620179]
3690 class C(object):
3691 def __ipow__(self, other):
3692 pass
3693 a = C()
3694 a **= 2
3695
3696 def test_mutable_bases(self):
3697 # Testing mutable bases...
3698
3699 # stuff that should work:
3700 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003701 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003702 class C2(object):
3703 def __getattribute__(self, attr):
3704 if attr == 'a':
3705 return 2
3706 else:
3707 return super(C2, self).__getattribute__(attr)
3708 def meth(self):
3709 return 1
3710 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003711 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003712 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003713 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003714 d = D()
3715 e = E()
3716 D.__bases__ = (C,)
3717 D.__bases__ = (C2,)
3718 self.assertEqual(d.meth(), 1)
3719 self.assertEqual(e.meth(), 1)
3720 self.assertEqual(d.a, 2)
3721 self.assertEqual(e.a, 2)
3722 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003723
Georg Brandl479a7e72008-02-05 18:13:15 +00003724 try:
3725 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003726 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003727 pass
3728 else:
3729 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003730
Georg Brandl479a7e72008-02-05 18:13:15 +00003731 try:
3732 D.__bases__ = ()
3733 except TypeError as msg:
3734 if str(msg) == "a new-style class can't have only classic bases":
3735 self.fail("wrong error message for .__bases__ = ()")
3736 else:
3737 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003738
Georg Brandl479a7e72008-02-05 18:13:15 +00003739 try:
3740 D.__bases__ = (D,)
3741 except TypeError:
3742 pass
3743 else:
3744 # actually, we'll have crashed by here...
3745 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003746
Georg Brandl479a7e72008-02-05 18:13:15 +00003747 try:
3748 D.__bases__ = (C, C)
3749 except TypeError:
3750 pass
3751 else:
3752 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003753
Georg Brandl479a7e72008-02-05 18:13:15 +00003754 try:
3755 D.__bases__ = (E,)
3756 except TypeError:
3757 pass
3758 else:
3759 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003760
Benjamin Petersonae937c02009-04-18 20:54:08 +00003761 def test_builtin_bases(self):
3762 # Make sure all the builtin types can have their base queried without
3763 # segfaulting. See issue #5787.
3764 builtin_types = [tp for tp in builtins.__dict__.values()
3765 if isinstance(tp, type)]
3766 for tp in builtin_types:
3767 object.__getattribute__(tp, "__bases__")
3768 if tp is not object:
3769 self.assertEqual(len(tp.__bases__), 1, tp)
3770
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003771 class L(list):
3772 pass
3773
3774 class C(object):
3775 pass
3776
3777 class D(C):
3778 pass
3779
3780 try:
3781 L.__bases__ = (dict,)
3782 except TypeError:
3783 pass
3784 else:
3785 self.fail("shouldn't turn list subclass into dict subclass")
3786
3787 try:
3788 list.__bases__ = (dict,)
3789 except TypeError:
3790 pass
3791 else:
3792 self.fail("shouldn't be able to assign to list.__bases__")
3793
3794 try:
3795 D.__bases__ = (C, list)
3796 except TypeError:
3797 pass
3798 else:
3799 assert 0, "best_base calculation found wanting"
3800
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003801 def test_unsubclassable_types(self):
3802 with self.assertRaises(TypeError):
3803 class X(type(None)):
3804 pass
3805 with self.assertRaises(TypeError):
3806 class X(object, type(None)):
3807 pass
3808 with self.assertRaises(TypeError):
3809 class X(type(None), object):
3810 pass
3811 class O(object):
3812 pass
3813 with self.assertRaises(TypeError):
3814 class X(O, type(None)):
3815 pass
3816 with self.assertRaises(TypeError):
3817 class X(type(None), O):
3818 pass
3819
3820 class X(object):
3821 pass
3822 with self.assertRaises(TypeError):
3823 X.__bases__ = type(None),
3824 with self.assertRaises(TypeError):
3825 X.__bases__ = object, type(None)
3826 with self.assertRaises(TypeError):
3827 X.__bases__ = type(None), object
3828 with self.assertRaises(TypeError):
3829 X.__bases__ = O, type(None)
3830 with self.assertRaises(TypeError):
3831 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00003832
Georg Brandl479a7e72008-02-05 18:13:15 +00003833 def test_mutable_bases_with_failing_mro(self):
3834 # Testing mutable bases with failing mro...
3835 class WorkOnce(type):
3836 def __new__(self, name, bases, ns):
3837 self.flag = 0
3838 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3839 def mro(self):
3840 if self.flag > 0:
3841 raise RuntimeError("bozo")
3842 else:
3843 self.flag += 1
3844 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003845
Georg Brandl479a7e72008-02-05 18:13:15 +00003846 class WorkAlways(type):
3847 def mro(self):
3848 # this is here to make sure that .mro()s aren't called
3849 # with an exception set (which was possible at one point).
3850 # An error message will be printed in a debug build.
3851 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003852 return type.mro(self)
3853
Georg Brandl479a7e72008-02-05 18:13:15 +00003854 class C(object):
3855 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003856
Georg Brandl479a7e72008-02-05 18:13:15 +00003857 class C2(object):
3858 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003859
Georg Brandl479a7e72008-02-05 18:13:15 +00003860 class D(C):
3861 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003862
Georg Brandl479a7e72008-02-05 18:13:15 +00003863 class E(D):
3864 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003865
Georg Brandl479a7e72008-02-05 18:13:15 +00003866 class F(D, metaclass=WorkOnce):
3867 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003868
Georg Brandl479a7e72008-02-05 18:13:15 +00003869 class G(D, metaclass=WorkAlways):
3870 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003871
Georg Brandl479a7e72008-02-05 18:13:15 +00003872 # Immediate subclasses have their mro's adjusted in alphabetical
3873 # order, so E's will get adjusted before adjusting F's fails. We
3874 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003875
Georg Brandl479a7e72008-02-05 18:13:15 +00003876 E_mro_before = E.__mro__
3877 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003878
Armin Rigofd163f92005-12-29 15:59:19 +00003879 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003880 D.__bases__ = (C2,)
3881 except RuntimeError:
3882 self.assertEqual(E.__mro__, E_mro_before)
3883 self.assertEqual(D.__mro__, D_mro_before)
3884 else:
3885 self.fail("exception not propagated")
3886
3887 def test_mutable_bases_catch_mro_conflict(self):
3888 # Testing mutable bases catch mro conflict...
3889 class A(object):
3890 pass
3891
3892 class B(object):
3893 pass
3894
3895 class C(A, B):
3896 pass
3897
3898 class D(A, B):
3899 pass
3900
3901 class E(C, D):
3902 pass
3903
3904 try:
3905 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003906 except TypeError:
3907 pass
3908 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003909 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003910
Georg Brandl479a7e72008-02-05 18:13:15 +00003911 def test_mutable_names(self):
3912 # Testing mutable names...
3913 class C(object):
3914 pass
3915
3916 # C.__module__ could be 'test_descr' or '__main__'
3917 mod = C.__module__
3918
3919 C.__name__ = 'D'
3920 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3921
3922 C.__name__ = 'D.E'
3923 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3924
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003925 def test_evil_type_name(self):
3926 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3927 # execution while the type structure was not in a sane state, and a
3928 # possible segmentation fault as a result. See bug #16447.
3929 class Nasty(str):
3930 def __del__(self):
3931 C.__name__ = "other"
3932
3933 class C:
3934 pass
3935
3936 C.__name__ = Nasty("abc")
3937 C.__name__ = "normal"
3938
Georg Brandl479a7e72008-02-05 18:13:15 +00003939 def test_subclass_right_op(self):
3940 # Testing correct dispatch of subclass overloading __r<op>__...
3941
3942 # This code tests various cases where right-dispatch of a subclass
3943 # should be preferred over left-dispatch of a base class.
3944
3945 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3946
3947 class B(int):
3948 def __floordiv__(self, other):
3949 return "B.__floordiv__"
3950 def __rfloordiv__(self, other):
3951 return "B.__rfloordiv__"
3952
3953 self.assertEqual(B(1) // 1, "B.__floordiv__")
3954 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3955
3956 # Case 2: subclass of object; this is just the baseline for case 3
3957
3958 class C(object):
3959 def __floordiv__(self, other):
3960 return "C.__floordiv__"
3961 def __rfloordiv__(self, other):
3962 return "C.__rfloordiv__"
3963
3964 self.assertEqual(C() // 1, "C.__floordiv__")
3965 self.assertEqual(1 // C(), "C.__rfloordiv__")
3966
3967 # Case 3: subclass of new-style class; here it gets interesting
3968
3969 class D(C):
3970 def __floordiv__(self, other):
3971 return "D.__floordiv__"
3972 def __rfloordiv__(self, other):
3973 return "D.__rfloordiv__"
3974
3975 self.assertEqual(D() // C(), "D.__floordiv__")
3976 self.assertEqual(C() // D(), "D.__rfloordiv__")
3977
3978 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3979
3980 class E(C):
3981 pass
3982
3983 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3984
3985 self.assertEqual(E() // 1, "C.__floordiv__")
3986 self.assertEqual(1 // E(), "C.__rfloordiv__")
3987 self.assertEqual(E() // C(), "C.__floordiv__")
3988 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3989
Benjamin Petersone549ead2009-03-28 21:42:05 +00003990 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003991 def test_meth_class_get(self):
3992 # Testing __get__ method of METH_CLASS C methods...
3993 # Full coverage of descrobject.c::classmethod_get()
3994
3995 # Baseline
3996 arg = [1, 2, 3]
3997 res = {1: None, 2: None, 3: None}
3998 self.assertEqual(dict.fromkeys(arg), res)
3999 self.assertEqual({}.fromkeys(arg), res)
4000
4001 # Now get the descriptor
4002 descr = dict.__dict__["fromkeys"]
4003
4004 # More baseline using the descriptor directly
4005 self.assertEqual(descr.__get__(None, dict)(arg), res)
4006 self.assertEqual(descr.__get__({})(arg), res)
4007
4008 # Now check various error cases
4009 try:
4010 descr.__get__(None, None)
4011 except TypeError:
4012 pass
4013 else:
4014 self.fail("shouldn't have allowed descr.__get__(None, None)")
4015 try:
4016 descr.__get__(42)
4017 except TypeError:
4018 pass
4019 else:
4020 self.fail("shouldn't have allowed descr.__get__(42)")
4021 try:
4022 descr.__get__(None, 42)
4023 except TypeError:
4024 pass
4025 else:
4026 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4027 try:
4028 descr.__get__(None, int)
4029 except TypeError:
4030 pass
4031 else:
4032 self.fail("shouldn't have allowed descr.__get__(None, int)")
4033
4034 def test_isinst_isclass(self):
4035 # Testing proxy isinstance() and isclass()...
4036 class Proxy(object):
4037 def __init__(self, obj):
4038 self.__obj = obj
4039 def __getattribute__(self, name):
4040 if name.startswith("_Proxy__"):
4041 return object.__getattribute__(self, name)
4042 else:
4043 return getattr(self.__obj, name)
4044 # Test with a classic class
4045 class C:
4046 pass
4047 a = C()
4048 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004049 self.assertIsInstance(a, C) # Baseline
4050 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004051 # Test with a classic subclass
4052 class D(C):
4053 pass
4054 a = D()
4055 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004056 self.assertIsInstance(a, C) # Baseline
4057 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004058 # Test with a new-style class
4059 class C(object):
4060 pass
4061 a = C()
4062 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004063 self.assertIsInstance(a, C) # Baseline
4064 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004065 # Test with a new-style subclass
4066 class D(C):
4067 pass
4068 a = D()
4069 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004070 self.assertIsInstance(a, C) # Baseline
4071 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004072
4073 def test_proxy_super(self):
4074 # Testing super() for a proxy object...
4075 class Proxy(object):
4076 def __init__(self, obj):
4077 self.__obj = obj
4078 def __getattribute__(self, name):
4079 if name.startswith("_Proxy__"):
4080 return object.__getattribute__(self, name)
4081 else:
4082 return getattr(self.__obj, name)
4083
4084 class B(object):
4085 def f(self):
4086 return "B.f"
4087
4088 class C(B):
4089 def f(self):
4090 return super(C, self).f() + "->C.f"
4091
4092 obj = C()
4093 p = Proxy(obj)
4094 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4095
4096 def test_carloverre(self):
4097 # Testing prohibition of Carlo Verre's hack...
4098 try:
4099 object.__setattr__(str, "foo", 42)
4100 except TypeError:
4101 pass
4102 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004103 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004104 try:
4105 object.__delattr__(str, "lower")
4106 except TypeError:
4107 pass
4108 else:
4109 self.fail("Carlo Verre __delattr__ succeeded!")
4110
4111 def test_weakref_segfault(self):
4112 # Testing weakref segfault...
4113 # SF 742911
4114 import weakref
4115
4116 class Provoker:
4117 def __init__(self, referrent):
4118 self.ref = weakref.ref(referrent)
4119
4120 def __del__(self):
4121 x = self.ref()
4122
4123 class Oops(object):
4124 pass
4125
4126 o = Oops()
4127 o.whatever = Provoker(o)
4128 del o
4129
4130 def test_wrapper_segfault(self):
4131 # SF 927248: deeply nested wrappers could cause stack overflow
4132 f = lambda:None
4133 for i in range(1000000):
4134 f = f.__call__
4135 f = None
4136
4137 def test_file_fault(self):
4138 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004139 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004140 class StdoutGuard:
4141 def __getattr__(self, attr):
4142 sys.stdout = sys.__stdout__
4143 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4144 sys.stdout = StdoutGuard()
4145 try:
4146 print("Oops!")
4147 except RuntimeError:
4148 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004149 finally:
4150 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004151
4152 def test_vicious_descriptor_nonsense(self):
4153 # Testing vicious_descriptor_nonsense...
4154
4155 # A potential segfault spotted by Thomas Wouters in mail to
4156 # python-dev 2003-04-17, turned into an example & fixed by Michael
4157 # Hudson just less than four months later...
4158
4159 class Evil(object):
4160 def __hash__(self):
4161 return hash('attr')
4162 def __eq__(self, other):
4163 del C.attr
4164 return 0
4165
4166 class Descr(object):
4167 def __get__(self, ob, type=None):
4168 return 1
4169
4170 class C(object):
4171 attr = Descr()
4172
4173 c = C()
4174 c.__dict__[Evil()] = 0
4175
4176 self.assertEqual(c.attr, 1)
4177 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004178 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004179 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004180
4181 def test_init(self):
4182 # SF 1155938
4183 class Foo(object):
4184 def __init__(self):
4185 return 10
4186 try:
4187 Foo()
4188 except TypeError:
4189 pass
4190 else:
4191 self.fail("did not test __init__() for None return")
4192
4193 def test_method_wrapper(self):
4194 # Testing method-wrapper objects...
4195 # <type 'method-wrapper'> did not support any reflection before 2.5
4196
Mark Dickinson211c6252009-02-01 10:28:51 +00004197 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004198
4199 l = []
4200 self.assertEqual(l.__add__, l.__add__)
4201 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004202 self.assertNotEqual(l.__add__, [5].__add__)
4203 self.assertNotEqual(l.__add__, l.__mul__)
4204 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004205 if hasattr(l.__add__, '__self__'):
4206 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004207 self.assertIs(l.__add__.__self__, l)
4208 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004209 else:
4210 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004211 self.assertIs(l.__add__.im_self, l)
4212 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004213 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4214 try:
4215 hash(l.__add__)
4216 except TypeError:
4217 pass
4218 else:
4219 self.fail("no TypeError from hash([].__add__)")
4220
4221 t = ()
4222 t += (7,)
4223 self.assertEqual(t.__add__, (7,).__add__)
4224 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4225
4226 def test_not_implemented(self):
4227 # Testing NotImplemented...
4228 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004229 import operator
4230
4231 def specialmethod(self, other):
4232 return NotImplemented
4233
4234 def check(expr, x, y):
4235 try:
4236 exec(expr, {'x': x, 'y': y, 'operator': operator})
4237 except TypeError:
4238 pass
4239 else:
4240 self.fail("no TypeError from %r" % (expr,))
4241
4242 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4243 # TypeErrors
4244 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4245 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004246 for name, expr, iexpr in [
4247 ('__add__', 'x + y', 'x += y'),
4248 ('__sub__', 'x - y', 'x -= y'),
4249 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004250 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004251 ('__truediv__', 'x / y', 'x /= y'),
4252 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004253 ('__mod__', 'x % y', 'x %= y'),
4254 ('__divmod__', 'divmod(x, y)', None),
4255 ('__pow__', 'x ** y', 'x **= y'),
4256 ('__lshift__', 'x << y', 'x <<= y'),
4257 ('__rshift__', 'x >> y', 'x >>= y'),
4258 ('__and__', 'x & y', 'x &= y'),
4259 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004260 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004261 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004262 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004263 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004264 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004265 check(expr, a, N1)
4266 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004267 if iexpr:
4268 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004269 check(iexpr, a, N1)
4270 check(iexpr, a, N2)
4271 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004272 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004273 c = C()
4274 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004275 check(iexpr, c, N1)
4276 check(iexpr, c, N2)
4277
Georg Brandl479a7e72008-02-05 18:13:15 +00004278 def test_assign_slice(self):
4279 # ceval.c's assign_slice used to check for
4280 # tp->tp_as_sequence->sq_slice instead of
4281 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004282
Georg Brandl479a7e72008-02-05 18:13:15 +00004283 class C(object):
4284 def __setitem__(self, idx, value):
4285 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004286
Georg Brandl479a7e72008-02-05 18:13:15 +00004287 c = C()
4288 c[1:2] = 3
4289 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004290
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004291 def test_set_and_no_get(self):
4292 # See
4293 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4294 class Descr(object):
4295
4296 def __init__(self, name):
4297 self.name = name
4298
4299 def __set__(self, obj, value):
4300 obj.__dict__[self.name] = value
4301 descr = Descr("a")
4302
4303 class X(object):
4304 a = descr
4305
4306 x = X()
4307 self.assertIs(x.a, descr)
4308 x.a = 42
4309 self.assertEqual(x.a, 42)
4310
Benjamin Peterson21896a32010-03-21 22:03:03 +00004311 # Also check type_getattro for correctness.
4312 class Meta(type):
4313 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004314 class X(metaclass=Meta):
4315 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004316 X.a = 42
4317 Meta.a = Descr("a")
4318 self.assertEqual(X.a, 42)
4319
Benjamin Peterson9262b842008-11-17 22:45:50 +00004320 def test_getattr_hooks(self):
4321 # issue 4230
4322
4323 class Descriptor(object):
4324 counter = 0
4325 def __get__(self, obj, objtype=None):
4326 def getter(name):
4327 self.counter += 1
4328 raise AttributeError(name)
4329 return getter
4330
4331 descr = Descriptor()
4332 class A(object):
4333 __getattribute__ = descr
4334 class B(object):
4335 __getattr__ = descr
4336 class C(object):
4337 __getattribute__ = descr
4338 __getattr__ = descr
4339
4340 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004341 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004342 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004343 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004344 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004345 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004346
Benjamin Peterson9262b842008-11-17 22:45:50 +00004347 class EvilGetattribute(object):
4348 # This used to segfault
4349 def __getattr__(self, name):
4350 raise AttributeError(name)
4351 def __getattribute__(self, name):
4352 del EvilGetattribute.__getattr__
4353 for i in range(5):
4354 gc.collect()
4355 raise AttributeError(name)
4356
4357 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4358
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004359 def test_type___getattribute__(self):
4360 self.assertRaises(TypeError, type.__getattribute__, list, type)
4361
Benjamin Peterson477ba912011-01-12 15:34:01 +00004362 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004363 # type pretends not to have __abstractmethods__.
4364 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4365 class meta(type):
4366 pass
4367 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004368 class X(object):
4369 pass
4370 with self.assertRaises(AttributeError):
4371 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004372
Victor Stinner3249dec2011-05-01 23:19:15 +02004373 def test_proxy_call(self):
4374 class FakeStr:
4375 __class__ = str
4376
4377 fake_str = FakeStr()
4378 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004379 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004380
4381 # call a method descriptor
4382 with self.assertRaises(TypeError):
4383 str.split(fake_str)
4384
4385 # call a slot wrapper descriptor
4386 with self.assertRaises(TypeError):
4387 str.__add__(fake_str, "abc")
4388
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004389 def test_repr_as_str(self):
4390 # Issue #11603: crash or infinite loop when rebinding __str__ as
4391 # __repr__.
4392 class Foo:
4393 pass
4394 Foo.__repr__ = Foo.__str__
4395 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004396 self.assertRaises(RecursionError, str, foo)
4397 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004398
4399 def test_mixing_slot_wrappers(self):
4400 class X(dict):
4401 __setattr__ = dict.__setitem__
4402 x = X()
4403 x.y = 42
4404 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004405
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004406 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004407 with self.assertRaises(ValueError) as cm:
4408 class X:
4409 __slots__ = ["foo"]
4410 foo = None
4411 m = str(cm.exception)
4412 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4413
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004414 def test_set_doc(self):
4415 class X:
4416 "elephant"
4417 X.__doc__ = "banana"
4418 self.assertEqual(X.__doc__, "banana")
4419 with self.assertRaises(TypeError) as cm:
4420 type(list).__dict__["__doc__"].__set__(list, "blah")
4421 self.assertIn("can't set list.__doc__", str(cm.exception))
4422 with self.assertRaises(TypeError) as cm:
4423 type(X).__dict__["__doc__"].__delete__(X)
4424 self.assertIn("can't delete X.__doc__", str(cm.exception))
4425 self.assertEqual(X.__doc__, "banana")
4426
Antoine Pitrou9d574812011-12-12 13:47:25 +01004427 def test_qualname(self):
4428 descriptors = [str.lower, complex.real, float.real, int.__add__]
4429 types = ['method', 'member', 'getset', 'wrapper']
4430
4431 # make sure we have an example of each type of descriptor
4432 for d, n in zip(descriptors, types):
4433 self.assertEqual(type(d).__name__, n + '_descriptor')
4434
4435 for d in descriptors:
4436 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4437 self.assertEqual(d.__qualname__, qualname)
4438
4439 self.assertEqual(str.lower.__qualname__, 'str.lower')
4440 self.assertEqual(complex.real.__qualname__, 'complex.real')
4441 self.assertEqual(float.real.__qualname__, 'float.real')
4442 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4443
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004444 class X:
4445 pass
4446 with self.assertRaises(TypeError):
4447 del X.__qualname__
4448
4449 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4450 str, 'Oink')
4451
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004452 global Y
4453 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004454 class Inside:
4455 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004456 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004457 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004458
Victor Stinner6f738742012-02-25 01:22:36 +01004459 def test_qualname_dict(self):
4460 ns = {'__qualname__': 'some.name'}
4461 tp = type('Foo', (), ns)
4462 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004463 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004464 self.assertEqual(ns, {'__qualname__': 'some.name'})
4465
4466 ns = {'__qualname__': 1}
4467 self.assertRaises(TypeError, type, 'Foo', (), ns)
4468
Benjamin Peterson52c42432012-03-07 18:41:11 -06004469 def test_cycle_through_dict(self):
4470 # See bug #1469629
4471 class X(dict):
4472 def __init__(self):
4473 dict.__init__(self)
4474 self.__dict__ = self
4475 x = X()
4476 x.attr = 42
4477 wr = weakref.ref(x)
4478 del x
4479 support.gc_collect()
4480 self.assertIsNone(wr())
4481 for o in gc.get_objects():
4482 self.assertIsNot(type(o), X)
4483
Benjamin Peterson96384b92012-03-17 00:05:44 -05004484 def test_object_new_and_init_with_parameters(self):
4485 # See issue #1683368
4486 class OverrideNeither:
4487 pass
4488 self.assertRaises(TypeError, OverrideNeither, 1)
4489 self.assertRaises(TypeError, OverrideNeither, kw=1)
4490 class OverrideNew:
4491 def __new__(cls, foo, kw=0, *args, **kwds):
4492 return object.__new__(cls, *args, **kwds)
4493 class OverrideInit:
4494 def __init__(self, foo, kw=0, *args, **kwargs):
4495 return object.__init__(self, *args, **kwargs)
4496 class OverrideBoth(OverrideNew, OverrideInit):
4497 pass
4498 for case in OverrideNew, OverrideInit, OverrideBoth:
4499 case(1)
4500 case(1, kw=2)
4501 self.assertRaises(TypeError, case, 1, 2, 3)
4502 self.assertRaises(TypeError, case, 1, 2, foo=3)
4503
Benjamin Petersondf813792014-03-17 15:57:17 -05004504 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4505 class Base:
4506 pass
4507 class Sub(Base):
4508 pass
4509 self.assertIn("__dict__", Base.__dict__)
4510 self.assertNotIn("__dict__", Sub.__dict__)
4511
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004512 def test_bound_method_repr(self):
4513 class Foo:
4514 def method(self):
4515 pass
4516 self.assertRegex(repr(Foo().method),
4517 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4518
4519
4520 class Base:
4521 def method(self):
4522 pass
4523 class Derived1(Base):
4524 pass
4525 class Derived2(Base):
4526 def method(self):
4527 pass
4528 base = Base()
4529 derived1 = Derived1()
4530 derived2 = Derived2()
4531 super_d2 = super(Derived2, derived2)
4532 self.assertRegex(repr(base.method),
4533 r"<bound method .*Base\.method of <.*Base object at .*>>")
4534 self.assertRegex(repr(derived1.method),
4535 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4536 self.assertRegex(repr(derived2.method),
4537 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4538 self.assertRegex(repr(super_d2.method),
4539 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4540
4541 class Foo:
4542 @classmethod
4543 def method(cls):
4544 pass
4545 foo = Foo()
4546 self.assertRegex(repr(foo.method), # access via instance
4547 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4548 self.assertRegex(repr(Foo.method), # access via the class
4549 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4550
4551
4552 class MyCallable:
4553 def __call__(self, arg):
4554 pass
4555 func = MyCallable() # func has no __name__ or __qualname__ attributes
4556 instance = object()
4557 method = types.MethodType(func, instance)
4558 self.assertRegex(repr(method),
4559 r"<bound method \? of <object object at .*>>")
4560 func.__name__ = "name"
4561 self.assertRegex(repr(method),
4562 r"<bound method name of <object object at .*>>")
4563 func.__qualname__ = "qualname"
4564 self.assertRegex(repr(method),
4565 r"<bound method qualname of <object object at .*>>")
4566
Antoine Pitrou9d574812011-12-12 13:47:25 +01004567
Georg Brandl479a7e72008-02-05 18:13:15 +00004568class DictProxyTests(unittest.TestCase):
4569 def setUp(self):
4570 class C(object):
4571 def meth(self):
4572 pass
4573 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004574
Brett Cannon7a540732011-02-22 03:04:06 +00004575 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4576 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004577 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004578 # Testing dict-proxy keys...
4579 it = self.C.__dict__.keys()
4580 self.assertNotIsInstance(it, list)
4581 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004582 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004583 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004584 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004585
Brett Cannon7a540732011-02-22 03:04:06 +00004586 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4587 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004588 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004589 # Testing dict-proxy values...
4590 it = self.C.__dict__.values()
4591 self.assertNotIsInstance(it, list)
4592 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004593 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004594
Brett Cannon7a540732011-02-22 03:04:06 +00004595 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4596 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004597 def test_iter_items(self):
4598 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004599 it = self.C.__dict__.items()
4600 self.assertNotIsInstance(it, list)
4601 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004602 keys.sort()
4603 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004604 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004605
Georg Brandl479a7e72008-02-05 18:13:15 +00004606 def test_dict_type_with_metaclass(self):
4607 # Testing type of __dict__ when metaclass set...
4608 class B(object):
4609 pass
4610 class M(type):
4611 pass
4612 class C(metaclass=M):
4613 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4614 pass
4615 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004616
Ezio Melottiac53ab62010-12-18 14:59:43 +00004617 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004618 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004619 # We can't blindly compare with the repr of another dict as ordering
4620 # of keys and values is arbitrary and may differ.
4621 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004622 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004623 self.assertTrue(r.endswith(')'), r)
4624 for k, v in self.C.__dict__.items():
4625 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004626
Christian Heimesbbffeb62008-01-24 09:42:52 +00004627
Georg Brandl479a7e72008-02-05 18:13:15 +00004628class PTypesLongInitTest(unittest.TestCase):
4629 # This is in its own TestCase so that it can be run before any other tests.
4630 def test_pytype_long_ready(self):
4631 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004632
Georg Brandl479a7e72008-02-05 18:13:15 +00004633 # This dumps core when SF bug 551412 isn't fixed --
4634 # but only when test_descr.py is run separately.
4635 # (That can't be helped -- as soon as PyType_Ready()
4636 # is called for PyLong_Type, the bug is gone.)
4637 class UserLong(object):
4638 def __pow__(self, *args):
4639 pass
4640 try:
4641 pow(0, UserLong(), 0)
4642 except:
4643 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004644
Georg Brandl479a7e72008-02-05 18:13:15 +00004645 # Another segfault only when run early
4646 # (before PyType_Ready(tuple) is called)
4647 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004648
4649
Victor Stinnerd74782b2012-03-09 00:39:08 +01004650class MiscTests(unittest.TestCase):
4651 def test_type_lookup_mro_reference(self):
4652 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4653 # the type MRO because it may be modified during the lookup, if
4654 # __bases__ is set during the lookup for example.
4655 class MyKey(object):
4656 def __hash__(self):
4657 return hash('mykey')
4658
4659 def __eq__(self, other):
4660 X.__bases__ = (Base2,)
4661
4662 class Base(object):
4663 mykey = 'from Base'
4664 mykey2 = 'from Base'
4665
4666 class Base2(object):
4667 mykey = 'from Base2'
4668 mykey2 = 'from Base2'
4669
4670 X = type('X', (Base,), {MyKey(): 5})
4671 # mykey is read from Base
4672 self.assertEqual(X.mykey, 'from Base')
4673 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4674 self.assertEqual(X.mykey2, 'from Base2')
4675
4676
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004677class PicklingTests(unittest.TestCase):
4678
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004679 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004680 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004681 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004682 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004683 if kwargs:
4684 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4685 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004686 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004687 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4688 self.assertEqual(reduce_value[1], (type(obj),) + args)
4689 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004690 if listitems is not None:
4691 self.assertListEqual(list(reduce_value[3]), listitems)
4692 else:
4693 self.assertIsNone(reduce_value[3])
4694 if dictitems is not None:
4695 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4696 else:
4697 self.assertIsNone(reduce_value[4])
4698 else:
4699 base_type = type(obj).__base__
4700 reduce_value = (copyreg._reconstructor,
4701 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004702 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004703 None if base_type is object else base_type(obj)))
4704 if state is not None:
4705 reduce_value += (state,)
4706 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4707 self.assertEqual(obj.__reduce__(), reduce_value)
4708
4709 def test_reduce(self):
4710 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4711 args = (-101, "spam")
4712 kwargs = {'bacon': -201, 'fish': -301}
4713 state = {'cheese': -401}
4714
4715 class C1:
4716 def __getnewargs__(self):
4717 return args
4718 obj = C1()
4719 for proto in protocols:
4720 self._check_reduce(proto, obj, args)
4721
4722 for name, value in state.items():
4723 setattr(obj, name, value)
4724 for proto in protocols:
4725 self._check_reduce(proto, obj, args, state=state)
4726
4727 class C2:
4728 def __getnewargs__(self):
4729 return "bad args"
4730 obj = C2()
4731 for proto in protocols:
4732 if proto >= 2:
4733 with self.assertRaises(TypeError):
4734 obj.__reduce_ex__(proto)
4735
4736 class C3:
4737 def __getnewargs_ex__(self):
4738 return (args, kwargs)
4739 obj = C3()
4740 for proto in protocols:
4741 if proto >= 4:
4742 self._check_reduce(proto, obj, args, kwargs)
4743 elif proto >= 2:
4744 with self.assertRaises(ValueError):
4745 obj.__reduce_ex__(proto)
4746
4747 class C4:
4748 def __getnewargs_ex__(self):
4749 return (args, "bad dict")
4750 class C5:
4751 def __getnewargs_ex__(self):
4752 return ("bad tuple", kwargs)
4753 class C6:
4754 def __getnewargs_ex__(self):
4755 return ()
4756 class C7:
4757 def __getnewargs_ex__(self):
4758 return "bad args"
4759 for proto in protocols:
4760 for cls in C4, C5, C6, C7:
4761 obj = cls()
4762 if proto >= 2:
4763 with self.assertRaises((TypeError, ValueError)):
4764 obj.__reduce_ex__(proto)
4765
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004766 class C9:
4767 def __getnewargs_ex__(self):
4768 return (args, {})
4769 obj = C9()
4770 for proto in protocols:
4771 self._check_reduce(proto, obj, args)
4772
4773 class C10:
4774 def __getnewargs_ex__(self):
4775 raise IndexError
4776 obj = C10()
4777 for proto in protocols:
4778 if proto >= 2:
4779 with self.assertRaises(IndexError):
4780 obj.__reduce_ex__(proto)
4781
4782 class C11:
4783 def __getstate__(self):
4784 return state
4785 obj = C11()
4786 for proto in protocols:
4787 self._check_reduce(proto, obj, state=state)
4788
4789 class C12:
4790 def __getstate__(self):
4791 return "not dict"
4792 obj = C12()
4793 for proto in protocols:
4794 self._check_reduce(proto, obj, state="not dict")
4795
4796 class C13:
4797 def __getstate__(self):
4798 raise IndexError
4799 obj = C13()
4800 for proto in protocols:
4801 with self.assertRaises(IndexError):
4802 obj.__reduce_ex__(proto)
4803 if proto < 2:
4804 with self.assertRaises(IndexError):
4805 obj.__reduce__()
4806
4807 class C14:
4808 __slots__ = tuple(state)
4809 def __init__(self):
4810 for name, value in state.items():
4811 setattr(self, name, value)
4812
4813 obj = C14()
4814 for proto in protocols:
4815 if proto >= 2:
4816 self._check_reduce(proto, obj, state=(None, state))
4817 else:
4818 with self.assertRaises(TypeError):
4819 obj.__reduce_ex__(proto)
4820 with self.assertRaises(TypeError):
4821 obj.__reduce__()
4822
4823 class C15(dict):
4824 pass
4825 obj = C15({"quebec": -601})
4826 for proto in protocols:
4827 self._check_reduce(proto, obj, dictitems=dict(obj))
4828
4829 class C16(list):
4830 pass
4831 obj = C16(["yukon"])
4832 for proto in protocols:
4833 self._check_reduce(proto, obj, listitems=list(obj))
4834
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004835 def test_special_method_lookup(self):
4836 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4837 class Picky:
4838 def __getstate__(self):
4839 return {}
4840
4841 def __getattr__(self, attr):
4842 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4843 raise AssertionError(attr)
4844 return None
4845 for protocol in protocols:
4846 state = {} if protocol >= 2 else None
4847 self._check_reduce(protocol, Picky(), state=state)
4848
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004849 def _assert_is_copy(self, obj, objcopy, msg=None):
4850 """Utility method to verify if two objects are copies of each others.
4851 """
4852 if msg is None:
4853 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4854 if type(obj).__repr__ is object.__repr__:
4855 # We have this limitation for now because we use the object's repr
4856 # to help us verify that the two objects are copies. This allows
4857 # us to delegate the non-generic verification logic to the objects
4858 # themselves.
4859 raise ValueError("object passed to _assert_is_copy must " +
4860 "override the __repr__ method.")
4861 self.assertIsNot(obj, objcopy, msg=msg)
4862 self.assertIs(type(obj), type(objcopy), msg=msg)
4863 if hasattr(obj, '__dict__'):
4864 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4865 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4866 if hasattr(obj, '__slots__'):
4867 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4868 for slot in obj.__slots__:
4869 self.assertEqual(
4870 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4871 self.assertEqual(getattr(obj, slot, None),
4872 getattr(objcopy, slot, None), msg=msg)
4873 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4874
4875 @staticmethod
4876 def _generate_pickle_copiers():
4877 """Utility method to generate the many possible pickle configurations.
4878 """
4879 class PickleCopier:
4880 "This class copies object using pickle."
4881 def __init__(self, proto, dumps, loads):
4882 self.proto = proto
4883 self.dumps = dumps
4884 self.loads = loads
4885 def copy(self, obj):
4886 return self.loads(self.dumps(obj, self.proto))
4887 def __repr__(self):
4888 # We try to be as descriptive as possible here since this is
4889 # the string which we will allow us to tell the pickle
4890 # configuration we are using during debugging.
4891 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4892 .format(self.proto,
4893 self.dumps.__module__, self.dumps.__qualname__,
4894 self.loads.__module__, self.loads.__qualname__))
4895 return (PickleCopier(*args) for args in
4896 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4897 {pickle.dumps, pickle._dumps},
4898 {pickle.loads, pickle._loads}))
4899
4900 def test_pickle_slots(self):
4901 # Tests pickling of classes with __slots__.
4902
4903 # Pickling of classes with __slots__ but without __getstate__ should
4904 # fail (if using protocol 0 or 1)
4905 global C
4906 class C:
4907 __slots__ = ['a']
4908 with self.assertRaises(TypeError):
4909 pickle.dumps(C(), 0)
4910
4911 global D
4912 class D(C):
4913 pass
4914 with self.assertRaises(TypeError):
4915 pickle.dumps(D(), 0)
4916
4917 class C:
4918 "A class with __getstate__ and __setstate__ implemented."
4919 __slots__ = ['a']
4920 def __getstate__(self):
4921 state = getattr(self, '__dict__', {}).copy()
4922 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004923 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004924 try:
4925 state[slot] = getattr(self, slot)
4926 except AttributeError:
4927 pass
4928 return state
4929 def __setstate__(self, state):
4930 for k, v in state.items():
4931 setattr(self, k, v)
4932 def __repr__(self):
4933 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4934
4935 class D(C):
4936 "A subclass of a class with slots."
4937 pass
4938
4939 global E
4940 class E(C):
4941 "A subclass with an extra slot."
4942 __slots__ = ['b']
4943
4944 # Now it should work
4945 for pickle_copier in self._generate_pickle_copiers():
4946 with self.subTest(pickle_copier=pickle_copier):
4947 x = C()
4948 y = pickle_copier.copy(x)
4949 self._assert_is_copy(x, y)
4950
4951 x.a = 42
4952 y = pickle_copier.copy(x)
4953 self._assert_is_copy(x, y)
4954
4955 x = D()
4956 x.a = 42
4957 x.b = 100
4958 y = pickle_copier.copy(x)
4959 self._assert_is_copy(x, y)
4960
4961 x = E()
4962 x.a = 42
4963 x.b = "foo"
4964 y = pickle_copier.copy(x)
4965 self._assert_is_copy(x, y)
4966
4967 def test_reduce_copying(self):
4968 # Tests pickling and copying new-style classes and objects.
4969 global C1
4970 class C1:
4971 "The state of this class is copyable via its instance dict."
4972 ARGS = (1, 2)
4973 NEED_DICT_COPYING = True
4974 def __init__(self, a, b):
4975 super().__init__()
4976 self.a = a
4977 self.b = b
4978 def __repr__(self):
4979 return "C1(%r, %r)" % (self.a, self.b)
4980
4981 global C2
4982 class C2(list):
4983 "A list subclass copyable via __getnewargs__."
4984 ARGS = (1, 2)
4985 NEED_DICT_COPYING = False
4986 def __new__(cls, a, b):
4987 self = super().__new__(cls)
4988 self.a = a
4989 self.b = b
4990 return self
4991 def __init__(self, *args):
4992 super().__init__()
4993 # This helps testing that __init__ is not called during the
4994 # unpickling process, which would cause extra appends.
4995 self.append("cheese")
4996 @classmethod
4997 def __getnewargs__(cls):
4998 return cls.ARGS
4999 def __repr__(self):
5000 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5001
5002 global C3
5003 class C3(list):
5004 "A list subclass copyable via __getstate__."
5005 ARGS = (1, 2)
5006 NEED_DICT_COPYING = False
5007 def __init__(self, a, b):
5008 self.a = a
5009 self.b = b
5010 # This helps testing that __init__ is not called during the
5011 # unpickling process, which would cause extra appends.
5012 self.append("cheese")
5013 @classmethod
5014 def __getstate__(cls):
5015 return cls.ARGS
5016 def __setstate__(self, state):
5017 a, b = state
5018 self.a = a
5019 self.b = b
5020 def __repr__(self):
5021 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5022
5023 global C4
5024 class C4(int):
5025 "An int subclass copyable via __getnewargs__."
5026 ARGS = ("hello", "world", 1)
5027 NEED_DICT_COPYING = False
5028 def __new__(cls, a, b, value):
5029 self = super().__new__(cls, value)
5030 self.a = a
5031 self.b = b
5032 return self
5033 @classmethod
5034 def __getnewargs__(cls):
5035 return cls.ARGS
5036 def __repr__(self):
5037 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5038
5039 global C5
5040 class C5(int):
5041 "An int subclass copyable via __getnewargs_ex__."
5042 ARGS = (1, 2)
5043 KWARGS = {'value': 3}
5044 NEED_DICT_COPYING = False
5045 def __new__(cls, a, b, *, value=0):
5046 self = super().__new__(cls, value)
5047 self.a = a
5048 self.b = b
5049 return self
5050 @classmethod
5051 def __getnewargs_ex__(cls):
5052 return (cls.ARGS, cls.KWARGS)
5053 def __repr__(self):
5054 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5055
5056 test_classes = (C1, C2, C3, C4, C5)
5057 # Testing copying through pickle
5058 pickle_copiers = self._generate_pickle_copiers()
5059 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5060 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5061 kwargs = getattr(cls, 'KWARGS', {})
5062 obj = cls(*cls.ARGS, **kwargs)
5063 proto = pickle_copier.proto
5064 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
5065 with self.assertRaises(ValueError):
5066 pickle_copier.dumps(obj, proto)
5067 continue
5068 objcopy = pickle_copier.copy(obj)
5069 self._assert_is_copy(obj, objcopy)
5070 # For test classes that supports this, make sure we didn't go
5071 # around the reduce protocol by simply copying the attribute
5072 # dictionary. We clear attributes using the previous copy to
5073 # not mutate the original argument.
5074 if proto >= 2 and not cls.NEED_DICT_COPYING:
5075 objcopy.__dict__.clear()
5076 objcopy2 = pickle_copier.copy(objcopy)
5077 self._assert_is_copy(obj, objcopy2)
5078
5079 # Testing copying through copy.deepcopy()
5080 for cls in test_classes:
5081 with self.subTest(cls=cls):
5082 kwargs = getattr(cls, 'KWARGS', {})
5083 obj = cls(*cls.ARGS, **kwargs)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005084 objcopy = deepcopy(obj)
5085 self._assert_is_copy(obj, objcopy)
5086 # For test classes that supports this, make sure we didn't go
5087 # around the reduce protocol by simply copying the attribute
5088 # dictionary. We clear attributes using the previous copy to
5089 # not mutate the original argument.
5090 if not cls.NEED_DICT_COPYING:
5091 objcopy.__dict__.clear()
5092 objcopy2 = deepcopy(objcopy)
5093 self._assert_is_copy(obj, objcopy2)
5094
Serhiy Storchakad28bb622015-11-25 18:33:29 +02005095 def test_issue24097(self):
5096 # Slot name is freed inside __getattr__ and is later used.
5097 class S(str): # Not interned
5098 pass
5099 class A:
5100 __slotnames__ = [S('spam')]
5101 def __getattr__(self, attr):
5102 if attr == 'spam':
5103 A.__slotnames__[:] = [S('spam')]
5104 return 42
5105 else:
5106 raise AttributeError
5107
5108 import copyreg
5109 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
5110 self.assertEqual(A().__reduce__(2), expected) # Shouldn't crash
5111
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01005112
Benjamin Peterson2a605342014-03-17 16:20:12 -05005113class SharedKeyTests(unittest.TestCase):
5114
5115 @support.cpython_only
5116 def test_subclasses(self):
5117 # Verify that subclasses can share keys (per PEP 412)
5118 class A:
5119 pass
5120 class B(A):
5121 pass
5122
5123 a, b = A(), B()
5124 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5125 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5126 a.x, a.y, a.z, a.w = range(4)
5127 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5128 a2 = A()
5129 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5130 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5131 b.u, b.v, b.w, b.t = range(4)
5132 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5133
5134
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005135class DebugHelperMeta(type):
5136 """
5137 Sets default __doc__ and simplifies repr() output.
5138 """
5139 def __new__(mcls, name, bases, attrs):
5140 if attrs.get('__doc__') is None:
5141 attrs['__doc__'] = name # helps when debugging with gdb
5142 return type.__new__(mcls, name, bases, attrs)
5143 def __repr__(cls):
5144 return repr(cls.__name__)
5145
5146
5147class MroTest(unittest.TestCase):
5148 """
5149 Regressions for some bugs revealed through
5150 mcsl.mro() customization (typeobject.c: mro_internal()) and
5151 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5152 """
5153
5154 def setUp(self):
5155 self.step = 0
5156 self.ready = False
5157
5158 def step_until(self, limit):
5159 ret = (self.step < limit)
5160 if ret:
5161 self.step += 1
5162 return ret
5163
5164 def test_incomplete_set_bases_on_self(self):
5165 """
5166 type_set_bases must be aware that type->tp_mro can be NULL.
5167 """
5168 class M(DebugHelperMeta):
5169 def mro(cls):
5170 if self.step_until(1):
5171 assert cls.__mro__ is None
5172 cls.__bases__ += ()
5173
5174 return type.mro(cls)
5175
5176 class A(metaclass=M):
5177 pass
5178
5179 def test_reent_set_bases_on_base(self):
5180 """
5181 Deep reentrancy must not over-decref old_mro.
5182 """
5183 class M(DebugHelperMeta):
5184 def mro(cls):
5185 if cls.__mro__ is not None and cls.__name__ == 'B':
5186 # 4-5 steps are usually enough to make it crash somewhere
5187 if self.step_until(10):
5188 A.__bases__ += ()
5189
5190 return type.mro(cls)
5191
5192 class A(metaclass=M):
5193 pass
5194 class B(A):
5195 pass
5196 B.__bases__ += ()
5197
5198 def test_reent_set_bases_on_direct_base(self):
5199 """
5200 Similar to test_reent_set_bases_on_base, but may crash differently.
5201 """
5202 class M(DebugHelperMeta):
5203 def mro(cls):
5204 base = cls.__bases__[0]
5205 if base is not object:
5206 if self.step_until(5):
5207 base.__bases__ += ()
5208
5209 return type.mro(cls)
5210
5211 class A(metaclass=M):
5212 pass
5213 class B(A):
5214 pass
5215 class C(B):
5216 pass
5217
5218 def test_reent_set_bases_tp_base_cycle(self):
5219 """
5220 type_set_bases must check for an inheritance cycle not only through
5221 MRO of the type, which may be not yet updated in case of reentrance,
5222 but also through tp_base chain, which is assigned before diving into
5223 inner calls to mro().
5224
5225 Otherwise, the following snippet can loop forever:
5226 do {
5227 // ...
5228 type = type->tp_base;
5229 } while (type != NULL);
5230
5231 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5232 would not be happy in that case, causing a stack overflow.
5233 """
5234 class M(DebugHelperMeta):
5235 def mro(cls):
5236 if self.ready:
5237 if cls.__name__ == 'B1':
5238 B2.__bases__ = (B1,)
5239 if cls.__name__ == 'B2':
5240 B1.__bases__ = (B2,)
5241 return type.mro(cls)
5242
5243 class A(metaclass=M):
5244 pass
5245 class B1(A):
5246 pass
5247 class B2(A):
5248 pass
5249
5250 self.ready = True
5251 with self.assertRaises(TypeError):
5252 B1.__bases__ += ()
5253
5254 def test_tp_subclasses_cycle_in_update_slots(self):
5255 """
5256 type_set_bases must check for reentrancy upon finishing its job
5257 by updating tp_subclasses of old/new bases of the type.
5258 Otherwise, an implicit inheritance cycle through tp_subclasses
5259 can break functions that recurse on elements of that field
5260 (like recurse_down_subclasses and mro_hierarchy) eventually
5261 leading to a stack overflow.
5262 """
5263 class M(DebugHelperMeta):
5264 def mro(cls):
5265 if self.ready and cls.__name__ == 'C':
5266 self.ready = False
5267 C.__bases__ = (B2,)
5268 return type.mro(cls)
5269
5270 class A(metaclass=M):
5271 pass
5272 class B1(A):
5273 pass
5274 class B2(A):
5275 pass
5276 class C(A):
5277 pass
5278
5279 self.ready = True
5280 C.__bases__ = (B1,)
5281 B1.__bases__ = (C,)
5282
5283 self.assertEqual(C.__bases__, (B2,))
5284 self.assertEqual(B2.__subclasses__(), [C])
5285 self.assertEqual(B1.__subclasses__(), [])
5286
5287 self.assertEqual(B1.__bases__, (C,))
5288 self.assertEqual(C.__subclasses__(), [B1])
5289
5290 def test_tp_subclasses_cycle_error_return_path(self):
5291 """
5292 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5293 a code path executed on error (goto bail).
5294 """
5295 class E(Exception):
5296 pass
5297 class M(DebugHelperMeta):
5298 def mro(cls):
5299 if self.ready and cls.__name__ == 'C':
5300 if C.__bases__ == (B2,):
5301 self.ready = False
5302 else:
5303 C.__bases__ = (B2,)
5304 raise E
5305 return type.mro(cls)
5306
5307 class A(metaclass=M):
5308 pass
5309 class B1(A):
5310 pass
5311 class B2(A):
5312 pass
5313 class C(A):
5314 pass
5315
5316 self.ready = True
5317 with self.assertRaises(E):
5318 C.__bases__ = (B1,)
5319 B1.__bases__ = (C,)
5320
5321 self.assertEqual(C.__bases__, (B2,))
5322 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5323
5324 def test_incomplete_extend(self):
5325 """
5326 Extending an unitialized type with type->tp_mro == NULL must
5327 throw a reasonable TypeError exception, instead of failing
5328 with PyErr_BadInternalCall.
5329 """
5330 class M(DebugHelperMeta):
5331 def mro(cls):
5332 if cls.__mro__ is None and cls.__name__ != 'X':
5333 with self.assertRaises(TypeError):
5334 class X(cls):
5335 pass
5336
5337 return type.mro(cls)
5338
5339 class A(metaclass=M):
5340 pass
5341
5342 def test_incomplete_super(self):
5343 """
5344 Attrubute lookup on a super object must be aware that
5345 its target type can be uninitialized (type->tp_mro == NULL).
5346 """
5347 class M(DebugHelperMeta):
5348 def mro(cls):
5349 if cls.__mro__ is None:
5350 with self.assertRaises(AttributeError):
5351 super(cls, cls).xxx
5352
5353 return type.mro(cls)
5354
5355 class A(metaclass=M):
5356 pass
5357
5358
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005359def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005360 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005361 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005362 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005363 MiscTests, PicklingTests, SharedKeyTests,
5364 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005365
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005366if __name__ == "__main__":
5367 test_main()