blob: cdaae0ac697f5f7df378cb3dd063578e0130459a [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__ = []
3023 cant(2, Int)
3024 cant(Int(), int)
3025 cant(True, int)
3026 cant(2, bool)
3027 o = object()
3028 cant(o, type(1))
3029 cant(o, type(None))
3030 del o
3031 class G(object):
3032 __slots__ = ["a", "b"]
3033 class H(object):
3034 __slots__ = ["b", "a"]
3035 class I(object):
3036 __slots__ = ["a", "b"]
3037 class J(object):
3038 __slots__ = ["c", "b"]
3039 class K(object):
3040 __slots__ = ["a", "b", "d"]
3041 class L(H):
3042 __slots__ = ["e"]
3043 class M(I):
3044 __slots__ = ["e"]
3045 class N(J):
3046 __slots__ = ["__weakref__"]
3047 class P(J):
3048 __slots__ = ["__dict__"]
3049 class Q(J):
3050 pass
3051 class R(J):
3052 __slots__ = ["__dict__", "__weakref__"]
3053
3054 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3055 x = cls()
3056 x.a = 1
3057 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003058 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003059 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3060 self.assertEqual(x.a, 1)
3061 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003062 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003063 "assigning %r as __class__ for %r silently failed" % (cls, x))
3064 self.assertEqual(x.a, 1)
3065 for cls in G, J, K, L, M, N, P, R, list, Int:
3066 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3067 if cls is cls2:
3068 continue
3069 cant(cls(), cls2)
3070
Benjamin Peterson193152c2009-04-25 01:08:45 +00003071 # Issue5283: when __class__ changes in __del__, the wrong
3072 # type gets DECREF'd.
3073 class O(object):
3074 pass
3075 class A(object):
3076 def __del__(self):
3077 self.__class__ = O
3078 l = [A() for x in range(100)]
3079 del l
3080
Georg Brandl479a7e72008-02-05 18:13:15 +00003081 def test_set_dict(self):
3082 # Testing __dict__ assignment...
3083 class C(object): pass
3084 a = C()
3085 a.__dict__ = {'b': 1}
3086 self.assertEqual(a.b, 1)
3087 def cant(x, dict):
3088 try:
3089 x.__dict__ = dict
3090 except (AttributeError, TypeError):
3091 pass
3092 else:
3093 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3094 cant(a, None)
3095 cant(a, [])
3096 cant(a, 1)
3097 del a.__dict__ # Deleting __dict__ is allowed
3098
3099 class Base(object):
3100 pass
3101 def verify_dict_readonly(x):
3102 """
3103 x has to be an instance of a class inheriting from Base.
3104 """
3105 cant(x, {})
3106 try:
3107 del x.__dict__
3108 except (AttributeError, TypeError):
3109 pass
3110 else:
3111 self.fail("shouldn't allow del %r.__dict__" % x)
3112 dict_descr = Base.__dict__["__dict__"]
3113 try:
3114 dict_descr.__set__(x, {})
3115 except (AttributeError, TypeError):
3116 pass
3117 else:
3118 self.fail("dict_descr allowed access to %r's dict" % x)
3119
3120 # Classes don't allow __dict__ assignment and have readonly dicts
3121 class Meta1(type, Base):
3122 pass
3123 class Meta2(Base, type):
3124 pass
3125 class D(object, metaclass=Meta1):
3126 pass
3127 class E(object, metaclass=Meta2):
3128 pass
3129 for cls in C, D, E:
3130 verify_dict_readonly(cls)
3131 class_dict = cls.__dict__
3132 try:
3133 class_dict["spam"] = "eggs"
3134 except TypeError:
3135 pass
3136 else:
3137 self.fail("%r's __dict__ can be modified" % cls)
3138
3139 # Modules also disallow __dict__ assignment
3140 class Module1(types.ModuleType, Base):
3141 pass
3142 class Module2(Base, types.ModuleType):
3143 pass
3144 for ModuleType in Module1, Module2:
3145 mod = ModuleType("spam")
3146 verify_dict_readonly(mod)
3147 mod.__dict__["spam"] = "eggs"
3148
3149 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003150 # (at least not any more than regular exception's __dict__ can
3151 # be deleted; on CPython it is not the case, whereas on PyPy they
3152 # can, just like any other new-style instance's __dict__.)
3153 def can_delete_dict(e):
3154 try:
3155 del e.__dict__
3156 except (TypeError, AttributeError):
3157 return False
3158 else:
3159 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003160 class Exception1(Exception, Base):
3161 pass
3162 class Exception2(Base, Exception):
3163 pass
3164 for ExceptionType in Exception, Exception1, Exception2:
3165 e = ExceptionType()
3166 e.__dict__ = {"a": 1}
3167 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003168 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003169
Georg Brandl479a7e72008-02-05 18:13:15 +00003170 def test_binary_operator_override(self):
3171 # Testing overrides of binary operations...
3172 class I(int):
3173 def __repr__(self):
3174 return "I(%r)" % int(self)
3175 def __add__(self, other):
3176 return I(int(self) + int(other))
3177 __radd__ = __add__
3178 def __pow__(self, other, mod=None):
3179 if mod is None:
3180 return I(pow(int(self), int(other)))
3181 else:
3182 return I(pow(int(self), int(other), int(mod)))
3183 def __rpow__(self, other, mod=None):
3184 if mod is None:
3185 return I(pow(int(other), int(self), mod))
3186 else:
3187 return I(pow(int(other), int(self), int(mod)))
3188
3189 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3190 self.assertEqual(repr(I(1) + 2), "I(3)")
3191 self.assertEqual(repr(1 + I(2)), "I(3)")
3192 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3193 self.assertEqual(repr(2 ** I(3)), "I(8)")
3194 self.assertEqual(repr(I(2) ** 3), "I(8)")
3195 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3196 class S(str):
3197 def __eq__(self, other):
3198 return self.lower() == other.lower()
3199
3200 def test_subclass_propagation(self):
3201 # Testing propagation of slot functions to subclasses...
3202 class A(object):
3203 pass
3204 class B(A):
3205 pass
3206 class C(A):
3207 pass
3208 class D(B, C):
3209 pass
3210 d = D()
3211 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3212 A.__hash__ = lambda self: 42
3213 self.assertEqual(hash(d), 42)
3214 C.__hash__ = lambda self: 314
3215 self.assertEqual(hash(d), 314)
3216 B.__hash__ = lambda self: 144
3217 self.assertEqual(hash(d), 144)
3218 D.__hash__ = lambda self: 100
3219 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003220 D.__hash__ = None
3221 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003222 del D.__hash__
3223 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003224 B.__hash__ = None
3225 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003226 del B.__hash__
3227 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003228 C.__hash__ = None
3229 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003230 del C.__hash__
3231 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003232 A.__hash__ = None
3233 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003234 del A.__hash__
3235 self.assertEqual(hash(d), orig_hash)
3236 d.foo = 42
3237 d.bar = 42
3238 self.assertEqual(d.foo, 42)
3239 self.assertEqual(d.bar, 42)
3240 def __getattribute__(self, name):
3241 if name == "foo":
3242 return 24
3243 return object.__getattribute__(self, name)
3244 A.__getattribute__ = __getattribute__
3245 self.assertEqual(d.foo, 24)
3246 self.assertEqual(d.bar, 42)
3247 def __getattr__(self, name):
3248 if name in ("spam", "foo", "bar"):
3249 return "hello"
3250 raise AttributeError(name)
3251 B.__getattr__ = __getattr__
3252 self.assertEqual(d.spam, "hello")
3253 self.assertEqual(d.foo, 24)
3254 self.assertEqual(d.bar, 42)
3255 del A.__getattribute__
3256 self.assertEqual(d.foo, 42)
3257 del d.foo
3258 self.assertEqual(d.foo, "hello")
3259 self.assertEqual(d.bar, 42)
3260 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003261 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003262 d.foo
3263 except AttributeError:
3264 pass
3265 else:
3266 self.fail("d.foo should be undefined now")
3267
3268 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003269 class A(object):
3270 pass
3271 class B(A):
3272 pass
3273 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003274 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003275 A.__setitem__ = lambda *a: None # crash
3276
3277 def test_buffer_inheritance(self):
3278 # Testing that buffer interface is inherited ...
3279
3280 import binascii
3281 # SF bug [#470040] ParseTuple t# vs subclasses.
3282
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003283 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003284 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003285 base = b'abc'
3286 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003287 # b2a_hex uses the buffer interface to get its argument's value, via
3288 # PyArg_ParseTuple 't#' code.
3289 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3290
Georg Brandl479a7e72008-02-05 18:13:15 +00003291 class MyInt(int):
3292 pass
3293 m = MyInt(42)
3294 try:
3295 binascii.b2a_hex(m)
3296 self.fail('subclass of int should not have a buffer interface')
3297 except TypeError:
3298 pass
3299
3300 def test_str_of_str_subclass(self):
3301 # Testing __str__ defined in subclass of str ...
3302 import binascii
3303 import io
3304
3305 class octetstring(str):
3306 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003307 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003308 def __repr__(self):
3309 return self + " repr"
3310
3311 o = octetstring('A')
3312 self.assertEqual(type(o), octetstring)
3313 self.assertEqual(type(str(o)), str)
3314 self.assertEqual(type(repr(o)), str)
3315 self.assertEqual(ord(o), 0x41)
3316 self.assertEqual(str(o), '41')
3317 self.assertEqual(repr(o), 'A repr')
3318 self.assertEqual(o.__str__(), '41')
3319 self.assertEqual(o.__repr__(), 'A repr')
3320
3321 capture = io.StringIO()
3322 # Calling str() or not exercises different internal paths.
3323 print(o, file=capture)
3324 print(str(o), file=capture)
3325 self.assertEqual(capture.getvalue(), '41\n41\n')
3326 capture.close()
3327
3328 def test_keyword_arguments(self):
3329 # Testing keyword arguments to __init__, __call__...
3330 def f(a): return a
3331 self.assertEqual(f.__call__(a=42), 42)
3332 a = []
3333 list.__init__(a, sequence=[0, 1, 2])
3334 self.assertEqual(a, [0, 1, 2])
3335
3336 def test_recursive_call(self):
3337 # Testing recursive __call__() by setting to instance of class...
3338 class A(object):
3339 pass
3340
3341 A.__call__ = A()
3342 try:
3343 A()()
3344 except RuntimeError:
3345 pass
3346 else:
3347 self.fail("Recursion limit should have been reached for __call__()")
3348
3349 def test_delete_hook(self):
3350 # Testing __del__ hook...
3351 log = []
3352 class C(object):
3353 def __del__(self):
3354 log.append(1)
3355 c = C()
3356 self.assertEqual(log, [])
3357 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003358 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003359 self.assertEqual(log, [1])
3360
3361 class D(object): pass
3362 d = D()
3363 try: del d[0]
3364 except TypeError: pass
3365 else: self.fail("invalid del() didn't raise TypeError")
3366
3367 def test_hash_inheritance(self):
3368 # Testing hash of mutable subclasses...
3369
3370 class mydict(dict):
3371 pass
3372 d = mydict()
3373 try:
3374 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003375 except TypeError:
3376 pass
3377 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003378 self.fail("hash() of dict subclass should fail")
3379
3380 class mylist(list):
3381 pass
3382 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003383 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003384 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003385 except TypeError:
3386 pass
3387 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003388 self.fail("hash() of list subclass should fail")
3389
3390 def test_str_operations(self):
3391 try: 'a' + 5
3392 except TypeError: pass
3393 else: self.fail("'' + 5 doesn't raise TypeError")
3394
3395 try: ''.split('')
3396 except ValueError: pass
3397 else: self.fail("''.split('') doesn't raise ValueError")
3398
3399 try: ''.join([0])
3400 except TypeError: pass
3401 else: self.fail("''.join([0]) doesn't raise TypeError")
3402
3403 try: ''.rindex('5')
3404 except ValueError: pass
3405 else: self.fail("''.rindex('5') doesn't raise ValueError")
3406
3407 try: '%(n)s' % None
3408 except TypeError: pass
3409 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3410
3411 try: '%(n' % {}
3412 except ValueError: pass
3413 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3414
3415 try: '%*s' % ('abc')
3416 except TypeError: pass
3417 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3418
3419 try: '%*.*s' % ('abc', 5)
3420 except TypeError: pass
3421 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3422
3423 try: '%s' % (1, 2)
3424 except TypeError: pass
3425 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3426
3427 try: '%' % None
3428 except ValueError: pass
3429 else: self.fail("'%' % None doesn't raise ValueError")
3430
3431 self.assertEqual('534253'.isdigit(), 1)
3432 self.assertEqual('534253x'.isdigit(), 0)
3433 self.assertEqual('%c' % 5, '\x05')
3434 self.assertEqual('%c' % '5', '5')
3435
3436 def test_deepcopy_recursive(self):
3437 # Testing deepcopy of recursive objects...
3438 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003439 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003440 a = Node()
3441 b = Node()
3442 a.b = b
3443 b.a = a
3444 z = deepcopy(a) # This blew up before
3445
3446 def test_unintialized_modules(self):
3447 # Testing uninitialized module objects...
3448 from types import ModuleType as M
3449 m = M.__new__(M)
3450 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003451 self.assertNotHasAttr(m, "__name__")
3452 self.assertNotHasAttr(m, "__file__")
3453 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003454 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003455 m.foo = 1
3456 self.assertEqual(m.__dict__, {"foo": 1})
3457
3458 def test_funny_new(self):
3459 # Testing __new__ returning something unexpected...
3460 class C(object):
3461 def __new__(cls, arg):
3462 if isinstance(arg, str): return [1, 2, 3]
3463 elif isinstance(arg, int): return object.__new__(D)
3464 else: return object.__new__(cls)
3465 class D(C):
3466 def __init__(self, arg):
3467 self.foo = arg
3468 self.assertEqual(C("1"), [1, 2, 3])
3469 self.assertEqual(D("1"), [1, 2, 3])
3470 d = D(None)
3471 self.assertEqual(d.foo, None)
3472 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003473 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003474 self.assertEqual(d.foo, 1)
3475 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003476 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003477 self.assertEqual(d.foo, 1)
3478
3479 def test_imul_bug(self):
3480 # Testing for __imul__ problems...
3481 # SF bug 544647
3482 class C(object):
3483 def __imul__(self, other):
3484 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003485 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003486 y = x
3487 y *= 1.0
3488 self.assertEqual(y, (x, 1.0))
3489 y = x
3490 y *= 2
3491 self.assertEqual(y, (x, 2))
3492 y = x
3493 y *= 3
3494 self.assertEqual(y, (x, 3))
3495 y = x
3496 y *= 1<<100
3497 self.assertEqual(y, (x, 1<<100))
3498 y = x
3499 y *= None
3500 self.assertEqual(y, (x, None))
3501 y = x
3502 y *= "foo"
3503 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003504
Georg Brandl479a7e72008-02-05 18:13:15 +00003505 def test_copy_setstate(self):
3506 # Testing that copy.*copy() correctly uses __setstate__...
3507 import copy
3508 class C(object):
3509 def __init__(self, foo=None):
3510 self.foo = foo
3511 self.__foo = foo
3512 def setfoo(self, foo=None):
3513 self.foo = foo
3514 def getfoo(self):
3515 return self.__foo
3516 def __getstate__(self):
3517 return [self.foo]
3518 def __setstate__(self_, lst):
3519 self.assertEqual(len(lst), 1)
3520 self_.__foo = self_.foo = lst[0]
3521 a = C(42)
3522 a.setfoo(24)
3523 self.assertEqual(a.foo, 24)
3524 self.assertEqual(a.getfoo(), 42)
3525 b = copy.copy(a)
3526 self.assertEqual(b.foo, 24)
3527 self.assertEqual(b.getfoo(), 24)
3528 b = copy.deepcopy(a)
3529 self.assertEqual(b.foo, 24)
3530 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003531
Georg Brandl479a7e72008-02-05 18:13:15 +00003532 def test_slices(self):
3533 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003534
Georg Brandl479a7e72008-02-05 18:13:15 +00003535 # Strings
3536 self.assertEqual("hello"[:4], "hell")
3537 self.assertEqual("hello"[slice(4)], "hell")
3538 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3539 class S(str):
3540 def __getitem__(self, x):
3541 return str.__getitem__(self, x)
3542 self.assertEqual(S("hello")[:4], "hell")
3543 self.assertEqual(S("hello")[slice(4)], "hell")
3544 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3545 # Tuples
3546 self.assertEqual((1,2,3)[:2], (1,2))
3547 self.assertEqual((1,2,3)[slice(2)], (1,2))
3548 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3549 class T(tuple):
3550 def __getitem__(self, x):
3551 return tuple.__getitem__(self, x)
3552 self.assertEqual(T((1,2,3))[:2], (1,2))
3553 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3554 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3555 # Lists
3556 self.assertEqual([1,2,3][:2], [1,2])
3557 self.assertEqual([1,2,3][slice(2)], [1,2])
3558 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3559 class L(list):
3560 def __getitem__(self, x):
3561 return list.__getitem__(self, x)
3562 self.assertEqual(L([1,2,3])[:2], [1,2])
3563 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3564 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3565 # Now do lists and __setitem__
3566 a = L([1,2,3])
3567 a[slice(1, 3)] = [3,2]
3568 self.assertEqual(a, [1,3,2])
3569 a[slice(0, 2, 1)] = [3,1]
3570 self.assertEqual(a, [3,1,2])
3571 a.__setitem__(slice(1, 3), [2,1])
3572 self.assertEqual(a, [3,2,1])
3573 a.__setitem__(slice(0, 2, 1), [2,3])
3574 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003575
Georg Brandl479a7e72008-02-05 18:13:15 +00003576 def test_subtype_resurrection(self):
3577 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003578
Georg Brandl479a7e72008-02-05 18:13:15 +00003579 class C(object):
3580 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003581
Georg Brandl479a7e72008-02-05 18:13:15 +00003582 def __del__(self):
3583 # resurrect the instance
3584 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003585
Georg Brandl479a7e72008-02-05 18:13:15 +00003586 c = C()
3587 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003588
Benjamin Petersone549ead2009-03-28 21:42:05 +00003589 # The most interesting thing here is whether this blows up, due to
3590 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3591 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003592 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003593
Benjamin Petersone549ead2009-03-28 21:42:05 +00003594 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003595 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003596
Georg Brandl479a7e72008-02-05 18:13:15 +00003597 # Make c mortal again, so that the test framework with -l doesn't report
3598 # it as a leak.
3599 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003600
Georg Brandl479a7e72008-02-05 18:13:15 +00003601 def test_slots_trash(self):
3602 # Testing slot trash...
3603 # Deallocating deeply nested slotted trash caused stack overflows
3604 class trash(object):
3605 __slots__ = ['x']
3606 def __init__(self, x):
3607 self.x = x
3608 o = None
3609 for i in range(50000):
3610 o = trash(o)
3611 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003612
Georg Brandl479a7e72008-02-05 18:13:15 +00003613 def test_slots_multiple_inheritance(self):
3614 # SF bug 575229, multiple inheritance w/ slots dumps core
3615 class A(object):
3616 __slots__=()
3617 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003618 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003619 class C(A,B) :
3620 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003621 if support.check_impl_detail():
3622 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003623 self.assertHasAttr(C, '__dict__')
3624 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003625 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003626
Georg Brandl479a7e72008-02-05 18:13:15 +00003627 def test_rmul(self):
3628 # Testing correct invocation of __rmul__...
3629 # SF patch 592646
3630 class C(object):
3631 def __mul__(self, other):
3632 return "mul"
3633 def __rmul__(self, other):
3634 return "rmul"
3635 a = C()
3636 self.assertEqual(a*2, "mul")
3637 self.assertEqual(a*2.2, "mul")
3638 self.assertEqual(2*a, "rmul")
3639 self.assertEqual(2.2*a, "rmul")
3640
3641 def test_ipow(self):
3642 # Testing correct invocation of __ipow__...
3643 # [SF bug 620179]
3644 class C(object):
3645 def __ipow__(self, other):
3646 pass
3647 a = C()
3648 a **= 2
3649
3650 def test_mutable_bases(self):
3651 # Testing mutable bases...
3652
3653 # stuff that should work:
3654 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003655 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003656 class C2(object):
3657 def __getattribute__(self, attr):
3658 if attr == 'a':
3659 return 2
3660 else:
3661 return super(C2, self).__getattribute__(attr)
3662 def meth(self):
3663 return 1
3664 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003665 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003666 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003667 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003668 d = D()
3669 e = E()
3670 D.__bases__ = (C,)
3671 D.__bases__ = (C2,)
3672 self.assertEqual(d.meth(), 1)
3673 self.assertEqual(e.meth(), 1)
3674 self.assertEqual(d.a, 2)
3675 self.assertEqual(e.a, 2)
3676 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003677
Georg Brandl479a7e72008-02-05 18:13:15 +00003678 try:
3679 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003680 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003681 pass
3682 else:
3683 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003684
Georg Brandl479a7e72008-02-05 18:13:15 +00003685 try:
3686 D.__bases__ = ()
3687 except TypeError as msg:
3688 if str(msg) == "a new-style class can't have only classic bases":
3689 self.fail("wrong error message for .__bases__ = ()")
3690 else:
3691 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003692
Georg Brandl479a7e72008-02-05 18:13:15 +00003693 try:
3694 D.__bases__ = (D,)
3695 except TypeError:
3696 pass
3697 else:
3698 # actually, we'll have crashed by here...
3699 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003700
Georg Brandl479a7e72008-02-05 18:13:15 +00003701 try:
3702 D.__bases__ = (C, C)
3703 except TypeError:
3704 pass
3705 else:
3706 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003707
Georg Brandl479a7e72008-02-05 18:13:15 +00003708 try:
3709 D.__bases__ = (E,)
3710 except TypeError:
3711 pass
3712 else:
3713 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003714
Benjamin Petersonae937c02009-04-18 20:54:08 +00003715 def test_builtin_bases(self):
3716 # Make sure all the builtin types can have their base queried without
3717 # segfaulting. See issue #5787.
3718 builtin_types = [tp for tp in builtins.__dict__.values()
3719 if isinstance(tp, type)]
3720 for tp in builtin_types:
3721 object.__getattribute__(tp, "__bases__")
3722 if tp is not object:
3723 self.assertEqual(len(tp.__bases__), 1, tp)
3724
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003725 class L(list):
3726 pass
3727
3728 class C(object):
3729 pass
3730
3731 class D(C):
3732 pass
3733
3734 try:
3735 L.__bases__ = (dict,)
3736 except TypeError:
3737 pass
3738 else:
3739 self.fail("shouldn't turn list subclass into dict subclass")
3740
3741 try:
3742 list.__bases__ = (dict,)
3743 except TypeError:
3744 pass
3745 else:
3746 self.fail("shouldn't be able to assign to list.__bases__")
3747
3748 try:
3749 D.__bases__ = (C, list)
3750 except TypeError:
3751 pass
3752 else:
3753 assert 0, "best_base calculation found wanting"
3754
Benjamin Petersonae937c02009-04-18 20:54:08 +00003755
Georg Brandl479a7e72008-02-05 18:13:15 +00003756 def test_mutable_bases_with_failing_mro(self):
3757 # Testing mutable bases with failing mro...
3758 class WorkOnce(type):
3759 def __new__(self, name, bases, ns):
3760 self.flag = 0
3761 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3762 def mro(self):
3763 if self.flag > 0:
3764 raise RuntimeError("bozo")
3765 else:
3766 self.flag += 1
3767 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003768
Georg Brandl479a7e72008-02-05 18:13:15 +00003769 class WorkAlways(type):
3770 def mro(self):
3771 # this is here to make sure that .mro()s aren't called
3772 # with an exception set (which was possible at one point).
3773 # An error message will be printed in a debug build.
3774 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003775 return type.mro(self)
3776
Georg Brandl479a7e72008-02-05 18:13:15 +00003777 class C(object):
3778 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003779
Georg Brandl479a7e72008-02-05 18:13:15 +00003780 class C2(object):
3781 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003782
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 class D(C):
3784 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003785
Georg Brandl479a7e72008-02-05 18:13:15 +00003786 class E(D):
3787 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003788
Georg Brandl479a7e72008-02-05 18:13:15 +00003789 class F(D, metaclass=WorkOnce):
3790 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003791
Georg Brandl479a7e72008-02-05 18:13:15 +00003792 class G(D, metaclass=WorkAlways):
3793 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003794
Georg Brandl479a7e72008-02-05 18:13:15 +00003795 # Immediate subclasses have their mro's adjusted in alphabetical
3796 # order, so E's will get adjusted before adjusting F's fails. We
3797 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003798
Georg Brandl479a7e72008-02-05 18:13:15 +00003799 E_mro_before = E.__mro__
3800 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003801
Armin Rigofd163f92005-12-29 15:59:19 +00003802 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003803 D.__bases__ = (C2,)
3804 except RuntimeError:
3805 self.assertEqual(E.__mro__, E_mro_before)
3806 self.assertEqual(D.__mro__, D_mro_before)
3807 else:
3808 self.fail("exception not propagated")
3809
3810 def test_mutable_bases_catch_mro_conflict(self):
3811 # Testing mutable bases catch mro conflict...
3812 class A(object):
3813 pass
3814
3815 class B(object):
3816 pass
3817
3818 class C(A, B):
3819 pass
3820
3821 class D(A, B):
3822 pass
3823
3824 class E(C, D):
3825 pass
3826
3827 try:
3828 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003829 except TypeError:
3830 pass
3831 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003832 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003833
Georg Brandl479a7e72008-02-05 18:13:15 +00003834 def test_mutable_names(self):
3835 # Testing mutable names...
3836 class C(object):
3837 pass
3838
3839 # C.__module__ could be 'test_descr' or '__main__'
3840 mod = C.__module__
3841
3842 C.__name__ = 'D'
3843 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3844
3845 C.__name__ = 'D.E'
3846 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3847
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003848 def test_evil_type_name(self):
3849 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3850 # execution while the type structure was not in a sane state, and a
3851 # possible segmentation fault as a result. See bug #16447.
3852 class Nasty(str):
3853 def __del__(self):
3854 C.__name__ = "other"
3855
3856 class C:
3857 pass
3858
3859 C.__name__ = Nasty("abc")
3860 C.__name__ = "normal"
3861
Georg Brandl479a7e72008-02-05 18:13:15 +00003862 def test_subclass_right_op(self):
3863 # Testing correct dispatch of subclass overloading __r<op>__...
3864
3865 # This code tests various cases where right-dispatch of a subclass
3866 # should be preferred over left-dispatch of a base class.
3867
3868 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3869
3870 class B(int):
3871 def __floordiv__(self, other):
3872 return "B.__floordiv__"
3873 def __rfloordiv__(self, other):
3874 return "B.__rfloordiv__"
3875
3876 self.assertEqual(B(1) // 1, "B.__floordiv__")
3877 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3878
3879 # Case 2: subclass of object; this is just the baseline for case 3
3880
3881 class C(object):
3882 def __floordiv__(self, other):
3883 return "C.__floordiv__"
3884 def __rfloordiv__(self, other):
3885 return "C.__rfloordiv__"
3886
3887 self.assertEqual(C() // 1, "C.__floordiv__")
3888 self.assertEqual(1 // C(), "C.__rfloordiv__")
3889
3890 # Case 3: subclass of new-style class; here it gets interesting
3891
3892 class D(C):
3893 def __floordiv__(self, other):
3894 return "D.__floordiv__"
3895 def __rfloordiv__(self, other):
3896 return "D.__rfloordiv__"
3897
3898 self.assertEqual(D() // C(), "D.__floordiv__")
3899 self.assertEqual(C() // D(), "D.__rfloordiv__")
3900
3901 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3902
3903 class E(C):
3904 pass
3905
3906 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3907
3908 self.assertEqual(E() // 1, "C.__floordiv__")
3909 self.assertEqual(1 // E(), "C.__rfloordiv__")
3910 self.assertEqual(E() // C(), "C.__floordiv__")
3911 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3912
Benjamin Petersone549ead2009-03-28 21:42:05 +00003913 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003914 def test_meth_class_get(self):
3915 # Testing __get__ method of METH_CLASS C methods...
3916 # Full coverage of descrobject.c::classmethod_get()
3917
3918 # Baseline
3919 arg = [1, 2, 3]
3920 res = {1: None, 2: None, 3: None}
3921 self.assertEqual(dict.fromkeys(arg), res)
3922 self.assertEqual({}.fromkeys(arg), res)
3923
3924 # Now get the descriptor
3925 descr = dict.__dict__["fromkeys"]
3926
3927 # More baseline using the descriptor directly
3928 self.assertEqual(descr.__get__(None, dict)(arg), res)
3929 self.assertEqual(descr.__get__({})(arg), res)
3930
3931 # Now check various error cases
3932 try:
3933 descr.__get__(None, None)
3934 except TypeError:
3935 pass
3936 else:
3937 self.fail("shouldn't have allowed descr.__get__(None, None)")
3938 try:
3939 descr.__get__(42)
3940 except TypeError:
3941 pass
3942 else:
3943 self.fail("shouldn't have allowed descr.__get__(42)")
3944 try:
3945 descr.__get__(None, 42)
3946 except TypeError:
3947 pass
3948 else:
3949 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3950 try:
3951 descr.__get__(None, int)
3952 except TypeError:
3953 pass
3954 else:
3955 self.fail("shouldn't have allowed descr.__get__(None, int)")
3956
3957 def test_isinst_isclass(self):
3958 # Testing proxy isinstance() and isclass()...
3959 class Proxy(object):
3960 def __init__(self, obj):
3961 self.__obj = obj
3962 def __getattribute__(self, name):
3963 if name.startswith("_Proxy__"):
3964 return object.__getattribute__(self, name)
3965 else:
3966 return getattr(self.__obj, name)
3967 # Test with a classic class
3968 class C:
3969 pass
3970 a = C()
3971 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003972 self.assertIsInstance(a, C) # Baseline
3973 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003974 # Test with a classic subclass
3975 class D(C):
3976 pass
3977 a = D()
3978 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003979 self.assertIsInstance(a, C) # Baseline
3980 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003981 # Test with a new-style class
3982 class C(object):
3983 pass
3984 a = C()
3985 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003986 self.assertIsInstance(a, C) # Baseline
3987 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003988 # Test with a new-style subclass
3989 class D(C):
3990 pass
3991 a = D()
3992 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003993 self.assertIsInstance(a, C) # Baseline
3994 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003995
3996 def test_proxy_super(self):
3997 # Testing super() for a proxy object...
3998 class Proxy(object):
3999 def __init__(self, obj):
4000 self.__obj = obj
4001 def __getattribute__(self, name):
4002 if name.startswith("_Proxy__"):
4003 return object.__getattribute__(self, name)
4004 else:
4005 return getattr(self.__obj, name)
4006
4007 class B(object):
4008 def f(self):
4009 return "B.f"
4010
4011 class C(B):
4012 def f(self):
4013 return super(C, self).f() + "->C.f"
4014
4015 obj = C()
4016 p = Proxy(obj)
4017 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4018
4019 def test_carloverre(self):
4020 # Testing prohibition of Carlo Verre's hack...
4021 try:
4022 object.__setattr__(str, "foo", 42)
4023 except TypeError:
4024 pass
4025 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004026 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004027 try:
4028 object.__delattr__(str, "lower")
4029 except TypeError:
4030 pass
4031 else:
4032 self.fail("Carlo Verre __delattr__ succeeded!")
4033
4034 def test_weakref_segfault(self):
4035 # Testing weakref segfault...
4036 # SF 742911
4037 import weakref
4038
4039 class Provoker:
4040 def __init__(self, referrent):
4041 self.ref = weakref.ref(referrent)
4042
4043 def __del__(self):
4044 x = self.ref()
4045
4046 class Oops(object):
4047 pass
4048
4049 o = Oops()
4050 o.whatever = Provoker(o)
4051 del o
4052
4053 def test_wrapper_segfault(self):
4054 # SF 927248: deeply nested wrappers could cause stack overflow
4055 f = lambda:None
4056 for i in range(1000000):
4057 f = f.__call__
4058 f = None
4059
4060 def test_file_fault(self):
4061 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004062 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004063 class StdoutGuard:
4064 def __getattr__(self, attr):
4065 sys.stdout = sys.__stdout__
4066 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4067 sys.stdout = StdoutGuard()
4068 try:
4069 print("Oops!")
4070 except RuntimeError:
4071 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004072 finally:
4073 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004074
4075 def test_vicious_descriptor_nonsense(self):
4076 # Testing vicious_descriptor_nonsense...
4077
4078 # A potential segfault spotted by Thomas Wouters in mail to
4079 # python-dev 2003-04-17, turned into an example & fixed by Michael
4080 # Hudson just less than four months later...
4081
4082 class Evil(object):
4083 def __hash__(self):
4084 return hash('attr')
4085 def __eq__(self, other):
4086 del C.attr
4087 return 0
4088
4089 class Descr(object):
4090 def __get__(self, ob, type=None):
4091 return 1
4092
4093 class C(object):
4094 attr = Descr()
4095
4096 c = C()
4097 c.__dict__[Evil()] = 0
4098
4099 self.assertEqual(c.attr, 1)
4100 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004101 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004102 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004103
4104 def test_init(self):
4105 # SF 1155938
4106 class Foo(object):
4107 def __init__(self):
4108 return 10
4109 try:
4110 Foo()
4111 except TypeError:
4112 pass
4113 else:
4114 self.fail("did not test __init__() for None return")
4115
4116 def test_method_wrapper(self):
4117 # Testing method-wrapper objects...
4118 # <type 'method-wrapper'> did not support any reflection before 2.5
4119
Mark Dickinson211c6252009-02-01 10:28:51 +00004120 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004121
4122 l = []
4123 self.assertEqual(l.__add__, l.__add__)
4124 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004125 self.assertNotEqual(l.__add__, [5].__add__)
4126 self.assertNotEqual(l.__add__, l.__mul__)
4127 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004128 if hasattr(l.__add__, '__self__'):
4129 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004130 self.assertIs(l.__add__.__self__, l)
4131 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004132 else:
4133 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004134 self.assertIs(l.__add__.im_self, l)
4135 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004136 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4137 try:
4138 hash(l.__add__)
4139 except TypeError:
4140 pass
4141 else:
4142 self.fail("no TypeError from hash([].__add__)")
4143
4144 t = ()
4145 t += (7,)
4146 self.assertEqual(t.__add__, (7,).__add__)
4147 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4148
4149 def test_not_implemented(self):
4150 # Testing NotImplemented...
4151 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004152 import operator
4153
4154 def specialmethod(self, other):
4155 return NotImplemented
4156
4157 def check(expr, x, y):
4158 try:
4159 exec(expr, {'x': x, 'y': y, 'operator': operator})
4160 except TypeError:
4161 pass
4162 else:
4163 self.fail("no TypeError from %r" % (expr,))
4164
4165 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4166 # TypeErrors
4167 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4168 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004169 for name, expr, iexpr in [
4170 ('__add__', 'x + y', 'x += y'),
4171 ('__sub__', 'x - y', 'x -= y'),
4172 ('__mul__', 'x * y', 'x *= y'),
Benjamin Petersond51374e2014-04-09 23:55:56 -04004173 ('__matmul__', 'x @ y', 'x @= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004174 ('__truediv__', 'x / y', 'x /= y'),
4175 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004176 ('__mod__', 'x % y', 'x %= y'),
4177 ('__divmod__', 'divmod(x, y)', None),
4178 ('__pow__', 'x ** y', 'x **= y'),
4179 ('__lshift__', 'x << y', 'x <<= y'),
4180 ('__rshift__', 'x >> y', 'x >>= y'),
4181 ('__and__', 'x & y', 'x &= y'),
4182 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004183 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004184 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004185 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004186 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004187 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004188 check(expr, a, N1)
4189 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004190 if iexpr:
4191 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004192 check(iexpr, a, N1)
4193 check(iexpr, a, N2)
4194 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004195 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004196 c = C()
4197 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004198 check(iexpr, c, N1)
4199 check(iexpr, c, N2)
4200
Georg Brandl479a7e72008-02-05 18:13:15 +00004201 def test_assign_slice(self):
4202 # ceval.c's assign_slice used to check for
4203 # tp->tp_as_sequence->sq_slice instead of
4204 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004205
Georg Brandl479a7e72008-02-05 18:13:15 +00004206 class C(object):
4207 def __setitem__(self, idx, value):
4208 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004209
Georg Brandl479a7e72008-02-05 18:13:15 +00004210 c = C()
4211 c[1:2] = 3
4212 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004213
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004214 def test_set_and_no_get(self):
4215 # See
4216 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4217 class Descr(object):
4218
4219 def __init__(self, name):
4220 self.name = name
4221
4222 def __set__(self, obj, value):
4223 obj.__dict__[self.name] = value
4224 descr = Descr("a")
4225
4226 class X(object):
4227 a = descr
4228
4229 x = X()
4230 self.assertIs(x.a, descr)
4231 x.a = 42
4232 self.assertEqual(x.a, 42)
4233
Benjamin Peterson21896a32010-03-21 22:03:03 +00004234 # Also check type_getattro for correctness.
4235 class Meta(type):
4236 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004237 class X(metaclass=Meta):
4238 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004239 X.a = 42
4240 Meta.a = Descr("a")
4241 self.assertEqual(X.a, 42)
4242
Benjamin Peterson9262b842008-11-17 22:45:50 +00004243 def test_getattr_hooks(self):
4244 # issue 4230
4245
4246 class Descriptor(object):
4247 counter = 0
4248 def __get__(self, obj, objtype=None):
4249 def getter(name):
4250 self.counter += 1
4251 raise AttributeError(name)
4252 return getter
4253
4254 descr = Descriptor()
4255 class A(object):
4256 __getattribute__ = descr
4257 class B(object):
4258 __getattr__ = descr
4259 class C(object):
4260 __getattribute__ = descr
4261 __getattr__ = descr
4262
4263 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004264 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004265 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004266 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004267 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004268 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004269
Benjamin Peterson9262b842008-11-17 22:45:50 +00004270 class EvilGetattribute(object):
4271 # This used to segfault
4272 def __getattr__(self, name):
4273 raise AttributeError(name)
4274 def __getattribute__(self, name):
4275 del EvilGetattribute.__getattr__
4276 for i in range(5):
4277 gc.collect()
4278 raise AttributeError(name)
4279
4280 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4281
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004282 def test_type___getattribute__(self):
4283 self.assertRaises(TypeError, type.__getattribute__, list, type)
4284
Benjamin Peterson477ba912011-01-12 15:34:01 +00004285 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004286 # type pretends not to have __abstractmethods__.
4287 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4288 class meta(type):
4289 pass
4290 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004291 class X(object):
4292 pass
4293 with self.assertRaises(AttributeError):
4294 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004295
Victor Stinner3249dec2011-05-01 23:19:15 +02004296 def test_proxy_call(self):
4297 class FakeStr:
4298 __class__ = str
4299
4300 fake_str = FakeStr()
4301 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004302 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004303
4304 # call a method descriptor
4305 with self.assertRaises(TypeError):
4306 str.split(fake_str)
4307
4308 # call a slot wrapper descriptor
4309 with self.assertRaises(TypeError):
4310 str.__add__(fake_str, "abc")
4311
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004312 def test_repr_as_str(self):
4313 # Issue #11603: crash or infinite loop when rebinding __str__ as
4314 # __repr__.
4315 class Foo:
4316 pass
4317 Foo.__repr__ = Foo.__str__
4318 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004319 self.assertRaises(RuntimeError, str, foo)
4320 self.assertRaises(RuntimeError, repr, foo)
4321
4322 def test_mixing_slot_wrappers(self):
4323 class X(dict):
4324 __setattr__ = dict.__setitem__
4325 x = X()
4326 x.y = 42
4327 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004328
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004329 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004330 with self.assertRaises(ValueError) as cm:
4331 class X:
4332 __slots__ = ["foo"]
4333 foo = None
4334 m = str(cm.exception)
4335 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4336
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004337 def test_set_doc(self):
4338 class X:
4339 "elephant"
4340 X.__doc__ = "banana"
4341 self.assertEqual(X.__doc__, "banana")
4342 with self.assertRaises(TypeError) as cm:
4343 type(list).__dict__["__doc__"].__set__(list, "blah")
4344 self.assertIn("can't set list.__doc__", str(cm.exception))
4345 with self.assertRaises(TypeError) as cm:
4346 type(X).__dict__["__doc__"].__delete__(X)
4347 self.assertIn("can't delete X.__doc__", str(cm.exception))
4348 self.assertEqual(X.__doc__, "banana")
4349
Antoine Pitrou9d574812011-12-12 13:47:25 +01004350 def test_qualname(self):
4351 descriptors = [str.lower, complex.real, float.real, int.__add__]
4352 types = ['method', 'member', 'getset', 'wrapper']
4353
4354 # make sure we have an example of each type of descriptor
4355 for d, n in zip(descriptors, types):
4356 self.assertEqual(type(d).__name__, n + '_descriptor')
4357
4358 for d in descriptors:
4359 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4360 self.assertEqual(d.__qualname__, qualname)
4361
4362 self.assertEqual(str.lower.__qualname__, 'str.lower')
4363 self.assertEqual(complex.real.__qualname__, 'complex.real')
4364 self.assertEqual(float.real.__qualname__, 'float.real')
4365 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4366
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004367 class X:
4368 pass
4369 with self.assertRaises(TypeError):
4370 del X.__qualname__
4371
4372 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4373 str, 'Oink')
4374
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004375 global Y
4376 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004377 class Inside:
4378 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004379 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004380 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004381
Victor Stinner6f738742012-02-25 01:22:36 +01004382 def test_qualname_dict(self):
4383 ns = {'__qualname__': 'some.name'}
4384 tp = type('Foo', (), ns)
4385 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004386 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004387 self.assertEqual(ns, {'__qualname__': 'some.name'})
4388
4389 ns = {'__qualname__': 1}
4390 self.assertRaises(TypeError, type, 'Foo', (), ns)
4391
Benjamin Peterson52c42432012-03-07 18:41:11 -06004392 def test_cycle_through_dict(self):
4393 # See bug #1469629
4394 class X(dict):
4395 def __init__(self):
4396 dict.__init__(self)
4397 self.__dict__ = self
4398 x = X()
4399 x.attr = 42
4400 wr = weakref.ref(x)
4401 del x
4402 support.gc_collect()
4403 self.assertIsNone(wr())
4404 for o in gc.get_objects():
4405 self.assertIsNot(type(o), X)
4406
Benjamin Peterson96384b92012-03-17 00:05:44 -05004407 def test_object_new_and_init_with_parameters(self):
4408 # See issue #1683368
4409 class OverrideNeither:
4410 pass
4411 self.assertRaises(TypeError, OverrideNeither, 1)
4412 self.assertRaises(TypeError, OverrideNeither, kw=1)
4413 class OverrideNew:
4414 def __new__(cls, foo, kw=0, *args, **kwds):
4415 return object.__new__(cls, *args, **kwds)
4416 class OverrideInit:
4417 def __init__(self, foo, kw=0, *args, **kwargs):
4418 return object.__init__(self, *args, **kwargs)
4419 class OverrideBoth(OverrideNew, OverrideInit):
4420 pass
4421 for case in OverrideNew, OverrideInit, OverrideBoth:
4422 case(1)
4423 case(1, kw=2)
4424 self.assertRaises(TypeError, case, 1, 2, 3)
4425 self.assertRaises(TypeError, case, 1, 2, foo=3)
4426
Benjamin Petersondf813792014-03-17 15:57:17 -05004427 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4428 class Base:
4429 pass
4430 class Sub(Base):
4431 pass
4432 self.assertIn("__dict__", Base.__dict__)
4433 self.assertNotIn("__dict__", Sub.__dict__)
4434
Benjamin Peterson48ad7c02014-08-20 18:41:57 -05004435 def test_bound_method_repr(self):
4436 class Foo:
4437 def method(self):
4438 pass
4439 self.assertRegex(repr(Foo().method),
4440 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4441
4442
4443 class Base:
4444 def method(self):
4445 pass
4446 class Derived1(Base):
4447 pass
4448 class Derived2(Base):
4449 def method(self):
4450 pass
4451 base = Base()
4452 derived1 = Derived1()
4453 derived2 = Derived2()
4454 super_d2 = super(Derived2, derived2)
4455 self.assertRegex(repr(base.method),
4456 r"<bound method .*Base\.method of <.*Base object at .*>>")
4457 self.assertRegex(repr(derived1.method),
4458 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4459 self.assertRegex(repr(derived2.method),
4460 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4461 self.assertRegex(repr(super_d2.method),
4462 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4463
4464 class Foo:
4465 @classmethod
4466 def method(cls):
4467 pass
4468 foo = Foo()
4469 self.assertRegex(repr(foo.method), # access via instance
4470 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4471 self.assertRegex(repr(Foo.method), # access via the class
4472 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4473
4474
4475 class MyCallable:
4476 def __call__(self, arg):
4477 pass
4478 func = MyCallable() # func has no __name__ or __qualname__ attributes
4479 instance = object()
4480 method = types.MethodType(func, instance)
4481 self.assertRegex(repr(method),
4482 r"<bound method \? of <object object at .*>>")
4483 func.__name__ = "name"
4484 self.assertRegex(repr(method),
4485 r"<bound method name of <object object at .*>>")
4486 func.__qualname__ = "qualname"
4487 self.assertRegex(repr(method),
4488 r"<bound method qualname of <object object at .*>>")
4489
Antoine Pitrou9d574812011-12-12 13:47:25 +01004490
Georg Brandl479a7e72008-02-05 18:13:15 +00004491class DictProxyTests(unittest.TestCase):
4492 def setUp(self):
4493 class C(object):
4494 def meth(self):
4495 pass
4496 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004497
Brett Cannon7a540732011-02-22 03:04:06 +00004498 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4499 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004500 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004501 # Testing dict-proxy keys...
4502 it = self.C.__dict__.keys()
4503 self.assertNotIsInstance(it, list)
4504 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004505 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004506 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004507 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004508
Brett Cannon7a540732011-02-22 03:04:06 +00004509 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4510 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004511 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004512 # Testing dict-proxy values...
4513 it = self.C.__dict__.values()
4514 self.assertNotIsInstance(it, list)
4515 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004516 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004517
Brett Cannon7a540732011-02-22 03:04:06 +00004518 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4519 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004520 def test_iter_items(self):
4521 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004522 it = self.C.__dict__.items()
4523 self.assertNotIsInstance(it, list)
4524 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004525 keys.sort()
4526 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004527 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004528
Georg Brandl479a7e72008-02-05 18:13:15 +00004529 def test_dict_type_with_metaclass(self):
4530 # Testing type of __dict__ when metaclass set...
4531 class B(object):
4532 pass
4533 class M(type):
4534 pass
4535 class C(metaclass=M):
4536 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4537 pass
4538 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004539
Ezio Melottiac53ab62010-12-18 14:59:43 +00004540 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004541 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004542 # We can't blindly compare with the repr of another dict as ordering
4543 # of keys and values is arbitrary and may differ.
4544 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004545 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004546 self.assertTrue(r.endswith(')'), r)
4547 for k, v in self.C.__dict__.items():
4548 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004549
Christian Heimesbbffeb62008-01-24 09:42:52 +00004550
Georg Brandl479a7e72008-02-05 18:13:15 +00004551class PTypesLongInitTest(unittest.TestCase):
4552 # This is in its own TestCase so that it can be run before any other tests.
4553 def test_pytype_long_ready(self):
4554 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004555
Georg Brandl479a7e72008-02-05 18:13:15 +00004556 # This dumps core when SF bug 551412 isn't fixed --
4557 # but only when test_descr.py is run separately.
4558 # (That can't be helped -- as soon as PyType_Ready()
4559 # is called for PyLong_Type, the bug is gone.)
4560 class UserLong(object):
4561 def __pow__(self, *args):
4562 pass
4563 try:
4564 pow(0, UserLong(), 0)
4565 except:
4566 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004567
Georg Brandl479a7e72008-02-05 18:13:15 +00004568 # Another segfault only when run early
4569 # (before PyType_Ready(tuple) is called)
4570 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004571
4572
Victor Stinnerd74782b2012-03-09 00:39:08 +01004573class MiscTests(unittest.TestCase):
4574 def test_type_lookup_mro_reference(self):
4575 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4576 # the type MRO because it may be modified during the lookup, if
4577 # __bases__ is set during the lookup for example.
4578 class MyKey(object):
4579 def __hash__(self):
4580 return hash('mykey')
4581
4582 def __eq__(self, other):
4583 X.__bases__ = (Base2,)
4584
4585 class Base(object):
4586 mykey = 'from Base'
4587 mykey2 = 'from Base'
4588
4589 class Base2(object):
4590 mykey = 'from Base2'
4591 mykey2 = 'from Base2'
4592
4593 X = type('X', (Base,), {MyKey(): 5})
4594 # mykey is read from Base
4595 self.assertEqual(X.mykey, 'from Base')
4596 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4597 self.assertEqual(X.mykey2, 'from Base2')
4598
4599
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004600class PicklingTests(unittest.TestCase):
4601
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004602 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004603 listitems=None, dictitems=None):
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004604 if proto >= 2:
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004605 reduce_value = obj.__reduce_ex__(proto)
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004606 if kwargs:
4607 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4608 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004609 else:
Serhiy Storchaka707b5cc2014-12-16 19:43:46 +02004610 self.assertEqual(reduce_value[0], copyreg.__newobj__)
4611 self.assertEqual(reduce_value[1], (type(obj),) + args)
4612 self.assertEqual(reduce_value[2], state)
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004613 if listitems is not None:
4614 self.assertListEqual(list(reduce_value[3]), listitems)
4615 else:
4616 self.assertIsNone(reduce_value[3])
4617 if dictitems is not None:
4618 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4619 else:
4620 self.assertIsNone(reduce_value[4])
4621 else:
4622 base_type = type(obj).__base__
4623 reduce_value = (copyreg._reconstructor,
4624 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004625 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004626 None if base_type is object else base_type(obj)))
4627 if state is not None:
4628 reduce_value += (state,)
4629 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4630 self.assertEqual(obj.__reduce__(), reduce_value)
4631
4632 def test_reduce(self):
4633 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4634 args = (-101, "spam")
4635 kwargs = {'bacon': -201, 'fish': -301}
4636 state = {'cheese': -401}
4637
4638 class C1:
4639 def __getnewargs__(self):
4640 return args
4641 obj = C1()
4642 for proto in protocols:
4643 self._check_reduce(proto, obj, args)
4644
4645 for name, value in state.items():
4646 setattr(obj, name, value)
4647 for proto in protocols:
4648 self._check_reduce(proto, obj, args, state=state)
4649
4650 class C2:
4651 def __getnewargs__(self):
4652 return "bad args"
4653 obj = C2()
4654 for proto in protocols:
4655 if proto >= 2:
4656 with self.assertRaises(TypeError):
4657 obj.__reduce_ex__(proto)
4658
4659 class C3:
4660 def __getnewargs_ex__(self):
4661 return (args, kwargs)
4662 obj = C3()
4663 for proto in protocols:
4664 if proto >= 4:
4665 self._check_reduce(proto, obj, args, kwargs)
4666 elif proto >= 2:
4667 with self.assertRaises(ValueError):
4668 obj.__reduce_ex__(proto)
4669
4670 class C4:
4671 def __getnewargs_ex__(self):
4672 return (args, "bad dict")
4673 class C5:
4674 def __getnewargs_ex__(self):
4675 return ("bad tuple", kwargs)
4676 class C6:
4677 def __getnewargs_ex__(self):
4678 return ()
4679 class C7:
4680 def __getnewargs_ex__(self):
4681 return "bad args"
4682 for proto in protocols:
4683 for cls in C4, C5, C6, C7:
4684 obj = cls()
4685 if proto >= 2:
4686 with self.assertRaises((TypeError, ValueError)):
4687 obj.__reduce_ex__(proto)
4688
4689 class C8:
4690 def __getnewargs_ex__(self):
4691 return (args, kwargs)
4692 obj = C8()
4693 for proto in protocols:
4694 if 2 <= proto < 4:
4695 with self.assertRaises(ValueError):
4696 obj.__reduce_ex__(proto)
4697 class C9:
4698 def __getnewargs_ex__(self):
4699 return (args, {})
4700 obj = C9()
4701 for proto in protocols:
4702 self._check_reduce(proto, obj, args)
4703
4704 class C10:
4705 def __getnewargs_ex__(self):
4706 raise IndexError
4707 obj = C10()
4708 for proto in protocols:
4709 if proto >= 2:
4710 with self.assertRaises(IndexError):
4711 obj.__reduce_ex__(proto)
4712
4713 class C11:
4714 def __getstate__(self):
4715 return state
4716 obj = C11()
4717 for proto in protocols:
4718 self._check_reduce(proto, obj, state=state)
4719
4720 class C12:
4721 def __getstate__(self):
4722 return "not dict"
4723 obj = C12()
4724 for proto in protocols:
4725 self._check_reduce(proto, obj, state="not dict")
4726
4727 class C13:
4728 def __getstate__(self):
4729 raise IndexError
4730 obj = C13()
4731 for proto in protocols:
4732 with self.assertRaises(IndexError):
4733 obj.__reduce_ex__(proto)
4734 if proto < 2:
4735 with self.assertRaises(IndexError):
4736 obj.__reduce__()
4737
4738 class C14:
4739 __slots__ = tuple(state)
4740 def __init__(self):
4741 for name, value in state.items():
4742 setattr(self, name, value)
4743
4744 obj = C14()
4745 for proto in protocols:
4746 if proto >= 2:
4747 self._check_reduce(proto, obj, state=(None, state))
4748 else:
4749 with self.assertRaises(TypeError):
4750 obj.__reduce_ex__(proto)
4751 with self.assertRaises(TypeError):
4752 obj.__reduce__()
4753
4754 class C15(dict):
4755 pass
4756 obj = C15({"quebec": -601})
4757 for proto in protocols:
4758 self._check_reduce(proto, obj, dictitems=dict(obj))
4759
4760 class C16(list):
4761 pass
4762 obj = C16(["yukon"])
4763 for proto in protocols:
4764 self._check_reduce(proto, obj, listitems=list(obj))
4765
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004766 def test_special_method_lookup(self):
4767 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4768 class Picky:
4769 def __getstate__(self):
4770 return {}
4771
4772 def __getattr__(self, attr):
4773 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4774 raise AssertionError(attr)
4775 return None
4776 for protocol in protocols:
4777 state = {} if protocol >= 2 else None
4778 self._check_reduce(protocol, Picky(), state=state)
4779
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004780 def _assert_is_copy(self, obj, objcopy, msg=None):
4781 """Utility method to verify if two objects are copies of each others.
4782 """
4783 if msg is None:
4784 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4785 if type(obj).__repr__ is object.__repr__:
4786 # We have this limitation for now because we use the object's repr
4787 # to help us verify that the two objects are copies. This allows
4788 # us to delegate the non-generic verification logic to the objects
4789 # themselves.
4790 raise ValueError("object passed to _assert_is_copy must " +
4791 "override the __repr__ method.")
4792 self.assertIsNot(obj, objcopy, msg=msg)
4793 self.assertIs(type(obj), type(objcopy), msg=msg)
4794 if hasattr(obj, '__dict__'):
4795 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4796 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4797 if hasattr(obj, '__slots__'):
4798 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4799 for slot in obj.__slots__:
4800 self.assertEqual(
4801 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4802 self.assertEqual(getattr(obj, slot, None),
4803 getattr(objcopy, slot, None), msg=msg)
4804 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4805
4806 @staticmethod
4807 def _generate_pickle_copiers():
4808 """Utility method to generate the many possible pickle configurations.
4809 """
4810 class PickleCopier:
4811 "This class copies object using pickle."
4812 def __init__(self, proto, dumps, loads):
4813 self.proto = proto
4814 self.dumps = dumps
4815 self.loads = loads
4816 def copy(self, obj):
4817 return self.loads(self.dumps(obj, self.proto))
4818 def __repr__(self):
4819 # We try to be as descriptive as possible here since this is
4820 # the string which we will allow us to tell the pickle
4821 # configuration we are using during debugging.
4822 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4823 .format(self.proto,
4824 self.dumps.__module__, self.dumps.__qualname__,
4825 self.loads.__module__, self.loads.__qualname__))
4826 return (PickleCopier(*args) for args in
4827 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4828 {pickle.dumps, pickle._dumps},
4829 {pickle.loads, pickle._loads}))
4830
4831 def test_pickle_slots(self):
4832 # Tests pickling of classes with __slots__.
4833
4834 # Pickling of classes with __slots__ but without __getstate__ should
4835 # fail (if using protocol 0 or 1)
4836 global C
4837 class C:
4838 __slots__ = ['a']
4839 with self.assertRaises(TypeError):
4840 pickle.dumps(C(), 0)
4841
4842 global D
4843 class D(C):
4844 pass
4845 with self.assertRaises(TypeError):
4846 pickle.dumps(D(), 0)
4847
4848 class C:
4849 "A class with __getstate__ and __setstate__ implemented."
4850 __slots__ = ['a']
4851 def __getstate__(self):
4852 state = getattr(self, '__dict__', {}).copy()
4853 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004854 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004855 try:
4856 state[slot] = getattr(self, slot)
4857 except AttributeError:
4858 pass
4859 return state
4860 def __setstate__(self, state):
4861 for k, v in state.items():
4862 setattr(self, k, v)
4863 def __repr__(self):
4864 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4865
4866 class D(C):
4867 "A subclass of a class with slots."
4868 pass
4869
4870 global E
4871 class E(C):
4872 "A subclass with an extra slot."
4873 __slots__ = ['b']
4874
4875 # Now it should work
4876 for pickle_copier in self._generate_pickle_copiers():
4877 with self.subTest(pickle_copier=pickle_copier):
4878 x = C()
4879 y = pickle_copier.copy(x)
4880 self._assert_is_copy(x, y)
4881
4882 x.a = 42
4883 y = pickle_copier.copy(x)
4884 self._assert_is_copy(x, y)
4885
4886 x = D()
4887 x.a = 42
4888 x.b = 100
4889 y = pickle_copier.copy(x)
4890 self._assert_is_copy(x, y)
4891
4892 x = E()
4893 x.a = 42
4894 x.b = "foo"
4895 y = pickle_copier.copy(x)
4896 self._assert_is_copy(x, y)
4897
4898 def test_reduce_copying(self):
4899 # Tests pickling and copying new-style classes and objects.
4900 global C1
4901 class C1:
4902 "The state of this class is copyable via its instance dict."
4903 ARGS = (1, 2)
4904 NEED_DICT_COPYING = True
4905 def __init__(self, a, b):
4906 super().__init__()
4907 self.a = a
4908 self.b = b
4909 def __repr__(self):
4910 return "C1(%r, %r)" % (self.a, self.b)
4911
4912 global C2
4913 class C2(list):
4914 "A list subclass copyable via __getnewargs__."
4915 ARGS = (1, 2)
4916 NEED_DICT_COPYING = False
4917 def __new__(cls, a, b):
4918 self = super().__new__(cls)
4919 self.a = a
4920 self.b = b
4921 return self
4922 def __init__(self, *args):
4923 super().__init__()
4924 # This helps testing that __init__ is not called during the
4925 # unpickling process, which would cause extra appends.
4926 self.append("cheese")
4927 @classmethod
4928 def __getnewargs__(cls):
4929 return cls.ARGS
4930 def __repr__(self):
4931 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
4932
4933 global C3
4934 class C3(list):
4935 "A list subclass copyable via __getstate__."
4936 ARGS = (1, 2)
4937 NEED_DICT_COPYING = False
4938 def __init__(self, a, b):
4939 self.a = a
4940 self.b = b
4941 # This helps testing that __init__ is not called during the
4942 # unpickling process, which would cause extra appends.
4943 self.append("cheese")
4944 @classmethod
4945 def __getstate__(cls):
4946 return cls.ARGS
4947 def __setstate__(self, state):
4948 a, b = state
4949 self.a = a
4950 self.b = b
4951 def __repr__(self):
4952 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
4953
4954 global C4
4955 class C4(int):
4956 "An int subclass copyable via __getnewargs__."
4957 ARGS = ("hello", "world", 1)
4958 NEED_DICT_COPYING = False
4959 def __new__(cls, a, b, value):
4960 self = super().__new__(cls, value)
4961 self.a = a
4962 self.b = b
4963 return self
4964 @classmethod
4965 def __getnewargs__(cls):
4966 return cls.ARGS
4967 def __repr__(self):
4968 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
4969
4970 global C5
4971 class C5(int):
4972 "An int subclass copyable via __getnewargs_ex__."
4973 ARGS = (1, 2)
4974 KWARGS = {'value': 3}
4975 NEED_DICT_COPYING = False
4976 def __new__(cls, a, b, *, value=0):
4977 self = super().__new__(cls, value)
4978 self.a = a
4979 self.b = b
4980 return self
4981 @classmethod
4982 def __getnewargs_ex__(cls):
4983 return (cls.ARGS, cls.KWARGS)
4984 def __repr__(self):
4985 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
4986
4987 test_classes = (C1, C2, C3, C4, C5)
4988 # Testing copying through pickle
4989 pickle_copiers = self._generate_pickle_copiers()
4990 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
4991 with self.subTest(cls=cls, pickle_copier=pickle_copier):
4992 kwargs = getattr(cls, 'KWARGS', {})
4993 obj = cls(*cls.ARGS, **kwargs)
4994 proto = pickle_copier.proto
4995 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
4996 with self.assertRaises(ValueError):
4997 pickle_copier.dumps(obj, proto)
4998 continue
4999 objcopy = pickle_copier.copy(obj)
5000 self._assert_is_copy(obj, objcopy)
5001 # For test classes that supports this, make sure we didn't go
5002 # around the reduce protocol by simply copying the attribute
5003 # dictionary. We clear attributes using the previous copy to
5004 # not mutate the original argument.
5005 if proto >= 2 and not cls.NEED_DICT_COPYING:
5006 objcopy.__dict__.clear()
5007 objcopy2 = pickle_copier.copy(objcopy)
5008 self._assert_is_copy(obj, objcopy2)
5009
5010 # Testing copying through copy.deepcopy()
5011 for cls in test_classes:
5012 with self.subTest(cls=cls):
5013 kwargs = getattr(cls, 'KWARGS', {})
5014 obj = cls(*cls.ARGS, **kwargs)
5015 # XXX: We need to modify the copy module to support PEP 3154's
5016 # reduce protocol 4.
5017 if hasattr(cls, '__getnewargs_ex__'):
5018 continue
5019 objcopy = deepcopy(obj)
5020 self._assert_is_copy(obj, objcopy)
5021 # For test classes that supports this, make sure we didn't go
5022 # around the reduce protocol by simply copying the attribute
5023 # dictionary. We clear attributes using the previous copy to
5024 # not mutate the original argument.
5025 if not cls.NEED_DICT_COPYING:
5026 objcopy.__dict__.clear()
5027 objcopy2 = deepcopy(objcopy)
5028 self._assert_is_copy(obj, objcopy2)
5029
5030
Benjamin Peterson2a605342014-03-17 16:20:12 -05005031class SharedKeyTests(unittest.TestCase):
5032
5033 @support.cpython_only
5034 def test_subclasses(self):
5035 # Verify that subclasses can share keys (per PEP 412)
5036 class A:
5037 pass
5038 class B(A):
5039 pass
5040
5041 a, b = A(), B()
5042 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5043 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5044 a.x, a.y, a.z, a.w = range(4)
5045 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5046 a2 = A()
5047 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5048 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5049 b.u, b.v, b.w, b.t = range(4)
5050 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5051
5052
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005053class DebugHelperMeta(type):
5054 """
5055 Sets default __doc__ and simplifies repr() output.
5056 """
5057 def __new__(mcls, name, bases, attrs):
5058 if attrs.get('__doc__') is None:
5059 attrs['__doc__'] = name # helps when debugging with gdb
5060 return type.__new__(mcls, name, bases, attrs)
5061 def __repr__(cls):
5062 return repr(cls.__name__)
5063
5064
5065class MroTest(unittest.TestCase):
5066 """
5067 Regressions for some bugs revealed through
5068 mcsl.mro() customization (typeobject.c: mro_internal()) and
5069 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5070 """
5071
5072 def setUp(self):
5073 self.step = 0
5074 self.ready = False
5075
5076 def step_until(self, limit):
5077 ret = (self.step < limit)
5078 if ret:
5079 self.step += 1
5080 return ret
5081
5082 def test_incomplete_set_bases_on_self(self):
5083 """
5084 type_set_bases must be aware that type->tp_mro can be NULL.
5085 """
5086 class M(DebugHelperMeta):
5087 def mro(cls):
5088 if self.step_until(1):
5089 assert cls.__mro__ is None
5090 cls.__bases__ += ()
5091
5092 return type.mro(cls)
5093
5094 class A(metaclass=M):
5095 pass
5096
5097 def test_reent_set_bases_on_base(self):
5098 """
5099 Deep reentrancy must not over-decref old_mro.
5100 """
5101 class M(DebugHelperMeta):
5102 def mro(cls):
5103 if cls.__mro__ is not None and cls.__name__ == 'B':
5104 # 4-5 steps are usually enough to make it crash somewhere
5105 if self.step_until(10):
5106 A.__bases__ += ()
5107
5108 return type.mro(cls)
5109
5110 class A(metaclass=M):
5111 pass
5112 class B(A):
5113 pass
5114 B.__bases__ += ()
5115
5116 def test_reent_set_bases_on_direct_base(self):
5117 """
5118 Similar to test_reent_set_bases_on_base, but may crash differently.
5119 """
5120 class M(DebugHelperMeta):
5121 def mro(cls):
5122 base = cls.__bases__[0]
5123 if base is not object:
5124 if self.step_until(5):
5125 base.__bases__ += ()
5126
5127 return type.mro(cls)
5128
5129 class A(metaclass=M):
5130 pass
5131 class B(A):
5132 pass
5133 class C(B):
5134 pass
5135
5136 def test_reent_set_bases_tp_base_cycle(self):
5137 """
5138 type_set_bases must check for an inheritance cycle not only through
5139 MRO of the type, which may be not yet updated in case of reentrance,
5140 but also through tp_base chain, which is assigned before diving into
5141 inner calls to mro().
5142
5143 Otherwise, the following snippet can loop forever:
5144 do {
5145 // ...
5146 type = type->tp_base;
5147 } while (type != NULL);
5148
5149 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5150 would not be happy in that case, causing a stack overflow.
5151 """
5152 class M(DebugHelperMeta):
5153 def mro(cls):
5154 if self.ready:
5155 if cls.__name__ == 'B1':
5156 B2.__bases__ = (B1,)
5157 if cls.__name__ == 'B2':
5158 B1.__bases__ = (B2,)
5159 return type.mro(cls)
5160
5161 class A(metaclass=M):
5162 pass
5163 class B1(A):
5164 pass
5165 class B2(A):
5166 pass
5167
5168 self.ready = True
5169 with self.assertRaises(TypeError):
5170 B1.__bases__ += ()
5171
5172 def test_tp_subclasses_cycle_in_update_slots(self):
5173 """
5174 type_set_bases must check for reentrancy upon finishing its job
5175 by updating tp_subclasses of old/new bases of the type.
5176 Otherwise, an implicit inheritance cycle through tp_subclasses
5177 can break functions that recurse on elements of that field
5178 (like recurse_down_subclasses and mro_hierarchy) eventually
5179 leading to a stack overflow.
5180 """
5181 class M(DebugHelperMeta):
5182 def mro(cls):
5183 if self.ready and cls.__name__ == 'C':
5184 self.ready = False
5185 C.__bases__ = (B2,)
5186 return type.mro(cls)
5187
5188 class A(metaclass=M):
5189 pass
5190 class B1(A):
5191 pass
5192 class B2(A):
5193 pass
5194 class C(A):
5195 pass
5196
5197 self.ready = True
5198 C.__bases__ = (B1,)
5199 B1.__bases__ = (C,)
5200
5201 self.assertEqual(C.__bases__, (B2,))
5202 self.assertEqual(B2.__subclasses__(), [C])
5203 self.assertEqual(B1.__subclasses__(), [])
5204
5205 self.assertEqual(B1.__bases__, (C,))
5206 self.assertEqual(C.__subclasses__(), [B1])
5207
5208 def test_tp_subclasses_cycle_error_return_path(self):
5209 """
5210 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5211 a code path executed on error (goto bail).
5212 """
5213 class E(Exception):
5214 pass
5215 class M(DebugHelperMeta):
5216 def mro(cls):
5217 if self.ready and cls.__name__ == 'C':
5218 if C.__bases__ == (B2,):
5219 self.ready = False
5220 else:
5221 C.__bases__ = (B2,)
5222 raise E
5223 return type.mro(cls)
5224
5225 class A(metaclass=M):
5226 pass
5227 class B1(A):
5228 pass
5229 class B2(A):
5230 pass
5231 class C(A):
5232 pass
5233
5234 self.ready = True
5235 with self.assertRaises(E):
5236 C.__bases__ = (B1,)
5237 B1.__bases__ = (C,)
5238
5239 self.assertEqual(C.__bases__, (B2,))
5240 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5241
5242 def test_incomplete_extend(self):
5243 """
5244 Extending an unitialized type with type->tp_mro == NULL must
5245 throw a reasonable TypeError exception, instead of failing
5246 with PyErr_BadInternalCall.
5247 """
5248 class M(DebugHelperMeta):
5249 def mro(cls):
5250 if cls.__mro__ is None and cls.__name__ != 'X':
5251 with self.assertRaises(TypeError):
5252 class X(cls):
5253 pass
5254
5255 return type.mro(cls)
5256
5257 class A(metaclass=M):
5258 pass
5259
5260 def test_incomplete_super(self):
5261 """
5262 Attrubute lookup on a super object must be aware that
5263 its target type can be uninitialized (type->tp_mro == NULL).
5264 """
5265 class M(DebugHelperMeta):
5266 def mro(cls):
5267 if cls.__mro__ is None:
5268 with self.assertRaises(AttributeError):
5269 super(cls, cls).xxx
5270
5271 return type.mro(cls)
5272
5273 class A(metaclass=M):
5274 pass
5275
5276
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005277def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005278 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005279 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005280 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005281 MiscTests, PicklingTests, SharedKeyTests,
5282 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005284if __name__ == "__main__":
5285 test_main()