blob: 0ef1a31e0f449742651ce3db3c98110c2502f3a7 [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
Georg Brandl479a7e72008-02-05 18:13:15 +00001039 def test_slots(self):
1040 # Testing __slots__...
1041 class C0(object):
1042 __slots__ = []
1043 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001044 self.assertNotHasAttr(x, "__dict__")
1045 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001046
1047 class C1(object):
1048 __slots__ = ['a']
1049 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001050 self.assertNotHasAttr(x, "__dict__")
1051 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001052 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001053 self.assertEqual(x.a, 1)
1054 x.a = None
1055 self.assertEqual(x.a, None)
1056 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001057 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001058
Georg Brandl479a7e72008-02-05 18:13:15 +00001059 class C3(object):
1060 __slots__ = ['a', 'b', 'c']
1061 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001062 self.assertNotHasAttr(x, "__dict__")
1063 self.assertNotHasAttr(x, 'a')
1064 self.assertNotHasAttr(x, 'b')
1065 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001066 x.a = 1
1067 x.b = 2
1068 x.c = 3
1069 self.assertEqual(x.a, 1)
1070 self.assertEqual(x.b, 2)
1071 self.assertEqual(x.c, 3)
1072
1073 class C4(object):
1074 """Validate name mangling"""
1075 __slots__ = ['__a']
1076 def __init__(self, value):
1077 self.__a = value
1078 def get(self):
1079 return self.__a
1080 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001081 self.assertNotHasAttr(x, '__dict__')
1082 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001083 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001084 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001085 x.__a = 6
1086 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001087 pass
1088 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001089 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001090
Georg Brandl479a7e72008-02-05 18:13:15 +00001091 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001092 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001093 class C(object):
1094 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001095 except TypeError:
1096 pass
1097 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001098 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001099 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001100 class C(object):
1101 __slots__ = ["foo bar"]
1102 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001103 pass
1104 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001105 self.fail("['foo bar'] slots not caught")
1106 try:
1107 class C(object):
1108 __slots__ = ["foo\0bar"]
1109 except TypeError:
1110 pass
1111 else:
1112 self.fail("['foo\\0bar'] slots not caught")
1113 try:
1114 class C(object):
1115 __slots__ = ["1"]
1116 except TypeError:
1117 pass
1118 else:
1119 self.fail("['1'] slots not caught")
1120 try:
1121 class C(object):
1122 __slots__ = [""]
1123 except TypeError:
1124 pass
1125 else:
1126 self.fail("[''] slots not caught")
1127 class C(object):
1128 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1129 # XXX(nnorwitz): was there supposed to be something tested
1130 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001131
Georg Brandl479a7e72008-02-05 18:13:15 +00001132 # Test a single string is not expanded as a sequence.
1133 class C(object):
1134 __slots__ = "abc"
1135 c = C()
1136 c.abc = 5
1137 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001138
Georg Brandl479a7e72008-02-05 18:13:15 +00001139 # Test unicode slot names
1140 # Test a single unicode string is not expanded as a sequence.
1141 class C(object):
1142 __slots__ = "abc"
1143 c = C()
1144 c.abc = 5
1145 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001146
Georg Brandl479a7e72008-02-05 18:13:15 +00001147 # _unicode_to_string used to modify slots in certain circumstances
1148 slots = ("foo", "bar")
1149 class C(object):
1150 __slots__ = slots
1151 x = C()
1152 x.foo = 5
1153 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001154 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001155 # this used to leak references
1156 try:
1157 class C(object):
1158 __slots__ = [chr(128)]
1159 except (TypeError, UnicodeEncodeError):
1160 pass
1161 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001162 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001163
Georg Brandl479a7e72008-02-05 18:13:15 +00001164 # Test leaks
1165 class Counted(object):
1166 counter = 0 # counts the number of instances alive
1167 def __init__(self):
1168 Counted.counter += 1
1169 def __del__(self):
1170 Counted.counter -= 1
1171 class C(object):
1172 __slots__ = ['a', 'b', 'c']
1173 x = C()
1174 x.a = Counted()
1175 x.b = Counted()
1176 x.c = Counted()
1177 self.assertEqual(Counted.counter, 3)
1178 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001179 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001180 self.assertEqual(Counted.counter, 0)
1181 class D(C):
1182 pass
1183 x = D()
1184 x.a = Counted()
1185 x.z = Counted()
1186 self.assertEqual(Counted.counter, 2)
1187 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001188 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001189 self.assertEqual(Counted.counter, 0)
1190 class E(D):
1191 __slots__ = ['e']
1192 x = E()
1193 x.a = Counted()
1194 x.z = Counted()
1195 x.e = Counted()
1196 self.assertEqual(Counted.counter, 3)
1197 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001198 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001199 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001200
Georg Brandl479a7e72008-02-05 18:13:15 +00001201 # Test cyclical leaks [SF bug 519621]
1202 class F(object):
1203 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001204 s = F()
1205 s.a = [Counted(), s]
1206 self.assertEqual(Counted.counter, 1)
1207 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001208 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001209 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001210
Georg Brandl479a7e72008-02-05 18:13:15 +00001211 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001212 if hasattr(gc, 'get_objects'):
1213 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001214 def __eq__(self, other):
1215 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001216 g = G()
1217 orig_objects = len(gc.get_objects())
1218 for i in range(10):
1219 g==g
1220 new_objects = len(gc.get_objects())
1221 self.assertEqual(orig_objects, new_objects)
1222
Georg Brandl479a7e72008-02-05 18:13:15 +00001223 class H(object):
1224 __slots__ = ['a', 'b']
1225 def __init__(self):
1226 self.a = 1
1227 self.b = 2
1228 def __del__(self_):
1229 self.assertEqual(self_.a, 1)
1230 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001231 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001232 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001233 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001234 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001235
Benjamin Petersond12362a2009-12-30 19:44:54 +00001236 class X(object):
1237 __slots__ = "a"
1238 with self.assertRaises(AttributeError):
1239 del X().a
1240
Georg Brandl479a7e72008-02-05 18:13:15 +00001241 def test_slots_special(self):
1242 # Testing __dict__ and __weakref__ in __slots__...
1243 class D(object):
1244 __slots__ = ["__dict__"]
1245 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001246 self.assertHasAttr(a, "__dict__")
1247 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001248 a.foo = 42
1249 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001250
Georg Brandl479a7e72008-02-05 18:13:15 +00001251 class W(object):
1252 __slots__ = ["__weakref__"]
1253 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001254 self.assertHasAttr(a, "__weakref__")
1255 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001256 try:
1257 a.foo = 42
1258 except AttributeError:
1259 pass
1260 else:
1261 self.fail("shouldn't be allowed to set a.foo")
1262
1263 class C1(W, D):
1264 __slots__ = []
1265 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001266 self.assertHasAttr(a, "__dict__")
1267 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001268 a.foo = 42
1269 self.assertEqual(a.__dict__, {"foo": 42})
1270
1271 class C2(D, W):
1272 __slots__ = []
1273 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001274 self.assertHasAttr(a, "__dict__")
1275 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001276 a.foo = 42
1277 self.assertEqual(a.__dict__, {"foo": 42})
1278
Christian Heimesa156e092008-02-16 07:38:31 +00001279 def test_slots_descriptor(self):
1280 # Issue2115: slot descriptors did not correctly check
1281 # the type of the given object
1282 import abc
1283 class MyABC(metaclass=abc.ABCMeta):
1284 __slots__ = "a"
1285
1286 class Unrelated(object):
1287 pass
1288 MyABC.register(Unrelated)
1289
1290 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001291 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001292
1293 # This used to crash
1294 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1295
Georg Brandl479a7e72008-02-05 18:13:15 +00001296 def test_dynamics(self):
1297 # Testing class attribute propagation...
1298 class D(object):
1299 pass
1300 class E(D):
1301 pass
1302 class F(D):
1303 pass
1304 D.foo = 1
1305 self.assertEqual(D.foo, 1)
1306 # Test that dynamic attributes are inherited
1307 self.assertEqual(E.foo, 1)
1308 self.assertEqual(F.foo, 1)
1309 # Test dynamic instances
1310 class C(object):
1311 pass
1312 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001313 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001314 C.foobar = 2
1315 self.assertEqual(a.foobar, 2)
1316 C.method = lambda self: 42
1317 self.assertEqual(a.method(), 42)
1318 C.__repr__ = lambda self: "C()"
1319 self.assertEqual(repr(a), "C()")
1320 C.__int__ = lambda self: 100
1321 self.assertEqual(int(a), 100)
1322 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001323 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001324 def mygetattr(self, name):
1325 if name == "spam":
1326 return "spam"
1327 raise AttributeError
1328 C.__getattr__ = mygetattr
1329 self.assertEqual(a.spam, "spam")
1330 a.new = 12
1331 self.assertEqual(a.new, 12)
1332 def mysetattr(self, name, value):
1333 if name == "spam":
1334 raise AttributeError
1335 return object.__setattr__(self, name, value)
1336 C.__setattr__ = mysetattr
1337 try:
1338 a.spam = "not spam"
1339 except AttributeError:
1340 pass
1341 else:
1342 self.fail("expected AttributeError")
1343 self.assertEqual(a.spam, "spam")
1344 class D(C):
1345 pass
1346 d = D()
1347 d.foo = 1
1348 self.assertEqual(d.foo, 1)
1349
1350 # Test handling of int*seq and seq*int
1351 class I(int):
1352 pass
1353 self.assertEqual("a"*I(2), "aa")
1354 self.assertEqual(I(2)*"a", "aa")
1355 self.assertEqual(2*I(3), 6)
1356 self.assertEqual(I(3)*2, 6)
1357 self.assertEqual(I(3)*I(2), 6)
1358
Georg Brandl479a7e72008-02-05 18:13:15 +00001359 # Test comparison of classes with dynamic metaclasses
1360 class dynamicmetaclass(type):
1361 pass
1362 class someclass(metaclass=dynamicmetaclass):
1363 pass
1364 self.assertNotEqual(someclass, object)
1365
1366 def test_errors(self):
1367 # Testing errors...
1368 try:
1369 class C(list, dict):
1370 pass
1371 except TypeError:
1372 pass
1373 else:
1374 self.fail("inheritance from both list and dict should be illegal")
1375
1376 try:
1377 class C(object, None):
1378 pass
1379 except TypeError:
1380 pass
1381 else:
1382 self.fail("inheritance from non-type should be illegal")
1383 class Classic:
1384 pass
1385
1386 try:
1387 class C(type(len)):
1388 pass
1389 except TypeError:
1390 pass
1391 else:
1392 self.fail("inheritance from CFunction should be illegal")
1393
1394 try:
1395 class C(object):
1396 __slots__ = 1
1397 except TypeError:
1398 pass
1399 else:
1400 self.fail("__slots__ = 1 should be illegal")
1401
1402 try:
1403 class C(object):
1404 __slots__ = [1]
1405 except TypeError:
1406 pass
1407 else:
1408 self.fail("__slots__ = [1] should be illegal")
1409
1410 class M1(type):
1411 pass
1412 class M2(type):
1413 pass
1414 class A1(object, metaclass=M1):
1415 pass
1416 class A2(object, metaclass=M2):
1417 pass
1418 try:
1419 class B(A1, A2):
1420 pass
1421 except TypeError:
1422 pass
1423 else:
1424 self.fail("finding the most derived metaclass should have failed")
1425
1426 def test_classmethods(self):
1427 # Testing class methods...
1428 class C(object):
1429 def foo(*a): return a
1430 goo = classmethod(foo)
1431 c = C()
1432 self.assertEqual(C.goo(1), (C, 1))
1433 self.assertEqual(c.goo(1), (C, 1))
1434 self.assertEqual(c.foo(1), (c, 1))
1435 class D(C):
1436 pass
1437 d = D()
1438 self.assertEqual(D.goo(1), (D, 1))
1439 self.assertEqual(d.goo(1), (D, 1))
1440 self.assertEqual(d.foo(1), (d, 1))
1441 self.assertEqual(D.foo(d, 1), (d, 1))
1442 # Test for a specific crash (SF bug 528132)
1443 def f(cls, arg): return (cls, arg)
1444 ff = classmethod(f)
1445 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1446 self.assertEqual(ff.__get__(0)(42), (int, 42))
1447
1448 # Test super() with classmethods (SF bug 535444)
1449 self.assertEqual(C.goo.__self__, C)
1450 self.assertEqual(D.goo.__self__, D)
1451 self.assertEqual(super(D,D).goo.__self__, D)
1452 self.assertEqual(super(D,d).goo.__self__, D)
1453 self.assertEqual(super(D,D).goo(), (D,))
1454 self.assertEqual(super(D,d).goo(), (D,))
1455
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001456 # Verify that a non-callable will raise
1457 meth = classmethod(1).__get__(1)
1458 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001459
1460 # Verify that classmethod() doesn't allow keyword args
1461 try:
1462 classmethod(f, kw=1)
1463 except TypeError:
1464 pass
1465 else:
1466 self.fail("classmethod shouldn't accept keyword args")
1467
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001468 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001469 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001470 cm.x = 42
1471 self.assertEqual(cm.x, 42)
1472 self.assertEqual(cm.__dict__, {"x" : 42})
1473 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001474 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001475
Benjamin Petersone549ead2009-03-28 21:42:05 +00001476 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001477 def test_classmethods_in_c(self):
1478 # Testing C-based class methods...
1479 import xxsubtype as spam
1480 a = (1, 2, 3)
1481 d = {'abc': 123}
1482 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1483 self.assertEqual(x, spam.spamlist)
1484 self.assertEqual(a, a1)
1485 self.assertEqual(d, d1)
1486 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1487 self.assertEqual(x, spam.spamlist)
1488 self.assertEqual(a, a1)
1489 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001490 spam_cm = spam.spamlist.__dict__['classmeth']
1491 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1492 self.assertEqual(x2, spam.spamlist)
1493 self.assertEqual(a2, a1)
1494 self.assertEqual(d2, d1)
1495 class SubSpam(spam.spamlist): pass
1496 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1497 self.assertEqual(x2, SubSpam)
1498 self.assertEqual(a2, a1)
1499 self.assertEqual(d2, d1)
1500 with self.assertRaises(TypeError):
1501 spam_cm()
1502 with self.assertRaises(TypeError):
1503 spam_cm(spam.spamlist())
1504 with self.assertRaises(TypeError):
1505 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001506
1507 def test_staticmethods(self):
1508 # Testing static methods...
1509 class C(object):
1510 def foo(*a): return a
1511 goo = staticmethod(foo)
1512 c = C()
1513 self.assertEqual(C.goo(1), (1,))
1514 self.assertEqual(c.goo(1), (1,))
1515 self.assertEqual(c.foo(1), (c, 1,))
1516 class D(C):
1517 pass
1518 d = D()
1519 self.assertEqual(D.goo(1), (1,))
1520 self.assertEqual(d.goo(1), (1,))
1521 self.assertEqual(d.foo(1), (d, 1))
1522 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001523 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001524 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001525 sm.x = 42
1526 self.assertEqual(sm.x, 42)
1527 self.assertEqual(sm.__dict__, {"x" : 42})
1528 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001529 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001530
Benjamin Petersone549ead2009-03-28 21:42:05 +00001531 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001532 def test_staticmethods_in_c(self):
1533 # Testing C-based static methods...
1534 import xxsubtype as spam
1535 a = (1, 2, 3)
1536 d = {"abc": 123}
1537 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1538 self.assertEqual(x, None)
1539 self.assertEqual(a, a1)
1540 self.assertEqual(d, d1)
1541 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1542 self.assertEqual(x, None)
1543 self.assertEqual(a, a1)
1544 self.assertEqual(d, d1)
1545
1546 def test_classic(self):
1547 # Testing classic classes...
1548 class C:
1549 def foo(*a): return a
1550 goo = classmethod(foo)
1551 c = C()
1552 self.assertEqual(C.goo(1), (C, 1))
1553 self.assertEqual(c.goo(1), (C, 1))
1554 self.assertEqual(c.foo(1), (c, 1))
1555 class D(C):
1556 pass
1557 d = D()
1558 self.assertEqual(D.goo(1), (D, 1))
1559 self.assertEqual(d.goo(1), (D, 1))
1560 self.assertEqual(d.foo(1), (d, 1))
1561 self.assertEqual(D.foo(d, 1), (d, 1))
1562 class E: # *not* subclassing from C
1563 foo = C.foo
1564 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001565 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001566
1567 def test_compattr(self):
1568 # Testing computed attributes...
1569 class C(object):
1570 class computed_attribute(object):
1571 def __init__(self, get, set=None, delete=None):
1572 self.__get = get
1573 self.__set = set
1574 self.__delete = delete
1575 def __get__(self, obj, type=None):
1576 return self.__get(obj)
1577 def __set__(self, obj, value):
1578 return self.__set(obj, value)
1579 def __delete__(self, obj):
1580 return self.__delete(obj)
1581 def __init__(self):
1582 self.__x = 0
1583 def __get_x(self):
1584 x = self.__x
1585 self.__x = x+1
1586 return x
1587 def __set_x(self, x):
1588 self.__x = x
1589 def __delete_x(self):
1590 del self.__x
1591 x = computed_attribute(__get_x, __set_x, __delete_x)
1592 a = C()
1593 self.assertEqual(a.x, 0)
1594 self.assertEqual(a.x, 1)
1595 a.x = 10
1596 self.assertEqual(a.x, 10)
1597 self.assertEqual(a.x, 11)
1598 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001599 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001600
1601 def test_newslots(self):
1602 # Testing __new__ slot override...
1603 class C(list):
1604 def __new__(cls):
1605 self = list.__new__(cls)
1606 self.foo = 1
1607 return self
1608 def __init__(self):
1609 self.foo = self.foo + 2
1610 a = C()
1611 self.assertEqual(a.foo, 3)
1612 self.assertEqual(a.__class__, C)
1613 class D(C):
1614 pass
1615 b = D()
1616 self.assertEqual(b.foo, 3)
1617 self.assertEqual(b.__class__, D)
1618
1619 def test_altmro(self):
1620 # Testing mro() and overriding it...
1621 class A(object):
1622 def f(self): return "A"
1623 class B(A):
1624 pass
1625 class C(A):
1626 def f(self): return "C"
1627 class D(B, C):
1628 pass
1629 self.assertEqual(D.mro(), [D, B, C, A, object])
1630 self.assertEqual(D.__mro__, (D, B, C, A, object))
1631 self.assertEqual(D().f(), "C")
1632
1633 class PerverseMetaType(type):
1634 def mro(cls):
1635 L = type.mro(cls)
1636 L.reverse()
1637 return L
1638 class X(D,B,C,A, metaclass=PerverseMetaType):
1639 pass
1640 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1641 self.assertEqual(X().f(), "A")
1642
1643 try:
1644 class _metaclass(type):
1645 def mro(self):
1646 return [self, dict, object]
1647 class X(object, metaclass=_metaclass):
1648 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001649 # In CPython, the class creation above already raises
1650 # TypeError, as a protection against the fact that
1651 # instances of X would segfault it. In other Python
1652 # implementations it would be ok to let the class X
1653 # be created, but instead get a clean TypeError on the
1654 # __setitem__ below.
1655 x = object.__new__(X)
1656 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001657 except TypeError:
1658 pass
1659 else:
1660 self.fail("devious mro() return not caught")
1661
1662 try:
1663 class _metaclass(type):
1664 def mro(self):
1665 return [1]
1666 class X(object, metaclass=_metaclass):
1667 pass
1668 except TypeError:
1669 pass
1670 else:
1671 self.fail("non-class mro() return not caught")
1672
1673 try:
1674 class _metaclass(type):
1675 def mro(self):
1676 return 1
1677 class X(object, metaclass=_metaclass):
1678 pass
1679 except TypeError:
1680 pass
1681 else:
1682 self.fail("non-sequence mro() return not caught")
1683
1684 def test_overloading(self):
1685 # Testing operator overloading...
1686
1687 class B(object):
1688 "Intermediate class because object doesn't have a __setattr__"
1689
1690 class C(B):
1691 def __getattr__(self, name):
1692 if name == "foo":
1693 return ("getattr", name)
1694 else:
1695 raise AttributeError
1696 def __setattr__(self, name, value):
1697 if name == "foo":
1698 self.setattr = (name, value)
1699 else:
1700 return B.__setattr__(self, name, value)
1701 def __delattr__(self, name):
1702 if name == "foo":
1703 self.delattr = name
1704 else:
1705 return B.__delattr__(self, name)
1706
1707 def __getitem__(self, key):
1708 return ("getitem", key)
1709 def __setitem__(self, key, value):
1710 self.setitem = (key, value)
1711 def __delitem__(self, key):
1712 self.delitem = key
1713
1714 a = C()
1715 self.assertEqual(a.foo, ("getattr", "foo"))
1716 a.foo = 12
1717 self.assertEqual(a.setattr, ("foo", 12))
1718 del a.foo
1719 self.assertEqual(a.delattr, "foo")
1720
1721 self.assertEqual(a[12], ("getitem", 12))
1722 a[12] = 21
1723 self.assertEqual(a.setitem, (12, 21))
1724 del a[12]
1725 self.assertEqual(a.delitem, 12)
1726
1727 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1728 a[0:10] = "foo"
1729 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1730 del a[0:10]
1731 self.assertEqual(a.delitem, (slice(0, 10)))
1732
1733 def test_methods(self):
1734 # Testing methods...
1735 class C(object):
1736 def __init__(self, x):
1737 self.x = x
1738 def foo(self):
1739 return self.x
1740 c1 = C(1)
1741 self.assertEqual(c1.foo(), 1)
1742 class D(C):
1743 boo = C.foo
1744 goo = c1.foo
1745 d2 = D(2)
1746 self.assertEqual(d2.foo(), 2)
1747 self.assertEqual(d2.boo(), 2)
1748 self.assertEqual(d2.goo(), 1)
1749 class E(object):
1750 foo = C.foo
1751 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001752 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001753
Benjamin Peterson224205f2009-05-08 03:25:19 +00001754 def test_special_method_lookup(self):
1755 # The lookup of special methods bypasses __getattr__ and
1756 # __getattribute__, but they still can be descriptors.
1757
1758 def run_context(manager):
1759 with manager:
1760 pass
1761 def iden(self):
1762 return self
1763 def hello(self):
1764 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001765 def empty_seq(self):
1766 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001767 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001768 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001769 def complex_num(self):
1770 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001771 def stop(self):
1772 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001773 def return_true(self, thing=None):
1774 return True
1775 def do_isinstance(obj):
1776 return isinstance(int, obj)
1777 def do_issubclass(obj):
1778 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001779 def do_dict_missing(checker):
1780 class DictSub(checker.__class__, dict):
1781 pass
1782 self.assertEqual(DictSub()["hi"], 4)
1783 def some_number(self_, key):
1784 self.assertEqual(key, "hi")
1785 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001786 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001787 def format_impl(self, spec):
1788 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001789
1790 # It would be nice to have every special method tested here, but I'm
1791 # only listing the ones I can remember outside of typeobject.c, since it
1792 # does it right.
1793 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001794 ("__bytes__", bytes, hello, set(), {}),
1795 ("__reversed__", reversed, empty_seq, set(), {}),
1796 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001797 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001798 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1799 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001800 ("__missing__", do_dict_missing, some_number,
1801 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001802 ("__subclasscheck__", do_issubclass, return_true,
1803 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001804 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1805 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001806 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001807 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001808 ("__floor__", math.floor, zero, set(), {}),
1809 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001810 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001811 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001812 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001813 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001814 ]
1815
1816 class Checker(object):
1817 def __getattr__(self, attr, test=self):
1818 test.fail("__getattr__ called with {0}".format(attr))
1819 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001820 if attr not in ok:
1821 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001822 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001823 class SpecialDescr(object):
1824 def __init__(self, impl):
1825 self.impl = impl
1826 def __get__(self, obj, owner):
1827 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001828 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001829 class MyException(Exception):
1830 pass
1831 class ErrDescr(object):
1832 def __get__(self, obj, owner):
1833 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001834
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001835 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001836 class X(Checker):
1837 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001838 for attr, obj in env.items():
1839 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001840 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001841 runner(X())
1842
1843 record = []
1844 class X(Checker):
1845 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001846 for attr, obj in env.items():
1847 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001848 setattr(X, name, SpecialDescr(meth_impl))
1849 runner(X())
1850 self.assertEqual(record, [1], name)
1851
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001852 class X(Checker):
1853 pass
1854 for attr, obj in env.items():
1855 setattr(X, attr, obj)
1856 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001857 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001858
Georg Brandl479a7e72008-02-05 18:13:15 +00001859 def test_specials(self):
1860 # Testing special operators...
1861 # Test operators like __hash__ for which a built-in default exists
1862
1863 # Test the default behavior for static classes
1864 class C(object):
1865 def __getitem__(self, i):
1866 if 0 <= i < 10: return i
1867 raise IndexError
1868 c1 = C()
1869 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001870 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001871 self.assertNotEqual(id(c1), id(c2))
1872 hash(c1)
1873 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001874 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001875 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001876 self.assertFalse(c1 != c1)
1877 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001878 # Note that the module name appears in str/repr, and that varies
1879 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001880 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001881 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001882 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001883 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001884 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001885 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001886 # Test the default behavior for dynamic classes
1887 class D(object):
1888 def __getitem__(self, i):
1889 if 0 <= i < 10: return i
1890 raise IndexError
1891 d1 = D()
1892 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001893 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001894 self.assertNotEqual(id(d1), id(d2))
1895 hash(d1)
1896 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001897 self.assertEqual(d1, d1)
1898 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001899 self.assertFalse(d1 != d1)
1900 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001901 # Note that the module name appears in str/repr, and that varies
1902 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001903 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001904 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001905 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001906 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001907 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001908 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001909 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001910 class Proxy(object):
1911 def __init__(self, x):
1912 self.x = x
1913 def __bool__(self):
1914 return not not self.x
1915 def __hash__(self):
1916 return hash(self.x)
1917 def __eq__(self, other):
1918 return self.x == other
1919 def __ne__(self, other):
1920 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001921 def __ge__(self, other):
1922 return self.x >= other
1923 def __gt__(self, other):
1924 return self.x > other
1925 def __le__(self, other):
1926 return self.x <= other
1927 def __lt__(self, other):
1928 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001929 def __str__(self):
1930 return "Proxy:%s" % self.x
1931 def __repr__(self):
1932 return "Proxy(%r)" % self.x
1933 def __contains__(self, value):
1934 return value in self.x
1935 p0 = Proxy(0)
1936 p1 = Proxy(1)
1937 p_1 = Proxy(-1)
1938 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001939 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001940 self.assertEqual(hash(p0), hash(0))
1941 self.assertEqual(p0, p0)
1942 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001943 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001944 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001945 self.assertTrue(p0 < p1)
1946 self.assertTrue(p0 <= p1)
1947 self.assertTrue(p1 > p0)
1948 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001949 self.assertEqual(str(p0), "Proxy:0")
1950 self.assertEqual(repr(p0), "Proxy(0)")
1951 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001952 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001953 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001954 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001955 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001956
Georg Brandl479a7e72008-02-05 18:13:15 +00001957 def test_weakrefs(self):
1958 # Testing weak references...
1959 import weakref
1960 class C(object):
1961 pass
1962 c = C()
1963 r = weakref.ref(c)
1964 self.assertEqual(r(), c)
1965 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001966 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001967 self.assertEqual(r(), None)
1968 del r
1969 class NoWeak(object):
1970 __slots__ = ['foo']
1971 no = NoWeak()
1972 try:
1973 weakref.ref(no)
1974 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001975 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00001976 else:
1977 self.fail("weakref.ref(no) should be illegal")
1978 class Weak(object):
1979 __slots__ = ['foo', '__weakref__']
1980 yes = Weak()
1981 r = weakref.ref(yes)
1982 self.assertEqual(r(), yes)
1983 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001984 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001985 self.assertEqual(r(), None)
1986 del r
1987
1988 def test_properties(self):
1989 # Testing property...
1990 class C(object):
1991 def getx(self):
1992 return self.__x
1993 def setx(self, value):
1994 self.__x = value
1995 def delx(self):
1996 del self.__x
1997 x = property(getx, setx, delx, doc="I'm the x property.")
1998 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001999 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002000 a.x = 42
2001 self.assertEqual(a._C__x, 42)
2002 self.assertEqual(a.x, 42)
2003 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002004 self.assertNotHasAttr(a, "x")
2005 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002006 C.x.__set__(a, 100)
2007 self.assertEqual(C.x.__get__(a), 100)
2008 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002009 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002010
2011 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002012 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002013
2014 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002015 self.assertIn("__doc__", attrs)
2016 self.assertIn("fget", attrs)
2017 self.assertIn("fset", attrs)
2018 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002019
2020 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002021 self.assertIs(raw.fget, C.__dict__['getx'])
2022 self.assertIs(raw.fset, C.__dict__['setx'])
2023 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002024
Raymond Hettingereac503a2015-05-13 01:09:59 -07002025 for attr in "fget", "fset", "fdel":
Georg Brandl479a7e72008-02-05 18:13:15 +00002026 try:
2027 setattr(raw, attr, 42)
2028 except AttributeError as msg:
2029 if str(msg).find('readonly') < 0:
2030 self.fail("when setting readonly attr %r on a property, "
2031 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2032 else:
2033 self.fail("expected AttributeError from trying to set readonly %r "
2034 "attr on a property" % attr)
2035
Raymond Hettingereac503a2015-05-13 01:09:59 -07002036 raw.__doc__ = 42
2037 self.assertEqual(raw.__doc__, 42)
2038
Georg Brandl479a7e72008-02-05 18:13:15 +00002039 class D(object):
2040 __getitem__ = property(lambda s: 1/0)
2041
2042 d = D()
2043 try:
2044 for i in d:
2045 str(i)
2046 except ZeroDivisionError:
2047 pass
2048 else:
2049 self.fail("expected ZeroDivisionError from bad property")
2050
R. David Murray378c0cf2010-02-24 01:46:21 +00002051 @unittest.skipIf(sys.flags.optimize >= 2,
2052 "Docstrings are omitted with -O2 and above")
2053 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002054 class E(object):
2055 def getter(self):
2056 "getter method"
2057 return 0
2058 def setter(self_, value):
2059 "setter method"
2060 pass
2061 prop = property(getter)
2062 self.assertEqual(prop.__doc__, "getter method")
2063 prop2 = property(fset=setter)
2064 self.assertEqual(prop2.__doc__, None)
2065
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002066 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002067 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002068 # this segfaulted in 2.5b2
2069 try:
2070 import _testcapi
2071 except ImportError:
2072 pass
2073 else:
2074 class X(object):
2075 p = property(_testcapi.test_with_docstring)
2076
2077 def test_properties_plus(self):
2078 class C(object):
2079 foo = property(doc="hello")
2080 @foo.getter
2081 def foo(self):
2082 return self._foo
2083 @foo.setter
2084 def foo(self, value):
2085 self._foo = abs(value)
2086 @foo.deleter
2087 def foo(self):
2088 del self._foo
2089 c = C()
2090 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002091 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002092 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002093 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002094 self.assertEqual(c._foo, 42)
2095 self.assertEqual(c.foo, 42)
2096 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002097 self.assertNotHasAttr(c, '_foo')
2098 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002099
2100 class D(C):
2101 @C.foo.deleter
2102 def foo(self):
2103 try:
2104 del self._foo
2105 except AttributeError:
2106 pass
2107 d = D()
2108 d.foo = 24
2109 self.assertEqual(d.foo, 24)
2110 del d.foo
2111 del d.foo
2112
2113 class E(object):
2114 @property
2115 def foo(self):
2116 return self._foo
2117 @foo.setter
2118 def foo(self, value):
2119 raise RuntimeError
2120 @foo.setter
2121 def foo(self, value):
2122 self._foo = abs(value)
2123 @foo.deleter
2124 def foo(self, value=None):
2125 del self._foo
2126
2127 e = E()
2128 e.foo = -42
2129 self.assertEqual(e.foo, 42)
2130 del e.foo
2131
2132 class F(E):
2133 @E.foo.deleter
2134 def foo(self):
2135 del self._foo
2136 @foo.setter
2137 def foo(self, value):
2138 self._foo = max(0, value)
2139 f = F()
2140 f.foo = -10
2141 self.assertEqual(f.foo, 0)
2142 del f.foo
2143
2144 def test_dict_constructors(self):
2145 # Testing dict constructor ...
2146 d = dict()
2147 self.assertEqual(d, {})
2148 d = dict({})
2149 self.assertEqual(d, {})
2150 d = dict({1: 2, 'a': 'b'})
2151 self.assertEqual(d, {1: 2, 'a': 'b'})
2152 self.assertEqual(d, dict(list(d.items())))
2153 self.assertEqual(d, dict(iter(d.items())))
2154 d = dict({'one':1, 'two':2})
2155 self.assertEqual(d, dict(one=1, two=2))
2156 self.assertEqual(d, dict(**d))
2157 self.assertEqual(d, dict({"one": 1}, two=2))
2158 self.assertEqual(d, dict([("two", 2)], one=1))
2159 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2160 self.assertEqual(d, dict(**d))
2161
2162 for badarg in 0, 0, 0j, "0", [0], (0,):
2163 try:
2164 dict(badarg)
2165 except TypeError:
2166 pass
2167 except ValueError:
2168 if badarg == "0":
2169 # It's a sequence, and its elements are also sequences (gotta
2170 # love strings <wink>), but they aren't of length 2, so this
2171 # one seemed better as a ValueError than a TypeError.
2172 pass
2173 else:
2174 self.fail("no TypeError from dict(%r)" % badarg)
2175 else:
2176 self.fail("no TypeError from dict(%r)" % badarg)
2177
2178 try:
2179 dict({}, {})
2180 except TypeError:
2181 pass
2182 else:
2183 self.fail("no TypeError from dict({}, {})")
2184
2185 class Mapping:
2186 # Lacks a .keys() method; will be added later.
2187 dict = {1:2, 3:4, 'a':1j}
2188
2189 try:
2190 dict(Mapping())
2191 except TypeError:
2192 pass
2193 else:
2194 self.fail("no TypeError from dict(incomplete mapping)")
2195
2196 Mapping.keys = lambda self: list(self.dict.keys())
2197 Mapping.__getitem__ = lambda self, i: self.dict[i]
2198 d = dict(Mapping())
2199 self.assertEqual(d, Mapping.dict)
2200
2201 # Init from sequence of iterable objects, each producing a 2-sequence.
2202 class AddressBookEntry:
2203 def __init__(self, first, last):
2204 self.first = first
2205 self.last = last
2206 def __iter__(self):
2207 return iter([self.first, self.last])
2208
2209 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2210 AddressBookEntry('Barry', 'Peters'),
2211 AddressBookEntry('Tim', 'Peters'),
2212 AddressBookEntry('Barry', 'Warsaw')])
2213 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2214
2215 d = dict(zip(range(4), range(1, 5)))
2216 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2217
2218 # Bad sequence lengths.
2219 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2220 try:
2221 dict(bad)
2222 except ValueError:
2223 pass
2224 else:
2225 self.fail("no ValueError from dict(%r)" % bad)
2226
2227 def test_dir(self):
2228 # Testing dir() ...
2229 junk = 12
2230 self.assertEqual(dir(), ['junk', 'self'])
2231 del junk
2232
2233 # Just make sure these don't blow up!
2234 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2235 dir(arg)
2236
2237 # Test dir on new-style classes. Since these have object as a
2238 # base class, a lot more gets sucked in.
2239 def interesting(strings):
2240 return [s for s in strings if not s.startswith('_')]
2241
2242 class C(object):
2243 Cdata = 1
2244 def Cmethod(self): pass
2245
2246 cstuff = ['Cdata', 'Cmethod']
2247 self.assertEqual(interesting(dir(C)), cstuff)
2248
2249 c = C()
2250 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002251 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002252
2253 c.cdata = 2
2254 c.cmethod = lambda self: 0
2255 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002256 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002257
2258 class A(C):
2259 Adata = 1
2260 def Amethod(self): pass
2261
2262 astuff = ['Adata', 'Amethod'] + cstuff
2263 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002264 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002265 a = A()
2266 self.assertEqual(interesting(dir(a)), astuff)
2267 a.adata = 42
2268 a.amethod = lambda self: 3
2269 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002270 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002271
2272 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002273 class M(type(sys)):
2274 pass
2275 minstance = M("m")
2276 minstance.b = 2
2277 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002278 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002279 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002280 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002281 self.assertEqual(names, ['a', 'b'])
2282
2283 class M2(M):
2284 def getdict(self):
2285 return "Not a dict!"
2286 __dict__ = property(getdict)
2287
2288 m2instance = M2("m2")
2289 m2instance.b = 2
2290 m2instance.a = 1
2291 self.assertEqual(m2instance.__dict__, "Not a dict!")
2292 try:
2293 dir(m2instance)
2294 except TypeError:
2295 pass
2296
2297 # Two essentially featureless objects, just inheriting stuff from
2298 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002299 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002300
2301 # Nasty test case for proxied objects
2302 class Wrapper(object):
2303 def __init__(self, obj):
2304 self.__obj = obj
2305 def __repr__(self):
2306 return "Wrapper(%s)" % repr(self.__obj)
2307 def __getitem__(self, key):
2308 return Wrapper(self.__obj[key])
2309 def __len__(self):
2310 return len(self.__obj)
2311 def __getattr__(self, name):
2312 return Wrapper(getattr(self.__obj, name))
2313
2314 class C(object):
2315 def __getclass(self):
2316 return Wrapper(type(self))
2317 __class__ = property(__getclass)
2318
2319 dir(C()) # This used to segfault
2320
2321 def test_supers(self):
2322 # Testing super...
2323
2324 class A(object):
2325 def meth(self, a):
2326 return "A(%r)" % a
2327
2328 self.assertEqual(A().meth(1), "A(1)")
2329
2330 class B(A):
2331 def __init__(self):
2332 self.__super = super(B, self)
2333 def meth(self, a):
2334 return "B(%r)" % a + self.__super.meth(a)
2335
2336 self.assertEqual(B().meth(2), "B(2)A(2)")
2337
2338 class C(A):
2339 def meth(self, a):
2340 return "C(%r)" % a + self.__super.meth(a)
2341 C._C__super = super(C)
2342
2343 self.assertEqual(C().meth(3), "C(3)A(3)")
2344
2345 class D(C, B):
2346 def meth(self, a):
2347 return "D(%r)" % a + super(D, self).meth(a)
2348
2349 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2350
2351 # Test for subclassing super
2352
2353 class mysuper(super):
2354 def __init__(self, *args):
2355 return super(mysuper, self).__init__(*args)
2356
2357 class E(D):
2358 def meth(self, a):
2359 return "E(%r)" % a + mysuper(E, self).meth(a)
2360
2361 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2362
2363 class F(E):
2364 def meth(self, a):
2365 s = self.__super # == mysuper(F, self)
2366 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2367 F._F__super = mysuper(F)
2368
2369 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2370
2371 # Make sure certain errors are raised
2372
2373 try:
2374 super(D, 42)
2375 except TypeError:
2376 pass
2377 else:
2378 self.fail("shouldn't allow super(D, 42)")
2379
2380 try:
2381 super(D, C())
2382 except TypeError:
2383 pass
2384 else:
2385 self.fail("shouldn't allow super(D, C())")
2386
2387 try:
2388 super(D).__get__(12)
2389 except TypeError:
2390 pass
2391 else:
2392 self.fail("shouldn't allow super(D).__get__(12)")
2393
2394 try:
2395 super(D).__get__(C())
2396 except TypeError:
2397 pass
2398 else:
2399 self.fail("shouldn't allow super(D).__get__(C())")
2400
2401 # Make sure data descriptors can be overridden and accessed via super
2402 # (new feature in Python 2.3)
2403
2404 class DDbase(object):
2405 def getx(self): return 42
2406 x = property(getx)
2407
2408 class DDsub(DDbase):
2409 def getx(self): return "hello"
2410 x = property(getx)
2411
2412 dd = DDsub()
2413 self.assertEqual(dd.x, "hello")
2414 self.assertEqual(super(DDsub, dd).x, 42)
2415
2416 # Ensure that super() lookup of descriptor from classmethod
2417 # works (SF ID# 743627)
2418
2419 class Base(object):
2420 aProp = property(lambda self: "foo")
2421
2422 class Sub(Base):
2423 @classmethod
2424 def test(klass):
2425 return super(Sub,klass).aProp
2426
2427 self.assertEqual(Sub.test(), Base.aProp)
2428
2429 # Verify that super() doesn't allow keyword args
2430 try:
2431 super(Base, kw=1)
2432 except TypeError:
2433 pass
2434 else:
2435 self.assertEqual("super shouldn't accept keyword args")
2436
2437 def test_basic_inheritance(self):
2438 # Testing inheritance from basic types...
2439
2440 class hexint(int):
2441 def __repr__(self):
2442 return hex(self)
2443 def __add__(self, other):
2444 return hexint(int.__add__(self, other))
2445 # (Note that overriding __radd__ doesn't work,
2446 # because the int type gets first dibs.)
2447 self.assertEqual(repr(hexint(7) + 9), "0x10")
2448 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2449 a = hexint(12345)
2450 self.assertEqual(a, 12345)
2451 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002452 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002453 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002454 self.assertIs((+a).__class__, int)
2455 self.assertIs((a >> 0).__class__, int)
2456 self.assertIs((a << 0).__class__, int)
2457 self.assertIs((hexint(0) << 12).__class__, int)
2458 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002459
2460 class octlong(int):
2461 __slots__ = []
2462 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002463 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002464 def __add__(self, other):
2465 return self.__class__(super(octlong, self).__add__(other))
2466 __radd__ = __add__
2467 self.assertEqual(str(octlong(3) + 5), "0o10")
2468 # (Note that overriding __radd__ here only seems to work
2469 # because the example uses a short int left argument.)
2470 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2471 a = octlong(12345)
2472 self.assertEqual(a, 12345)
2473 self.assertEqual(int(a), 12345)
2474 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002475 self.assertIs(int(a).__class__, int)
2476 self.assertIs((+a).__class__, int)
2477 self.assertIs((-a).__class__, int)
2478 self.assertIs((-octlong(0)).__class__, int)
2479 self.assertIs((a >> 0).__class__, int)
2480 self.assertIs((a << 0).__class__, int)
2481 self.assertIs((a - 0).__class__, int)
2482 self.assertIs((a * 1).__class__, int)
2483 self.assertIs((a ** 1).__class__, int)
2484 self.assertIs((a // 1).__class__, int)
2485 self.assertIs((1 * a).__class__, int)
2486 self.assertIs((a | 0).__class__, int)
2487 self.assertIs((a ^ 0).__class__, int)
2488 self.assertIs((a & -1).__class__, int)
2489 self.assertIs((octlong(0) << 12).__class__, int)
2490 self.assertIs((octlong(0) >> 12).__class__, int)
2491 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002492
2493 # Because octlong overrides __add__, we can't check the absence of +0
2494 # optimizations using octlong.
2495 class longclone(int):
2496 pass
2497 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002498 self.assertIs((a + 0).__class__, int)
2499 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002500
2501 # Check that negative clones don't segfault
2502 a = longclone(-1)
2503 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002504 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002505
2506 class precfloat(float):
2507 __slots__ = ['prec']
2508 def __init__(self, value=0.0, prec=12):
2509 self.prec = int(prec)
2510 def __repr__(self):
2511 return "%.*g" % (self.prec, self)
2512 self.assertEqual(repr(precfloat(1.1)), "1.1")
2513 a = precfloat(12345)
2514 self.assertEqual(a, 12345.0)
2515 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002516 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002517 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002518 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002519
2520 class madcomplex(complex):
2521 def __repr__(self):
2522 return "%.17gj%+.17g" % (self.imag, self.real)
2523 a = madcomplex(-3, 4)
2524 self.assertEqual(repr(a), "4j-3")
2525 base = complex(-3, 4)
2526 self.assertEqual(base.__class__, complex)
2527 self.assertEqual(a, base)
2528 self.assertEqual(complex(a), base)
2529 self.assertEqual(complex(a).__class__, complex)
2530 a = madcomplex(a) # just trying another form of the constructor
2531 self.assertEqual(repr(a), "4j-3")
2532 self.assertEqual(a, base)
2533 self.assertEqual(complex(a), base)
2534 self.assertEqual(complex(a).__class__, complex)
2535 self.assertEqual(hash(a), hash(base))
2536 self.assertEqual((+a).__class__, complex)
2537 self.assertEqual((a + 0).__class__, complex)
2538 self.assertEqual(a + 0, base)
2539 self.assertEqual((a - 0).__class__, complex)
2540 self.assertEqual(a - 0, base)
2541 self.assertEqual((a * 1).__class__, complex)
2542 self.assertEqual(a * 1, base)
2543 self.assertEqual((a / 1).__class__, complex)
2544 self.assertEqual(a / 1, base)
2545
2546 class madtuple(tuple):
2547 _rev = None
2548 def rev(self):
2549 if self._rev is not None:
2550 return self._rev
2551 L = list(self)
2552 L.reverse()
2553 self._rev = self.__class__(L)
2554 return self._rev
2555 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2556 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2557 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2558 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2559 for i in range(512):
2560 t = madtuple(range(i))
2561 u = t.rev()
2562 v = u.rev()
2563 self.assertEqual(v, t)
2564 a = madtuple((1,2,3,4,5))
2565 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002566 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002567 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002568 self.assertIs(a[:].__class__, tuple)
2569 self.assertIs((a * 1).__class__, tuple)
2570 self.assertIs((a * 0).__class__, tuple)
2571 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002572 a = madtuple(())
2573 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002574 self.assertIs(tuple(a).__class__, tuple)
2575 self.assertIs((a + a).__class__, tuple)
2576 self.assertIs((a * 0).__class__, tuple)
2577 self.assertIs((a * 1).__class__, tuple)
2578 self.assertIs((a * 2).__class__, tuple)
2579 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002580
2581 class madstring(str):
2582 _rev = None
2583 def rev(self):
2584 if self._rev is not None:
2585 return self._rev
2586 L = list(self)
2587 L.reverse()
2588 self._rev = self.__class__("".join(L))
2589 return self._rev
2590 s = madstring("abcdefghijklmnopqrstuvwxyz")
2591 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2592 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2593 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2594 for i in range(256):
2595 s = madstring("".join(map(chr, range(i))))
2596 t = s.rev()
2597 u = t.rev()
2598 self.assertEqual(u, s)
2599 s = madstring("12345")
2600 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002601 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002602
2603 base = "\x00" * 5
2604 s = madstring(base)
2605 self.assertEqual(s, base)
2606 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002607 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002608 self.assertEqual(hash(s), hash(base))
2609 self.assertEqual({s: 1}[base], 1)
2610 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002611 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002612 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002613 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002614 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002615 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002616 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002617 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002618 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002619 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002620 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002621 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002622 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002623 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002624 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002625 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002626 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002627 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002628 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002629 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002630 self.assertEqual(s.rstrip(), base)
2631 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002632 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002633 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002634 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002635 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002636 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002637 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002638 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002639 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002640 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002641 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002642 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002643 self.assertEqual(s.lower(), base)
2644
2645 class madunicode(str):
2646 _rev = None
2647 def rev(self):
2648 if self._rev is not None:
2649 return self._rev
2650 L = list(self)
2651 L.reverse()
2652 self._rev = self.__class__("".join(L))
2653 return self._rev
2654 u = madunicode("ABCDEF")
2655 self.assertEqual(u, "ABCDEF")
2656 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2657 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2658 base = "12345"
2659 u = madunicode(base)
2660 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002661 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002662 self.assertEqual(hash(u), hash(base))
2663 self.assertEqual({u: 1}[base], 1)
2664 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002665 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002666 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002667 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002668 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002669 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002670 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002671 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002672 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002673 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002674 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002675 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002676 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002677 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002678 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002679 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002680 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002681 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002683 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002684 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002685 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002686 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002687 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002688 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002689 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002690 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002691 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002692 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002693 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002694 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002695 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002696 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002697 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002698 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002699 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002700 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002701 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002702 self.assertEqual(u[0:0], "")
2703
2704 class sublist(list):
2705 pass
2706 a = sublist(range(5))
2707 self.assertEqual(a, list(range(5)))
2708 a.append("hello")
2709 self.assertEqual(a, list(range(5)) + ["hello"])
2710 a[5] = 5
2711 self.assertEqual(a, list(range(6)))
2712 a.extend(range(6, 20))
2713 self.assertEqual(a, list(range(20)))
2714 a[-5:] = []
2715 self.assertEqual(a, list(range(15)))
2716 del a[10:15]
2717 self.assertEqual(len(a), 10)
2718 self.assertEqual(a, list(range(10)))
2719 self.assertEqual(list(a), list(range(10)))
2720 self.assertEqual(a[0], 0)
2721 self.assertEqual(a[9], 9)
2722 self.assertEqual(a[-10], 0)
2723 self.assertEqual(a[-1], 9)
2724 self.assertEqual(a[:5], list(range(5)))
2725
2726 ## class CountedInput(file):
2727 ## """Counts lines read by self.readline().
2728 ##
2729 ## self.lineno is the 0-based ordinal of the last line read, up to
2730 ## a maximum of one greater than the number of lines in the file.
2731 ##
2732 ## self.ateof is true if and only if the final "" line has been read,
2733 ## at which point self.lineno stops incrementing, and further calls
2734 ## to readline() continue to return "".
2735 ## """
2736 ##
2737 ## lineno = 0
2738 ## ateof = 0
2739 ## def readline(self):
2740 ## if self.ateof:
2741 ## return ""
2742 ## s = file.readline(self)
2743 ## # Next line works too.
2744 ## # s = super(CountedInput, self).readline()
2745 ## self.lineno += 1
2746 ## if s == "":
2747 ## self.ateof = 1
2748 ## return s
2749 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002750 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002751 ## lines = ['a\n', 'b\n', 'c\n']
2752 ## try:
2753 ## f.writelines(lines)
2754 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002755 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002756 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2757 ## got = f.readline()
2758 ## self.assertEqual(expected, got)
2759 ## self.assertEqual(f.lineno, i)
2760 ## self.assertEqual(f.ateof, (i > len(lines)))
2761 ## f.close()
2762 ## finally:
2763 ## try:
2764 ## f.close()
2765 ## except:
2766 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002767 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002768
2769 def test_keywords(self):
2770 # Testing keyword args to basic type constructors ...
2771 self.assertEqual(int(x=1), 1)
2772 self.assertEqual(float(x=2), 2.0)
2773 self.assertEqual(int(x=3), 3)
2774 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2775 self.assertEqual(str(object=500), '500')
2776 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2777 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2778 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2779 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2780
2781 for constructor in (int, float, int, complex, str, str,
2782 tuple, list):
2783 try:
2784 constructor(bogus_keyword_arg=1)
2785 except TypeError:
2786 pass
2787 else:
2788 self.fail("expected TypeError from bogus keyword argument to %r"
2789 % constructor)
2790
2791 def test_str_subclass_as_dict_key(self):
2792 # Testing a str subclass used as dict key ..
2793
2794 class cistr(str):
2795 """Sublcass of str that computes __eq__ case-insensitively.
2796
2797 Also computes a hash code of the string in canonical form.
2798 """
2799
2800 def __init__(self, value):
2801 self.canonical = value.lower()
2802 self.hashcode = hash(self.canonical)
2803
2804 def __eq__(self, other):
2805 if not isinstance(other, cistr):
2806 other = cistr(other)
2807 return self.canonical == other.canonical
2808
2809 def __hash__(self):
2810 return self.hashcode
2811
2812 self.assertEqual(cistr('ABC'), 'abc')
2813 self.assertEqual('aBc', cistr('ABC'))
2814 self.assertEqual(str(cistr('ABC')), 'ABC')
2815
2816 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2817 self.assertEqual(d[cistr('one')], 1)
2818 self.assertEqual(d[cistr('tWo')], 2)
2819 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002820 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002821 self.assertEqual(d.get(cistr('thrEE')), 3)
2822
2823 def test_classic_comparisons(self):
2824 # Testing classic comparisons...
2825 class classic:
2826 pass
2827
2828 for base in (classic, int, object):
2829 class C(base):
2830 def __init__(self, value):
2831 self.value = int(value)
2832 def __eq__(self, other):
2833 if isinstance(other, C):
2834 return self.value == other.value
2835 if isinstance(other, int) or isinstance(other, int):
2836 return self.value == other
2837 return NotImplemented
2838 def __ne__(self, other):
2839 if isinstance(other, C):
2840 return self.value != other.value
2841 if isinstance(other, int) or isinstance(other, int):
2842 return self.value != other
2843 return NotImplemented
2844 def __lt__(self, other):
2845 if isinstance(other, C):
2846 return self.value < other.value
2847 if isinstance(other, int) or isinstance(other, int):
2848 return self.value < other
2849 return NotImplemented
2850 def __le__(self, other):
2851 if isinstance(other, C):
2852 return self.value <= other.value
2853 if isinstance(other, int) or isinstance(other, int):
2854 return self.value <= other
2855 return NotImplemented
2856 def __gt__(self, other):
2857 if isinstance(other, C):
2858 return self.value > other.value
2859 if isinstance(other, int) or isinstance(other, int):
2860 return self.value > other
2861 return NotImplemented
2862 def __ge__(self, other):
2863 if isinstance(other, C):
2864 return self.value >= other.value
2865 if isinstance(other, int) or isinstance(other, int):
2866 return self.value >= other
2867 return NotImplemented
2868
2869 c1 = C(1)
2870 c2 = C(2)
2871 c3 = C(3)
2872 self.assertEqual(c1, 1)
2873 c = {1: c1, 2: c2, 3: c3}
2874 for x in 1, 2, 3:
2875 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002876 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002877 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002878 eval("x %s y" % op),
2879 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002880 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002881 eval("x %s y" % op),
2882 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002883 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002884 eval("x %s y" % op),
2885 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002886
2887 def test_rich_comparisons(self):
2888 # Testing rich comparisons...
2889 class Z(complex):
2890 pass
2891 z = Z(1)
2892 self.assertEqual(z, 1+0j)
2893 self.assertEqual(1+0j, z)
2894 class ZZ(complex):
2895 def __eq__(self, other):
2896 try:
2897 return abs(self - other) <= 1e-6
2898 except:
2899 return NotImplemented
2900 zz = ZZ(1.0000003)
2901 self.assertEqual(zz, 1+0j)
2902 self.assertEqual(1+0j, zz)
2903
2904 class classic:
2905 pass
2906 for base in (classic, int, object, list):
2907 class C(base):
2908 def __init__(self, value):
2909 self.value = int(value)
2910 def __cmp__(self_, other):
2911 self.fail("shouldn't call __cmp__")
2912 def __eq__(self, other):
2913 if isinstance(other, C):
2914 return self.value == other.value
2915 if isinstance(other, int) or isinstance(other, int):
2916 return self.value == other
2917 return NotImplemented
2918 def __ne__(self, other):
2919 if isinstance(other, C):
2920 return self.value != other.value
2921 if isinstance(other, int) or isinstance(other, int):
2922 return self.value != other
2923 return NotImplemented
2924 def __lt__(self, other):
2925 if isinstance(other, C):
2926 return self.value < other.value
2927 if isinstance(other, int) or isinstance(other, int):
2928 return self.value < other
2929 return NotImplemented
2930 def __le__(self, other):
2931 if isinstance(other, C):
2932 return self.value <= other.value
2933 if isinstance(other, int) or isinstance(other, int):
2934 return self.value <= other
2935 return NotImplemented
2936 def __gt__(self, other):
2937 if isinstance(other, C):
2938 return self.value > other.value
2939 if isinstance(other, int) or isinstance(other, int):
2940 return self.value > other
2941 return NotImplemented
2942 def __ge__(self, other):
2943 if isinstance(other, C):
2944 return self.value >= other.value
2945 if isinstance(other, int) or isinstance(other, int):
2946 return self.value >= other
2947 return NotImplemented
2948 c1 = C(1)
2949 c2 = C(2)
2950 c3 = C(3)
2951 self.assertEqual(c1, 1)
2952 c = {1: c1, 2: c2, 3: c3}
2953 for x in 1, 2, 3:
2954 for y in 1, 2, 3:
2955 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002956 self.assertEqual(eval("c[x] %s c[y]" % op),
2957 eval("x %s y" % op),
2958 "x=%d, y=%d" % (x, y))
2959 self.assertEqual(eval("c[x] %s y" % op),
2960 eval("x %s y" % op),
2961 "x=%d, y=%d" % (x, y))
2962 self.assertEqual(eval("x %s c[y]" % op),
2963 eval("x %s y" % op),
2964 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002965
2966 def test_descrdoc(self):
2967 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002968 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002969 def check(descr, what):
2970 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002971 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002972 check(complex.real, "the real part of a complex number") # member descriptor
2973
2974 def test_doc_descriptor(self):
2975 # Testing __doc__ descriptor...
2976 # SF bug 542984
2977 class DocDescr(object):
2978 def __get__(self, object, otype):
2979 if object:
2980 object = object.__class__.__name__ + ' instance'
2981 if otype:
2982 otype = otype.__name__
2983 return 'object=%s; type=%s' % (object, otype)
2984 class OldClass:
2985 __doc__ = DocDescr()
2986 class NewClass(object):
2987 __doc__ = DocDescr()
2988 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2989 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2990 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2991 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2992
2993 def test_set_class(self):
2994 # Testing __class__ assignment...
2995 class C(object): pass
2996 class D(object): pass
2997 class E(object): pass
2998 class F(D, E): pass
2999 for cls in C, D, E, F:
3000 for cls2 in C, D, E, F:
3001 x = cls()
3002 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003003 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003004 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003005 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003006 def cant(x, C):
3007 try:
3008 x.__class__ = C
3009 except TypeError:
3010 pass
3011 else:
3012 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3013 try:
3014 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003015 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003016 pass
3017 else:
3018 self.fail("shouldn't allow del %r.__class__" % x)
3019 cant(C(), list)
3020 cant(list(), C)
3021 cant(C(), 1)
3022 cant(C(), object)
3023 cant(object(), list)
3024 cant(list(), object)
3025 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003026 cant(True, int)
3027 cant(2, bool)
3028 o = object()
3029 cant(o, type(1))
3030 cant(o, type(None))
3031 del o
3032 class G(object):
3033 __slots__ = ["a", "b"]
3034 class H(object):
3035 __slots__ = ["b", "a"]
3036 class I(object):
3037 __slots__ = ["a", "b"]
3038 class J(object):
3039 __slots__ = ["c", "b"]
3040 class K(object):
3041 __slots__ = ["a", "b", "d"]
3042 class L(H):
3043 __slots__ = ["e"]
3044 class M(I):
3045 __slots__ = ["e"]
3046 class N(J):
3047 __slots__ = ["__weakref__"]
3048 class P(J):
3049 __slots__ = ["__dict__"]
3050 class Q(J):
3051 pass
3052 class R(J):
3053 __slots__ = ["__dict__", "__weakref__"]
3054
3055 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3056 x = cls()
3057 x.a = 1
3058 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003059 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003060 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3061 self.assertEqual(x.a, 1)
3062 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003063 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003064 "assigning %r as __class__ for %r silently failed" % (cls, x))
3065 self.assertEqual(x.a, 1)
3066 for cls in G, J, K, L, M, N, P, R, list, Int:
3067 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3068 if cls is cls2:
3069 continue
3070 cant(cls(), cls2)
3071
Benjamin Peterson193152c2009-04-25 01:08:45 +00003072 # Issue5283: when __class__ changes in __del__, the wrong
3073 # type gets DECREF'd.
3074 class O(object):
3075 pass
3076 class A(object):
3077 def __del__(self):
3078 self.__class__ = O
3079 l = [A() for x in range(100)]
3080 del l
3081
Georg Brandl479a7e72008-02-05 18:13:15 +00003082 def test_set_dict(self):
3083 # Testing __dict__ assignment...
3084 class C(object): pass
3085 a = C()
3086 a.__dict__ = {'b': 1}
3087 self.assertEqual(a.b, 1)
3088 def cant(x, dict):
3089 try:
3090 x.__dict__ = dict
3091 except (AttributeError, TypeError):
3092 pass
3093 else:
3094 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3095 cant(a, None)
3096 cant(a, [])
3097 cant(a, 1)
3098 del a.__dict__ # Deleting __dict__ is allowed
3099
3100 class Base(object):
3101 pass
3102 def verify_dict_readonly(x):
3103 """
3104 x has to be an instance of a class inheriting from Base.
3105 """
3106 cant(x, {})
3107 try:
3108 del x.__dict__
3109 except (AttributeError, TypeError):
3110 pass
3111 else:
3112 self.fail("shouldn't allow del %r.__dict__" % x)
3113 dict_descr = Base.__dict__["__dict__"]
3114 try:
3115 dict_descr.__set__(x, {})
3116 except (AttributeError, TypeError):
3117 pass
3118 else:
3119 self.fail("dict_descr allowed access to %r's dict" % x)
3120
3121 # Classes don't allow __dict__ assignment and have readonly dicts
3122 class Meta1(type, Base):
3123 pass
3124 class Meta2(Base, type):
3125 pass
3126 class D(object, metaclass=Meta1):
3127 pass
3128 class E(object, metaclass=Meta2):
3129 pass
3130 for cls in C, D, E:
3131 verify_dict_readonly(cls)
3132 class_dict = cls.__dict__
3133 try:
3134 class_dict["spam"] = "eggs"
3135 except TypeError:
3136 pass
3137 else:
3138 self.fail("%r's __dict__ can be modified" % cls)
3139
3140 # Modules also disallow __dict__ assignment
3141 class Module1(types.ModuleType, Base):
3142 pass
3143 class Module2(Base, types.ModuleType):
3144 pass
3145 for ModuleType in Module1, Module2:
3146 mod = ModuleType("spam")
3147 verify_dict_readonly(mod)
3148 mod.__dict__["spam"] = "eggs"
3149
3150 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003151 # (at least not any more than regular exception's __dict__ can
3152 # be deleted; on CPython it is not the case, whereas on PyPy they
3153 # can, just like any other new-style instance's __dict__.)
3154 def can_delete_dict(e):
3155 try:
3156 del e.__dict__
3157 except (TypeError, AttributeError):
3158 return False
3159 else:
3160 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003161 class Exception1(Exception, Base):
3162 pass
3163 class Exception2(Base, Exception):
3164 pass
3165 for ExceptionType in Exception, Exception1, Exception2:
3166 e = ExceptionType()
3167 e.__dict__ = {"a": 1}
3168 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003169 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003170
Georg Brandl479a7e72008-02-05 18:13:15 +00003171 def test_binary_operator_override(self):
3172 # Testing overrides of binary operations...
3173 class I(int):
3174 def __repr__(self):
3175 return "I(%r)" % int(self)
3176 def __add__(self, other):
3177 return I(int(self) + int(other))
3178 __radd__ = __add__
3179 def __pow__(self, other, mod=None):
3180 if mod is None:
3181 return I(pow(int(self), int(other)))
3182 else:
3183 return I(pow(int(self), int(other), int(mod)))
3184 def __rpow__(self, other, mod=None):
3185 if mod is None:
3186 return I(pow(int(other), int(self), mod))
3187 else:
3188 return I(pow(int(other), int(self), int(mod)))
3189
3190 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3191 self.assertEqual(repr(I(1) + 2), "I(3)")
3192 self.assertEqual(repr(1 + I(2)), "I(3)")
3193 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3194 self.assertEqual(repr(2 ** I(3)), "I(8)")
3195 self.assertEqual(repr(I(2) ** 3), "I(8)")
3196 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3197 class S(str):
3198 def __eq__(self, other):
3199 return self.lower() == other.lower()
3200
3201 def test_subclass_propagation(self):
3202 # Testing propagation of slot functions to subclasses...
3203 class A(object):
3204 pass
3205 class B(A):
3206 pass
3207 class C(A):
3208 pass
3209 class D(B, C):
3210 pass
3211 d = D()
3212 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3213 A.__hash__ = lambda self: 42
3214 self.assertEqual(hash(d), 42)
3215 C.__hash__ = lambda self: 314
3216 self.assertEqual(hash(d), 314)
3217 B.__hash__ = lambda self: 144
3218 self.assertEqual(hash(d), 144)
3219 D.__hash__ = lambda self: 100
3220 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003221 D.__hash__ = None
3222 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003223 del D.__hash__
3224 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003225 B.__hash__ = None
3226 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003227 del B.__hash__
3228 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003229 C.__hash__ = None
3230 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003231 del C.__hash__
3232 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003233 A.__hash__ = None
3234 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003235 del A.__hash__
3236 self.assertEqual(hash(d), orig_hash)
3237 d.foo = 42
3238 d.bar = 42
3239 self.assertEqual(d.foo, 42)
3240 self.assertEqual(d.bar, 42)
3241 def __getattribute__(self, name):
3242 if name == "foo":
3243 return 24
3244 return object.__getattribute__(self, name)
3245 A.__getattribute__ = __getattribute__
3246 self.assertEqual(d.foo, 24)
3247 self.assertEqual(d.bar, 42)
3248 def __getattr__(self, name):
3249 if name in ("spam", "foo", "bar"):
3250 return "hello"
3251 raise AttributeError(name)
3252 B.__getattr__ = __getattr__
3253 self.assertEqual(d.spam, "hello")
3254 self.assertEqual(d.foo, 24)
3255 self.assertEqual(d.bar, 42)
3256 del A.__getattribute__
3257 self.assertEqual(d.foo, 42)
3258 del d.foo
3259 self.assertEqual(d.foo, "hello")
3260 self.assertEqual(d.bar, 42)
3261 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003262 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003263 d.foo
3264 except AttributeError:
3265 pass
3266 else:
3267 self.fail("d.foo should be undefined now")
3268
3269 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003270 class A(object):
3271 pass
3272 class B(A):
3273 pass
3274 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003275 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003276 A.__setitem__ = lambda *a: None # crash
3277
3278 def test_buffer_inheritance(self):
3279 # Testing that buffer interface is inherited ...
3280
3281 import binascii
3282 # SF bug [#470040] ParseTuple t# vs subclasses.
3283
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003284 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003285 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003286 base = b'abc'
3287 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003288 # b2a_hex uses the buffer interface to get its argument's value, via
3289 # PyArg_ParseTuple 't#' code.
3290 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3291
Georg Brandl479a7e72008-02-05 18:13:15 +00003292 class MyInt(int):
3293 pass
3294 m = MyInt(42)
3295 try:
3296 binascii.b2a_hex(m)
3297 self.fail('subclass of int should not have a buffer interface')
3298 except TypeError:
3299 pass
3300
3301 def test_str_of_str_subclass(self):
3302 # Testing __str__ defined in subclass of str ...
3303 import binascii
3304 import io
3305
3306 class octetstring(str):
3307 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003308 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003309 def __repr__(self):
3310 return self + " repr"
3311
3312 o = octetstring('A')
3313 self.assertEqual(type(o), octetstring)
3314 self.assertEqual(type(str(o)), str)
3315 self.assertEqual(type(repr(o)), str)
3316 self.assertEqual(ord(o), 0x41)
3317 self.assertEqual(str(o), '41')
3318 self.assertEqual(repr(o), 'A repr')
3319 self.assertEqual(o.__str__(), '41')
3320 self.assertEqual(o.__repr__(), 'A repr')
3321
3322 capture = io.StringIO()
3323 # Calling str() or not exercises different internal paths.
3324 print(o, file=capture)
3325 print(str(o), file=capture)
3326 self.assertEqual(capture.getvalue(), '41\n41\n')
3327 capture.close()
3328
3329 def test_keyword_arguments(self):
3330 # Testing keyword arguments to __init__, __call__...
3331 def f(a): return a
3332 self.assertEqual(f.__call__(a=42), 42)
3333 a = []
3334 list.__init__(a, sequence=[0, 1, 2])
3335 self.assertEqual(a, [0, 1, 2])
3336
3337 def test_recursive_call(self):
3338 # Testing recursive __call__() by setting to instance of class...
3339 class A(object):
3340 pass
3341
3342 A.__call__ = A()
3343 try:
3344 A()()
Yury Selivanovf488fb42015-07-03 01:04:23 -04003345 except RecursionError:
Georg Brandl479a7e72008-02-05 18:13:15 +00003346 pass
3347 else:
3348 self.fail("Recursion limit should have been reached for __call__()")
3349
3350 def test_delete_hook(self):
3351 # Testing __del__ hook...
3352 log = []
3353 class C(object):
3354 def __del__(self):
3355 log.append(1)
3356 c = C()
3357 self.assertEqual(log, [])
3358 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003359 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003360 self.assertEqual(log, [1])
3361
3362 class D(object): pass
3363 d = D()
3364 try: del d[0]
3365 except TypeError: pass
3366 else: self.fail("invalid del() didn't raise TypeError")
3367
3368 def test_hash_inheritance(self):
3369 # Testing hash of mutable subclasses...
3370
3371 class mydict(dict):
3372 pass
3373 d = mydict()
3374 try:
3375 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003376 except TypeError:
3377 pass
3378 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003379 self.fail("hash() of dict subclass should fail")
3380
3381 class mylist(list):
3382 pass
3383 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003384 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003385 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003386 except TypeError:
3387 pass
3388 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003389 self.fail("hash() of list subclass should fail")
3390
3391 def test_str_operations(self):
3392 try: 'a' + 5
3393 except TypeError: pass
3394 else: self.fail("'' + 5 doesn't raise TypeError")
3395
3396 try: ''.split('')
3397 except ValueError: pass
3398 else: self.fail("''.split('') doesn't raise ValueError")
3399
3400 try: ''.join([0])
3401 except TypeError: pass
3402 else: self.fail("''.join([0]) doesn't raise TypeError")
3403
3404 try: ''.rindex('5')
3405 except ValueError: pass
3406 else: self.fail("''.rindex('5') doesn't raise ValueError")
3407
3408 try: '%(n)s' % None
3409 except TypeError: pass
3410 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3411
3412 try: '%(n' % {}
3413 except ValueError: pass
3414 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3415
3416 try: '%*s' % ('abc')
3417 except TypeError: pass
3418 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3419
3420 try: '%*.*s' % ('abc', 5)
3421 except TypeError: pass
3422 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3423
3424 try: '%s' % (1, 2)
3425 except TypeError: pass
3426 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3427
3428 try: '%' % None
3429 except ValueError: pass
3430 else: self.fail("'%' % None doesn't raise ValueError")
3431
3432 self.assertEqual('534253'.isdigit(), 1)
3433 self.assertEqual('534253x'.isdigit(), 0)
3434 self.assertEqual('%c' % 5, '\x05')
3435 self.assertEqual('%c' % '5', '5')
3436
3437 def test_deepcopy_recursive(self):
3438 # Testing deepcopy of recursive objects...
3439 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003440 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003441 a = Node()
3442 b = Node()
3443 a.b = b
3444 b.a = a
3445 z = deepcopy(a) # This blew up before
3446
3447 def test_unintialized_modules(self):
3448 # Testing uninitialized module objects...
3449 from types import ModuleType as M
3450 m = M.__new__(M)
3451 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003452 self.assertNotHasAttr(m, "__name__")
3453 self.assertNotHasAttr(m, "__file__")
3454 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003455 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003456 m.foo = 1
3457 self.assertEqual(m.__dict__, {"foo": 1})
3458
3459 def test_funny_new(self):
3460 # Testing __new__ returning something unexpected...
3461 class C(object):
3462 def __new__(cls, arg):
3463 if isinstance(arg, str): return [1, 2, 3]
3464 elif isinstance(arg, int): return object.__new__(D)
3465 else: return object.__new__(cls)
3466 class D(C):
3467 def __init__(self, arg):
3468 self.foo = arg
3469 self.assertEqual(C("1"), [1, 2, 3])
3470 self.assertEqual(D("1"), [1, 2, 3])
3471 d = D(None)
3472 self.assertEqual(d.foo, None)
3473 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003474 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003475 self.assertEqual(d.foo, 1)
3476 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003477 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003478 self.assertEqual(d.foo, 1)
3479
3480 def test_imul_bug(self):
3481 # Testing for __imul__ problems...
3482 # SF bug 544647
3483 class C(object):
3484 def __imul__(self, other):
3485 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003486 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003487 y = x
3488 y *= 1.0
3489 self.assertEqual(y, (x, 1.0))
3490 y = x
3491 y *= 2
3492 self.assertEqual(y, (x, 2))
3493 y = x
3494 y *= 3
3495 self.assertEqual(y, (x, 3))
3496 y = x
3497 y *= 1<<100
3498 self.assertEqual(y, (x, 1<<100))
3499 y = x
3500 y *= None
3501 self.assertEqual(y, (x, None))
3502 y = x
3503 y *= "foo"
3504 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003505
Georg Brandl479a7e72008-02-05 18:13:15 +00003506 def test_copy_setstate(self):
3507 # Testing that copy.*copy() correctly uses __setstate__...
3508 import copy
3509 class C(object):
3510 def __init__(self, foo=None):
3511 self.foo = foo
3512 self.__foo = foo
3513 def setfoo(self, foo=None):
3514 self.foo = foo
3515 def getfoo(self):
3516 return self.__foo
3517 def __getstate__(self):
3518 return [self.foo]
3519 def __setstate__(self_, lst):
3520 self.assertEqual(len(lst), 1)
3521 self_.__foo = self_.foo = lst[0]
3522 a = C(42)
3523 a.setfoo(24)
3524 self.assertEqual(a.foo, 24)
3525 self.assertEqual(a.getfoo(), 42)
3526 b = copy.copy(a)
3527 self.assertEqual(b.foo, 24)
3528 self.assertEqual(b.getfoo(), 24)
3529 b = copy.deepcopy(a)
3530 self.assertEqual(b.foo, 24)
3531 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003532
Georg Brandl479a7e72008-02-05 18:13:15 +00003533 def test_slices(self):
3534 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003535
Georg Brandl479a7e72008-02-05 18:13:15 +00003536 # Strings
3537 self.assertEqual("hello"[:4], "hell")
3538 self.assertEqual("hello"[slice(4)], "hell")
3539 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3540 class S(str):
3541 def __getitem__(self, x):
3542 return str.__getitem__(self, x)
3543 self.assertEqual(S("hello")[:4], "hell")
3544 self.assertEqual(S("hello")[slice(4)], "hell")
3545 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3546 # Tuples
3547 self.assertEqual((1,2,3)[:2], (1,2))
3548 self.assertEqual((1,2,3)[slice(2)], (1,2))
3549 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3550 class T(tuple):
3551 def __getitem__(self, x):
3552 return tuple.__getitem__(self, x)
3553 self.assertEqual(T((1,2,3))[:2], (1,2))
3554 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3555 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3556 # Lists
3557 self.assertEqual([1,2,3][:2], [1,2])
3558 self.assertEqual([1,2,3][slice(2)], [1,2])
3559 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3560 class L(list):
3561 def __getitem__(self, x):
3562 return list.__getitem__(self, x)
3563 self.assertEqual(L([1,2,3])[:2], [1,2])
3564 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3565 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3566 # Now do lists and __setitem__
3567 a = L([1,2,3])
3568 a[slice(1, 3)] = [3,2]
3569 self.assertEqual(a, [1,3,2])
3570 a[slice(0, 2, 1)] = [3,1]
3571 self.assertEqual(a, [3,1,2])
3572 a.__setitem__(slice(1, 3), [2,1])
3573 self.assertEqual(a, [3,2,1])
3574 a.__setitem__(slice(0, 2, 1), [2,3])
3575 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003576
Georg Brandl479a7e72008-02-05 18:13:15 +00003577 def test_subtype_resurrection(self):
3578 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003579
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 class C(object):
3581 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003582
Georg Brandl479a7e72008-02-05 18:13:15 +00003583 def __del__(self):
3584 # resurrect the instance
3585 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003586
Georg Brandl479a7e72008-02-05 18:13:15 +00003587 c = C()
3588 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003589
Benjamin Petersone549ead2009-03-28 21:42:05 +00003590 # The most interesting thing here is whether this blows up, due to
3591 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3592 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003593 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003594
Benjamin Petersone549ead2009-03-28 21:42:05 +00003595 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003596 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003597
Georg Brandl479a7e72008-02-05 18:13:15 +00003598 # Make c mortal again, so that the test framework with -l doesn't report
3599 # it as a leak.
3600 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003601
Georg Brandl479a7e72008-02-05 18:13:15 +00003602 def test_slots_trash(self):
3603 # Testing slot trash...
3604 # Deallocating deeply nested slotted trash caused stack overflows
3605 class trash(object):
3606 __slots__ = ['x']
3607 def __init__(self, x):
3608 self.x = x
3609 o = None
3610 for i in range(50000):
3611 o = trash(o)
3612 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003613
Georg Brandl479a7e72008-02-05 18:13:15 +00003614 def test_slots_multiple_inheritance(self):
3615 # SF bug 575229, multiple inheritance w/ slots dumps core
3616 class A(object):
3617 __slots__=()
3618 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003619 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003620 class C(A,B) :
3621 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003622 if support.check_impl_detail():
3623 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003624 self.assertHasAttr(C, '__dict__')
3625 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003626 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003627
Georg Brandl479a7e72008-02-05 18:13:15 +00003628 def test_rmul(self):
3629 # Testing correct invocation of __rmul__...
3630 # SF patch 592646
3631 class C(object):
3632 def __mul__(self, other):
3633 return "mul"
3634 def __rmul__(self, other):
3635 return "rmul"
3636 a = C()
3637 self.assertEqual(a*2, "mul")
3638 self.assertEqual(a*2.2, "mul")
3639 self.assertEqual(2*a, "rmul")
3640 self.assertEqual(2.2*a, "rmul")
3641
3642 def test_ipow(self):
3643 # Testing correct invocation of __ipow__...
3644 # [SF bug 620179]
3645 class C(object):
3646 def __ipow__(self, other):
3647 pass
3648 a = C()
3649 a **= 2
3650
3651 def test_mutable_bases(self):
3652 # Testing mutable bases...
3653
3654 # stuff that should work:
3655 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003656 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003657 class C2(object):
3658 def __getattribute__(self, attr):
3659 if attr == 'a':
3660 return 2
3661 else:
3662 return super(C2, self).__getattribute__(attr)
3663 def meth(self):
3664 return 1
3665 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003666 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003667 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003668 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003669 d = D()
3670 e = E()
3671 D.__bases__ = (C,)
3672 D.__bases__ = (C2,)
3673 self.assertEqual(d.meth(), 1)
3674 self.assertEqual(e.meth(), 1)
3675 self.assertEqual(d.a, 2)
3676 self.assertEqual(e.a, 2)
3677 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003678
Georg Brandl479a7e72008-02-05 18:13:15 +00003679 try:
3680 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003681 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003682 pass
3683 else:
3684 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003685
Georg Brandl479a7e72008-02-05 18:13:15 +00003686 try:
3687 D.__bases__ = ()
3688 except TypeError as msg:
3689 if str(msg) == "a new-style class can't have only classic bases":
3690 self.fail("wrong error message for .__bases__ = ()")
3691 else:
3692 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003693
Georg Brandl479a7e72008-02-05 18:13:15 +00003694 try:
3695 D.__bases__ = (D,)
3696 except TypeError:
3697 pass
3698 else:
3699 # actually, we'll have crashed by here...
3700 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003701
Georg Brandl479a7e72008-02-05 18:13:15 +00003702 try:
3703 D.__bases__ = (C, C)
3704 except TypeError:
3705 pass
3706 else:
3707 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003708
Georg Brandl479a7e72008-02-05 18:13:15 +00003709 try:
3710 D.__bases__ = (E,)
3711 except TypeError:
3712 pass
3713 else:
3714 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003715
Benjamin Petersonae937c02009-04-18 20:54:08 +00003716 def test_builtin_bases(self):
3717 # Make sure all the builtin types can have their base queried without
3718 # segfaulting. See issue #5787.
3719 builtin_types = [tp for tp in builtins.__dict__.values()
3720 if isinstance(tp, type)]
3721 for tp in builtin_types:
3722 object.__getattribute__(tp, "__bases__")
3723 if tp is not object:
3724 self.assertEqual(len(tp.__bases__), 1, tp)
3725
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003726 class L(list):
3727 pass
3728
3729 class C(object):
3730 pass
3731
3732 class D(C):
3733 pass
3734
3735 try:
3736 L.__bases__ = (dict,)
3737 except TypeError:
3738 pass
3739 else:
3740 self.fail("shouldn't turn list subclass into dict subclass")
3741
3742 try:
3743 list.__bases__ = (dict,)
3744 except TypeError:
3745 pass
3746 else:
3747 self.fail("shouldn't be able to assign to list.__bases__")
3748
3749 try:
3750 D.__bases__ = (C, list)
3751 except TypeError:
3752 pass
3753 else:
3754 assert 0, "best_base calculation found wanting"
3755
Benjamin Petersonae937c02009-04-18 20:54:08 +00003756
Georg Brandl479a7e72008-02-05 18:13:15 +00003757 def test_mutable_bases_with_failing_mro(self):
3758 # Testing mutable bases with failing mro...
3759 class WorkOnce(type):
3760 def __new__(self, name, bases, ns):
3761 self.flag = 0
3762 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3763 def mro(self):
3764 if self.flag > 0:
3765 raise RuntimeError("bozo")
3766 else:
3767 self.flag += 1
3768 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003769
Georg Brandl479a7e72008-02-05 18:13:15 +00003770 class WorkAlways(type):
3771 def mro(self):
3772 # this is here to make sure that .mro()s aren't called
3773 # with an exception set (which was possible at one point).
3774 # An error message will be printed in a debug build.
3775 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003776 return type.mro(self)
3777
Georg Brandl479a7e72008-02-05 18:13:15 +00003778 class C(object):
3779 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003780
Georg Brandl479a7e72008-02-05 18:13:15 +00003781 class C2(object):
3782 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003783
Georg Brandl479a7e72008-02-05 18:13:15 +00003784 class D(C):
3785 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003786
Georg Brandl479a7e72008-02-05 18:13:15 +00003787 class E(D):
3788 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003789
Georg Brandl479a7e72008-02-05 18:13:15 +00003790 class F(D, metaclass=WorkOnce):
3791 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003792
Georg Brandl479a7e72008-02-05 18:13:15 +00003793 class G(D, metaclass=WorkAlways):
3794 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003795
Georg Brandl479a7e72008-02-05 18:13:15 +00003796 # Immediate subclasses have their mro's adjusted in alphabetical
3797 # order, so E's will get adjusted before adjusting F's fails. We
3798 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003799
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 E_mro_before = E.__mro__
3801 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003802
Armin Rigofd163f92005-12-29 15:59:19 +00003803 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003804 D.__bases__ = (C2,)
3805 except RuntimeError:
3806 self.assertEqual(E.__mro__, E_mro_before)
3807 self.assertEqual(D.__mro__, D_mro_before)
3808 else:
3809 self.fail("exception not propagated")
3810
3811 def test_mutable_bases_catch_mro_conflict(self):
3812 # Testing mutable bases catch mro conflict...
3813 class A(object):
3814 pass
3815
3816 class B(object):
3817 pass
3818
3819 class C(A, B):
3820 pass
3821
3822 class D(A, B):
3823 pass
3824
3825 class E(C, D):
3826 pass
3827
3828 try:
3829 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003830 except TypeError:
3831 pass
3832 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003833 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003834
Georg Brandl479a7e72008-02-05 18:13:15 +00003835 def test_mutable_names(self):
3836 # Testing mutable names...
3837 class C(object):
3838 pass
3839
3840 # C.__module__ could be 'test_descr' or '__main__'
3841 mod = C.__module__
3842
3843 C.__name__ = 'D'
3844 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3845
3846 C.__name__ = 'D.E'
3847 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3848
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003849 def test_evil_type_name(self):
3850 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3851 # execution while the type structure was not in a sane state, and a
3852 # possible segmentation fault as a result. See bug #16447.
3853 class Nasty(str):
3854 def __del__(self):
3855 C.__name__ = "other"
3856
3857 class C:
3858 pass
3859
3860 C.__name__ = Nasty("abc")
3861 C.__name__ = "normal"
3862
Georg Brandl479a7e72008-02-05 18:13:15 +00003863 def test_subclass_right_op(self):
3864 # Testing correct dispatch of subclass overloading __r<op>__...
3865
3866 # This code tests various cases where right-dispatch of a subclass
3867 # should be preferred over left-dispatch of a base class.
3868
3869 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3870
3871 class B(int):
3872 def __floordiv__(self, other):
3873 return "B.__floordiv__"
3874 def __rfloordiv__(self, other):
3875 return "B.__rfloordiv__"
3876
3877 self.assertEqual(B(1) // 1, "B.__floordiv__")
3878 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3879
3880 # Case 2: subclass of object; this is just the baseline for case 3
3881
3882 class C(object):
3883 def __floordiv__(self, other):
3884 return "C.__floordiv__"
3885 def __rfloordiv__(self, other):
3886 return "C.__rfloordiv__"
3887
3888 self.assertEqual(C() // 1, "C.__floordiv__")
3889 self.assertEqual(1 // C(), "C.__rfloordiv__")
3890
3891 # Case 3: subclass of new-style class; here it gets interesting
3892
3893 class D(C):
3894 def __floordiv__(self, other):
3895 return "D.__floordiv__"
3896 def __rfloordiv__(self, other):
3897 return "D.__rfloordiv__"
3898
3899 self.assertEqual(D() // C(), "D.__floordiv__")
3900 self.assertEqual(C() // D(), "D.__rfloordiv__")
3901
3902 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3903
3904 class E(C):
3905 pass
3906
3907 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3908
3909 self.assertEqual(E() // 1, "C.__floordiv__")
3910 self.assertEqual(1 // E(), "C.__rfloordiv__")
3911 self.assertEqual(E() // C(), "C.__floordiv__")
3912 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3913
Benjamin Petersone549ead2009-03-28 21:42:05 +00003914 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003915 def test_meth_class_get(self):
3916 # Testing __get__ method of METH_CLASS C methods...
3917 # Full coverage of descrobject.c::classmethod_get()
3918
3919 # Baseline
3920 arg = [1, 2, 3]
3921 res = {1: None, 2: None, 3: None}
3922 self.assertEqual(dict.fromkeys(arg), res)
3923 self.assertEqual({}.fromkeys(arg), res)
3924
3925 # Now get the descriptor
3926 descr = dict.__dict__["fromkeys"]
3927
3928 # More baseline using the descriptor directly
3929 self.assertEqual(descr.__get__(None, dict)(arg), res)
3930 self.assertEqual(descr.__get__({})(arg), res)
3931
3932 # Now check various error cases
3933 try:
3934 descr.__get__(None, None)
3935 except TypeError:
3936 pass
3937 else:
3938 self.fail("shouldn't have allowed descr.__get__(None, None)")
3939 try:
3940 descr.__get__(42)
3941 except TypeError:
3942 pass
3943 else:
3944 self.fail("shouldn't have allowed descr.__get__(42)")
3945 try:
3946 descr.__get__(None, 42)
3947 except TypeError:
3948 pass
3949 else:
3950 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3951 try:
3952 descr.__get__(None, int)
3953 except TypeError:
3954 pass
3955 else:
3956 self.fail("shouldn't have allowed descr.__get__(None, int)")
3957
3958 def test_isinst_isclass(self):
3959 # Testing proxy isinstance() and isclass()...
3960 class Proxy(object):
3961 def __init__(self, obj):
3962 self.__obj = obj
3963 def __getattribute__(self, name):
3964 if name.startswith("_Proxy__"):
3965 return object.__getattribute__(self, name)
3966 else:
3967 return getattr(self.__obj, name)
3968 # Test with a classic class
3969 class C:
3970 pass
3971 a = C()
3972 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003973 self.assertIsInstance(a, C) # Baseline
3974 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003975 # Test with a classic subclass
3976 class D(C):
3977 pass
3978 a = D()
3979 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003980 self.assertIsInstance(a, C) # Baseline
3981 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003982 # Test with a new-style class
3983 class C(object):
3984 pass
3985 a = C()
3986 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003987 self.assertIsInstance(a, C) # Baseline
3988 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003989 # Test with a new-style subclass
3990 class D(C):
3991 pass
3992 a = D()
3993 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003994 self.assertIsInstance(a, C) # Baseline
3995 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003996
3997 def test_proxy_super(self):
3998 # Testing super() for a proxy object...
3999 class Proxy(object):
4000 def __init__(self, obj):
4001 self.__obj = obj
4002 def __getattribute__(self, name):
4003 if name.startswith("_Proxy__"):
4004 return object.__getattribute__(self, name)
4005 else:
4006 return getattr(self.__obj, name)
4007
4008 class B(object):
4009 def f(self):
4010 return "B.f"
4011
4012 class C(B):
4013 def f(self):
4014 return super(C, self).f() + "->C.f"
4015
4016 obj = C()
4017 p = Proxy(obj)
4018 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4019
4020 def test_carloverre(self):
4021 # Testing prohibition of Carlo Verre's hack...
4022 try:
4023 object.__setattr__(str, "foo", 42)
4024 except TypeError:
4025 pass
4026 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004027 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004028 try:
4029 object.__delattr__(str, "lower")
4030 except TypeError:
4031 pass
4032 else:
4033 self.fail("Carlo Verre __delattr__ succeeded!")
4034
4035 def test_weakref_segfault(self):
4036 # Testing weakref segfault...
4037 # SF 742911
4038 import weakref
4039
4040 class Provoker:
4041 def __init__(self, referrent):
4042 self.ref = weakref.ref(referrent)
4043
4044 def __del__(self):
4045 x = self.ref()
4046
4047 class Oops(object):
4048 pass
4049
4050 o = Oops()
4051 o.whatever = Provoker(o)
4052 del o
4053
4054 def test_wrapper_segfault(self):
4055 # SF 927248: deeply nested wrappers could cause stack overflow
4056 f = lambda:None
4057 for i in range(1000000):
4058 f = f.__call__
4059 f = None
4060
4061 def test_file_fault(self):
4062 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004063 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004064 class StdoutGuard:
4065 def __getattr__(self, attr):
4066 sys.stdout = sys.__stdout__
4067 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4068 sys.stdout = StdoutGuard()
4069 try:
4070 print("Oops!")
4071 except RuntimeError:
4072 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004073 finally:
4074 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004075
4076 def test_vicious_descriptor_nonsense(self):
4077 # Testing vicious_descriptor_nonsense...
4078
4079 # A potential segfault spotted by Thomas Wouters in mail to
4080 # python-dev 2003-04-17, turned into an example & fixed by Michael
4081 # Hudson just less than four months later...
4082
4083 class Evil(object):
4084 def __hash__(self):
4085 return hash('attr')
4086 def __eq__(self, other):
4087 del C.attr
4088 return 0
4089
4090 class Descr(object):
4091 def __get__(self, ob, type=None):
4092 return 1
4093
4094 class C(object):
4095 attr = Descr()
4096
4097 c = C()
4098 c.__dict__[Evil()] = 0
4099
4100 self.assertEqual(c.attr, 1)
4101 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004102 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004103 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004104
4105 def test_init(self):
4106 # SF 1155938
4107 class Foo(object):
4108 def __init__(self):
4109 return 10
4110 try:
4111 Foo()
4112 except TypeError:
4113 pass
4114 else:
4115 self.fail("did not test __init__() for None return")
4116
4117 def test_method_wrapper(self):
4118 # Testing method-wrapper objects...
4119 # <type 'method-wrapper'> did not support any reflection before 2.5
4120
Mark Dickinson211c6252009-02-01 10:28:51 +00004121 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004122
4123 l = []
4124 self.assertEqual(l.__add__, l.__add__)
4125 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004126 self.assertNotEqual(l.__add__, [5].__add__)
4127 self.assertNotEqual(l.__add__, l.__mul__)
4128 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004129 if hasattr(l.__add__, '__self__'):
4130 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004131 self.assertIs(l.__add__.__self__, l)
4132 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004133 else:
4134 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004135 self.assertIs(l.__add__.im_self, l)
4136 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004137 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4138 try:
4139 hash(l.__add__)
4140 except TypeError:
4141 pass
4142 else:
4143 self.fail("no TypeError from hash([].__add__)")
4144
4145 t = ()
4146 t += (7,)
4147 self.assertEqual(t.__add__, (7,).__add__)
4148 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4149
4150 def test_not_implemented(self):
4151 # Testing NotImplemented...
4152 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004153 import operator
4154
4155 def specialmethod(self, other):
4156 return NotImplemented
4157
4158 def check(expr, x, y):
4159 try:
4160 exec(expr, {'x': x, 'y': y, 'operator': operator})
4161 except TypeError:
4162 pass
4163 else:
4164 self.fail("no TypeError from %r" % (expr,))
4165
4166 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4167 # TypeErrors
4168 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4169 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004170 for name, expr, iexpr in [
4171 ('__add__', 'x + y', 'x += y'),
4172 ('__sub__', 'x - y', 'x -= y'),
4173 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004174 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004175 ('__truediv__', 'x / y', 'x /= y'),
4176 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004177 ('__mod__', 'x % y', 'x %= y'),
4178 ('__divmod__', 'divmod(x, y)', None),
4179 ('__pow__', 'x ** y', 'x **= y'),
4180 ('__lshift__', 'x << y', 'x <<= y'),
4181 ('__rshift__', 'x >> y', 'x >>= y'),
4182 ('__and__', 'x & y', 'x &= y'),
4183 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004184 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004185 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004186 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004187 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004188 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004189 check(expr, a, N1)
4190 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004191 if iexpr:
4192 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004193 check(iexpr, a, N1)
4194 check(iexpr, a, N2)
4195 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004196 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004197 c = C()
4198 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004199 check(iexpr, c, N1)
4200 check(iexpr, c, N2)
4201
Georg Brandl479a7e72008-02-05 18:13:15 +00004202 def test_assign_slice(self):
4203 # ceval.c's assign_slice used to check for
4204 # tp->tp_as_sequence->sq_slice instead of
4205 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004206
Georg Brandl479a7e72008-02-05 18:13:15 +00004207 class C(object):
4208 def __setitem__(self, idx, value):
4209 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004210
Georg Brandl479a7e72008-02-05 18:13:15 +00004211 c = C()
4212 c[1:2] = 3
4213 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004214
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004215 def test_set_and_no_get(self):
4216 # See
4217 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4218 class Descr(object):
4219
4220 def __init__(self, name):
4221 self.name = name
4222
4223 def __set__(self, obj, value):
4224 obj.__dict__[self.name] = value
4225 descr = Descr("a")
4226
4227 class X(object):
4228 a = descr
4229
4230 x = X()
4231 self.assertIs(x.a, descr)
4232 x.a = 42
4233 self.assertEqual(x.a, 42)
4234
Benjamin Peterson21896a32010-03-21 22:03:03 +00004235 # Also check type_getattro for correctness.
4236 class Meta(type):
4237 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004238 class X(metaclass=Meta):
4239 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004240 X.a = 42
4241 Meta.a = Descr("a")
4242 self.assertEqual(X.a, 42)
4243
Benjamin Peterson9262b842008-11-17 22:45:50 +00004244 def test_getattr_hooks(self):
4245 # issue 4230
4246
4247 class Descriptor(object):
4248 counter = 0
4249 def __get__(self, obj, objtype=None):
4250 def getter(name):
4251 self.counter += 1
4252 raise AttributeError(name)
4253 return getter
4254
4255 descr = Descriptor()
4256 class A(object):
4257 __getattribute__ = descr
4258 class B(object):
4259 __getattr__ = descr
4260 class C(object):
4261 __getattribute__ = descr
4262 __getattr__ = descr
4263
4264 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004265 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004266 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004267 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004268 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004269 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004270
Benjamin Peterson9262b842008-11-17 22:45:50 +00004271 class EvilGetattribute(object):
4272 # This used to segfault
4273 def __getattr__(self, name):
4274 raise AttributeError(name)
4275 def __getattribute__(self, name):
4276 del EvilGetattribute.__getattr__
4277 for i in range(5):
4278 gc.collect()
4279 raise AttributeError(name)
4280
4281 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4282
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004283 def test_type___getattribute__(self):
4284 self.assertRaises(TypeError, type.__getattribute__, list, type)
4285
Benjamin Peterson477ba912011-01-12 15:34:01 +00004286 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004287 # type pretends not to have __abstractmethods__.
4288 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4289 class meta(type):
4290 pass
4291 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004292 class X(object):
4293 pass
4294 with self.assertRaises(AttributeError):
4295 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004296
Victor Stinner3249dec2011-05-01 23:19:15 +02004297 def test_proxy_call(self):
4298 class FakeStr:
4299 __class__ = str
4300
4301 fake_str = FakeStr()
4302 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004303 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004304
4305 # call a method descriptor
4306 with self.assertRaises(TypeError):
4307 str.split(fake_str)
4308
4309 # call a slot wrapper descriptor
4310 with self.assertRaises(TypeError):
4311 str.__add__(fake_str, "abc")
4312
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004313 def test_repr_as_str(self):
4314 # Issue #11603: crash or infinite loop when rebinding __str__ as
4315 # __repr__.
4316 class Foo:
4317 pass
4318 Foo.__repr__ = Foo.__str__
4319 foo = Foo()
Yury Selivanovf488fb42015-07-03 01:04:23 -04004320 self.assertRaises(RecursionError, str, foo)
4321 self.assertRaises(RecursionError, repr, foo)
Benjamin Peterson7b166872012-04-24 11:06:25 -04004322
4323 def test_mixing_slot_wrappers(self):
4324 class X(dict):
4325 __setattr__ = dict.__setitem__
4326 x = X()
4327 x.y = 42
4328 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004329
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004330 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004331 with self.assertRaises(ValueError) as cm:
4332 class X:
4333 __slots__ = ["foo"]
4334 foo = None
4335 m = str(cm.exception)
4336 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4337
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004338 def test_set_doc(self):
4339 class X:
4340 "elephant"
4341 X.__doc__ = "banana"
4342 self.assertEqual(X.__doc__, "banana")
4343 with self.assertRaises(TypeError) as cm:
4344 type(list).__dict__["__doc__"].__set__(list, "blah")
4345 self.assertIn("can't set list.__doc__", str(cm.exception))
4346 with self.assertRaises(TypeError) as cm:
4347 type(X).__dict__["__doc__"].__delete__(X)
4348 self.assertIn("can't delete X.__doc__", str(cm.exception))
4349 self.assertEqual(X.__doc__, "banana")
4350
Antoine Pitrou9d574812011-12-12 13:47:25 +01004351 def test_qualname(self):
4352 descriptors = [str.lower, complex.real, float.real, int.__add__]
4353 types = ['method', 'member', 'getset', 'wrapper']
4354
4355 # make sure we have an example of each type of descriptor
4356 for d, n in zip(descriptors, types):
4357 self.assertEqual(type(d).__name__, n + '_descriptor')
4358
4359 for d in descriptors:
4360 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4361 self.assertEqual(d.__qualname__, qualname)
4362
4363 self.assertEqual(str.lower.__qualname__, 'str.lower')
4364 self.assertEqual(complex.real.__qualname__, 'complex.real')
4365 self.assertEqual(float.real.__qualname__, 'float.real')
4366 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4367
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004368 class X:
4369 pass
4370 with self.assertRaises(TypeError):
4371 del X.__qualname__
4372
4373 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4374 str, 'Oink')
4375
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004376 global Y
4377 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004378 class Inside:
4379 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004380 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004381 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004382
Victor Stinner6f738742012-02-25 01:22:36 +01004383 def test_qualname_dict(self):
4384 ns = {'__qualname__': 'some.name'}
4385 tp = type('Foo', (), ns)
4386 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004387 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004388 self.assertEqual(ns, {'__qualname__': 'some.name'})
4389
4390 ns = {'__qualname__': 1}
4391 self.assertRaises(TypeError, type, 'Foo', (), ns)
4392
Benjamin Peterson52c42432012-03-07 18:41:11 -06004393 def test_cycle_through_dict(self):
4394 # See bug #1469629
4395 class X(dict):
4396 def __init__(self):
4397 dict.__init__(self)
4398 self.__dict__ = self
4399 x = X()
4400 x.attr = 42
4401 wr = weakref.ref(x)
4402 del x
4403 support.gc_collect()
4404 self.assertIsNone(wr())
4405 for o in gc.get_objects():
4406 self.assertIsNot(type(o), X)
4407
Benjamin Peterson96384b92012-03-17 00:05:44 -05004408 def test_object_new_and_init_with_parameters(self):
4409 # See issue #1683368
4410 class OverrideNeither:
4411 pass
4412 self.assertRaises(TypeError, OverrideNeither, 1)
4413 self.assertRaises(TypeError, OverrideNeither, kw=1)
4414 class OverrideNew:
4415 def __new__(cls, foo, kw=0, *args, **kwds):
4416 return object.__new__(cls, *args, **kwds)
4417 class OverrideInit:
4418 def __init__(self, foo, kw=0, *args, **kwargs):
4419 return object.__init__(self, *args, **kwargs)
4420 class OverrideBoth(OverrideNew, OverrideInit):
4421 pass
4422 for case in OverrideNew, OverrideInit, OverrideBoth:
4423 case(1)
4424 case(1, kw=2)
4425 self.assertRaises(TypeError, case, 1, 2, 3)
4426 self.assertRaises(TypeError, case, 1, 2, foo=3)
4427
Benjamin Petersondf813792014-03-17 15:57:17 -05004428 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4429 class Base:
4430 pass
4431 class Sub(Base):
4432 pass
4433 self.assertIn("__dict__", Base.__dict__)
4434 self.assertNotIn("__dict__", Sub.__dict__)
4435
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004436 def test_bound_method_repr(self):
4437 class Foo:
4438 def method(self):
4439 pass
4440 self.assertRegex(repr(Foo().method),
4441 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4442
4443
4444 class Base:
4445 def method(self):
4446 pass
4447 class Derived1(Base):
4448 pass
4449 class Derived2(Base):
4450 def method(self):
4451 pass
4452 base = Base()
4453 derived1 = Derived1()
4454 derived2 = Derived2()
4455 super_d2 = super(Derived2, derived2)
4456 self.assertRegex(repr(base.method),
4457 r"<bound method .*Base\.method of <.*Base object at .*>>")
4458 self.assertRegex(repr(derived1.method),
4459 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4460 self.assertRegex(repr(derived2.method),
4461 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4462 self.assertRegex(repr(super_d2.method),
4463 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4464
4465 class Foo:
4466 @classmethod
4467 def method(cls):
4468 pass
4469 foo = Foo()
4470 self.assertRegex(repr(foo.method), # access via instance
4471 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4472 self.assertRegex(repr(Foo.method), # access via the class
4473 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4474
4475
4476 class MyCallable:
4477 def __call__(self, arg):
4478 pass
4479 func = MyCallable() # func has no __name__ or __qualname__ attributes
4480 instance = object()
4481 method = types.MethodType(func, instance)
4482 self.assertRegex(repr(method),
4483 r"<bound method \? of <object object at .*>>")
4484 func.__name__ = "name"
4485 self.assertRegex(repr(method),
4486 r"<bound method name of <object object at .*>>")
4487 func.__qualname__ = "qualname"
4488 self.assertRegex(repr(method),
4489 r"<bound method qualname of <object object at .*>>")
4490
Antoine Pitrou9d574812011-12-12 13:47:25 +01004491
Georg Brandl479a7e72008-02-05 18:13:15 +00004492class DictProxyTests(unittest.TestCase):
4493 def setUp(self):
4494 class C(object):
4495 def meth(self):
4496 pass
4497 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004498
Brett Cannon7a540732011-02-22 03:04:06 +00004499 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4500 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004501 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004502 # Testing dict-proxy keys...
4503 it = self.C.__dict__.keys()
4504 self.assertNotIsInstance(it, list)
4505 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004506 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004507 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004508 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004509
Brett Cannon7a540732011-02-22 03:04:06 +00004510 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4511 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004512 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004513 # Testing dict-proxy values...
4514 it = self.C.__dict__.values()
4515 self.assertNotIsInstance(it, list)
4516 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004517 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004518
Brett Cannon7a540732011-02-22 03:04:06 +00004519 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4520 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004521 def test_iter_items(self):
4522 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004523 it = self.C.__dict__.items()
4524 self.assertNotIsInstance(it, list)
4525 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004526 keys.sort()
4527 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004528 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004529
Georg Brandl479a7e72008-02-05 18:13:15 +00004530 def test_dict_type_with_metaclass(self):
4531 # Testing type of __dict__ when metaclass set...
4532 class B(object):
4533 pass
4534 class M(type):
4535 pass
4536 class C(metaclass=M):
4537 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4538 pass
4539 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004540
Ezio Melottiac53ab62010-12-18 14:59:43 +00004541 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004542 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004543 # We can't blindly compare with the repr of another dict as ordering
4544 # of keys and values is arbitrary and may differ.
4545 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004546 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004547 self.assertTrue(r.endswith(')'), r)
4548 for k, v in self.C.__dict__.items():
4549 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004550
Christian Heimesbbffeb62008-01-24 09:42:52 +00004551
Georg Brandl479a7e72008-02-05 18:13:15 +00004552class PTypesLongInitTest(unittest.TestCase):
4553 # This is in its own TestCase so that it can be run before any other tests.
4554 def test_pytype_long_ready(self):
4555 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004556
Georg Brandl479a7e72008-02-05 18:13:15 +00004557 # This dumps core when SF bug 551412 isn't fixed --
4558 # but only when test_descr.py is run separately.
4559 # (That can't be helped -- as soon as PyType_Ready()
4560 # is called for PyLong_Type, the bug is gone.)
4561 class UserLong(object):
4562 def __pow__(self, *args):
4563 pass
4564 try:
4565 pow(0, UserLong(), 0)
4566 except:
4567 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004568
Georg Brandl479a7e72008-02-05 18:13:15 +00004569 # Another segfault only when run early
4570 # (before PyType_Ready(tuple) is called)
4571 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004572
4573
Victor Stinnerd74782b2012-03-09 00:39:08 +01004574class MiscTests(unittest.TestCase):
4575 def test_type_lookup_mro_reference(self):
4576 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4577 # the type MRO because it may be modified during the lookup, if
4578 # __bases__ is set during the lookup for example.
4579 class MyKey(object):
4580 def __hash__(self):
4581 return hash('mykey')
4582
4583 def __eq__(self, other):
4584 X.__bases__ = (Base2,)
4585
4586 class Base(object):
4587 mykey = 'from Base'
4588 mykey2 = 'from Base'
4589
4590 class Base2(object):
4591 mykey = 'from Base2'
4592 mykey2 = 'from Base2'
4593
4594 X = type('X', (Base,), {MyKey(): 5})
4595 # mykey is read from Base
4596 self.assertEqual(X.mykey, 'from Base')
4597 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4598 self.assertEqual(X.mykey2, 'from Base2')
4599
4600
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004601class PicklingTests(unittest.TestCase):
4602
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004603 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004604 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004605 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004606 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004607 if kwargs:
4608 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4609 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004610 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004611 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4612 self.assertEqual(reduce_value[1], (type(obj),) + args)
4613 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004614 if listitems is not None:
4615 self.assertListEqual(list(reduce_value[3]), listitems)
4616 else:
4617 self.assertIsNone(reduce_value[3])
4618 if dictitems is not None:
4619 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4620 else:
4621 self.assertIsNone(reduce_value[4])
4622 else:
4623 base_type = type(obj).__base__
4624 reduce_value = (copyreg._reconstructor,
4625 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004626 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004627 None if base_type is object else base_type(obj)))
4628 if state is not None:
4629 reduce_value += (state,)
4630 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4631 self.assertEqual(obj.__reduce__(), reduce_value)
4632
4633 def test_reduce(self):
4634 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4635 args = (-101, "spam")
4636 kwargs = {'bacon': -201, 'fish': -301}
4637 state = {'cheese': -401}
4638
4639 class C1:
4640 def __getnewargs__(self):
4641 return args
4642 obj = C1()
4643 for proto in protocols:
4644 self._check_reduce(proto, obj, args)
4645
4646 for name, value in state.items():
4647 setattr(obj, name, value)
4648 for proto in protocols:
4649 self._check_reduce(proto, obj, args, state=state)
4650
4651 class C2:
4652 def __getnewargs__(self):
4653 return "bad args"
4654 obj = C2()
4655 for proto in protocols:
4656 if proto >= 2:
4657 with self.assertRaises(TypeError):
4658 obj.__reduce_ex__(proto)
4659
4660 class C3:
4661 def __getnewargs_ex__(self):
4662 return (args, kwargs)
4663 obj = C3()
4664 for proto in protocols:
4665 if proto >= 4:
4666 self._check_reduce(proto, obj, args, kwargs)
4667 elif proto >= 2:
4668 with self.assertRaises(ValueError):
4669 obj.__reduce_ex__(proto)
4670
4671 class C4:
4672 def __getnewargs_ex__(self):
4673 return (args, "bad dict")
4674 class C5:
4675 def __getnewargs_ex__(self):
4676 return ("bad tuple", kwargs)
4677 class C6:
4678 def __getnewargs_ex__(self):
4679 return ()
4680 class C7:
4681 def __getnewargs_ex__(self):
4682 return "bad args"
4683 for proto in protocols:
4684 for cls in C4, C5, C6, C7:
4685 obj = cls()
4686 if proto >= 2:
4687 with self.assertRaises((TypeError, ValueError)):
4688 obj.__reduce_ex__(proto)
4689
4690 class C8:
4691 def __getnewargs_ex__(self):
4692 return (args, kwargs)
4693 obj = C8()
4694 for proto in protocols:
4695 if 2 <= proto < 4:
4696 with self.assertRaises(ValueError):
4697 obj.__reduce_ex__(proto)
4698 class C9:
4699 def __getnewargs_ex__(self):
4700 return (args, {})
4701 obj = C9()
4702 for proto in protocols:
4703 self._check_reduce(proto, obj, args)
4704
4705 class C10:
4706 def __getnewargs_ex__(self):
4707 raise IndexError
4708 obj = C10()
4709 for proto in protocols:
4710 if proto >= 2:
4711 with self.assertRaises(IndexError):
4712 obj.__reduce_ex__(proto)
4713
4714 class C11:
4715 def __getstate__(self):
4716 return state
4717 obj = C11()
4718 for proto in protocols:
4719 self._check_reduce(proto, obj, state=state)
4720
4721 class C12:
4722 def __getstate__(self):
4723 return "not dict"
4724 obj = C12()
4725 for proto in protocols:
4726 self._check_reduce(proto, obj, state="not dict")
4727
4728 class C13:
4729 def __getstate__(self):
4730 raise IndexError
4731 obj = C13()
4732 for proto in protocols:
4733 with self.assertRaises(IndexError):
4734 obj.__reduce_ex__(proto)
4735 if proto < 2:
4736 with self.assertRaises(IndexError):
4737 obj.__reduce__()
4738
4739 class C14:
4740 __slots__ = tuple(state)
4741 def __init__(self):
4742 for name, value in state.items():
4743 setattr(self, name, value)
4744
4745 obj = C14()
4746 for proto in protocols:
4747 if proto >= 2:
4748 self._check_reduce(proto, obj, state=(None, state))
4749 else:
4750 with self.assertRaises(TypeError):
4751 obj.__reduce_ex__(proto)
4752 with self.assertRaises(TypeError):
4753 obj.__reduce__()
4754
4755 class C15(dict):
4756 pass
4757 obj = C15({"quebec": -601})
4758 for proto in protocols:
4759 self._check_reduce(proto, obj, dictitems=dict(obj))
4760
4761 class C16(list):
4762 pass
4763 obj = C16(["yukon"])
4764 for proto in protocols:
4765 self._check_reduce(proto, obj, listitems=list(obj))
4766
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004767 def test_special_method_lookup(self):
4768 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4769 class Picky:
4770 def __getstate__(self):
4771 return {}
4772
4773 def __getattr__(self, attr):
4774 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4775 raise AssertionError(attr)
4776 return None
4777 for protocol in protocols:
4778 state = {} if protocol >= 2 else None
4779 self._check_reduce(protocol, Picky(), state=state)
4780
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004781 def _assert_is_copy(self, obj, objcopy, msg=None):
4782 """Utility method to verify if two objects are copies of each others.
4783 """
4784 if msg is None:
4785 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4786 if type(obj).__repr__ is object.__repr__:
4787 # We have this limitation for now because we use the object's repr
4788 # to help us verify that the two objects are copies. This allows
4789 # us to delegate the non-generic verification logic to the objects
4790 # themselves.
4791 raise ValueError("object passed to _assert_is_copy must " +
4792 "override the __repr__ method.")
4793 self.assertIsNot(obj, objcopy, msg=msg)
4794 self.assertIs(type(obj), type(objcopy), msg=msg)
4795 if hasattr(obj, '__dict__'):
4796 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4797 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4798 if hasattr(obj, '__slots__'):
4799 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4800 for slot in obj.__slots__:
4801 self.assertEqual(
4802 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4803 self.assertEqual(getattr(obj, slot, None),
4804 getattr(objcopy, slot, None), msg=msg)
4805 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4806
4807 @staticmethod
4808 def _generate_pickle_copiers():
4809 """Utility method to generate the many possible pickle configurations.
4810 """
4811 class PickleCopier:
4812 "This class copies object using pickle."
4813 def __init__(self, proto, dumps, loads):
4814 self.proto = proto
4815 self.dumps = dumps
4816 self.loads = loads
4817 def copy(self, obj):
4818 return self.loads(self.dumps(obj, self.proto))
4819 def __repr__(self):
4820 # We try to be as descriptive as possible here since this is
4821 # the string which we will allow us to tell the pickle
4822 # configuration we are using during debugging.
4823 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4824 .format(self.proto,
4825 self.dumps.__module__, self.dumps.__qualname__,
4826 self.loads.__module__, self.loads.__qualname__))
4827 return (PickleCopier(*args) for args in
4828 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4829 {pickle.dumps, pickle._dumps},
4830 {pickle.loads, pickle._loads}))
4831
4832 def test_pickle_slots(self):
4833 # Tests pickling of classes with __slots__.
4834
4835 # Pickling of classes with __slots__ but without __getstate__ should
4836 # fail (if using protocol 0 or 1)
4837 global C
4838 class C:
4839 __slots__ = ['a']
4840 with self.assertRaises(TypeError):
4841 pickle.dumps(C(), 0)
4842
4843 global D
4844 class D(C):
4845 pass
4846 with self.assertRaises(TypeError):
4847 pickle.dumps(D(), 0)
4848
4849 class C:
4850 "A class with __getstate__ and __setstate__ implemented."
4851 __slots__ = ['a']
4852 def __getstate__(self):
4853 state = getattr(self, '__dict__', {}).copy()
4854 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004855 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004856 try:
4857 state[slot] = getattr(self, slot)
4858 except AttributeError:
4859 pass
4860 return state
4861 def __setstate__(self, state):
4862 for k, v in state.items():
4863 setattr(self, k, v)
4864 def __repr__(self):
4865 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4866
4867 class D(C):
4868 "A subclass of a class with slots."
4869 pass
4870
4871 global E
4872 class E(C):
4873 "A subclass with an extra slot."
4874 __slots__ = ['b']
4875
4876 # Now it should work
4877 for pickle_copier in self._generate_pickle_copiers():
4878 with self.subTest(pickle_copier=pickle_copier):
4879 x = C()
4880 y = pickle_copier.copy(x)
4881 self._assert_is_copy(x, y)
4882
4883 x.a = 42
4884 y = pickle_copier.copy(x)
4885 self._assert_is_copy(x, y)
4886
4887 x = D()
4888 x.a = 42
4889 x.b = 100
4890 y = pickle_copier.copy(x)
4891 self._assert_is_copy(x, y)
4892
4893 x = E()
4894 x.a = 42
4895 x.b = "foo"
4896 y = pickle_copier.copy(x)
4897 self._assert_is_copy(x, y)
4898
4899 def test_reduce_copying(self):
4900 # Tests pickling and copying new-style classes and objects.
4901 global C1
4902 class C1:
4903 "The state of this class is copyable via its instance dict."
4904 ARGS = (1, 2)
4905 NEED_DICT_COPYING = True
4906 def __init__(self, a, b):
4907 super().__init__()
4908 self.a = a
4909 self.b = b
4910 def __repr__(self):
4911 return "C1(%r, %r)" % (self.a, self.b)
4912
4913 global C2
4914 class C2(list):
4915 "A list subclass copyable via __getnewargs__."
4916 ARGS = (1, 2)
4917 NEED_DICT_COPYING = False
4918 def __new__(cls, a, b):
4919 self = super().__new__(cls)
4920 self.a = a
4921 self.b = b
4922 return self
4923 def __init__(self, *args):
4924 super().__init__()
4925 # This helps testing that __init__ is not called during the
4926 # unpickling process, which would cause extra appends.
4927 self.append("cheese")
4928 @classmethod
4929 def __getnewargs__(cls):
4930 return cls.ARGS
4931 def __repr__(self):
4932 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
4933
4934 global C3
4935 class C3(list):
4936 "A list subclass copyable via __getstate__."
4937 ARGS = (1, 2)
4938 NEED_DICT_COPYING = False
4939 def __init__(self, a, b):
4940 self.a = a
4941 self.b = b
4942 # This helps testing that __init__ is not called during the
4943 # unpickling process, which would cause extra appends.
4944 self.append("cheese")
4945 @classmethod
4946 def __getstate__(cls):
4947 return cls.ARGS
4948 def __setstate__(self, state):
4949 a, b = state
4950 self.a = a
4951 self.b = b
4952 def __repr__(self):
4953 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
4954
4955 global C4
4956 class C4(int):
4957 "An int subclass copyable via __getnewargs__."
4958 ARGS = ("hello", "world", 1)
4959 NEED_DICT_COPYING = False
4960 def __new__(cls, a, b, value):
4961 self = super().__new__(cls, value)
4962 self.a = a
4963 self.b = b
4964 return self
4965 @classmethod
4966 def __getnewargs__(cls):
4967 return cls.ARGS
4968 def __repr__(self):
4969 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
4970
4971 global C5
4972 class C5(int):
4973 "An int subclass copyable via __getnewargs_ex__."
4974 ARGS = (1, 2)
4975 KWARGS = {'value': 3}
4976 NEED_DICT_COPYING = False
4977 def __new__(cls, a, b, *, value=0):
4978 self = super().__new__(cls, value)
4979 self.a = a
4980 self.b = b
4981 return self
4982 @classmethod
4983 def __getnewargs_ex__(cls):
4984 return (cls.ARGS, cls.KWARGS)
4985 def __repr__(self):
4986 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
4987
4988 test_classes = (C1, C2, C3, C4, C5)
4989 # Testing copying through pickle
4990 pickle_copiers = self._generate_pickle_copiers()
4991 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
4992 with self.subTest(cls=cls, pickle_copier=pickle_copier):
4993 kwargs = getattr(cls, 'KWARGS', {})
4994 obj = cls(*cls.ARGS, **kwargs)
4995 proto = pickle_copier.proto
4996 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
4997 with self.assertRaises(ValueError):
4998 pickle_copier.dumps(obj, proto)
4999 continue
5000 objcopy = pickle_copier.copy(obj)
5001 self._assert_is_copy(obj, objcopy)
5002 # For test classes that supports this, make sure we didn't go
5003 # around the reduce protocol by simply copying the attribute
5004 # dictionary. We clear attributes using the previous copy to
5005 # not mutate the original argument.
5006 if proto >= 2 and not cls.NEED_DICT_COPYING:
5007 objcopy.__dict__.clear()
5008 objcopy2 = pickle_copier.copy(objcopy)
5009 self._assert_is_copy(obj, objcopy2)
5010
5011 # Testing copying through copy.deepcopy()
5012 for cls in test_classes:
5013 with self.subTest(cls=cls):
5014 kwargs = getattr(cls, 'KWARGS', {})
5015 obj = cls(*cls.ARGS, **kwargs)
5016 # XXX: We need to modify the copy module to support PEP 3154's
5017 # reduce protocol 4.
5018 if hasattr(cls, '__getnewargs_ex__'):
5019 continue
5020 objcopy = deepcopy(obj)
5021 self._assert_is_copy(obj, objcopy)
5022 # For test classes that supports this, make sure we didn't go
5023 # around the reduce protocol by simply copying the attribute
5024 # dictionary. We clear attributes using the previous copy to
5025 # not mutate the original argument.
5026 if not cls.NEED_DICT_COPYING:
5027 objcopy.__dict__.clear()
5028 objcopy2 = deepcopy(objcopy)
5029 self._assert_is_copy(obj, objcopy2)
5030
5031
Benjamin Peterson2a605342014-03-17 16:20:12 -05005032class SharedKeyTests(unittest.TestCase):
5033
5034 @support.cpython_only
5035 def test_subclasses(self):
5036 # Verify that subclasses can share keys (per PEP 412)
5037 class A:
5038 pass
5039 class B(A):
5040 pass
5041
5042 a, b = A(), B()
5043 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5044 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5045 a.x, a.y, a.z, a.w = range(4)
5046 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5047 a2 = A()
5048 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5049 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5050 b.u, b.v, b.w, b.t = range(4)
5051 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5052
5053
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005054class DebugHelperMeta(type):
5055 """
5056 Sets default __doc__ and simplifies repr() output.
5057 """
5058 def __new__(mcls, name, bases, attrs):
5059 if attrs.get('__doc__') is None:
5060 attrs['__doc__'] = name # helps when debugging with gdb
5061 return type.__new__(mcls, name, bases, attrs)
5062 def __repr__(cls):
5063 return repr(cls.__name__)
5064
5065
5066class MroTest(unittest.TestCase):
5067 """
5068 Regressions for some bugs revealed through
5069 mcsl.mro() customization (typeobject.c: mro_internal()) and
5070 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5071 """
5072
5073 def setUp(self):
5074 self.step = 0
5075 self.ready = False
5076
5077 def step_until(self, limit):
5078 ret = (self.step < limit)
5079 if ret:
5080 self.step += 1
5081 return ret
5082
5083 def test_incomplete_set_bases_on_self(self):
5084 """
5085 type_set_bases must be aware that type->tp_mro can be NULL.
5086 """
5087 class M(DebugHelperMeta):
5088 def mro(cls):
5089 if self.step_until(1):
5090 assert cls.__mro__ is None
5091 cls.__bases__ += ()
5092
5093 return type.mro(cls)
5094
5095 class A(metaclass=M):
5096 pass
5097
5098 def test_reent_set_bases_on_base(self):
5099 """
5100 Deep reentrancy must not over-decref old_mro.
5101 """
5102 class M(DebugHelperMeta):
5103 def mro(cls):
5104 if cls.__mro__ is not None and cls.__name__ == 'B':
5105 # 4-5 steps are usually enough to make it crash somewhere
5106 if self.step_until(10):
5107 A.__bases__ += ()
5108
5109 return type.mro(cls)
5110
5111 class A(metaclass=M):
5112 pass
5113 class B(A):
5114 pass
5115 B.__bases__ += ()
5116
5117 def test_reent_set_bases_on_direct_base(self):
5118 """
5119 Similar to test_reent_set_bases_on_base, but may crash differently.
5120 """
5121 class M(DebugHelperMeta):
5122 def mro(cls):
5123 base = cls.__bases__[0]
5124 if base is not object:
5125 if self.step_until(5):
5126 base.__bases__ += ()
5127
5128 return type.mro(cls)
5129
5130 class A(metaclass=M):
5131 pass
5132 class B(A):
5133 pass
5134 class C(B):
5135 pass
5136
5137 def test_reent_set_bases_tp_base_cycle(self):
5138 """
5139 type_set_bases must check for an inheritance cycle not only through
5140 MRO of the type, which may be not yet updated in case of reentrance,
5141 but also through tp_base chain, which is assigned before diving into
5142 inner calls to mro().
5143
5144 Otherwise, the following snippet can loop forever:
5145 do {
5146 // ...
5147 type = type->tp_base;
5148 } while (type != NULL);
5149
5150 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5151 would not be happy in that case, causing a stack overflow.
5152 """
5153 class M(DebugHelperMeta):
5154 def mro(cls):
5155 if self.ready:
5156 if cls.__name__ == 'B1':
5157 B2.__bases__ = (B1,)
5158 if cls.__name__ == 'B2':
5159 B1.__bases__ = (B2,)
5160 return type.mro(cls)
5161
5162 class A(metaclass=M):
5163 pass
5164 class B1(A):
5165 pass
5166 class B2(A):
5167 pass
5168
5169 self.ready = True
5170 with self.assertRaises(TypeError):
5171 B1.__bases__ += ()
5172
5173 def test_tp_subclasses_cycle_in_update_slots(self):
5174 """
5175 type_set_bases must check for reentrancy upon finishing its job
5176 by updating tp_subclasses of old/new bases of the type.
5177 Otherwise, an implicit inheritance cycle through tp_subclasses
5178 can break functions that recurse on elements of that field
5179 (like recurse_down_subclasses and mro_hierarchy) eventually
5180 leading to a stack overflow.
5181 """
5182 class M(DebugHelperMeta):
5183 def mro(cls):
5184 if self.ready and cls.__name__ == 'C':
5185 self.ready = False
5186 C.__bases__ = (B2,)
5187 return type.mro(cls)
5188
5189 class A(metaclass=M):
5190 pass
5191 class B1(A):
5192 pass
5193 class B2(A):
5194 pass
5195 class C(A):
5196 pass
5197
5198 self.ready = True
5199 C.__bases__ = (B1,)
5200 B1.__bases__ = (C,)
5201
5202 self.assertEqual(C.__bases__, (B2,))
5203 self.assertEqual(B2.__subclasses__(), [C])
5204 self.assertEqual(B1.__subclasses__(), [])
5205
5206 self.assertEqual(B1.__bases__, (C,))
5207 self.assertEqual(C.__subclasses__(), [B1])
5208
5209 def test_tp_subclasses_cycle_error_return_path(self):
5210 """
5211 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5212 a code path executed on error (goto bail).
5213 """
5214 class E(Exception):
5215 pass
5216 class M(DebugHelperMeta):
5217 def mro(cls):
5218 if self.ready and cls.__name__ == 'C':
5219 if C.__bases__ == (B2,):
5220 self.ready = False
5221 else:
5222 C.__bases__ = (B2,)
5223 raise E
5224 return type.mro(cls)
5225
5226 class A(metaclass=M):
5227 pass
5228 class B1(A):
5229 pass
5230 class B2(A):
5231 pass
5232 class C(A):
5233 pass
5234
5235 self.ready = True
5236 with self.assertRaises(E):
5237 C.__bases__ = (B1,)
5238 B1.__bases__ = (C,)
5239
5240 self.assertEqual(C.__bases__, (B2,))
5241 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5242
5243 def test_incomplete_extend(self):
5244 """
5245 Extending an unitialized type with type->tp_mro == NULL must
5246 throw a reasonable TypeError exception, instead of failing
5247 with PyErr_BadInternalCall.
5248 """
5249 class M(DebugHelperMeta):
5250 def mro(cls):
5251 if cls.__mro__ is None and cls.__name__ != 'X':
5252 with self.assertRaises(TypeError):
5253 class X(cls):
5254 pass
5255
5256 return type.mro(cls)
5257
5258 class A(metaclass=M):
5259 pass
5260
5261 def test_incomplete_super(self):
5262 """
5263 Attrubute lookup on a super object must be aware that
5264 its target type can be uninitialized (type->tp_mro == NULL).
5265 """
5266 class M(DebugHelperMeta):
5267 def mro(cls):
5268 if cls.__mro__ is None:
5269 with self.assertRaises(AttributeError):
5270 super(cls, cls).xxx
5271
5272 return type.mro(cls)
5273
5274 class A(metaclass=M):
5275 pass
5276
5277
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005278def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005279 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005280 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005281 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005282 MiscTests, PicklingTests, SharedKeyTests,
5283 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005284
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005285if __name__ == "__main__":
5286 test_main()