blob: 9f3d34d1e49d6ffb334f5ac75ef39ab412e6ef7f [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
2025 for attr in "__doc__", "fget", "fset", "fdel":
2026 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
2036 class D(object):
2037 __getitem__ = property(lambda s: 1/0)
2038
2039 d = D()
2040 try:
2041 for i in d:
2042 str(i)
2043 except ZeroDivisionError:
2044 pass
2045 else:
2046 self.fail("expected ZeroDivisionError from bad property")
2047
R. David Murray378c0cf2010-02-24 01:46:21 +00002048 @unittest.skipIf(sys.flags.optimize >= 2,
2049 "Docstrings are omitted with -O2 and above")
2050 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002051 class E(object):
2052 def getter(self):
2053 "getter method"
2054 return 0
2055 def setter(self_, value):
2056 "setter method"
2057 pass
2058 prop = property(getter)
2059 self.assertEqual(prop.__doc__, "getter method")
2060 prop2 = property(fset=setter)
2061 self.assertEqual(prop2.__doc__, None)
2062
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002063 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002064 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002065 # this segfaulted in 2.5b2
2066 try:
2067 import _testcapi
2068 except ImportError:
2069 pass
2070 else:
2071 class X(object):
2072 p = property(_testcapi.test_with_docstring)
2073
2074 def test_properties_plus(self):
2075 class C(object):
2076 foo = property(doc="hello")
2077 @foo.getter
2078 def foo(self):
2079 return self._foo
2080 @foo.setter
2081 def foo(self, value):
2082 self._foo = abs(value)
2083 @foo.deleter
2084 def foo(self):
2085 del self._foo
2086 c = C()
2087 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002088 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002089 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002090 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002091 self.assertEqual(c._foo, 42)
2092 self.assertEqual(c.foo, 42)
2093 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002094 self.assertNotHasAttr(c, '_foo')
2095 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002096
2097 class D(C):
2098 @C.foo.deleter
2099 def foo(self):
2100 try:
2101 del self._foo
2102 except AttributeError:
2103 pass
2104 d = D()
2105 d.foo = 24
2106 self.assertEqual(d.foo, 24)
2107 del d.foo
2108 del d.foo
2109
2110 class E(object):
2111 @property
2112 def foo(self):
2113 return self._foo
2114 @foo.setter
2115 def foo(self, value):
2116 raise RuntimeError
2117 @foo.setter
2118 def foo(self, value):
2119 self._foo = abs(value)
2120 @foo.deleter
2121 def foo(self, value=None):
2122 del self._foo
2123
2124 e = E()
2125 e.foo = -42
2126 self.assertEqual(e.foo, 42)
2127 del e.foo
2128
2129 class F(E):
2130 @E.foo.deleter
2131 def foo(self):
2132 del self._foo
2133 @foo.setter
2134 def foo(self, value):
2135 self._foo = max(0, value)
2136 f = F()
2137 f.foo = -10
2138 self.assertEqual(f.foo, 0)
2139 del f.foo
2140
2141 def test_dict_constructors(self):
2142 # Testing dict constructor ...
2143 d = dict()
2144 self.assertEqual(d, {})
2145 d = dict({})
2146 self.assertEqual(d, {})
2147 d = dict({1: 2, 'a': 'b'})
2148 self.assertEqual(d, {1: 2, 'a': 'b'})
2149 self.assertEqual(d, dict(list(d.items())))
2150 self.assertEqual(d, dict(iter(d.items())))
2151 d = dict({'one':1, 'two':2})
2152 self.assertEqual(d, dict(one=1, two=2))
2153 self.assertEqual(d, dict(**d))
2154 self.assertEqual(d, dict({"one": 1}, two=2))
2155 self.assertEqual(d, dict([("two", 2)], one=1))
2156 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2157 self.assertEqual(d, dict(**d))
2158
2159 for badarg in 0, 0, 0j, "0", [0], (0,):
2160 try:
2161 dict(badarg)
2162 except TypeError:
2163 pass
2164 except ValueError:
2165 if badarg == "0":
2166 # It's a sequence, and its elements are also sequences (gotta
2167 # love strings <wink>), but they aren't of length 2, so this
2168 # one seemed better as a ValueError than a TypeError.
2169 pass
2170 else:
2171 self.fail("no TypeError from dict(%r)" % badarg)
2172 else:
2173 self.fail("no TypeError from dict(%r)" % badarg)
2174
2175 try:
2176 dict({}, {})
2177 except TypeError:
2178 pass
2179 else:
2180 self.fail("no TypeError from dict({}, {})")
2181
2182 class Mapping:
2183 # Lacks a .keys() method; will be added later.
2184 dict = {1:2, 3:4, 'a':1j}
2185
2186 try:
2187 dict(Mapping())
2188 except TypeError:
2189 pass
2190 else:
2191 self.fail("no TypeError from dict(incomplete mapping)")
2192
2193 Mapping.keys = lambda self: list(self.dict.keys())
2194 Mapping.__getitem__ = lambda self, i: self.dict[i]
2195 d = dict(Mapping())
2196 self.assertEqual(d, Mapping.dict)
2197
2198 # Init from sequence of iterable objects, each producing a 2-sequence.
2199 class AddressBookEntry:
2200 def __init__(self, first, last):
2201 self.first = first
2202 self.last = last
2203 def __iter__(self):
2204 return iter([self.first, self.last])
2205
2206 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2207 AddressBookEntry('Barry', 'Peters'),
2208 AddressBookEntry('Tim', 'Peters'),
2209 AddressBookEntry('Barry', 'Warsaw')])
2210 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2211
2212 d = dict(zip(range(4), range(1, 5)))
2213 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2214
2215 # Bad sequence lengths.
2216 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2217 try:
2218 dict(bad)
2219 except ValueError:
2220 pass
2221 else:
2222 self.fail("no ValueError from dict(%r)" % bad)
2223
2224 def test_dir(self):
2225 # Testing dir() ...
2226 junk = 12
2227 self.assertEqual(dir(), ['junk', 'self'])
2228 del junk
2229
2230 # Just make sure these don't blow up!
2231 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2232 dir(arg)
2233
2234 # Test dir on new-style classes. Since these have object as a
2235 # base class, a lot more gets sucked in.
2236 def interesting(strings):
2237 return [s for s in strings if not s.startswith('_')]
2238
2239 class C(object):
2240 Cdata = 1
2241 def Cmethod(self): pass
2242
2243 cstuff = ['Cdata', 'Cmethod']
2244 self.assertEqual(interesting(dir(C)), cstuff)
2245
2246 c = C()
2247 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002248 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002249
2250 c.cdata = 2
2251 c.cmethod = lambda self: 0
2252 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002253 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002254
2255 class A(C):
2256 Adata = 1
2257 def Amethod(self): pass
2258
2259 astuff = ['Adata', 'Amethod'] + cstuff
2260 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002261 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002262 a = A()
2263 self.assertEqual(interesting(dir(a)), astuff)
2264 a.adata = 42
2265 a.amethod = lambda self: 3
2266 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002267 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002268
2269 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002270 class M(type(sys)):
2271 pass
2272 minstance = M("m")
2273 minstance.b = 2
2274 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002275 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002276 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002277 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002278 self.assertEqual(names, ['a', 'b'])
2279
2280 class M2(M):
2281 def getdict(self):
2282 return "Not a dict!"
2283 __dict__ = property(getdict)
2284
2285 m2instance = M2("m2")
2286 m2instance.b = 2
2287 m2instance.a = 1
2288 self.assertEqual(m2instance.__dict__, "Not a dict!")
2289 try:
2290 dir(m2instance)
2291 except TypeError:
2292 pass
2293
2294 # Two essentially featureless objects, just inheriting stuff from
2295 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002296 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002297
2298 # Nasty test case for proxied objects
2299 class Wrapper(object):
2300 def __init__(self, obj):
2301 self.__obj = obj
2302 def __repr__(self):
2303 return "Wrapper(%s)" % repr(self.__obj)
2304 def __getitem__(self, key):
2305 return Wrapper(self.__obj[key])
2306 def __len__(self):
2307 return len(self.__obj)
2308 def __getattr__(self, name):
2309 return Wrapper(getattr(self.__obj, name))
2310
2311 class C(object):
2312 def __getclass(self):
2313 return Wrapper(type(self))
2314 __class__ = property(__getclass)
2315
2316 dir(C()) # This used to segfault
2317
2318 def test_supers(self):
2319 # Testing super...
2320
2321 class A(object):
2322 def meth(self, a):
2323 return "A(%r)" % a
2324
2325 self.assertEqual(A().meth(1), "A(1)")
2326
2327 class B(A):
2328 def __init__(self):
2329 self.__super = super(B, self)
2330 def meth(self, a):
2331 return "B(%r)" % a + self.__super.meth(a)
2332
2333 self.assertEqual(B().meth(2), "B(2)A(2)")
2334
2335 class C(A):
2336 def meth(self, a):
2337 return "C(%r)" % a + self.__super.meth(a)
2338 C._C__super = super(C)
2339
2340 self.assertEqual(C().meth(3), "C(3)A(3)")
2341
2342 class D(C, B):
2343 def meth(self, a):
2344 return "D(%r)" % a + super(D, self).meth(a)
2345
2346 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2347
2348 # Test for subclassing super
2349
2350 class mysuper(super):
2351 def __init__(self, *args):
2352 return super(mysuper, self).__init__(*args)
2353
2354 class E(D):
2355 def meth(self, a):
2356 return "E(%r)" % a + mysuper(E, self).meth(a)
2357
2358 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2359
2360 class F(E):
2361 def meth(self, a):
2362 s = self.__super # == mysuper(F, self)
2363 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2364 F._F__super = mysuper(F)
2365
2366 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2367
2368 # Make sure certain errors are raised
2369
2370 try:
2371 super(D, 42)
2372 except TypeError:
2373 pass
2374 else:
2375 self.fail("shouldn't allow super(D, 42)")
2376
2377 try:
2378 super(D, C())
2379 except TypeError:
2380 pass
2381 else:
2382 self.fail("shouldn't allow super(D, C())")
2383
2384 try:
2385 super(D).__get__(12)
2386 except TypeError:
2387 pass
2388 else:
2389 self.fail("shouldn't allow super(D).__get__(12)")
2390
2391 try:
2392 super(D).__get__(C())
2393 except TypeError:
2394 pass
2395 else:
2396 self.fail("shouldn't allow super(D).__get__(C())")
2397
2398 # Make sure data descriptors can be overridden and accessed via super
2399 # (new feature in Python 2.3)
2400
2401 class DDbase(object):
2402 def getx(self): return 42
2403 x = property(getx)
2404
2405 class DDsub(DDbase):
2406 def getx(self): return "hello"
2407 x = property(getx)
2408
2409 dd = DDsub()
2410 self.assertEqual(dd.x, "hello")
2411 self.assertEqual(super(DDsub, dd).x, 42)
2412
2413 # Ensure that super() lookup of descriptor from classmethod
2414 # works (SF ID# 743627)
2415
2416 class Base(object):
2417 aProp = property(lambda self: "foo")
2418
2419 class Sub(Base):
2420 @classmethod
2421 def test(klass):
2422 return super(Sub,klass).aProp
2423
2424 self.assertEqual(Sub.test(), Base.aProp)
2425
2426 # Verify that super() doesn't allow keyword args
2427 try:
2428 super(Base, kw=1)
2429 except TypeError:
2430 pass
2431 else:
2432 self.assertEqual("super shouldn't accept keyword args")
2433
2434 def test_basic_inheritance(self):
2435 # Testing inheritance from basic types...
2436
2437 class hexint(int):
2438 def __repr__(self):
2439 return hex(self)
2440 def __add__(self, other):
2441 return hexint(int.__add__(self, other))
2442 # (Note that overriding __radd__ doesn't work,
2443 # because the int type gets first dibs.)
2444 self.assertEqual(repr(hexint(7) + 9), "0x10")
2445 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2446 a = hexint(12345)
2447 self.assertEqual(a, 12345)
2448 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002449 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002450 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002451 self.assertIs((+a).__class__, int)
2452 self.assertIs((a >> 0).__class__, int)
2453 self.assertIs((a << 0).__class__, int)
2454 self.assertIs((hexint(0) << 12).__class__, int)
2455 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002456
2457 class octlong(int):
2458 __slots__ = []
2459 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002460 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002461 def __add__(self, other):
2462 return self.__class__(super(octlong, self).__add__(other))
2463 __radd__ = __add__
2464 self.assertEqual(str(octlong(3) + 5), "0o10")
2465 # (Note that overriding __radd__ here only seems to work
2466 # because the example uses a short int left argument.)
2467 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2468 a = octlong(12345)
2469 self.assertEqual(a, 12345)
2470 self.assertEqual(int(a), 12345)
2471 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002472 self.assertIs(int(a).__class__, int)
2473 self.assertIs((+a).__class__, int)
2474 self.assertIs((-a).__class__, int)
2475 self.assertIs((-octlong(0)).__class__, int)
2476 self.assertIs((a >> 0).__class__, int)
2477 self.assertIs((a << 0).__class__, int)
2478 self.assertIs((a - 0).__class__, int)
2479 self.assertIs((a * 1).__class__, int)
2480 self.assertIs((a ** 1).__class__, int)
2481 self.assertIs((a // 1).__class__, int)
2482 self.assertIs((1 * a).__class__, int)
2483 self.assertIs((a | 0).__class__, int)
2484 self.assertIs((a ^ 0).__class__, int)
2485 self.assertIs((a & -1).__class__, int)
2486 self.assertIs((octlong(0) << 12).__class__, int)
2487 self.assertIs((octlong(0) >> 12).__class__, int)
2488 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002489
2490 # Because octlong overrides __add__, we can't check the absence of +0
2491 # optimizations using octlong.
2492 class longclone(int):
2493 pass
2494 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002495 self.assertIs((a + 0).__class__, int)
2496 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002497
2498 # Check that negative clones don't segfault
2499 a = longclone(-1)
2500 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002501 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002502
2503 class precfloat(float):
2504 __slots__ = ['prec']
2505 def __init__(self, value=0.0, prec=12):
2506 self.prec = int(prec)
2507 def __repr__(self):
2508 return "%.*g" % (self.prec, self)
2509 self.assertEqual(repr(precfloat(1.1)), "1.1")
2510 a = precfloat(12345)
2511 self.assertEqual(a, 12345.0)
2512 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002513 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002514 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002515 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002516
2517 class madcomplex(complex):
2518 def __repr__(self):
2519 return "%.17gj%+.17g" % (self.imag, self.real)
2520 a = madcomplex(-3, 4)
2521 self.assertEqual(repr(a), "4j-3")
2522 base = complex(-3, 4)
2523 self.assertEqual(base.__class__, complex)
2524 self.assertEqual(a, base)
2525 self.assertEqual(complex(a), base)
2526 self.assertEqual(complex(a).__class__, complex)
2527 a = madcomplex(a) # just trying another form of the constructor
2528 self.assertEqual(repr(a), "4j-3")
2529 self.assertEqual(a, base)
2530 self.assertEqual(complex(a), base)
2531 self.assertEqual(complex(a).__class__, complex)
2532 self.assertEqual(hash(a), hash(base))
2533 self.assertEqual((+a).__class__, complex)
2534 self.assertEqual((a + 0).__class__, complex)
2535 self.assertEqual(a + 0, base)
2536 self.assertEqual((a - 0).__class__, complex)
2537 self.assertEqual(a - 0, base)
2538 self.assertEqual((a * 1).__class__, complex)
2539 self.assertEqual(a * 1, base)
2540 self.assertEqual((a / 1).__class__, complex)
2541 self.assertEqual(a / 1, base)
2542
2543 class madtuple(tuple):
2544 _rev = None
2545 def rev(self):
2546 if self._rev is not None:
2547 return self._rev
2548 L = list(self)
2549 L.reverse()
2550 self._rev = self.__class__(L)
2551 return self._rev
2552 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2553 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2554 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2555 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2556 for i in range(512):
2557 t = madtuple(range(i))
2558 u = t.rev()
2559 v = u.rev()
2560 self.assertEqual(v, t)
2561 a = madtuple((1,2,3,4,5))
2562 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002563 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002564 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002565 self.assertIs(a[:].__class__, tuple)
2566 self.assertIs((a * 1).__class__, tuple)
2567 self.assertIs((a * 0).__class__, tuple)
2568 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002569 a = madtuple(())
2570 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002571 self.assertIs(tuple(a).__class__, tuple)
2572 self.assertIs((a + a).__class__, tuple)
2573 self.assertIs((a * 0).__class__, tuple)
2574 self.assertIs((a * 1).__class__, tuple)
2575 self.assertIs((a * 2).__class__, tuple)
2576 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002577
2578 class madstring(str):
2579 _rev = None
2580 def rev(self):
2581 if self._rev is not None:
2582 return self._rev
2583 L = list(self)
2584 L.reverse()
2585 self._rev = self.__class__("".join(L))
2586 return self._rev
2587 s = madstring("abcdefghijklmnopqrstuvwxyz")
2588 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2589 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2590 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2591 for i in range(256):
2592 s = madstring("".join(map(chr, range(i))))
2593 t = s.rev()
2594 u = t.rev()
2595 self.assertEqual(u, s)
2596 s = madstring("12345")
2597 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002598 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002599
2600 base = "\x00" * 5
2601 s = madstring(base)
2602 self.assertEqual(s, base)
2603 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002604 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002605 self.assertEqual(hash(s), hash(base))
2606 self.assertEqual({s: 1}[base], 1)
2607 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002608 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002609 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002610 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002611 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002612 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002613 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002614 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002615 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002616 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002618 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002619 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002620 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002622 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002623 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002624 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002625 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002626 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002627 self.assertEqual(s.rstrip(), base)
2628 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002629 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002630 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002631 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002632 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002633 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002634 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002635 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002636 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002637 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002638 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002639 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002640 self.assertEqual(s.lower(), base)
2641
2642 class madunicode(str):
2643 _rev = None
2644 def rev(self):
2645 if self._rev is not None:
2646 return self._rev
2647 L = list(self)
2648 L.reverse()
2649 self._rev = self.__class__("".join(L))
2650 return self._rev
2651 u = madunicode("ABCDEF")
2652 self.assertEqual(u, "ABCDEF")
2653 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2654 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2655 base = "12345"
2656 u = madunicode(base)
2657 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002658 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002659 self.assertEqual(hash(u), hash(base))
2660 self.assertEqual({u: 1}[base], 1)
2661 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002662 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002663 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002664 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002665 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002666 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002667 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002668 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002669 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002670 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002671 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002672 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002673 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002674 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002675 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002676 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002677 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002678 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002679 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002680 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002681 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002682 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002683 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002684 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002685 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002686 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002687 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002688 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002689 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002690 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002691 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002692 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002693 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002694 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002695 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002696 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002697 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002698 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002699 self.assertEqual(u[0:0], "")
2700
2701 class sublist(list):
2702 pass
2703 a = sublist(range(5))
2704 self.assertEqual(a, list(range(5)))
2705 a.append("hello")
2706 self.assertEqual(a, list(range(5)) + ["hello"])
2707 a[5] = 5
2708 self.assertEqual(a, list(range(6)))
2709 a.extend(range(6, 20))
2710 self.assertEqual(a, list(range(20)))
2711 a[-5:] = []
2712 self.assertEqual(a, list(range(15)))
2713 del a[10:15]
2714 self.assertEqual(len(a), 10)
2715 self.assertEqual(a, list(range(10)))
2716 self.assertEqual(list(a), list(range(10)))
2717 self.assertEqual(a[0], 0)
2718 self.assertEqual(a[9], 9)
2719 self.assertEqual(a[-10], 0)
2720 self.assertEqual(a[-1], 9)
2721 self.assertEqual(a[:5], list(range(5)))
2722
2723 ## class CountedInput(file):
2724 ## """Counts lines read by self.readline().
2725 ##
2726 ## self.lineno is the 0-based ordinal of the last line read, up to
2727 ## a maximum of one greater than the number of lines in the file.
2728 ##
2729 ## self.ateof is true if and only if the final "" line has been read,
2730 ## at which point self.lineno stops incrementing, and further calls
2731 ## to readline() continue to return "".
2732 ## """
2733 ##
2734 ## lineno = 0
2735 ## ateof = 0
2736 ## def readline(self):
2737 ## if self.ateof:
2738 ## return ""
2739 ## s = file.readline(self)
2740 ## # Next line works too.
2741 ## # s = super(CountedInput, self).readline()
2742 ## self.lineno += 1
2743 ## if s == "":
2744 ## self.ateof = 1
2745 ## return s
2746 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002747 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002748 ## lines = ['a\n', 'b\n', 'c\n']
2749 ## try:
2750 ## f.writelines(lines)
2751 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002752 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002753 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2754 ## got = f.readline()
2755 ## self.assertEqual(expected, got)
2756 ## self.assertEqual(f.lineno, i)
2757 ## self.assertEqual(f.ateof, (i > len(lines)))
2758 ## f.close()
2759 ## finally:
2760 ## try:
2761 ## f.close()
2762 ## except:
2763 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002764 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002765
2766 def test_keywords(self):
2767 # Testing keyword args to basic type constructors ...
2768 self.assertEqual(int(x=1), 1)
2769 self.assertEqual(float(x=2), 2.0)
2770 self.assertEqual(int(x=3), 3)
2771 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2772 self.assertEqual(str(object=500), '500')
2773 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2774 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2775 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2776 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2777
2778 for constructor in (int, float, int, complex, str, str,
2779 tuple, list):
2780 try:
2781 constructor(bogus_keyword_arg=1)
2782 except TypeError:
2783 pass
2784 else:
2785 self.fail("expected TypeError from bogus keyword argument to %r"
2786 % constructor)
2787
2788 def test_str_subclass_as_dict_key(self):
2789 # Testing a str subclass used as dict key ..
2790
2791 class cistr(str):
2792 """Sublcass of str that computes __eq__ case-insensitively.
2793
2794 Also computes a hash code of the string in canonical form.
2795 """
2796
2797 def __init__(self, value):
2798 self.canonical = value.lower()
2799 self.hashcode = hash(self.canonical)
2800
2801 def __eq__(self, other):
2802 if not isinstance(other, cistr):
2803 other = cistr(other)
2804 return self.canonical == other.canonical
2805
2806 def __hash__(self):
2807 return self.hashcode
2808
2809 self.assertEqual(cistr('ABC'), 'abc')
2810 self.assertEqual('aBc', cistr('ABC'))
2811 self.assertEqual(str(cistr('ABC')), 'ABC')
2812
2813 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2814 self.assertEqual(d[cistr('one')], 1)
2815 self.assertEqual(d[cistr('tWo')], 2)
2816 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002817 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002818 self.assertEqual(d.get(cistr('thrEE')), 3)
2819
2820 def test_classic_comparisons(self):
2821 # Testing classic comparisons...
2822 class classic:
2823 pass
2824
2825 for base in (classic, int, object):
2826 class C(base):
2827 def __init__(self, value):
2828 self.value = int(value)
2829 def __eq__(self, other):
2830 if isinstance(other, C):
2831 return self.value == other.value
2832 if isinstance(other, int) or isinstance(other, int):
2833 return self.value == other
2834 return NotImplemented
2835 def __ne__(self, other):
2836 if isinstance(other, C):
2837 return self.value != other.value
2838 if isinstance(other, int) or isinstance(other, int):
2839 return self.value != other
2840 return NotImplemented
2841 def __lt__(self, other):
2842 if isinstance(other, C):
2843 return self.value < other.value
2844 if isinstance(other, int) or isinstance(other, int):
2845 return self.value < other
2846 return NotImplemented
2847 def __le__(self, other):
2848 if isinstance(other, C):
2849 return self.value <= other.value
2850 if isinstance(other, int) or isinstance(other, int):
2851 return self.value <= other
2852 return NotImplemented
2853 def __gt__(self, other):
2854 if isinstance(other, C):
2855 return self.value > other.value
2856 if isinstance(other, int) or isinstance(other, int):
2857 return self.value > other
2858 return NotImplemented
2859 def __ge__(self, other):
2860 if isinstance(other, C):
2861 return self.value >= other.value
2862 if isinstance(other, int) or isinstance(other, int):
2863 return self.value >= other
2864 return NotImplemented
2865
2866 c1 = C(1)
2867 c2 = C(2)
2868 c3 = C(3)
2869 self.assertEqual(c1, 1)
2870 c = {1: c1, 2: c2, 3: c3}
2871 for x in 1, 2, 3:
2872 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002873 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002874 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002875 eval("x %s y" % op),
2876 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002877 self.assertEqual(eval("c[x] %s 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("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002881 eval("x %s y" % op),
2882 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002883
2884 def test_rich_comparisons(self):
2885 # Testing rich comparisons...
2886 class Z(complex):
2887 pass
2888 z = Z(1)
2889 self.assertEqual(z, 1+0j)
2890 self.assertEqual(1+0j, z)
2891 class ZZ(complex):
2892 def __eq__(self, other):
2893 try:
2894 return abs(self - other) <= 1e-6
2895 except:
2896 return NotImplemented
2897 zz = ZZ(1.0000003)
2898 self.assertEqual(zz, 1+0j)
2899 self.assertEqual(1+0j, zz)
2900
2901 class classic:
2902 pass
2903 for base in (classic, int, object, list):
2904 class C(base):
2905 def __init__(self, value):
2906 self.value = int(value)
2907 def __cmp__(self_, other):
2908 self.fail("shouldn't call __cmp__")
2909 def __eq__(self, other):
2910 if isinstance(other, C):
2911 return self.value == other.value
2912 if isinstance(other, int) or isinstance(other, int):
2913 return self.value == other
2914 return NotImplemented
2915 def __ne__(self, other):
2916 if isinstance(other, C):
2917 return self.value != other.value
2918 if isinstance(other, int) or isinstance(other, int):
2919 return self.value != other
2920 return NotImplemented
2921 def __lt__(self, other):
2922 if isinstance(other, C):
2923 return self.value < other.value
2924 if isinstance(other, int) or isinstance(other, int):
2925 return self.value < other
2926 return NotImplemented
2927 def __le__(self, other):
2928 if isinstance(other, C):
2929 return self.value <= other.value
2930 if isinstance(other, int) or isinstance(other, int):
2931 return self.value <= other
2932 return NotImplemented
2933 def __gt__(self, other):
2934 if isinstance(other, C):
2935 return self.value > other.value
2936 if isinstance(other, int) or isinstance(other, int):
2937 return self.value > other
2938 return NotImplemented
2939 def __ge__(self, other):
2940 if isinstance(other, C):
2941 return self.value >= other.value
2942 if isinstance(other, int) or isinstance(other, int):
2943 return self.value >= other
2944 return NotImplemented
2945 c1 = C(1)
2946 c2 = C(2)
2947 c3 = C(3)
2948 self.assertEqual(c1, 1)
2949 c = {1: c1, 2: c2, 3: c3}
2950 for x in 1, 2, 3:
2951 for y in 1, 2, 3:
2952 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002953 self.assertEqual(eval("c[x] %s c[y]" % op),
2954 eval("x %s y" % op),
2955 "x=%d, y=%d" % (x, y))
2956 self.assertEqual(eval("c[x] %s y" % op),
2957 eval("x %s y" % op),
2958 "x=%d, y=%d" % (x, y))
2959 self.assertEqual(eval("x %s c[y]" % op),
2960 eval("x %s y" % op),
2961 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002962
2963 def test_descrdoc(self):
2964 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002965 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002966 def check(descr, what):
2967 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002968 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002969 check(complex.real, "the real part of a complex number") # member descriptor
2970
2971 def test_doc_descriptor(self):
2972 # Testing __doc__ descriptor...
2973 # SF bug 542984
2974 class DocDescr(object):
2975 def __get__(self, object, otype):
2976 if object:
2977 object = object.__class__.__name__ + ' instance'
2978 if otype:
2979 otype = otype.__name__
2980 return 'object=%s; type=%s' % (object, otype)
2981 class OldClass:
2982 __doc__ = DocDescr()
2983 class NewClass(object):
2984 __doc__ = DocDescr()
2985 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2986 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2987 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2988 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2989
2990 def test_set_class(self):
2991 # Testing __class__ assignment...
2992 class C(object): pass
2993 class D(object): pass
2994 class E(object): pass
2995 class F(D, E): pass
2996 for cls in C, D, E, F:
2997 for cls2 in C, D, E, F:
2998 x = cls()
2999 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003000 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00003001 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003002 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00003003 def cant(x, C):
3004 try:
3005 x.__class__ = C
3006 except TypeError:
3007 pass
3008 else:
3009 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3010 try:
3011 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003012 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003013 pass
3014 else:
3015 self.fail("shouldn't allow del %r.__class__" % x)
3016 cant(C(), list)
3017 cant(list(), C)
3018 cant(C(), 1)
3019 cant(C(), object)
3020 cant(object(), list)
3021 cant(list(), object)
3022 class Int(int): __slots__ = []
Georg Brandl479a7e72008-02-05 18:13:15 +00003023 cant(True, int)
3024 cant(2, bool)
3025 o = object()
3026 cant(o, type(1))
3027 cant(o, type(None))
3028 del o
3029 class G(object):
3030 __slots__ = ["a", "b"]
3031 class H(object):
3032 __slots__ = ["b", "a"]
3033 class I(object):
3034 __slots__ = ["a", "b"]
3035 class J(object):
3036 __slots__ = ["c", "b"]
3037 class K(object):
3038 __slots__ = ["a", "b", "d"]
3039 class L(H):
3040 __slots__ = ["e"]
3041 class M(I):
3042 __slots__ = ["e"]
3043 class N(J):
3044 __slots__ = ["__weakref__"]
3045 class P(J):
3046 __slots__ = ["__dict__"]
3047 class Q(J):
3048 pass
3049 class R(J):
3050 __slots__ = ["__dict__", "__weakref__"]
3051
3052 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3053 x = cls()
3054 x.a = 1
3055 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003056 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003057 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3058 self.assertEqual(x.a, 1)
3059 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003060 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003061 "assigning %r as __class__ for %r silently failed" % (cls, x))
3062 self.assertEqual(x.a, 1)
3063 for cls in G, J, K, L, M, N, P, R, list, Int:
3064 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3065 if cls is cls2:
3066 continue
3067 cant(cls(), cls2)
3068
Benjamin Peterson193152c2009-04-25 01:08:45 +00003069 # Issue5283: when __class__ changes in __del__, the wrong
3070 # type gets DECREF'd.
3071 class O(object):
3072 pass
3073 class A(object):
3074 def __del__(self):
3075 self.__class__ = O
3076 l = [A() for x in range(100)]
3077 del l
3078
Georg Brandl479a7e72008-02-05 18:13:15 +00003079 def test_set_dict(self):
3080 # Testing __dict__ assignment...
3081 class C(object): pass
3082 a = C()
3083 a.__dict__ = {'b': 1}
3084 self.assertEqual(a.b, 1)
3085 def cant(x, dict):
3086 try:
3087 x.__dict__ = dict
3088 except (AttributeError, TypeError):
3089 pass
3090 else:
3091 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3092 cant(a, None)
3093 cant(a, [])
3094 cant(a, 1)
3095 del a.__dict__ # Deleting __dict__ is allowed
3096
3097 class Base(object):
3098 pass
3099 def verify_dict_readonly(x):
3100 """
3101 x has to be an instance of a class inheriting from Base.
3102 """
3103 cant(x, {})
3104 try:
3105 del x.__dict__
3106 except (AttributeError, TypeError):
3107 pass
3108 else:
3109 self.fail("shouldn't allow del %r.__dict__" % x)
3110 dict_descr = Base.__dict__["__dict__"]
3111 try:
3112 dict_descr.__set__(x, {})
3113 except (AttributeError, TypeError):
3114 pass
3115 else:
3116 self.fail("dict_descr allowed access to %r's dict" % x)
3117
3118 # Classes don't allow __dict__ assignment and have readonly dicts
3119 class Meta1(type, Base):
3120 pass
3121 class Meta2(Base, type):
3122 pass
3123 class D(object, metaclass=Meta1):
3124 pass
3125 class E(object, metaclass=Meta2):
3126 pass
3127 for cls in C, D, E:
3128 verify_dict_readonly(cls)
3129 class_dict = cls.__dict__
3130 try:
3131 class_dict["spam"] = "eggs"
3132 except TypeError:
3133 pass
3134 else:
3135 self.fail("%r's __dict__ can be modified" % cls)
3136
3137 # Modules also disallow __dict__ assignment
3138 class Module1(types.ModuleType, Base):
3139 pass
3140 class Module2(Base, types.ModuleType):
3141 pass
3142 for ModuleType in Module1, Module2:
3143 mod = ModuleType("spam")
3144 verify_dict_readonly(mod)
3145 mod.__dict__["spam"] = "eggs"
3146
3147 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003148 # (at least not any more than regular exception's __dict__ can
3149 # be deleted; on CPython it is not the case, whereas on PyPy they
3150 # can, just like any other new-style instance's __dict__.)
3151 def can_delete_dict(e):
3152 try:
3153 del e.__dict__
3154 except (TypeError, AttributeError):
3155 return False
3156 else:
3157 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003158 class Exception1(Exception, Base):
3159 pass
3160 class Exception2(Base, Exception):
3161 pass
3162 for ExceptionType in Exception, Exception1, Exception2:
3163 e = ExceptionType()
3164 e.__dict__ = {"a": 1}
3165 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003166 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003167
Georg Brandl479a7e72008-02-05 18:13:15 +00003168 def test_binary_operator_override(self):
3169 # Testing overrides of binary operations...
3170 class I(int):
3171 def __repr__(self):
3172 return "I(%r)" % int(self)
3173 def __add__(self, other):
3174 return I(int(self) + int(other))
3175 __radd__ = __add__
3176 def __pow__(self, other, mod=None):
3177 if mod is None:
3178 return I(pow(int(self), int(other)))
3179 else:
3180 return I(pow(int(self), int(other), int(mod)))
3181 def __rpow__(self, other, mod=None):
3182 if mod is None:
3183 return I(pow(int(other), int(self), mod))
3184 else:
3185 return I(pow(int(other), int(self), int(mod)))
3186
3187 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3188 self.assertEqual(repr(I(1) + 2), "I(3)")
3189 self.assertEqual(repr(1 + I(2)), "I(3)")
3190 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3191 self.assertEqual(repr(2 ** I(3)), "I(8)")
3192 self.assertEqual(repr(I(2) ** 3), "I(8)")
3193 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3194 class S(str):
3195 def __eq__(self, other):
3196 return self.lower() == other.lower()
3197
3198 def test_subclass_propagation(self):
3199 # Testing propagation of slot functions to subclasses...
3200 class A(object):
3201 pass
3202 class B(A):
3203 pass
3204 class C(A):
3205 pass
3206 class D(B, C):
3207 pass
3208 d = D()
3209 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3210 A.__hash__ = lambda self: 42
3211 self.assertEqual(hash(d), 42)
3212 C.__hash__ = lambda self: 314
3213 self.assertEqual(hash(d), 314)
3214 B.__hash__ = lambda self: 144
3215 self.assertEqual(hash(d), 144)
3216 D.__hash__ = lambda self: 100
3217 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003218 D.__hash__ = None
3219 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003220 del D.__hash__
3221 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003222 B.__hash__ = None
3223 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003224 del B.__hash__
3225 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003226 C.__hash__ = None
3227 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 del C.__hash__
3229 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003230 A.__hash__ = None
3231 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003232 del A.__hash__
3233 self.assertEqual(hash(d), orig_hash)
3234 d.foo = 42
3235 d.bar = 42
3236 self.assertEqual(d.foo, 42)
3237 self.assertEqual(d.bar, 42)
3238 def __getattribute__(self, name):
3239 if name == "foo":
3240 return 24
3241 return object.__getattribute__(self, name)
3242 A.__getattribute__ = __getattribute__
3243 self.assertEqual(d.foo, 24)
3244 self.assertEqual(d.bar, 42)
3245 def __getattr__(self, name):
3246 if name in ("spam", "foo", "bar"):
3247 return "hello"
3248 raise AttributeError(name)
3249 B.__getattr__ = __getattr__
3250 self.assertEqual(d.spam, "hello")
3251 self.assertEqual(d.foo, 24)
3252 self.assertEqual(d.bar, 42)
3253 del A.__getattribute__
3254 self.assertEqual(d.foo, 42)
3255 del d.foo
3256 self.assertEqual(d.foo, "hello")
3257 self.assertEqual(d.bar, 42)
3258 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003259 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003260 d.foo
3261 except AttributeError:
3262 pass
3263 else:
3264 self.fail("d.foo should be undefined now")
3265
3266 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003267 class A(object):
3268 pass
3269 class B(A):
3270 pass
3271 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003272 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003273 A.__setitem__ = lambda *a: None # crash
3274
3275 def test_buffer_inheritance(self):
3276 # Testing that buffer interface is inherited ...
3277
3278 import binascii
3279 # SF bug [#470040] ParseTuple t# vs subclasses.
3280
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003281 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003282 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003283 base = b'abc'
3284 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003285 # b2a_hex uses the buffer interface to get its argument's value, via
3286 # PyArg_ParseTuple 't#' code.
3287 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3288
Georg Brandl479a7e72008-02-05 18:13:15 +00003289 class MyInt(int):
3290 pass
3291 m = MyInt(42)
3292 try:
3293 binascii.b2a_hex(m)
3294 self.fail('subclass of int should not have a buffer interface')
3295 except TypeError:
3296 pass
3297
3298 def test_str_of_str_subclass(self):
3299 # Testing __str__ defined in subclass of str ...
3300 import binascii
3301 import io
3302
3303 class octetstring(str):
3304 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003305 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003306 def __repr__(self):
3307 return self + " repr"
3308
3309 o = octetstring('A')
3310 self.assertEqual(type(o), octetstring)
3311 self.assertEqual(type(str(o)), str)
3312 self.assertEqual(type(repr(o)), str)
3313 self.assertEqual(ord(o), 0x41)
3314 self.assertEqual(str(o), '41')
3315 self.assertEqual(repr(o), 'A repr')
3316 self.assertEqual(o.__str__(), '41')
3317 self.assertEqual(o.__repr__(), 'A repr')
3318
3319 capture = io.StringIO()
3320 # Calling str() or not exercises different internal paths.
3321 print(o, file=capture)
3322 print(str(o), file=capture)
3323 self.assertEqual(capture.getvalue(), '41\n41\n')
3324 capture.close()
3325
3326 def test_keyword_arguments(self):
3327 # Testing keyword arguments to __init__, __call__...
3328 def f(a): return a
3329 self.assertEqual(f.__call__(a=42), 42)
3330 a = []
3331 list.__init__(a, sequence=[0, 1, 2])
3332 self.assertEqual(a, [0, 1, 2])
3333
3334 def test_recursive_call(self):
3335 # Testing recursive __call__() by setting to instance of class...
3336 class A(object):
3337 pass
3338
3339 A.__call__ = A()
3340 try:
3341 A()()
3342 except RuntimeError:
3343 pass
3344 else:
3345 self.fail("Recursion limit should have been reached for __call__()")
3346
3347 def test_delete_hook(self):
3348 # Testing __del__ hook...
3349 log = []
3350 class C(object):
3351 def __del__(self):
3352 log.append(1)
3353 c = C()
3354 self.assertEqual(log, [])
3355 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003356 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003357 self.assertEqual(log, [1])
3358
3359 class D(object): pass
3360 d = D()
3361 try: del d[0]
3362 except TypeError: pass
3363 else: self.fail("invalid del() didn't raise TypeError")
3364
3365 def test_hash_inheritance(self):
3366 # Testing hash of mutable subclasses...
3367
3368 class mydict(dict):
3369 pass
3370 d = mydict()
3371 try:
3372 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003373 except TypeError:
3374 pass
3375 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003376 self.fail("hash() of dict subclass should fail")
3377
3378 class mylist(list):
3379 pass
3380 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003381 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003382 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003383 except TypeError:
3384 pass
3385 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003386 self.fail("hash() of list subclass should fail")
3387
3388 def test_str_operations(self):
3389 try: 'a' + 5
3390 except TypeError: pass
3391 else: self.fail("'' + 5 doesn't raise TypeError")
3392
3393 try: ''.split('')
3394 except ValueError: pass
3395 else: self.fail("''.split('') doesn't raise ValueError")
3396
3397 try: ''.join([0])
3398 except TypeError: pass
3399 else: self.fail("''.join([0]) doesn't raise TypeError")
3400
3401 try: ''.rindex('5')
3402 except ValueError: pass
3403 else: self.fail("''.rindex('5') doesn't raise ValueError")
3404
3405 try: '%(n)s' % None
3406 except TypeError: pass
3407 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3408
3409 try: '%(n' % {}
3410 except ValueError: pass
3411 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3412
3413 try: '%*s' % ('abc')
3414 except TypeError: pass
3415 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3416
3417 try: '%*.*s' % ('abc', 5)
3418 except TypeError: pass
3419 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3420
3421 try: '%s' % (1, 2)
3422 except TypeError: pass
3423 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3424
3425 try: '%' % None
3426 except ValueError: pass
3427 else: self.fail("'%' % None doesn't raise ValueError")
3428
3429 self.assertEqual('534253'.isdigit(), 1)
3430 self.assertEqual('534253x'.isdigit(), 0)
3431 self.assertEqual('%c' % 5, '\x05')
3432 self.assertEqual('%c' % '5', '5')
3433
3434 def test_deepcopy_recursive(self):
3435 # Testing deepcopy of recursive objects...
3436 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003437 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003438 a = Node()
3439 b = Node()
3440 a.b = b
3441 b.a = a
3442 z = deepcopy(a) # This blew up before
3443
3444 def test_unintialized_modules(self):
3445 # Testing uninitialized module objects...
3446 from types import ModuleType as M
3447 m = M.__new__(M)
3448 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003449 self.assertNotHasAttr(m, "__name__")
3450 self.assertNotHasAttr(m, "__file__")
3451 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003452 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003453 m.foo = 1
3454 self.assertEqual(m.__dict__, {"foo": 1})
3455
3456 def test_funny_new(self):
3457 # Testing __new__ returning something unexpected...
3458 class C(object):
3459 def __new__(cls, arg):
3460 if isinstance(arg, str): return [1, 2, 3]
3461 elif isinstance(arg, int): return object.__new__(D)
3462 else: return object.__new__(cls)
3463 class D(C):
3464 def __init__(self, arg):
3465 self.foo = arg
3466 self.assertEqual(C("1"), [1, 2, 3])
3467 self.assertEqual(D("1"), [1, 2, 3])
3468 d = D(None)
3469 self.assertEqual(d.foo, None)
3470 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003471 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003472 self.assertEqual(d.foo, 1)
3473 d = D(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
3477 def test_imul_bug(self):
3478 # Testing for __imul__ problems...
3479 # SF bug 544647
3480 class C(object):
3481 def __imul__(self, other):
3482 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003483 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003484 y = x
3485 y *= 1.0
3486 self.assertEqual(y, (x, 1.0))
3487 y = x
3488 y *= 2
3489 self.assertEqual(y, (x, 2))
3490 y = x
3491 y *= 3
3492 self.assertEqual(y, (x, 3))
3493 y = x
3494 y *= 1<<100
3495 self.assertEqual(y, (x, 1<<100))
3496 y = x
3497 y *= None
3498 self.assertEqual(y, (x, None))
3499 y = x
3500 y *= "foo"
3501 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003502
Georg Brandl479a7e72008-02-05 18:13:15 +00003503 def test_copy_setstate(self):
3504 # Testing that copy.*copy() correctly uses __setstate__...
3505 import copy
3506 class C(object):
3507 def __init__(self, foo=None):
3508 self.foo = foo
3509 self.__foo = foo
3510 def setfoo(self, foo=None):
3511 self.foo = foo
3512 def getfoo(self):
3513 return self.__foo
3514 def __getstate__(self):
3515 return [self.foo]
3516 def __setstate__(self_, lst):
3517 self.assertEqual(len(lst), 1)
3518 self_.__foo = self_.foo = lst[0]
3519 a = C(42)
3520 a.setfoo(24)
3521 self.assertEqual(a.foo, 24)
3522 self.assertEqual(a.getfoo(), 42)
3523 b = copy.copy(a)
3524 self.assertEqual(b.foo, 24)
3525 self.assertEqual(b.getfoo(), 24)
3526 b = copy.deepcopy(a)
3527 self.assertEqual(b.foo, 24)
3528 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003529
Georg Brandl479a7e72008-02-05 18:13:15 +00003530 def test_slices(self):
3531 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003532
Georg Brandl479a7e72008-02-05 18:13:15 +00003533 # Strings
3534 self.assertEqual("hello"[:4], "hell")
3535 self.assertEqual("hello"[slice(4)], "hell")
3536 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3537 class S(str):
3538 def __getitem__(self, x):
3539 return str.__getitem__(self, x)
3540 self.assertEqual(S("hello")[:4], "hell")
3541 self.assertEqual(S("hello")[slice(4)], "hell")
3542 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3543 # Tuples
3544 self.assertEqual((1,2,3)[:2], (1,2))
3545 self.assertEqual((1,2,3)[slice(2)], (1,2))
3546 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3547 class T(tuple):
3548 def __getitem__(self, x):
3549 return tuple.__getitem__(self, x)
3550 self.assertEqual(T((1,2,3))[:2], (1,2))
3551 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3552 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3553 # Lists
3554 self.assertEqual([1,2,3][:2], [1,2])
3555 self.assertEqual([1,2,3][slice(2)], [1,2])
3556 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3557 class L(list):
3558 def __getitem__(self, x):
3559 return list.__getitem__(self, x)
3560 self.assertEqual(L([1,2,3])[:2], [1,2])
3561 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3562 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3563 # Now do lists and __setitem__
3564 a = L([1,2,3])
3565 a[slice(1, 3)] = [3,2]
3566 self.assertEqual(a, [1,3,2])
3567 a[slice(0, 2, 1)] = [3,1]
3568 self.assertEqual(a, [3,1,2])
3569 a.__setitem__(slice(1, 3), [2,1])
3570 self.assertEqual(a, [3,2,1])
3571 a.__setitem__(slice(0, 2, 1), [2,3])
3572 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003573
Georg Brandl479a7e72008-02-05 18:13:15 +00003574 def test_subtype_resurrection(self):
3575 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003576
Georg Brandl479a7e72008-02-05 18:13:15 +00003577 class C(object):
3578 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003579
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 def __del__(self):
3581 # resurrect the instance
3582 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003583
Georg Brandl479a7e72008-02-05 18:13:15 +00003584 c = C()
3585 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003586
Benjamin Petersone549ead2009-03-28 21:42:05 +00003587 # The most interesting thing here is whether this blows up, due to
3588 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3589 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003590 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003591
Benjamin Petersone549ead2009-03-28 21:42:05 +00003592 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003593 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003594
Georg Brandl479a7e72008-02-05 18:13:15 +00003595 # Make c mortal again, so that the test framework with -l doesn't report
3596 # it as a leak.
3597 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003598
Georg Brandl479a7e72008-02-05 18:13:15 +00003599 def test_slots_trash(self):
3600 # Testing slot trash...
3601 # Deallocating deeply nested slotted trash caused stack overflows
3602 class trash(object):
3603 __slots__ = ['x']
3604 def __init__(self, x):
3605 self.x = x
3606 o = None
3607 for i in range(50000):
3608 o = trash(o)
3609 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003610
Georg Brandl479a7e72008-02-05 18:13:15 +00003611 def test_slots_multiple_inheritance(self):
3612 # SF bug 575229, multiple inheritance w/ slots dumps core
3613 class A(object):
3614 __slots__=()
3615 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003616 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 class C(A,B) :
3618 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003619 if support.check_impl_detail():
3620 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003621 self.assertHasAttr(C, '__dict__')
3622 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003623 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003624
Georg Brandl479a7e72008-02-05 18:13:15 +00003625 def test_rmul(self):
3626 # Testing correct invocation of __rmul__...
3627 # SF patch 592646
3628 class C(object):
3629 def __mul__(self, other):
3630 return "mul"
3631 def __rmul__(self, other):
3632 return "rmul"
3633 a = C()
3634 self.assertEqual(a*2, "mul")
3635 self.assertEqual(a*2.2, "mul")
3636 self.assertEqual(2*a, "rmul")
3637 self.assertEqual(2.2*a, "rmul")
3638
3639 def test_ipow(self):
3640 # Testing correct invocation of __ipow__...
3641 # [SF bug 620179]
3642 class C(object):
3643 def __ipow__(self, other):
3644 pass
3645 a = C()
3646 a **= 2
3647
3648 def test_mutable_bases(self):
3649 # Testing mutable bases...
3650
3651 # stuff that should work:
3652 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003653 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003654 class C2(object):
3655 def __getattribute__(self, attr):
3656 if attr == 'a':
3657 return 2
3658 else:
3659 return super(C2, self).__getattribute__(attr)
3660 def meth(self):
3661 return 1
3662 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003663 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003664 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003665 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003666 d = D()
3667 e = E()
3668 D.__bases__ = (C,)
3669 D.__bases__ = (C2,)
3670 self.assertEqual(d.meth(), 1)
3671 self.assertEqual(e.meth(), 1)
3672 self.assertEqual(d.a, 2)
3673 self.assertEqual(e.a, 2)
3674 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003675
Georg Brandl479a7e72008-02-05 18:13:15 +00003676 try:
3677 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003678 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003679 pass
3680 else:
3681 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003682
Georg Brandl479a7e72008-02-05 18:13:15 +00003683 try:
3684 D.__bases__ = ()
3685 except TypeError as msg:
3686 if str(msg) == "a new-style class can't have only classic bases":
3687 self.fail("wrong error message for .__bases__ = ()")
3688 else:
3689 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003690
Georg Brandl479a7e72008-02-05 18:13:15 +00003691 try:
3692 D.__bases__ = (D,)
3693 except TypeError:
3694 pass
3695 else:
3696 # actually, we'll have crashed by here...
3697 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003698
Georg Brandl479a7e72008-02-05 18:13:15 +00003699 try:
3700 D.__bases__ = (C, C)
3701 except TypeError:
3702 pass
3703 else:
3704 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003705
Georg Brandl479a7e72008-02-05 18:13:15 +00003706 try:
3707 D.__bases__ = (E,)
3708 except TypeError:
3709 pass
3710 else:
3711 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003712
Benjamin Petersonae937c02009-04-18 20:54:08 +00003713 def test_builtin_bases(self):
3714 # Make sure all the builtin types can have their base queried without
3715 # segfaulting. See issue #5787.
3716 builtin_types = [tp for tp in builtins.__dict__.values()
3717 if isinstance(tp, type)]
3718 for tp in builtin_types:
3719 object.__getattribute__(tp, "__bases__")
3720 if tp is not object:
3721 self.assertEqual(len(tp.__bases__), 1, tp)
3722
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003723 class L(list):
3724 pass
3725
3726 class C(object):
3727 pass
3728
3729 class D(C):
3730 pass
3731
3732 try:
3733 L.__bases__ = (dict,)
3734 except TypeError:
3735 pass
3736 else:
3737 self.fail("shouldn't turn list subclass into dict subclass")
3738
3739 try:
3740 list.__bases__ = (dict,)
3741 except TypeError:
3742 pass
3743 else:
3744 self.fail("shouldn't be able to assign to list.__bases__")
3745
3746 try:
3747 D.__bases__ = (C, list)
3748 except TypeError:
3749 pass
3750 else:
3751 assert 0, "best_base calculation found wanting"
3752
Benjamin Petersonae937c02009-04-18 20:54:08 +00003753
Georg Brandl479a7e72008-02-05 18:13:15 +00003754 def test_mutable_bases_with_failing_mro(self):
3755 # Testing mutable bases with failing mro...
3756 class WorkOnce(type):
3757 def __new__(self, name, bases, ns):
3758 self.flag = 0
3759 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3760 def mro(self):
3761 if self.flag > 0:
3762 raise RuntimeError("bozo")
3763 else:
3764 self.flag += 1
3765 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003766
Georg Brandl479a7e72008-02-05 18:13:15 +00003767 class WorkAlways(type):
3768 def mro(self):
3769 # this is here to make sure that .mro()s aren't called
3770 # with an exception set (which was possible at one point).
3771 # An error message will be printed in a debug build.
3772 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003773 return type.mro(self)
3774
Georg Brandl479a7e72008-02-05 18:13:15 +00003775 class C(object):
3776 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003777
Georg Brandl479a7e72008-02-05 18:13:15 +00003778 class C2(object):
3779 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003780
Georg Brandl479a7e72008-02-05 18:13:15 +00003781 class D(C):
3782 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003783
Georg Brandl479a7e72008-02-05 18:13:15 +00003784 class E(D):
3785 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003786
Georg Brandl479a7e72008-02-05 18:13:15 +00003787 class F(D, metaclass=WorkOnce):
3788 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003789
Georg Brandl479a7e72008-02-05 18:13:15 +00003790 class G(D, metaclass=WorkAlways):
3791 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003792
Georg Brandl479a7e72008-02-05 18:13:15 +00003793 # Immediate subclasses have their mro's adjusted in alphabetical
3794 # order, so E's will get adjusted before adjusting F's fails. We
3795 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003796
Georg Brandl479a7e72008-02-05 18:13:15 +00003797 E_mro_before = E.__mro__
3798 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003799
Armin Rigofd163f92005-12-29 15:59:19 +00003800 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003801 D.__bases__ = (C2,)
3802 except RuntimeError:
3803 self.assertEqual(E.__mro__, E_mro_before)
3804 self.assertEqual(D.__mro__, D_mro_before)
3805 else:
3806 self.fail("exception not propagated")
3807
3808 def test_mutable_bases_catch_mro_conflict(self):
3809 # Testing mutable bases catch mro conflict...
3810 class A(object):
3811 pass
3812
3813 class B(object):
3814 pass
3815
3816 class C(A, B):
3817 pass
3818
3819 class D(A, B):
3820 pass
3821
3822 class E(C, D):
3823 pass
3824
3825 try:
3826 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003827 except TypeError:
3828 pass
3829 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003830 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003831
Georg Brandl479a7e72008-02-05 18:13:15 +00003832 def test_mutable_names(self):
3833 # Testing mutable names...
3834 class C(object):
3835 pass
3836
3837 # C.__module__ could be 'test_descr' or '__main__'
3838 mod = C.__module__
3839
3840 C.__name__ = 'D'
3841 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3842
3843 C.__name__ = 'D.E'
3844 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3845
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003846 def test_evil_type_name(self):
3847 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3848 # execution while the type structure was not in a sane state, and a
3849 # possible segmentation fault as a result. See bug #16447.
3850 class Nasty(str):
3851 def __del__(self):
3852 C.__name__ = "other"
3853
3854 class C:
3855 pass
3856
3857 C.__name__ = Nasty("abc")
3858 C.__name__ = "normal"
3859
Georg Brandl479a7e72008-02-05 18:13:15 +00003860 def test_subclass_right_op(self):
3861 # Testing correct dispatch of subclass overloading __r<op>__...
3862
3863 # This code tests various cases where right-dispatch of a subclass
3864 # should be preferred over left-dispatch of a base class.
3865
3866 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3867
3868 class B(int):
3869 def __floordiv__(self, other):
3870 return "B.__floordiv__"
3871 def __rfloordiv__(self, other):
3872 return "B.__rfloordiv__"
3873
3874 self.assertEqual(B(1) // 1, "B.__floordiv__")
3875 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3876
3877 # Case 2: subclass of object; this is just the baseline for case 3
3878
3879 class C(object):
3880 def __floordiv__(self, other):
3881 return "C.__floordiv__"
3882 def __rfloordiv__(self, other):
3883 return "C.__rfloordiv__"
3884
3885 self.assertEqual(C() // 1, "C.__floordiv__")
3886 self.assertEqual(1 // C(), "C.__rfloordiv__")
3887
3888 # Case 3: subclass of new-style class; here it gets interesting
3889
3890 class D(C):
3891 def __floordiv__(self, other):
3892 return "D.__floordiv__"
3893 def __rfloordiv__(self, other):
3894 return "D.__rfloordiv__"
3895
3896 self.assertEqual(D() // C(), "D.__floordiv__")
3897 self.assertEqual(C() // D(), "D.__rfloordiv__")
3898
3899 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3900
3901 class E(C):
3902 pass
3903
3904 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3905
3906 self.assertEqual(E() // 1, "C.__floordiv__")
3907 self.assertEqual(1 // E(), "C.__rfloordiv__")
3908 self.assertEqual(E() // C(), "C.__floordiv__")
3909 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3910
Benjamin Petersone549ead2009-03-28 21:42:05 +00003911 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003912 def test_meth_class_get(self):
3913 # Testing __get__ method of METH_CLASS C methods...
3914 # Full coverage of descrobject.c::classmethod_get()
3915
3916 # Baseline
3917 arg = [1, 2, 3]
3918 res = {1: None, 2: None, 3: None}
3919 self.assertEqual(dict.fromkeys(arg), res)
3920 self.assertEqual({}.fromkeys(arg), res)
3921
3922 # Now get the descriptor
3923 descr = dict.__dict__["fromkeys"]
3924
3925 # More baseline using the descriptor directly
3926 self.assertEqual(descr.__get__(None, dict)(arg), res)
3927 self.assertEqual(descr.__get__({})(arg), res)
3928
3929 # Now check various error cases
3930 try:
3931 descr.__get__(None, None)
3932 except TypeError:
3933 pass
3934 else:
3935 self.fail("shouldn't have allowed descr.__get__(None, None)")
3936 try:
3937 descr.__get__(42)
3938 except TypeError:
3939 pass
3940 else:
3941 self.fail("shouldn't have allowed descr.__get__(42)")
3942 try:
3943 descr.__get__(None, 42)
3944 except TypeError:
3945 pass
3946 else:
3947 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3948 try:
3949 descr.__get__(None, int)
3950 except TypeError:
3951 pass
3952 else:
3953 self.fail("shouldn't have allowed descr.__get__(None, int)")
3954
3955 def test_isinst_isclass(self):
3956 # Testing proxy isinstance() and isclass()...
3957 class Proxy(object):
3958 def __init__(self, obj):
3959 self.__obj = obj
3960 def __getattribute__(self, name):
3961 if name.startswith("_Proxy__"):
3962 return object.__getattribute__(self, name)
3963 else:
3964 return getattr(self.__obj, name)
3965 # Test with a classic class
3966 class C:
3967 pass
3968 a = C()
3969 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003970 self.assertIsInstance(a, C) # Baseline
3971 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003972 # Test with a classic subclass
3973 class D(C):
3974 pass
3975 a = D()
3976 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003977 self.assertIsInstance(a, C) # Baseline
3978 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003979 # Test with a new-style class
3980 class C(object):
3981 pass
3982 a = C()
3983 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003984 self.assertIsInstance(a, C) # Baseline
3985 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003986 # Test with a new-style subclass
3987 class D(C):
3988 pass
3989 a = D()
3990 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003991 self.assertIsInstance(a, C) # Baseline
3992 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003993
3994 def test_proxy_super(self):
3995 # Testing super() for a proxy object...
3996 class Proxy(object):
3997 def __init__(self, obj):
3998 self.__obj = obj
3999 def __getattribute__(self, name):
4000 if name.startswith("_Proxy__"):
4001 return object.__getattribute__(self, name)
4002 else:
4003 return getattr(self.__obj, name)
4004
4005 class B(object):
4006 def f(self):
4007 return "B.f"
4008
4009 class C(B):
4010 def f(self):
4011 return super(C, self).f() + "->C.f"
4012
4013 obj = C()
4014 p = Proxy(obj)
4015 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4016
4017 def test_carloverre(self):
4018 # Testing prohibition of Carlo Verre's hack...
4019 try:
4020 object.__setattr__(str, "foo", 42)
4021 except TypeError:
4022 pass
4023 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004024 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004025 try:
4026 object.__delattr__(str, "lower")
4027 except TypeError:
4028 pass
4029 else:
4030 self.fail("Carlo Verre __delattr__ succeeded!")
4031
4032 def test_weakref_segfault(self):
4033 # Testing weakref segfault...
4034 # SF 742911
4035 import weakref
4036
4037 class Provoker:
4038 def __init__(self, referrent):
4039 self.ref = weakref.ref(referrent)
4040
4041 def __del__(self):
4042 x = self.ref()
4043
4044 class Oops(object):
4045 pass
4046
4047 o = Oops()
4048 o.whatever = Provoker(o)
4049 del o
4050
4051 def test_wrapper_segfault(self):
4052 # SF 927248: deeply nested wrappers could cause stack overflow
4053 f = lambda:None
4054 for i in range(1000000):
4055 f = f.__call__
4056 f = None
4057
4058 def test_file_fault(self):
4059 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004060 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004061 class StdoutGuard:
4062 def __getattr__(self, attr):
4063 sys.stdout = sys.__stdout__
4064 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4065 sys.stdout = StdoutGuard()
4066 try:
4067 print("Oops!")
4068 except RuntimeError:
4069 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004070 finally:
4071 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004072
4073 def test_vicious_descriptor_nonsense(self):
4074 # Testing vicious_descriptor_nonsense...
4075
4076 # A potential segfault spotted by Thomas Wouters in mail to
4077 # python-dev 2003-04-17, turned into an example & fixed by Michael
4078 # Hudson just less than four months later...
4079
4080 class Evil(object):
4081 def __hash__(self):
4082 return hash('attr')
4083 def __eq__(self, other):
4084 del C.attr
4085 return 0
4086
4087 class Descr(object):
4088 def __get__(self, ob, type=None):
4089 return 1
4090
4091 class C(object):
4092 attr = Descr()
4093
4094 c = C()
4095 c.__dict__[Evil()] = 0
4096
4097 self.assertEqual(c.attr, 1)
4098 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004099 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004100 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004101
4102 def test_init(self):
4103 # SF 1155938
4104 class Foo(object):
4105 def __init__(self):
4106 return 10
4107 try:
4108 Foo()
4109 except TypeError:
4110 pass
4111 else:
4112 self.fail("did not test __init__() for None return")
4113
4114 def test_method_wrapper(self):
4115 # Testing method-wrapper objects...
4116 # <type 'method-wrapper'> did not support any reflection before 2.5
4117
Mark Dickinson211c6252009-02-01 10:28:51 +00004118 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004119
4120 l = []
4121 self.assertEqual(l.__add__, l.__add__)
4122 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004123 self.assertNotEqual(l.__add__, [5].__add__)
4124 self.assertNotEqual(l.__add__, l.__mul__)
4125 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004126 if hasattr(l.__add__, '__self__'):
4127 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004128 self.assertIs(l.__add__.__self__, l)
4129 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004130 else:
4131 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004132 self.assertIs(l.__add__.im_self, l)
4133 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004134 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4135 try:
4136 hash(l.__add__)
4137 except TypeError:
4138 pass
4139 else:
4140 self.fail("no TypeError from hash([].__add__)")
4141
4142 t = ()
4143 t += (7,)
4144 self.assertEqual(t.__add__, (7,).__add__)
4145 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4146
4147 def test_not_implemented(self):
4148 # Testing NotImplemented...
4149 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004150 import operator
4151
4152 def specialmethod(self, other):
4153 return NotImplemented
4154
4155 def check(expr, x, y):
4156 try:
4157 exec(expr, {'x': x, 'y': y, 'operator': operator})
4158 except TypeError:
4159 pass
4160 else:
4161 self.fail("no TypeError from %r" % (expr,))
4162
4163 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4164 # TypeErrors
4165 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4166 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004167 for name, expr, iexpr in [
4168 ('__add__', 'x + y', 'x += y'),
4169 ('__sub__', 'x - y', 'x -= y'),
4170 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004171 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004172 ('__truediv__', 'x / y', 'x /= y'),
4173 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004174 ('__mod__', 'x % y', 'x %= y'),
4175 ('__divmod__', 'divmod(x, y)', None),
4176 ('__pow__', 'x ** y', 'x **= y'),
4177 ('__lshift__', 'x << y', 'x <<= y'),
4178 ('__rshift__', 'x >> y', 'x >>= y'),
4179 ('__and__', 'x & y', 'x &= y'),
4180 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004181 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004182 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004183 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004184 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004185 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004186 check(expr, a, N1)
4187 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004188 if iexpr:
4189 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004190 check(iexpr, a, N1)
4191 check(iexpr, a, N2)
4192 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004193 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004194 c = C()
4195 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004196 check(iexpr, c, N1)
4197 check(iexpr, c, N2)
4198
Georg Brandl479a7e72008-02-05 18:13:15 +00004199 def test_assign_slice(self):
4200 # ceval.c's assign_slice used to check for
4201 # tp->tp_as_sequence->sq_slice instead of
4202 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004203
Georg Brandl479a7e72008-02-05 18:13:15 +00004204 class C(object):
4205 def __setitem__(self, idx, value):
4206 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004207
Georg Brandl479a7e72008-02-05 18:13:15 +00004208 c = C()
4209 c[1:2] = 3
4210 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004211
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004212 def test_set_and_no_get(self):
4213 # See
4214 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4215 class Descr(object):
4216
4217 def __init__(self, name):
4218 self.name = name
4219
4220 def __set__(self, obj, value):
4221 obj.__dict__[self.name] = value
4222 descr = Descr("a")
4223
4224 class X(object):
4225 a = descr
4226
4227 x = X()
4228 self.assertIs(x.a, descr)
4229 x.a = 42
4230 self.assertEqual(x.a, 42)
4231
Benjamin Peterson21896a32010-03-21 22:03:03 +00004232 # Also check type_getattro for correctness.
4233 class Meta(type):
4234 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004235 class X(metaclass=Meta):
4236 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004237 X.a = 42
4238 Meta.a = Descr("a")
4239 self.assertEqual(X.a, 42)
4240
Benjamin Peterson9262b842008-11-17 22:45:50 +00004241 def test_getattr_hooks(self):
4242 # issue 4230
4243
4244 class Descriptor(object):
4245 counter = 0
4246 def __get__(self, obj, objtype=None):
4247 def getter(name):
4248 self.counter += 1
4249 raise AttributeError(name)
4250 return getter
4251
4252 descr = Descriptor()
4253 class A(object):
4254 __getattribute__ = descr
4255 class B(object):
4256 __getattr__ = descr
4257 class C(object):
4258 __getattribute__ = descr
4259 __getattr__ = descr
4260
4261 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004262 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004263 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004264 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004265 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004266 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004267
Benjamin Peterson9262b842008-11-17 22:45:50 +00004268 class EvilGetattribute(object):
4269 # This used to segfault
4270 def __getattr__(self, name):
4271 raise AttributeError(name)
4272 def __getattribute__(self, name):
4273 del EvilGetattribute.__getattr__
4274 for i in range(5):
4275 gc.collect()
4276 raise AttributeError(name)
4277
4278 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4279
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004280 def test_type___getattribute__(self):
4281 self.assertRaises(TypeError, type.__getattribute__, list, type)
4282
Benjamin Peterson477ba912011-01-12 15:34:01 +00004283 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004284 # type pretends not to have __abstractmethods__.
4285 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4286 class meta(type):
4287 pass
4288 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004289 class X(object):
4290 pass
4291 with self.assertRaises(AttributeError):
4292 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004293
Victor Stinner3249dec2011-05-01 23:19:15 +02004294 def test_proxy_call(self):
4295 class FakeStr:
4296 __class__ = str
4297
4298 fake_str = FakeStr()
4299 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004300 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004301
4302 # call a method descriptor
4303 with self.assertRaises(TypeError):
4304 str.split(fake_str)
4305
4306 # call a slot wrapper descriptor
4307 with self.assertRaises(TypeError):
4308 str.__add__(fake_str, "abc")
4309
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004310 def test_repr_as_str(self):
4311 # Issue #11603: crash or infinite loop when rebinding __str__ as
4312 # __repr__.
4313 class Foo:
4314 pass
4315 Foo.__repr__ = Foo.__str__
4316 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004317 self.assertRaises(RuntimeError, str, foo)
4318 self.assertRaises(RuntimeError, repr, foo)
4319
4320 def test_mixing_slot_wrappers(self):
4321 class X(dict):
4322 __setattr__ = dict.__setitem__
4323 x = X()
4324 x.y = 42
4325 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004326
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004327 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004328 with self.assertRaises(ValueError) as cm:
4329 class X:
4330 __slots__ = ["foo"]
4331 foo = None
4332 m = str(cm.exception)
4333 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4334
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004335 def test_set_doc(self):
4336 class X:
4337 "elephant"
4338 X.__doc__ = "banana"
4339 self.assertEqual(X.__doc__, "banana")
4340 with self.assertRaises(TypeError) as cm:
4341 type(list).__dict__["__doc__"].__set__(list, "blah")
4342 self.assertIn("can't set list.__doc__", str(cm.exception))
4343 with self.assertRaises(TypeError) as cm:
4344 type(X).__dict__["__doc__"].__delete__(X)
4345 self.assertIn("can't delete X.__doc__", str(cm.exception))
4346 self.assertEqual(X.__doc__, "banana")
4347
Antoine Pitrou9d574812011-12-12 13:47:25 +01004348 def test_qualname(self):
4349 descriptors = [str.lower, complex.real, float.real, int.__add__]
4350 types = ['method', 'member', 'getset', 'wrapper']
4351
4352 # make sure we have an example of each type of descriptor
4353 for d, n in zip(descriptors, types):
4354 self.assertEqual(type(d).__name__, n + '_descriptor')
4355
4356 for d in descriptors:
4357 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4358 self.assertEqual(d.__qualname__, qualname)
4359
4360 self.assertEqual(str.lower.__qualname__, 'str.lower')
4361 self.assertEqual(complex.real.__qualname__, 'complex.real')
4362 self.assertEqual(float.real.__qualname__, 'float.real')
4363 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4364
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004365 class X:
4366 pass
4367 with self.assertRaises(TypeError):
4368 del X.__qualname__
4369
4370 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4371 str, 'Oink')
4372
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004373 global Y
4374 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004375 class Inside:
4376 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004377 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004378 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004379
Victor Stinner6f738742012-02-25 01:22:36 +01004380 def test_qualname_dict(self):
4381 ns = {'__qualname__': 'some.name'}
4382 tp = type('Foo', (), ns)
4383 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004384 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004385 self.assertEqual(ns, {'__qualname__': 'some.name'})
4386
4387 ns = {'__qualname__': 1}
4388 self.assertRaises(TypeError, type, 'Foo', (), ns)
4389
Benjamin Peterson52c42432012-03-07 18:41:11 -06004390 def test_cycle_through_dict(self):
4391 # See bug #1469629
4392 class X(dict):
4393 def __init__(self):
4394 dict.__init__(self)
4395 self.__dict__ = self
4396 x = X()
4397 x.attr = 42
4398 wr = weakref.ref(x)
4399 del x
4400 support.gc_collect()
4401 self.assertIsNone(wr())
4402 for o in gc.get_objects():
4403 self.assertIsNot(type(o), X)
4404
Benjamin Peterson96384b92012-03-17 00:05:44 -05004405 def test_object_new_and_init_with_parameters(self):
4406 # See issue #1683368
4407 class OverrideNeither:
4408 pass
4409 self.assertRaises(TypeError, OverrideNeither, 1)
4410 self.assertRaises(TypeError, OverrideNeither, kw=1)
4411 class OverrideNew:
4412 def __new__(cls, foo, kw=0, *args, **kwds):
4413 return object.__new__(cls, *args, **kwds)
4414 class OverrideInit:
4415 def __init__(self, foo, kw=0, *args, **kwargs):
4416 return object.__init__(self, *args, **kwargs)
4417 class OverrideBoth(OverrideNew, OverrideInit):
4418 pass
4419 for case in OverrideNew, OverrideInit, OverrideBoth:
4420 case(1)
4421 case(1, kw=2)
4422 self.assertRaises(TypeError, case, 1, 2, 3)
4423 self.assertRaises(TypeError, case, 1, 2, foo=3)
4424
Benjamin Petersondf813792014-03-17 15:57:17 -05004425 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4426 class Base:
4427 pass
4428 class Sub(Base):
4429 pass
4430 self.assertIn("__dict__", Base.__dict__)
4431 self.assertNotIn("__dict__", Sub.__dict__)
4432
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004433 def test_bound_method_repr(self):
4434 class Foo:
4435 def method(self):
4436 pass
4437 self.assertRegex(repr(Foo().method),
4438 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4439
4440
4441 class Base:
4442 def method(self):
4443 pass
4444 class Derived1(Base):
4445 pass
4446 class Derived2(Base):
4447 def method(self):
4448 pass
4449 base = Base()
4450 derived1 = Derived1()
4451 derived2 = Derived2()
4452 super_d2 = super(Derived2, derived2)
4453 self.assertRegex(repr(base.method),
4454 r"<bound method .*Base\.method of <.*Base object at .*>>")
4455 self.assertRegex(repr(derived1.method),
4456 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4457 self.assertRegex(repr(derived2.method),
4458 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4459 self.assertRegex(repr(super_d2.method),
4460 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4461
4462 class Foo:
4463 @classmethod
4464 def method(cls):
4465 pass
4466 foo = Foo()
4467 self.assertRegex(repr(foo.method), # access via instance
4468 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4469 self.assertRegex(repr(Foo.method), # access via the class
4470 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4471
4472
4473 class MyCallable:
4474 def __call__(self, arg):
4475 pass
4476 func = MyCallable() # func has no __name__ or __qualname__ attributes
4477 instance = object()
4478 method = types.MethodType(func, instance)
4479 self.assertRegex(repr(method),
4480 r"<bound method \? of <object object at .*>>")
4481 func.__name__ = "name"
4482 self.assertRegex(repr(method),
4483 r"<bound method name of <object object at .*>>")
4484 func.__qualname__ = "qualname"
4485 self.assertRegex(repr(method),
4486 r"<bound method qualname of <object object at .*>>")
4487
Antoine Pitrou9d574812011-12-12 13:47:25 +01004488
Georg Brandl479a7e72008-02-05 18:13:15 +00004489class DictProxyTests(unittest.TestCase):
4490 def setUp(self):
4491 class C(object):
4492 def meth(self):
4493 pass
4494 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004495
Brett Cannon7a540732011-02-22 03:04:06 +00004496 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4497 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004498 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004499 # Testing dict-proxy keys...
4500 it = self.C.__dict__.keys()
4501 self.assertNotIsInstance(it, list)
4502 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004503 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004504 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004505 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004506
Brett Cannon7a540732011-02-22 03:04:06 +00004507 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4508 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004509 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004510 # Testing dict-proxy values...
4511 it = self.C.__dict__.values()
4512 self.assertNotIsInstance(it, list)
4513 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004514 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004515
Brett Cannon7a540732011-02-22 03:04:06 +00004516 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4517 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004518 def test_iter_items(self):
4519 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004520 it = self.C.__dict__.items()
4521 self.assertNotIsInstance(it, list)
4522 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004523 keys.sort()
4524 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004525 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004526
Georg Brandl479a7e72008-02-05 18:13:15 +00004527 def test_dict_type_with_metaclass(self):
4528 # Testing type of __dict__ when metaclass set...
4529 class B(object):
4530 pass
4531 class M(type):
4532 pass
4533 class C(metaclass=M):
4534 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4535 pass
4536 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004537
Ezio Melottiac53ab62010-12-18 14:59:43 +00004538 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004539 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004540 # We can't blindly compare with the repr of another dict as ordering
4541 # of keys and values is arbitrary and may differ.
4542 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004543 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004544 self.assertTrue(r.endswith(')'), r)
4545 for k, v in self.C.__dict__.items():
4546 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004547
Christian Heimesbbffeb62008-01-24 09:42:52 +00004548
Georg Brandl479a7e72008-02-05 18:13:15 +00004549class PTypesLongInitTest(unittest.TestCase):
4550 # This is in its own TestCase so that it can be run before any other tests.
4551 def test_pytype_long_ready(self):
4552 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004553
Georg Brandl479a7e72008-02-05 18:13:15 +00004554 # This dumps core when SF bug 551412 isn't fixed --
4555 # but only when test_descr.py is run separately.
4556 # (That can't be helped -- as soon as PyType_Ready()
4557 # is called for PyLong_Type, the bug is gone.)
4558 class UserLong(object):
4559 def __pow__(self, *args):
4560 pass
4561 try:
4562 pow(0, UserLong(), 0)
4563 except:
4564 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004565
Georg Brandl479a7e72008-02-05 18:13:15 +00004566 # Another segfault only when run early
4567 # (before PyType_Ready(tuple) is called)
4568 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004569
4570
Victor Stinnerd74782b2012-03-09 00:39:08 +01004571class MiscTests(unittest.TestCase):
4572 def test_type_lookup_mro_reference(self):
4573 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4574 # the type MRO because it may be modified during the lookup, if
4575 # __bases__ is set during the lookup for example.
4576 class MyKey(object):
4577 def __hash__(self):
4578 return hash('mykey')
4579
4580 def __eq__(self, other):
4581 X.__bases__ = (Base2,)
4582
4583 class Base(object):
4584 mykey = 'from Base'
4585 mykey2 = 'from Base'
4586
4587 class Base2(object):
4588 mykey = 'from Base2'
4589 mykey2 = 'from Base2'
4590
4591 X = type('X', (Base,), {MyKey(): 5})
4592 # mykey is read from Base
4593 self.assertEqual(X.mykey, 'from Base')
4594 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4595 self.assertEqual(X.mykey2, 'from Base2')
4596
4597
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004598class PicklingTests(unittest.TestCase):
4599
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004600 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004601 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004602 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004603 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004604 if kwargs:
4605 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4606 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004607 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004608 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4609 self.assertEqual(reduce_value[1], (type(obj),) + args)
4610 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004611 if listitems is not None:
4612 self.assertListEqual(list(reduce_value[3]), listitems)
4613 else:
4614 self.assertIsNone(reduce_value[3])
4615 if dictitems is not None:
4616 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4617 else:
4618 self.assertIsNone(reduce_value[4])
4619 else:
4620 base_type = type(obj).__base__
4621 reduce_value = (copyreg._reconstructor,
4622 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004623 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004624 None if base_type is object else base_type(obj)))
4625 if state is not None:
4626 reduce_value += (state,)
4627 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4628 self.assertEqual(obj.__reduce__(), reduce_value)
4629
4630 def test_reduce(self):
4631 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4632 args = (-101, "spam")
4633 kwargs = {'bacon': -201, 'fish': -301}
4634 state = {'cheese': -401}
4635
4636 class C1:
4637 def __getnewargs__(self):
4638 return args
4639 obj = C1()
4640 for proto in protocols:
4641 self._check_reduce(proto, obj, args)
4642
4643 for name, value in state.items():
4644 setattr(obj, name, value)
4645 for proto in protocols:
4646 self._check_reduce(proto, obj, args, state=state)
4647
4648 class C2:
4649 def __getnewargs__(self):
4650 return "bad args"
4651 obj = C2()
4652 for proto in protocols:
4653 if proto >= 2:
4654 with self.assertRaises(TypeError):
4655 obj.__reduce_ex__(proto)
4656
4657 class C3:
4658 def __getnewargs_ex__(self):
4659 return (args, kwargs)
4660 obj = C3()
4661 for proto in protocols:
4662 if proto >= 4:
4663 self._check_reduce(proto, obj, args, kwargs)
4664 elif proto >= 2:
4665 with self.assertRaises(ValueError):
4666 obj.__reduce_ex__(proto)
4667
4668 class C4:
4669 def __getnewargs_ex__(self):
4670 return (args, "bad dict")
4671 class C5:
4672 def __getnewargs_ex__(self):
4673 return ("bad tuple", kwargs)
4674 class C6:
4675 def __getnewargs_ex__(self):
4676 return ()
4677 class C7:
4678 def __getnewargs_ex__(self):
4679 return "bad args"
4680 for proto in protocols:
4681 for cls in C4, C5, C6, C7:
4682 obj = cls()
4683 if proto >= 2:
4684 with self.assertRaises((TypeError, ValueError)):
4685 obj.__reduce_ex__(proto)
4686
4687 class C8:
4688 def __getnewargs_ex__(self):
4689 return (args, kwargs)
4690 obj = C8()
4691 for proto in protocols:
4692 if 2 <= proto < 4:
4693 with self.assertRaises(ValueError):
4694 obj.__reduce_ex__(proto)
4695 class C9:
4696 def __getnewargs_ex__(self):
4697 return (args, {})
4698 obj = C9()
4699 for proto in protocols:
4700 self._check_reduce(proto, obj, args)
4701
4702 class C10:
4703 def __getnewargs_ex__(self):
4704 raise IndexError
4705 obj = C10()
4706 for proto in protocols:
4707 if proto >= 2:
4708 with self.assertRaises(IndexError):
4709 obj.__reduce_ex__(proto)
4710
4711 class C11:
4712 def __getstate__(self):
4713 return state
4714 obj = C11()
4715 for proto in protocols:
4716 self._check_reduce(proto, obj, state=state)
4717
4718 class C12:
4719 def __getstate__(self):
4720 return "not dict"
4721 obj = C12()
4722 for proto in protocols:
4723 self._check_reduce(proto, obj, state="not dict")
4724
4725 class C13:
4726 def __getstate__(self):
4727 raise IndexError
4728 obj = C13()
4729 for proto in protocols:
4730 with self.assertRaises(IndexError):
4731 obj.__reduce_ex__(proto)
4732 if proto < 2:
4733 with self.assertRaises(IndexError):
4734 obj.__reduce__()
4735
4736 class C14:
4737 __slots__ = tuple(state)
4738 def __init__(self):
4739 for name, value in state.items():
4740 setattr(self, name, value)
4741
4742 obj = C14()
4743 for proto in protocols:
4744 if proto >= 2:
4745 self._check_reduce(proto, obj, state=(None, state))
4746 else:
4747 with self.assertRaises(TypeError):
4748 obj.__reduce_ex__(proto)
4749 with self.assertRaises(TypeError):
4750 obj.__reduce__()
4751
4752 class C15(dict):
4753 pass
4754 obj = C15({"quebec": -601})
4755 for proto in protocols:
4756 self._check_reduce(proto, obj, dictitems=dict(obj))
4757
4758 class C16(list):
4759 pass
4760 obj = C16(["yukon"])
4761 for proto in protocols:
4762 self._check_reduce(proto, obj, listitems=list(obj))
4763
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004764 def test_special_method_lookup(self):
4765 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4766 class Picky:
4767 def __getstate__(self):
4768 return {}
4769
4770 def __getattr__(self, attr):
4771 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4772 raise AssertionError(attr)
4773 return None
4774 for protocol in protocols:
4775 state = {} if protocol >= 2 else None
4776 self._check_reduce(protocol, Picky(), state=state)
4777
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004778 def _assert_is_copy(self, obj, objcopy, msg=None):
4779 """Utility method to verify if two objects are copies of each others.
4780 """
4781 if msg is None:
4782 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4783 if type(obj).__repr__ is object.__repr__:
4784 # We have this limitation for now because we use the object's repr
4785 # to help us verify that the two objects are copies. This allows
4786 # us to delegate the non-generic verification logic to the objects
4787 # themselves.
4788 raise ValueError("object passed to _assert_is_copy must " +
4789 "override the __repr__ method.")
4790 self.assertIsNot(obj, objcopy, msg=msg)
4791 self.assertIs(type(obj), type(objcopy), msg=msg)
4792 if hasattr(obj, '__dict__'):
4793 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4794 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4795 if hasattr(obj, '__slots__'):
4796 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4797 for slot in obj.__slots__:
4798 self.assertEqual(
4799 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4800 self.assertEqual(getattr(obj, slot, None),
4801 getattr(objcopy, slot, None), msg=msg)
4802 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4803
4804 @staticmethod
4805 def _generate_pickle_copiers():
4806 """Utility method to generate the many possible pickle configurations.
4807 """
4808 class PickleCopier:
4809 "This class copies object using pickle."
4810 def __init__(self, proto, dumps, loads):
4811 self.proto = proto
4812 self.dumps = dumps
4813 self.loads = loads
4814 def copy(self, obj):
4815 return self.loads(self.dumps(obj, self.proto))
4816 def __repr__(self):
4817 # We try to be as descriptive as possible here since this is
4818 # the string which we will allow us to tell the pickle
4819 # configuration we are using during debugging.
4820 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4821 .format(self.proto,
4822 self.dumps.__module__, self.dumps.__qualname__,
4823 self.loads.__module__, self.loads.__qualname__))
4824 return (PickleCopier(*args) for args in
4825 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4826 {pickle.dumps, pickle._dumps},
4827 {pickle.loads, pickle._loads}))
4828
4829 def test_pickle_slots(self):
4830 # Tests pickling of classes with __slots__.
4831
4832 # Pickling of classes with __slots__ but without __getstate__ should
4833 # fail (if using protocol 0 or 1)
4834 global C
4835 class C:
4836 __slots__ = ['a']
4837 with self.assertRaises(TypeError):
4838 pickle.dumps(C(), 0)
4839
4840 global D
4841 class D(C):
4842 pass
4843 with self.assertRaises(TypeError):
4844 pickle.dumps(D(), 0)
4845
4846 class C:
4847 "A class with __getstate__ and __setstate__ implemented."
4848 __slots__ = ['a']
4849 def __getstate__(self):
4850 state = getattr(self, '__dict__', {}).copy()
4851 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004852 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004853 try:
4854 state[slot] = getattr(self, slot)
4855 except AttributeError:
4856 pass
4857 return state
4858 def __setstate__(self, state):
4859 for k, v in state.items():
4860 setattr(self, k, v)
4861 def __repr__(self):
4862 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4863
4864 class D(C):
4865 "A subclass of a class with slots."
4866 pass
4867
4868 global E
4869 class E(C):
4870 "A subclass with an extra slot."
4871 __slots__ = ['b']
4872
4873 # Now it should work
4874 for pickle_copier in self._generate_pickle_copiers():
4875 with self.subTest(pickle_copier=pickle_copier):
4876 x = C()
4877 y = pickle_copier.copy(x)
4878 self._assert_is_copy(x, y)
4879
4880 x.a = 42
4881 y = pickle_copier.copy(x)
4882 self._assert_is_copy(x, y)
4883
4884 x = D()
4885 x.a = 42
4886 x.b = 100
4887 y = pickle_copier.copy(x)
4888 self._assert_is_copy(x, y)
4889
4890 x = E()
4891 x.a = 42
4892 x.b = "foo"
4893 y = pickle_copier.copy(x)
4894 self._assert_is_copy(x, y)
4895
4896 def test_reduce_copying(self):
4897 # Tests pickling and copying new-style classes and objects.
4898 global C1
4899 class C1:
4900 "The state of this class is copyable via its instance dict."
4901 ARGS = (1, 2)
4902 NEED_DICT_COPYING = True
4903 def __init__(self, a, b):
4904 super().__init__()
4905 self.a = a
4906 self.b = b
4907 def __repr__(self):
4908 return "C1(%r, %r)" % (self.a, self.b)
4909
4910 global C2
4911 class C2(list):
4912 "A list subclass copyable via __getnewargs__."
4913 ARGS = (1, 2)
4914 NEED_DICT_COPYING = False
4915 def __new__(cls, a, b):
4916 self = super().__new__(cls)
4917 self.a = a
4918 self.b = b
4919 return self
4920 def __init__(self, *args):
4921 super().__init__()
4922 # This helps testing that __init__ is not called during the
4923 # unpickling process, which would cause extra appends.
4924 self.append("cheese")
4925 @classmethod
4926 def __getnewargs__(cls):
4927 return cls.ARGS
4928 def __repr__(self):
4929 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
4930
4931 global C3
4932 class C3(list):
4933 "A list subclass copyable via __getstate__."
4934 ARGS = (1, 2)
4935 NEED_DICT_COPYING = False
4936 def __init__(self, a, b):
4937 self.a = a
4938 self.b = b
4939 # This helps testing that __init__ is not called during the
4940 # unpickling process, which would cause extra appends.
4941 self.append("cheese")
4942 @classmethod
4943 def __getstate__(cls):
4944 return cls.ARGS
4945 def __setstate__(self, state):
4946 a, b = state
4947 self.a = a
4948 self.b = b
4949 def __repr__(self):
4950 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
4951
4952 global C4
4953 class C4(int):
4954 "An int subclass copyable via __getnewargs__."
4955 ARGS = ("hello", "world", 1)
4956 NEED_DICT_COPYING = False
4957 def __new__(cls, a, b, value):
4958 self = super().__new__(cls, value)
4959 self.a = a
4960 self.b = b
4961 return self
4962 @classmethod
4963 def __getnewargs__(cls):
4964 return cls.ARGS
4965 def __repr__(self):
4966 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
4967
4968 global C5
4969 class C5(int):
4970 "An int subclass copyable via __getnewargs_ex__."
4971 ARGS = (1, 2)
4972 KWARGS = {'value': 3}
4973 NEED_DICT_COPYING = False
4974 def __new__(cls, a, b, *, value=0):
4975 self = super().__new__(cls, value)
4976 self.a = a
4977 self.b = b
4978 return self
4979 @classmethod
4980 def __getnewargs_ex__(cls):
4981 return (cls.ARGS, cls.KWARGS)
4982 def __repr__(self):
4983 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
4984
4985 test_classes = (C1, C2, C3, C4, C5)
4986 # Testing copying through pickle
4987 pickle_copiers = self._generate_pickle_copiers()
4988 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
4989 with self.subTest(cls=cls, pickle_copier=pickle_copier):
4990 kwargs = getattr(cls, 'KWARGS', {})
4991 obj = cls(*cls.ARGS, **kwargs)
4992 proto = pickle_copier.proto
4993 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
4994 with self.assertRaises(ValueError):
4995 pickle_copier.dumps(obj, proto)
4996 continue
4997 objcopy = pickle_copier.copy(obj)
4998 self._assert_is_copy(obj, objcopy)
4999 # For test classes that supports this, make sure we didn't go
5000 # around the reduce protocol by simply copying the attribute
5001 # dictionary. We clear attributes using the previous copy to
5002 # not mutate the original argument.
5003 if proto >= 2 and not cls.NEED_DICT_COPYING:
5004 objcopy.__dict__.clear()
5005 objcopy2 = pickle_copier.copy(objcopy)
5006 self._assert_is_copy(obj, objcopy2)
5007
5008 # Testing copying through copy.deepcopy()
5009 for cls in test_classes:
5010 with self.subTest(cls=cls):
5011 kwargs = getattr(cls, 'KWARGS', {})
5012 obj = cls(*cls.ARGS, **kwargs)
5013 # XXX: We need to modify the copy module to support PEP 3154's
5014 # reduce protocol 4.
5015 if hasattr(cls, '__getnewargs_ex__'):
5016 continue
5017 objcopy = deepcopy(obj)
5018 self._assert_is_copy(obj, objcopy)
5019 # For test classes that supports this, make sure we didn't go
5020 # around the reduce protocol by simply copying the attribute
5021 # dictionary. We clear attributes using the previous copy to
5022 # not mutate the original argument.
5023 if not cls.NEED_DICT_COPYING:
5024 objcopy.__dict__.clear()
5025 objcopy2 = deepcopy(objcopy)
5026 self._assert_is_copy(obj, objcopy2)
5027
5028
Benjamin Peterson2a605342014-03-17 16:20:12 -05005029class SharedKeyTests(unittest.TestCase):
5030
5031 @support.cpython_only
5032 def test_subclasses(self):
5033 # Verify that subclasses can share keys (per PEP 412)
5034 class A:
5035 pass
5036 class B(A):
5037 pass
5038
5039 a, b = A(), B()
5040 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5041 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5042 a.x, a.y, a.z, a.w = range(4)
5043 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5044 a2 = A()
5045 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5046 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5047 b.u, b.v, b.w, b.t = range(4)
5048 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5049
5050
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005051class DebugHelperMeta(type):
5052 """
5053 Sets default __doc__ and simplifies repr() output.
5054 """
5055 def __new__(mcls, name, bases, attrs):
5056 if attrs.get('__doc__') is None:
5057 attrs['__doc__'] = name # helps when debugging with gdb
5058 return type.__new__(mcls, name, bases, attrs)
5059 def __repr__(cls):
5060 return repr(cls.__name__)
5061
5062
5063class MroTest(unittest.TestCase):
5064 """
5065 Regressions for some bugs revealed through
5066 mcsl.mro() customization (typeobject.c: mro_internal()) and
5067 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5068 """
5069
5070 def setUp(self):
5071 self.step = 0
5072 self.ready = False
5073
5074 def step_until(self, limit):
5075 ret = (self.step < limit)
5076 if ret:
5077 self.step += 1
5078 return ret
5079
5080 def test_incomplete_set_bases_on_self(self):
5081 """
5082 type_set_bases must be aware that type->tp_mro can be NULL.
5083 """
5084 class M(DebugHelperMeta):
5085 def mro(cls):
5086 if self.step_until(1):
5087 assert cls.__mro__ is None
5088 cls.__bases__ += ()
5089
5090 return type.mro(cls)
5091
5092 class A(metaclass=M):
5093 pass
5094
5095 def test_reent_set_bases_on_base(self):
5096 """
5097 Deep reentrancy must not over-decref old_mro.
5098 """
5099 class M(DebugHelperMeta):
5100 def mro(cls):
5101 if cls.__mro__ is not None and cls.__name__ == 'B':
5102 # 4-5 steps are usually enough to make it crash somewhere
5103 if self.step_until(10):
5104 A.__bases__ += ()
5105
5106 return type.mro(cls)
5107
5108 class A(metaclass=M):
5109 pass
5110 class B(A):
5111 pass
5112 B.__bases__ += ()
5113
5114 def test_reent_set_bases_on_direct_base(self):
5115 """
5116 Similar to test_reent_set_bases_on_base, but may crash differently.
5117 """
5118 class M(DebugHelperMeta):
5119 def mro(cls):
5120 base = cls.__bases__[0]
5121 if base is not object:
5122 if self.step_until(5):
5123 base.__bases__ += ()
5124
5125 return type.mro(cls)
5126
5127 class A(metaclass=M):
5128 pass
5129 class B(A):
5130 pass
5131 class C(B):
5132 pass
5133
5134 def test_reent_set_bases_tp_base_cycle(self):
5135 """
5136 type_set_bases must check for an inheritance cycle not only through
5137 MRO of the type, which may be not yet updated in case of reentrance,
5138 but also through tp_base chain, which is assigned before diving into
5139 inner calls to mro().
5140
5141 Otherwise, the following snippet can loop forever:
5142 do {
5143 // ...
5144 type = type->tp_base;
5145 } while (type != NULL);
5146
5147 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5148 would not be happy in that case, causing a stack overflow.
5149 """
5150 class M(DebugHelperMeta):
5151 def mro(cls):
5152 if self.ready:
5153 if cls.__name__ == 'B1':
5154 B2.__bases__ = (B1,)
5155 if cls.__name__ == 'B2':
5156 B1.__bases__ = (B2,)
5157 return type.mro(cls)
5158
5159 class A(metaclass=M):
5160 pass
5161 class B1(A):
5162 pass
5163 class B2(A):
5164 pass
5165
5166 self.ready = True
5167 with self.assertRaises(TypeError):
5168 B1.__bases__ += ()
5169
5170 def test_tp_subclasses_cycle_in_update_slots(self):
5171 """
5172 type_set_bases must check for reentrancy upon finishing its job
5173 by updating tp_subclasses of old/new bases of the type.
5174 Otherwise, an implicit inheritance cycle through tp_subclasses
5175 can break functions that recurse on elements of that field
5176 (like recurse_down_subclasses and mro_hierarchy) eventually
5177 leading to a stack overflow.
5178 """
5179 class M(DebugHelperMeta):
5180 def mro(cls):
5181 if self.ready and cls.__name__ == 'C':
5182 self.ready = False
5183 C.__bases__ = (B2,)
5184 return type.mro(cls)
5185
5186 class A(metaclass=M):
5187 pass
5188 class B1(A):
5189 pass
5190 class B2(A):
5191 pass
5192 class C(A):
5193 pass
5194
5195 self.ready = True
5196 C.__bases__ = (B1,)
5197 B1.__bases__ = (C,)
5198
5199 self.assertEqual(C.__bases__, (B2,))
5200 self.assertEqual(B2.__subclasses__(), [C])
5201 self.assertEqual(B1.__subclasses__(), [])
5202
5203 self.assertEqual(B1.__bases__, (C,))
5204 self.assertEqual(C.__subclasses__(), [B1])
5205
5206 def test_tp_subclasses_cycle_error_return_path(self):
5207 """
5208 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5209 a code path executed on error (goto bail).
5210 """
5211 class E(Exception):
5212 pass
5213 class M(DebugHelperMeta):
5214 def mro(cls):
5215 if self.ready and cls.__name__ == 'C':
5216 if C.__bases__ == (B2,):
5217 self.ready = False
5218 else:
5219 C.__bases__ = (B2,)
5220 raise E
5221 return type.mro(cls)
5222
5223 class A(metaclass=M):
5224 pass
5225 class B1(A):
5226 pass
5227 class B2(A):
5228 pass
5229 class C(A):
5230 pass
5231
5232 self.ready = True
5233 with self.assertRaises(E):
5234 C.__bases__ = (B1,)
5235 B1.__bases__ = (C,)
5236
5237 self.assertEqual(C.__bases__, (B2,))
5238 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5239
5240 def test_incomplete_extend(self):
5241 """
5242 Extending an unitialized type with type->tp_mro == NULL must
5243 throw a reasonable TypeError exception, instead of failing
5244 with PyErr_BadInternalCall.
5245 """
5246 class M(DebugHelperMeta):
5247 def mro(cls):
5248 if cls.__mro__ is None and cls.__name__ != 'X':
5249 with self.assertRaises(TypeError):
5250 class X(cls):
5251 pass
5252
5253 return type.mro(cls)
5254
5255 class A(metaclass=M):
5256 pass
5257
5258 def test_incomplete_super(self):
5259 """
5260 Attrubute lookup on a super object must be aware that
5261 its target type can be uninitialized (type->tp_mro == NULL).
5262 """
5263 class M(DebugHelperMeta):
5264 def mro(cls):
5265 if cls.__mro__ is None:
5266 with self.assertRaises(AttributeError):
5267 super(cls, cls).xxx
5268
5269 return type.mro(cls)
5270
5271 class A(metaclass=M):
5272 pass
5273
5274
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005275def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005276 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005277 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005278 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005279 MiscTests, PicklingTests, SharedKeyTests,
5280 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005281
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005282if __name__ == "__main__":
5283 test_main()