blob: ce9626c77a77d2199914ac92111db89a623d6090 [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 Storchakaa60c2fe2015-03-12 21:56:08 +020024 'truediv': '/',
25 'floordiv': '//',
Georg Brandl479a7e72008-02-05 18:13:15 +000026 'divmod': 'divmod',
27 'pow': '**',
28 'lshift': '<<',
29 'rshift': '>>',
30 'and': '&',
31 'xor': '^',
32 'or': '|',
33 'cmp': 'cmp',
34 'lt': '<',
35 'le': '<=',
36 'eq': '==',
37 'ne': '!=',
38 'gt': '>',
39 'ge': '>=',
40 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000041
Georg Brandl479a7e72008-02-05 18:13:15 +000042 for name, expr in list(self.binops.items()):
43 if expr.islower():
44 expr = expr + "(a, b)"
45 else:
46 expr = 'a %s b' % expr
47 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000048
Georg Brandl479a7e72008-02-05 18:13:15 +000049 self.unops = {
50 'pos': '+',
51 'neg': '-',
52 'abs': 'abs',
53 'invert': '~',
54 'int': 'int',
55 'float': 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +000056 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000057
Georg Brandl479a7e72008-02-05 18:13:15 +000058 for name, expr in list(self.unops.items()):
59 if expr.islower():
60 expr = expr + "(a)"
61 else:
62 expr = '%s a' % expr
63 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000064
Georg Brandl479a7e72008-02-05 18:13:15 +000065 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
66 d = {'a': a}
67 self.assertEqual(eval(expr, d), res)
68 t = type(a)
69 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000070
Georg Brandl479a7e72008-02-05 18:13:15 +000071 # Find method in parent class
72 while meth not in t.__dict__:
73 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000074 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
75 # method object; the getattr() below obtains its underlying function.
76 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000077 self.assertEqual(m(a), res)
78 bm = getattr(a, meth)
79 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000080
Georg Brandl479a7e72008-02-05 18:13:15 +000081 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
82 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000083
Georg Brandl479a7e72008-02-05 18:13:15 +000084 self.assertEqual(eval(expr, d), res)
85 t = type(a)
86 m = getattr(t, meth)
87 while meth not in t.__dict__:
88 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000089 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
90 # method object; the getattr() below obtains its underlying function.
91 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000092 self.assertEqual(m(a, b), res)
93 bm = getattr(a, meth)
94 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000095
Georg Brandl479a7e72008-02-05 18:13:15 +000096 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
97 d = {'a': a, 'b': b, 'c': c}
98 self.assertEqual(eval(expr, d), res)
99 t = type(a)
100 m = getattr(t, meth)
101 while meth not in t.__dict__:
102 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000103 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
104 # method object; the getattr() below obtains its underlying function.
105 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000106 self.assertEqual(m(a, slice(b, c)), res)
107 bm = getattr(a, meth)
108 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000109
Georg Brandl479a7e72008-02-05 18:13:15 +0000110 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
111 d = {'a': deepcopy(a), 'b': b}
112 exec(stmt, d)
113 self.assertEqual(d['a'], res)
114 t = type(a)
115 m = getattr(t, meth)
116 while meth not in t.__dict__:
117 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000118 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
119 # method object; the getattr() below obtains its underlying function.
120 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000121 d['a'] = deepcopy(a)
122 m(d['a'], b)
123 self.assertEqual(d['a'], res)
124 d['a'] = deepcopy(a)
125 bm = getattr(d['a'], meth)
126 bm(b)
127 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000128
Georg Brandl479a7e72008-02-05 18:13:15 +0000129 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
130 d = {'a': deepcopy(a), 'b': b, 'c': c}
131 exec(stmt, d)
132 self.assertEqual(d['a'], res)
133 t = type(a)
134 m = getattr(t, meth)
135 while meth not in t.__dict__:
136 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000137 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
138 # method object; the getattr() below obtains its underlying function.
139 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000140 d['a'] = deepcopy(a)
141 m(d['a'], b, c)
142 self.assertEqual(d['a'], res)
143 d['a'] = deepcopy(a)
144 bm = getattr(d['a'], meth)
145 bm(b, c)
146 self.assertEqual(d['a'], res)
147
148 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
149 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
150 exec(stmt, dictionary)
151 self.assertEqual(dictionary['a'], res)
152 t = type(a)
153 while meth not in t.__dict__:
154 t = t.__bases__[0]
155 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000156 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
157 # method object; the getattr() below obtains its underlying function.
158 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000159 dictionary['a'] = deepcopy(a)
160 m(dictionary['a'], slice(b, c), d)
161 self.assertEqual(dictionary['a'], res)
162 dictionary['a'] = deepcopy(a)
163 bm = getattr(dictionary['a'], meth)
164 bm(slice(b, c), d)
165 self.assertEqual(dictionary['a'], res)
166
167 def test_lists(self):
168 # Testing list operations...
169 # Asserts are within individual test methods
170 self.binop_test([1], [2], [1,2], "a+b", "__add__")
171 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
172 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
173 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
174 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
175 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
176 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
177 self.unop_test([1,2,3], 3, "len(a)", "__len__")
178 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
179 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
180 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
181 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
182 "__setitem__")
183
184 def test_dicts(self):
185 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000186 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
187 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
188 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
189
190 d = {1:2, 3:4}
191 l1 = []
192 for i in list(d.keys()):
193 l1.append(i)
194 l = []
195 for i in iter(d):
196 l.append(i)
197 self.assertEqual(l, l1)
198 l = []
199 for i in d.__iter__():
200 l.append(i)
201 self.assertEqual(l, l1)
202 l = []
203 for i in dict.__iter__(d):
204 l.append(i)
205 self.assertEqual(l, l1)
206 d = {1:2, 3:4}
207 self.unop_test(d, 2, "len(a)", "__len__")
208 self.assertEqual(eval(repr(d), {}), d)
209 self.assertEqual(eval(d.__repr__(), {}), d)
210 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
211 "__setitem__")
212
213 # Tests for unary and binary operators
214 def number_operators(self, a, b, skip=[]):
215 dict = {'a': a, 'b': b}
216
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200217 for name, expr in self.binops.items():
Georg Brandl479a7e72008-02-05 18:13:15 +0000218 if name not in skip:
219 name = "__%s__" % name
220 if hasattr(a, name):
221 res = eval(expr, dict)
222 self.binop_test(a, b, res, expr, name)
223
224 for name, expr in list(self.unops.items()):
225 if name not in skip:
226 name = "__%s__" % name
227 if hasattr(a, name):
228 res = eval(expr, dict)
229 self.unop_test(a, res, expr, name)
230
231 def test_ints(self):
232 # Testing int operations...
233 self.number_operators(100, 3)
234 # The following crashes in Python 2.2
235 self.assertEqual((1).__bool__(), 1)
236 self.assertEqual((0).__bool__(), 0)
237 # This returns 'NotImplemented' in Python 2.2
238 class C(int):
239 def __add__(self, other):
240 return NotImplemented
241 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000242 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000243 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000244 except TypeError:
245 pass
246 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000247 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000248
Georg Brandl479a7e72008-02-05 18:13:15 +0000249 def test_floats(self):
250 # Testing float operations...
251 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000252
Georg Brandl479a7e72008-02-05 18:13:15 +0000253 def test_complexes(self):
254 # Testing complex operations...
255 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000256 'int', 'float',
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200257 'floordiv', 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000258
Georg Brandl479a7e72008-02-05 18:13:15 +0000259 class Number(complex):
260 __slots__ = ['prec']
261 def __new__(cls, *args, **kwds):
262 result = complex.__new__(cls, *args)
263 result.prec = kwds.get('prec', 12)
264 return result
265 def __repr__(self):
266 prec = self.prec
267 if self.imag == 0.0:
268 return "%.*g" % (prec, self.real)
269 if self.real == 0.0:
270 return "%.*gj" % (prec, self.imag)
271 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
272 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000273
Georg Brandl479a7e72008-02-05 18:13:15 +0000274 a = Number(3.14, prec=6)
275 self.assertEqual(repr(a), "3.14")
276 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000277
Georg Brandl479a7e72008-02-05 18:13:15 +0000278 a = Number(a, prec=2)
279 self.assertEqual(repr(a), "3.1")
280 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000281
Georg Brandl479a7e72008-02-05 18:13:15 +0000282 a = Number(234.5)
283 self.assertEqual(repr(a), "234.5")
284 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000285
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000286 def test_explicit_reverse_methods(self):
287 # see issue 9930
288 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
289 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
290
Benjamin Petersone549ead2009-03-28 21:42:05 +0000291 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000292 def test_spam_lists(self):
293 # Testing spamlist operations...
294 import copy, xxsubtype as spam
295
296 def spamlist(l, memo=None):
297 import xxsubtype as spam
298 return spam.spamlist(l)
299
300 # This is an ugly hack:
301 copy._deepcopy_dispatch[spam.spamlist] = spamlist
302
303 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
304 "__add__")
305 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
306 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
307 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
308 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
309 "__getitem__")
310 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
311 "__iadd__")
312 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
313 "__imul__")
314 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
315 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
316 "__mul__")
317 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
318 "__rmul__")
319 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
320 "__setitem__")
321 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
322 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
323 # Test subclassing
324 class C(spam.spamlist):
325 def foo(self): return 1
326 a = C()
327 self.assertEqual(a, [])
328 self.assertEqual(a.foo(), 1)
329 a.append(100)
330 self.assertEqual(a, [100])
331 self.assertEqual(a.getstate(), 0)
332 a.setstate(42)
333 self.assertEqual(a.getstate(), 42)
334
Benjamin Petersone549ead2009-03-28 21:42:05 +0000335 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000336 def test_spam_dicts(self):
337 # Testing spamdict operations...
338 import copy, xxsubtype as spam
339 def spamdict(d, memo=None):
340 import xxsubtype as spam
341 sd = spam.spamdict()
342 for k, v in list(d.items()):
343 sd[k] = v
344 return sd
345 # This is an ugly hack:
346 copy._deepcopy_dispatch[spam.spamdict] = spamdict
347
Georg Brandl479a7e72008-02-05 18:13:15 +0000348 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
349 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
350 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
351 d = spamdict({1:2,3:4})
352 l1 = []
353 for i in list(d.keys()):
354 l1.append(i)
355 l = []
356 for i in iter(d):
357 l.append(i)
358 self.assertEqual(l, l1)
359 l = []
360 for i in d.__iter__():
361 l.append(i)
362 self.assertEqual(l, l1)
363 l = []
364 for i in type(spamdict({})).__iter__(d):
365 l.append(i)
366 self.assertEqual(l, l1)
367 straightd = {1:2, 3:4}
368 spamd = spamdict(straightd)
369 self.unop_test(spamd, 2, "len(a)", "__len__")
370 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
371 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
372 "a[b]=c", "__setitem__")
373 # Test subclassing
374 class C(spam.spamdict):
375 def foo(self): return 1
376 a = C()
377 self.assertEqual(list(a.items()), [])
378 self.assertEqual(a.foo(), 1)
379 a['foo'] = 'bar'
380 self.assertEqual(list(a.items()), [('foo', 'bar')])
381 self.assertEqual(a.getstate(), 0)
382 a.setstate(100)
383 self.assertEqual(a.getstate(), 100)
384
385class ClassPropertiesAndMethods(unittest.TestCase):
386
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200387 def assertHasAttr(self, obj, name):
388 self.assertTrue(hasattr(obj, name),
389 '%r has no attribute %r' % (obj, name))
390
391 def assertNotHasAttr(self, obj, name):
392 self.assertFalse(hasattr(obj, name),
393 '%r has unexpected attribute %r' % (obj, name))
394
Georg Brandl479a7e72008-02-05 18:13:15 +0000395 def test_python_dicts(self):
396 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000397 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000398 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000399 d = dict()
400 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200401 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000402 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000403 class C(dict):
404 state = -1
405 def __init__(self_local, *a, **kw):
406 if a:
407 self.assertEqual(len(a), 1)
408 self_local.state = a[0]
409 if kw:
410 for k, v in list(kw.items()):
411 self_local[v] = k
412 def __getitem__(self, key):
413 return self.get(key, 0)
414 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000415 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000416 dict.__setitem__(self_local, key, value)
417 def setstate(self, state):
418 self.state = state
419 def getstate(self):
420 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000421 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000422 a1 = C(12)
423 self.assertEqual(a1.state, 12)
424 a2 = C(foo=1, bar=2)
425 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
426 a = C()
427 self.assertEqual(a.state, -1)
428 self.assertEqual(a.getstate(), -1)
429 a.setstate(0)
430 self.assertEqual(a.state, 0)
431 self.assertEqual(a.getstate(), 0)
432 a.setstate(10)
433 self.assertEqual(a.state, 10)
434 self.assertEqual(a.getstate(), 10)
435 self.assertEqual(a[42], 0)
436 a[42] = 24
437 self.assertEqual(a[42], 24)
438 N = 50
439 for i in range(N):
440 a[i] = C()
441 for j in range(N):
442 a[i][j] = i*j
443 for i in range(N):
444 for j in range(N):
445 self.assertEqual(a[i][j], i*j)
446
447 def test_python_lists(self):
448 # Testing Python subclass of list...
449 class C(list):
450 def __getitem__(self, i):
451 if isinstance(i, slice):
452 return i.start, i.stop
453 return list.__getitem__(self, i) + 100
454 a = C()
455 a.extend([0,1,2])
456 self.assertEqual(a[0], 100)
457 self.assertEqual(a[1], 101)
458 self.assertEqual(a[2], 102)
459 self.assertEqual(a[100:200], (100,200))
460
461 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000462 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000463 class C(metaclass=type):
464 def __init__(self):
465 self.__state = 0
466 def getstate(self):
467 return self.__state
468 def setstate(self, state):
469 self.__state = state
470 a = C()
471 self.assertEqual(a.getstate(), 0)
472 a.setstate(10)
473 self.assertEqual(a.getstate(), 10)
474 class _metaclass(type):
475 def myself(cls): return cls
476 class D(metaclass=_metaclass):
477 pass
478 self.assertEqual(D.myself(), D)
479 d = D()
480 self.assertEqual(d.__class__, D)
481 class M1(type):
482 def __new__(cls, name, bases, dict):
483 dict['__spam__'] = 1
484 return type.__new__(cls, name, bases, dict)
485 class C(metaclass=M1):
486 pass
487 self.assertEqual(C.__spam__, 1)
488 c = C()
489 self.assertEqual(c.__spam__, 1)
490
491 class _instance(object):
492 pass
493 class M2(object):
494 @staticmethod
495 def __new__(cls, name, bases, dict):
496 self = object.__new__(cls)
497 self.name = name
498 self.bases = bases
499 self.dict = dict
500 return self
501 def __call__(self):
502 it = _instance()
503 # Early binding of methods
504 for key in self.dict:
505 if key.startswith("__"):
506 continue
507 setattr(it, key, self.dict[key].__get__(it, self))
508 return it
509 class C(metaclass=M2):
510 def spam(self):
511 return 42
512 self.assertEqual(C.name, 'C')
513 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000514 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000515 c = C()
516 self.assertEqual(c.spam(), 42)
517
518 # More metaclass examples
519
520 class autosuper(type):
521 # Automatically add __super to the class
522 # This trick only works for dynamic classes
523 def __new__(metaclass, name, bases, dict):
524 cls = super(autosuper, metaclass).__new__(metaclass,
525 name, bases, dict)
526 # Name mangling for __super removes leading underscores
527 while name[:1] == "_":
528 name = name[1:]
529 if name:
530 name = "_%s__super" % name
531 else:
532 name = "__super"
533 setattr(cls, name, super(cls))
534 return cls
535 class A(metaclass=autosuper):
536 def meth(self):
537 return "A"
538 class B(A):
539 def meth(self):
540 return "B" + self.__super.meth()
541 class C(A):
542 def meth(self):
543 return "C" + self.__super.meth()
544 class D(C, B):
545 def meth(self):
546 return "D" + self.__super.meth()
547 self.assertEqual(D().meth(), "DCBA")
548 class E(B, C):
549 def meth(self):
550 return "E" + self.__super.meth()
551 self.assertEqual(E().meth(), "EBCA")
552
553 class autoproperty(type):
554 # Automatically create property attributes when methods
555 # named _get_x and/or _set_x are found
556 def __new__(metaclass, name, bases, dict):
557 hits = {}
558 for key, val in dict.items():
559 if key.startswith("_get_"):
560 key = key[5:]
561 get, set = hits.get(key, (None, None))
562 get = val
563 hits[key] = get, set
564 elif key.startswith("_set_"):
565 key = key[5:]
566 get, set = hits.get(key, (None, None))
567 set = val
568 hits[key] = get, set
569 for key, (get, set) in hits.items():
570 dict[key] = property(get, set)
571 return super(autoproperty, metaclass).__new__(metaclass,
572 name, bases, dict)
573 class A(metaclass=autoproperty):
574 def _get_x(self):
575 return -self.__x
576 def _set_x(self, x):
577 self.__x = -x
578 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200579 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000580 a.x = 12
581 self.assertEqual(a.x, 12)
582 self.assertEqual(a._A__x, -12)
583
584 class multimetaclass(autoproperty, autosuper):
585 # Merge of multiple cooperating metaclasses
586 pass
587 class A(metaclass=multimetaclass):
588 def _get_x(self):
589 return "A"
590 class B(A):
591 def _get_x(self):
592 return "B" + self.__super._get_x()
593 class C(A):
594 def _get_x(self):
595 return "C" + self.__super._get_x()
596 class D(C, B):
597 def _get_x(self):
598 return "D" + self.__super._get_x()
599 self.assertEqual(D().x, "DCBA")
600
601 # Make sure type(x) doesn't call x.__class__.__init__
602 class T(type):
603 counter = 0
604 def __init__(self, *args):
605 T.counter += 1
606 class C(metaclass=T):
607 pass
608 self.assertEqual(T.counter, 1)
609 a = C()
610 self.assertEqual(type(a), C)
611 self.assertEqual(T.counter, 1)
612
613 class C(object): pass
614 c = C()
615 try: c()
616 except TypeError: pass
617 else: self.fail("calling object w/o call method should raise "
618 "TypeError")
619
620 # Testing code to find most derived baseclass
621 class A(type):
622 def __new__(*args, **kwargs):
623 return type.__new__(*args, **kwargs)
624
625 class B(object):
626 pass
627
628 class C(object, metaclass=A):
629 pass
630
631 # The most derived metaclass of D is A rather than type.
632 class D(B, C):
633 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000634 self.assertIs(A, type(D))
635
636 # issue1294232: correct metaclass calculation
637 new_calls = [] # to check the order of __new__ calls
638 class AMeta(type):
639 @staticmethod
640 def __new__(mcls, name, bases, ns):
641 new_calls.append('AMeta')
642 return super().__new__(mcls, name, bases, ns)
643 @classmethod
644 def __prepare__(mcls, name, bases):
645 return {}
646
647 class BMeta(AMeta):
648 @staticmethod
649 def __new__(mcls, name, bases, ns):
650 new_calls.append('BMeta')
651 return super().__new__(mcls, name, bases, ns)
652 @classmethod
653 def __prepare__(mcls, name, bases):
654 ns = super().__prepare__(name, bases)
655 ns['BMeta_was_here'] = True
656 return ns
657
658 class A(metaclass=AMeta):
659 pass
660 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000661 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000662
663 class B(metaclass=BMeta):
664 pass
665 # BMeta.__new__ calls AMeta.__new__ with super:
666 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000667 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000668
669 class C(A, B):
670 pass
671 # The most derived metaclass is BMeta:
672 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000673 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000674 # BMeta.__prepare__ should've been called:
675 self.assertIn('BMeta_was_here', C.__dict__)
676
677 # The order of the bases shouldn't matter:
678 class C2(B, A):
679 pass
680 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000681 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000682 self.assertIn('BMeta_was_here', C2.__dict__)
683
684 # Check correct metaclass calculation when a metaclass is declared:
685 class D(C, metaclass=type):
686 pass
687 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000688 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000689 self.assertIn('BMeta_was_here', D.__dict__)
690
691 class E(C, metaclass=AMeta):
692 pass
693 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000694 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000695 self.assertIn('BMeta_was_here', E.__dict__)
696
697 # Special case: the given metaclass isn't a class,
698 # so there is no metaclass calculation.
699 marker = object()
700 def func(*args, **kwargs):
701 return marker
702 class X(metaclass=func):
703 pass
704 class Y(object, metaclass=func):
705 pass
706 class Z(D, metaclass=func):
707 pass
708 self.assertIs(marker, X)
709 self.assertIs(marker, Y)
710 self.assertIs(marker, Z)
711
712 # The given metaclass is a class,
713 # but not a descendant of type.
714 prepare_calls = [] # to track __prepare__ calls
715 class ANotMeta:
716 def __new__(mcls, *args, **kwargs):
717 new_calls.append('ANotMeta')
718 return super().__new__(mcls)
719 @classmethod
720 def __prepare__(mcls, name, bases):
721 prepare_calls.append('ANotMeta')
722 return {}
723 class BNotMeta(ANotMeta):
724 def __new__(mcls, *args, **kwargs):
725 new_calls.append('BNotMeta')
726 return super().__new__(mcls)
727 @classmethod
728 def __prepare__(mcls, name, bases):
729 prepare_calls.append('BNotMeta')
730 return super().__prepare__(name, bases)
731
732 class A(metaclass=ANotMeta):
733 pass
734 self.assertIs(ANotMeta, type(A))
735 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000736 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000737 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000738 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000739
740 class B(metaclass=BNotMeta):
741 pass
742 self.assertIs(BNotMeta, type(B))
743 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000744 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000745 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000746 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000747
748 class C(A, B):
749 pass
750 self.assertIs(BNotMeta, type(C))
751 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000752 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000753 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000754 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000755
756 class C2(B, A):
757 pass
758 self.assertIs(BNotMeta, type(C2))
759 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000760 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000761 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000762 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000763
764 # This is a TypeError, because of a metaclass conflict:
765 # BNotMeta is neither a subclass, nor a superclass of type
766 with self.assertRaises(TypeError):
767 class D(C, metaclass=type):
768 pass
769
770 class E(C, metaclass=ANotMeta):
771 pass
772 self.assertIs(BNotMeta, type(E))
773 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000774 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000775 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000776 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000777
778 class F(object(), C):
779 pass
780 self.assertIs(BNotMeta, type(F))
781 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000782 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000783 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000784 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000785
786 class F2(C, object()):
787 pass
788 self.assertIs(BNotMeta, type(F2))
789 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000790 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000791 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000792 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000793
794 # TypeError: BNotMeta is neither a
795 # subclass, nor a superclass of int
796 with self.assertRaises(TypeError):
797 class X(C, int()):
798 pass
799 with self.assertRaises(TypeError):
800 class X(int(), C):
801 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000802
803 def test_module_subclasses(self):
804 # Testing Python subclass of module...
805 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000806 MT = type(sys)
807 class MM(MT):
808 def __init__(self, name):
809 MT.__init__(self, name)
810 def __getattribute__(self, name):
811 log.append(("getattr", name))
812 return MT.__getattribute__(self, name)
813 def __setattr__(self, name, value):
814 log.append(("setattr", name, value))
815 MT.__setattr__(self, name, value)
816 def __delattr__(self, name):
817 log.append(("delattr", name))
818 MT.__delattr__(self, name)
819 a = MM("a")
820 a.foo = 12
821 x = a.foo
822 del a.foo
823 self.assertEqual(log, [("setattr", "foo", 12),
824 ("getattr", "foo"),
825 ("delattr", "foo")])
826
827 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000828 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000829 class Module(types.ModuleType, str):
830 pass
831 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000832 pass
833 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000834 self.fail("inheriting from ModuleType and str at the same time "
835 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000836
Georg Brandl479a7e72008-02-05 18:13:15 +0000837 def test_multiple_inheritance(self):
838 # Testing multiple inheritance...
839 class C(object):
840 def __init__(self):
841 self.__state = 0
842 def getstate(self):
843 return self.__state
844 def setstate(self, state):
845 self.__state = state
846 a = C()
847 self.assertEqual(a.getstate(), 0)
848 a.setstate(10)
849 self.assertEqual(a.getstate(), 10)
850 class D(dict, C):
851 def __init__(self):
852 type({}).__init__(self)
853 C.__init__(self)
854 d = D()
855 self.assertEqual(list(d.keys()), [])
856 d["hello"] = "world"
857 self.assertEqual(list(d.items()), [("hello", "world")])
858 self.assertEqual(d["hello"], "world")
859 self.assertEqual(d.getstate(), 0)
860 d.setstate(10)
861 self.assertEqual(d.getstate(), 10)
862 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000863
Georg Brandl479a7e72008-02-05 18:13:15 +0000864 # SF bug #442833
865 class Node(object):
866 def __int__(self):
867 return int(self.foo())
868 def foo(self):
869 return "23"
870 class Frag(Node, list):
871 def foo(self):
872 return "42"
873 self.assertEqual(Node().__int__(), 23)
874 self.assertEqual(int(Node()), 23)
875 self.assertEqual(Frag().__int__(), 42)
876 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000877
Georg Brandl479a7e72008-02-05 18:13:15 +0000878 def test_diamond_inheritence(self):
879 # Testing multiple inheritance special cases...
880 class A(object):
881 def spam(self): return "A"
882 self.assertEqual(A().spam(), "A")
883 class B(A):
884 def boo(self): return "B"
885 def spam(self): return "B"
886 self.assertEqual(B().spam(), "B")
887 self.assertEqual(B().boo(), "B")
888 class C(A):
889 def boo(self): return "C"
890 self.assertEqual(C().spam(), "A")
891 self.assertEqual(C().boo(), "C")
892 class D(B, C): pass
893 self.assertEqual(D().spam(), "B")
894 self.assertEqual(D().boo(), "B")
895 self.assertEqual(D.__mro__, (D, B, C, A, object))
896 class E(C, B): pass
897 self.assertEqual(E().spam(), "B")
898 self.assertEqual(E().boo(), "C")
899 self.assertEqual(E.__mro__, (E, C, B, A, object))
900 # MRO order disagreement
901 try:
902 class F(D, E): pass
903 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000904 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000905 else:
906 self.fail("expected MRO order disagreement (F)")
907 try:
908 class G(E, D): pass
909 except TypeError:
910 pass
911 else:
912 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000913
Georg Brandl479a7e72008-02-05 18:13:15 +0000914 # see thread python-dev/2002-October/029035.html
915 def test_ex5_from_c3_switch(self):
916 # Testing ex5 from C3 switch discussion...
917 class A(object): pass
918 class B(object): pass
919 class C(object): pass
920 class X(A): pass
921 class Y(A): pass
922 class Z(X,B,Y,C): pass
923 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924
Georg Brandl479a7e72008-02-05 18:13:15 +0000925 # see "A Monotonic Superclass Linearization for Dylan",
926 # by Kim Barrett et al. (OOPSLA 1996)
927 def test_monotonicity(self):
928 # Testing MRO monotonicity...
929 class Boat(object): pass
930 class DayBoat(Boat): pass
931 class WheelBoat(Boat): pass
932 class EngineLess(DayBoat): pass
933 class SmallMultihull(DayBoat): pass
934 class PedalWheelBoat(EngineLess,WheelBoat): pass
935 class SmallCatamaran(SmallMultihull): pass
936 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000937
Georg Brandl479a7e72008-02-05 18:13:15 +0000938 self.assertEqual(PedalWheelBoat.__mro__,
939 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
940 self.assertEqual(SmallCatamaran.__mro__,
941 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
942 self.assertEqual(Pedalo.__mro__,
943 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
944 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000945
Georg Brandl479a7e72008-02-05 18:13:15 +0000946 # see "A Monotonic Superclass Linearization for Dylan",
947 # by Kim Barrett et al. (OOPSLA 1996)
948 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200949 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000950 class Pane(object): pass
951 class ScrollingMixin(object): pass
952 class EditingMixin(object): pass
953 class ScrollablePane(Pane,ScrollingMixin): pass
954 class EditablePane(Pane,EditingMixin): pass
955 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000956
Georg Brandl479a7e72008-02-05 18:13:15 +0000957 self.assertEqual(EditableScrollablePane.__mro__,
958 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
959 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000960
Georg Brandl479a7e72008-02-05 18:13:15 +0000961 def test_mro_disagreement(self):
962 # Testing error messages for MRO disagreement...
963 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000964order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000965
Georg Brandl479a7e72008-02-05 18:13:15 +0000966 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000967 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000968 callable(*args)
969 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000970 # the exact msg is generally considered an impl detail
971 if support.check_impl_detail():
972 if not str(msg).startswith(expected):
973 self.fail("Message %r, expected %r" %
974 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000975 else:
976 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000977
Georg Brandl479a7e72008-02-05 18:13:15 +0000978 class A(object): pass
979 class B(A): pass
980 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000981
Georg Brandl479a7e72008-02-05 18:13:15 +0000982 # Test some very simple errors
983 raises(TypeError, "duplicate base class A",
984 type, "X", (A, A), {})
985 raises(TypeError, mro_err_msg,
986 type, "X", (A, B), {})
987 raises(TypeError, mro_err_msg,
988 type, "X", (A, C, B), {})
989 # Test a slightly more complex error
990 class GridLayout(object): pass
991 class HorizontalGrid(GridLayout): pass
992 class VerticalGrid(GridLayout): pass
993 class HVGrid(HorizontalGrid, VerticalGrid): pass
994 class VHGrid(VerticalGrid, HorizontalGrid): pass
995 raises(TypeError, mro_err_msg,
996 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000997
Georg Brandl479a7e72008-02-05 18:13:15 +0000998 def test_object_class(self):
999 # Testing object class...
1000 a = object()
1001 self.assertEqual(a.__class__, object)
1002 self.assertEqual(type(a), object)
1003 b = object()
1004 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001005 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001006 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001007 a.foo = 12
1008 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001009 pass
1010 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001011 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001012 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001013
Georg Brandl479a7e72008-02-05 18:13:15 +00001014 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001015 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001016 x = Cdict()
1017 self.assertEqual(x.__dict__, {})
1018 x.foo = 1
1019 self.assertEqual(x.foo, 1)
1020 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021
Georg Brandl479a7e72008-02-05 18:13:15 +00001022 def test_slots(self):
1023 # Testing __slots__...
1024 class C0(object):
1025 __slots__ = []
1026 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001027 self.assertNotHasAttr(x, "__dict__")
1028 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001029
1030 class C1(object):
1031 __slots__ = ['a']
1032 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001033 self.assertNotHasAttr(x, "__dict__")
1034 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001036 self.assertEqual(x.a, 1)
1037 x.a = None
1038 self.assertEqual(x.a, None)
1039 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001040 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001041
Georg Brandl479a7e72008-02-05 18:13:15 +00001042 class C3(object):
1043 __slots__ = ['a', 'b', 'c']
1044 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001045 self.assertNotHasAttr(x, "__dict__")
1046 self.assertNotHasAttr(x, 'a')
1047 self.assertNotHasAttr(x, 'b')
1048 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001049 x.a = 1
1050 x.b = 2
1051 x.c = 3
1052 self.assertEqual(x.a, 1)
1053 self.assertEqual(x.b, 2)
1054 self.assertEqual(x.c, 3)
1055
1056 class C4(object):
1057 """Validate name mangling"""
1058 __slots__ = ['__a']
1059 def __init__(self, value):
1060 self.__a = value
1061 def get(self):
1062 return self.__a
1063 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001064 self.assertNotHasAttr(x, '__dict__')
1065 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001066 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001067 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001068 x.__a = 6
1069 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001070 pass
1071 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001072 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001073
Georg Brandl479a7e72008-02-05 18:13:15 +00001074 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001075 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001076 class C(object):
1077 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001078 except TypeError:
1079 pass
1080 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001081 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001082 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001083 class C(object):
1084 __slots__ = ["foo bar"]
1085 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001086 pass
1087 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001088 self.fail("['foo bar'] slots not caught")
1089 try:
1090 class C(object):
1091 __slots__ = ["foo\0bar"]
1092 except TypeError:
1093 pass
1094 else:
1095 self.fail("['foo\\0bar'] slots not caught")
1096 try:
1097 class C(object):
1098 __slots__ = ["1"]
1099 except TypeError:
1100 pass
1101 else:
1102 self.fail("['1'] slots not caught")
1103 try:
1104 class C(object):
1105 __slots__ = [""]
1106 except TypeError:
1107 pass
1108 else:
1109 self.fail("[''] slots not caught")
1110 class C(object):
1111 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1112 # XXX(nnorwitz): was there supposed to be something tested
1113 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001114
Georg Brandl479a7e72008-02-05 18:13:15 +00001115 # Test a single string is not expanded as a sequence.
1116 class C(object):
1117 __slots__ = "abc"
1118 c = C()
1119 c.abc = 5
1120 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001121
Georg Brandl479a7e72008-02-05 18:13:15 +00001122 # Test unicode slot names
1123 # Test a single unicode string is not expanded as a sequence.
1124 class C(object):
1125 __slots__ = "abc"
1126 c = C()
1127 c.abc = 5
1128 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001129
Georg Brandl479a7e72008-02-05 18:13:15 +00001130 # _unicode_to_string used to modify slots in certain circumstances
1131 slots = ("foo", "bar")
1132 class C(object):
1133 __slots__ = slots
1134 x = C()
1135 x.foo = 5
1136 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001137 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001138 # this used to leak references
1139 try:
1140 class C(object):
1141 __slots__ = [chr(128)]
1142 except (TypeError, UnicodeEncodeError):
1143 pass
1144 else:
Terry Jan Reedyaf9eb962014-06-20 15:16:35 -04001145 self.fail("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001146
Georg Brandl479a7e72008-02-05 18:13:15 +00001147 # Test leaks
1148 class Counted(object):
1149 counter = 0 # counts the number of instances alive
1150 def __init__(self):
1151 Counted.counter += 1
1152 def __del__(self):
1153 Counted.counter -= 1
1154 class C(object):
1155 __slots__ = ['a', 'b', 'c']
1156 x = C()
1157 x.a = Counted()
1158 x.b = Counted()
1159 x.c = Counted()
1160 self.assertEqual(Counted.counter, 3)
1161 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001162 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001163 self.assertEqual(Counted.counter, 0)
1164 class D(C):
1165 pass
1166 x = D()
1167 x.a = Counted()
1168 x.z = Counted()
1169 self.assertEqual(Counted.counter, 2)
1170 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001171 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001172 self.assertEqual(Counted.counter, 0)
1173 class E(D):
1174 __slots__ = ['e']
1175 x = E()
1176 x.a = Counted()
1177 x.z = Counted()
1178 x.e = Counted()
1179 self.assertEqual(Counted.counter, 3)
1180 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001181 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001182 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001183
Georg Brandl479a7e72008-02-05 18:13:15 +00001184 # Test cyclical leaks [SF bug 519621]
1185 class F(object):
1186 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001187 s = F()
1188 s.a = [Counted(), s]
1189 self.assertEqual(Counted.counter, 1)
1190 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001191 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001192 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001193
Georg Brandl479a7e72008-02-05 18:13:15 +00001194 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001195 if hasattr(gc, 'get_objects'):
1196 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001197 def __eq__(self, other):
1198 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001199 g = G()
1200 orig_objects = len(gc.get_objects())
1201 for i in range(10):
1202 g==g
1203 new_objects = len(gc.get_objects())
1204 self.assertEqual(orig_objects, new_objects)
1205
Georg Brandl479a7e72008-02-05 18:13:15 +00001206 class H(object):
1207 __slots__ = ['a', 'b']
1208 def __init__(self):
1209 self.a = 1
1210 self.b = 2
1211 def __del__(self_):
1212 self.assertEqual(self_.a, 1)
1213 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001214 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001215 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001216 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001217 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001218
Benjamin Petersond12362a2009-12-30 19:44:54 +00001219 class X(object):
1220 __slots__ = "a"
1221 with self.assertRaises(AttributeError):
1222 del X().a
1223
Georg Brandl479a7e72008-02-05 18:13:15 +00001224 def test_slots_special(self):
1225 # Testing __dict__ and __weakref__ in __slots__...
1226 class D(object):
1227 __slots__ = ["__dict__"]
1228 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001229 self.assertHasAttr(a, "__dict__")
1230 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001231 a.foo = 42
1232 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001233
Georg Brandl479a7e72008-02-05 18:13:15 +00001234 class W(object):
1235 __slots__ = ["__weakref__"]
1236 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001237 self.assertHasAttr(a, "__weakref__")
1238 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001239 try:
1240 a.foo = 42
1241 except AttributeError:
1242 pass
1243 else:
1244 self.fail("shouldn't be allowed to set a.foo")
1245
1246 class C1(W, D):
1247 __slots__ = []
1248 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001249 self.assertHasAttr(a, "__dict__")
1250 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001251 a.foo = 42
1252 self.assertEqual(a.__dict__, {"foo": 42})
1253
1254 class C2(D, W):
1255 __slots__ = []
1256 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001257 self.assertHasAttr(a, "__dict__")
1258 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001259 a.foo = 42
1260 self.assertEqual(a.__dict__, {"foo": 42})
1261
Christian Heimesa156e092008-02-16 07:38:31 +00001262 def test_slots_descriptor(self):
1263 # Issue2115: slot descriptors did not correctly check
1264 # the type of the given object
1265 import abc
1266 class MyABC(metaclass=abc.ABCMeta):
1267 __slots__ = "a"
1268
1269 class Unrelated(object):
1270 pass
1271 MyABC.register(Unrelated)
1272
1273 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001274 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001275
1276 # This used to crash
1277 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1278
Georg Brandl479a7e72008-02-05 18:13:15 +00001279 def test_dynamics(self):
1280 # Testing class attribute propagation...
1281 class D(object):
1282 pass
1283 class E(D):
1284 pass
1285 class F(D):
1286 pass
1287 D.foo = 1
1288 self.assertEqual(D.foo, 1)
1289 # Test that dynamic attributes are inherited
1290 self.assertEqual(E.foo, 1)
1291 self.assertEqual(F.foo, 1)
1292 # Test dynamic instances
1293 class C(object):
1294 pass
1295 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001296 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001297 C.foobar = 2
1298 self.assertEqual(a.foobar, 2)
1299 C.method = lambda self: 42
1300 self.assertEqual(a.method(), 42)
1301 C.__repr__ = lambda self: "C()"
1302 self.assertEqual(repr(a), "C()")
1303 C.__int__ = lambda self: 100
1304 self.assertEqual(int(a), 100)
1305 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001306 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001307 def mygetattr(self, name):
1308 if name == "spam":
1309 return "spam"
1310 raise AttributeError
1311 C.__getattr__ = mygetattr
1312 self.assertEqual(a.spam, "spam")
1313 a.new = 12
1314 self.assertEqual(a.new, 12)
1315 def mysetattr(self, name, value):
1316 if name == "spam":
1317 raise AttributeError
1318 return object.__setattr__(self, name, value)
1319 C.__setattr__ = mysetattr
1320 try:
1321 a.spam = "not spam"
1322 except AttributeError:
1323 pass
1324 else:
1325 self.fail("expected AttributeError")
1326 self.assertEqual(a.spam, "spam")
1327 class D(C):
1328 pass
1329 d = D()
1330 d.foo = 1
1331 self.assertEqual(d.foo, 1)
1332
1333 # Test handling of int*seq and seq*int
1334 class I(int):
1335 pass
1336 self.assertEqual("a"*I(2), "aa")
1337 self.assertEqual(I(2)*"a", "aa")
1338 self.assertEqual(2*I(3), 6)
1339 self.assertEqual(I(3)*2, 6)
1340 self.assertEqual(I(3)*I(2), 6)
1341
Georg Brandl479a7e72008-02-05 18:13:15 +00001342 # Test comparison of classes with dynamic metaclasses
1343 class dynamicmetaclass(type):
1344 pass
1345 class someclass(metaclass=dynamicmetaclass):
1346 pass
1347 self.assertNotEqual(someclass, object)
1348
1349 def test_errors(self):
1350 # Testing errors...
1351 try:
1352 class C(list, dict):
1353 pass
1354 except TypeError:
1355 pass
1356 else:
1357 self.fail("inheritance from both list and dict should be illegal")
1358
1359 try:
1360 class C(object, None):
1361 pass
1362 except TypeError:
1363 pass
1364 else:
1365 self.fail("inheritance from non-type should be illegal")
1366 class Classic:
1367 pass
1368
1369 try:
1370 class C(type(len)):
1371 pass
1372 except TypeError:
1373 pass
1374 else:
1375 self.fail("inheritance from CFunction should be illegal")
1376
1377 try:
1378 class C(object):
1379 __slots__ = 1
1380 except TypeError:
1381 pass
1382 else:
1383 self.fail("__slots__ = 1 should be illegal")
1384
1385 try:
1386 class C(object):
1387 __slots__ = [1]
1388 except TypeError:
1389 pass
1390 else:
1391 self.fail("__slots__ = [1] should be illegal")
1392
1393 class M1(type):
1394 pass
1395 class M2(type):
1396 pass
1397 class A1(object, metaclass=M1):
1398 pass
1399 class A2(object, metaclass=M2):
1400 pass
1401 try:
1402 class B(A1, A2):
1403 pass
1404 except TypeError:
1405 pass
1406 else:
1407 self.fail("finding the most derived metaclass should have failed")
1408
1409 def test_classmethods(self):
1410 # Testing class methods...
1411 class C(object):
1412 def foo(*a): return a
1413 goo = classmethod(foo)
1414 c = C()
1415 self.assertEqual(C.goo(1), (C, 1))
1416 self.assertEqual(c.goo(1), (C, 1))
1417 self.assertEqual(c.foo(1), (c, 1))
1418 class D(C):
1419 pass
1420 d = D()
1421 self.assertEqual(D.goo(1), (D, 1))
1422 self.assertEqual(d.goo(1), (D, 1))
1423 self.assertEqual(d.foo(1), (d, 1))
1424 self.assertEqual(D.foo(d, 1), (d, 1))
1425 # Test for a specific crash (SF bug 528132)
1426 def f(cls, arg): return (cls, arg)
1427 ff = classmethod(f)
1428 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1429 self.assertEqual(ff.__get__(0)(42), (int, 42))
1430
1431 # Test super() with classmethods (SF bug 535444)
1432 self.assertEqual(C.goo.__self__, C)
1433 self.assertEqual(D.goo.__self__, D)
1434 self.assertEqual(super(D,D).goo.__self__, D)
1435 self.assertEqual(super(D,d).goo.__self__, D)
1436 self.assertEqual(super(D,D).goo(), (D,))
1437 self.assertEqual(super(D,d).goo(), (D,))
1438
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001439 # Verify that a non-callable will raise
1440 meth = classmethod(1).__get__(1)
1441 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001442
1443 # Verify that classmethod() doesn't allow keyword args
1444 try:
1445 classmethod(f, kw=1)
1446 except TypeError:
1447 pass
1448 else:
1449 self.fail("classmethod shouldn't accept keyword args")
1450
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001451 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001452 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001453 cm.x = 42
1454 self.assertEqual(cm.x, 42)
1455 self.assertEqual(cm.__dict__, {"x" : 42})
1456 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001457 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001458
Benjamin Petersone549ead2009-03-28 21:42:05 +00001459 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001460 def test_classmethods_in_c(self):
1461 # Testing C-based class methods...
1462 import xxsubtype as spam
1463 a = (1, 2, 3)
1464 d = {'abc': 123}
1465 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1466 self.assertEqual(x, spam.spamlist)
1467 self.assertEqual(a, a1)
1468 self.assertEqual(d, d1)
1469 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1470 self.assertEqual(x, spam.spamlist)
1471 self.assertEqual(a, a1)
1472 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001473 spam_cm = spam.spamlist.__dict__['classmeth']
1474 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1475 self.assertEqual(x2, spam.spamlist)
1476 self.assertEqual(a2, a1)
1477 self.assertEqual(d2, d1)
1478 class SubSpam(spam.spamlist): pass
1479 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1480 self.assertEqual(x2, SubSpam)
1481 self.assertEqual(a2, a1)
1482 self.assertEqual(d2, d1)
1483 with self.assertRaises(TypeError):
1484 spam_cm()
1485 with self.assertRaises(TypeError):
1486 spam_cm(spam.spamlist())
1487 with self.assertRaises(TypeError):
1488 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001489
1490 def test_staticmethods(self):
1491 # Testing static methods...
1492 class C(object):
1493 def foo(*a): return a
1494 goo = staticmethod(foo)
1495 c = C()
1496 self.assertEqual(C.goo(1), (1,))
1497 self.assertEqual(c.goo(1), (1,))
1498 self.assertEqual(c.foo(1), (c, 1,))
1499 class D(C):
1500 pass
1501 d = D()
1502 self.assertEqual(D.goo(1), (1,))
1503 self.assertEqual(d.goo(1), (1,))
1504 self.assertEqual(d.foo(1), (d, 1))
1505 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001506 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001507 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001508 sm.x = 42
1509 self.assertEqual(sm.x, 42)
1510 self.assertEqual(sm.__dict__, {"x" : 42})
1511 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001512 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001513
Benjamin Petersone549ead2009-03-28 21:42:05 +00001514 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001515 def test_staticmethods_in_c(self):
1516 # Testing C-based static methods...
1517 import xxsubtype as spam
1518 a = (1, 2, 3)
1519 d = {"abc": 123}
1520 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1521 self.assertEqual(x, None)
1522 self.assertEqual(a, a1)
1523 self.assertEqual(d, d1)
1524 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1525 self.assertEqual(x, None)
1526 self.assertEqual(a, a1)
1527 self.assertEqual(d, d1)
1528
1529 def test_classic(self):
1530 # Testing classic classes...
1531 class C:
1532 def foo(*a): return a
1533 goo = classmethod(foo)
1534 c = C()
1535 self.assertEqual(C.goo(1), (C, 1))
1536 self.assertEqual(c.goo(1), (C, 1))
1537 self.assertEqual(c.foo(1), (c, 1))
1538 class D(C):
1539 pass
1540 d = D()
1541 self.assertEqual(D.goo(1), (D, 1))
1542 self.assertEqual(d.goo(1), (D, 1))
1543 self.assertEqual(d.foo(1), (d, 1))
1544 self.assertEqual(D.foo(d, 1), (d, 1))
1545 class E: # *not* subclassing from C
1546 foo = C.foo
1547 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001548 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001549
1550 def test_compattr(self):
1551 # Testing computed attributes...
1552 class C(object):
1553 class computed_attribute(object):
1554 def __init__(self, get, set=None, delete=None):
1555 self.__get = get
1556 self.__set = set
1557 self.__delete = delete
1558 def __get__(self, obj, type=None):
1559 return self.__get(obj)
1560 def __set__(self, obj, value):
1561 return self.__set(obj, value)
1562 def __delete__(self, obj):
1563 return self.__delete(obj)
1564 def __init__(self):
1565 self.__x = 0
1566 def __get_x(self):
1567 x = self.__x
1568 self.__x = x+1
1569 return x
1570 def __set_x(self, x):
1571 self.__x = x
1572 def __delete_x(self):
1573 del self.__x
1574 x = computed_attribute(__get_x, __set_x, __delete_x)
1575 a = C()
1576 self.assertEqual(a.x, 0)
1577 self.assertEqual(a.x, 1)
1578 a.x = 10
1579 self.assertEqual(a.x, 10)
1580 self.assertEqual(a.x, 11)
1581 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001582 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001583
1584 def test_newslots(self):
1585 # Testing __new__ slot override...
1586 class C(list):
1587 def __new__(cls):
1588 self = list.__new__(cls)
1589 self.foo = 1
1590 return self
1591 def __init__(self):
1592 self.foo = self.foo + 2
1593 a = C()
1594 self.assertEqual(a.foo, 3)
1595 self.assertEqual(a.__class__, C)
1596 class D(C):
1597 pass
1598 b = D()
1599 self.assertEqual(b.foo, 3)
1600 self.assertEqual(b.__class__, D)
1601
1602 def test_altmro(self):
1603 # Testing mro() and overriding it...
1604 class A(object):
1605 def f(self): return "A"
1606 class B(A):
1607 pass
1608 class C(A):
1609 def f(self): return "C"
1610 class D(B, C):
1611 pass
1612 self.assertEqual(D.mro(), [D, B, C, A, object])
1613 self.assertEqual(D.__mro__, (D, B, C, A, object))
1614 self.assertEqual(D().f(), "C")
1615
1616 class PerverseMetaType(type):
1617 def mro(cls):
1618 L = type.mro(cls)
1619 L.reverse()
1620 return L
1621 class X(D,B,C,A, metaclass=PerverseMetaType):
1622 pass
1623 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1624 self.assertEqual(X().f(), "A")
1625
1626 try:
1627 class _metaclass(type):
1628 def mro(self):
1629 return [self, dict, object]
1630 class X(object, metaclass=_metaclass):
1631 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001632 # In CPython, the class creation above already raises
1633 # TypeError, as a protection against the fact that
1634 # instances of X would segfault it. In other Python
1635 # implementations it would be ok to let the class X
1636 # be created, but instead get a clean TypeError on the
1637 # __setitem__ below.
1638 x = object.__new__(X)
1639 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001640 except TypeError:
1641 pass
1642 else:
1643 self.fail("devious mro() return not caught")
1644
1645 try:
1646 class _metaclass(type):
1647 def mro(self):
1648 return [1]
1649 class X(object, metaclass=_metaclass):
1650 pass
1651 except TypeError:
1652 pass
1653 else:
1654 self.fail("non-class mro() return not caught")
1655
1656 try:
1657 class _metaclass(type):
1658 def mro(self):
1659 return 1
1660 class X(object, metaclass=_metaclass):
1661 pass
1662 except TypeError:
1663 pass
1664 else:
1665 self.fail("non-sequence mro() return not caught")
1666
1667 def test_overloading(self):
1668 # Testing operator overloading...
1669
1670 class B(object):
1671 "Intermediate class because object doesn't have a __setattr__"
1672
1673 class C(B):
1674 def __getattr__(self, name):
1675 if name == "foo":
1676 return ("getattr", name)
1677 else:
1678 raise AttributeError
1679 def __setattr__(self, name, value):
1680 if name == "foo":
1681 self.setattr = (name, value)
1682 else:
1683 return B.__setattr__(self, name, value)
1684 def __delattr__(self, name):
1685 if name == "foo":
1686 self.delattr = name
1687 else:
1688 return B.__delattr__(self, name)
1689
1690 def __getitem__(self, key):
1691 return ("getitem", key)
1692 def __setitem__(self, key, value):
1693 self.setitem = (key, value)
1694 def __delitem__(self, key):
1695 self.delitem = key
1696
1697 a = C()
1698 self.assertEqual(a.foo, ("getattr", "foo"))
1699 a.foo = 12
1700 self.assertEqual(a.setattr, ("foo", 12))
1701 del a.foo
1702 self.assertEqual(a.delattr, "foo")
1703
1704 self.assertEqual(a[12], ("getitem", 12))
1705 a[12] = 21
1706 self.assertEqual(a.setitem, (12, 21))
1707 del a[12]
1708 self.assertEqual(a.delitem, 12)
1709
1710 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1711 a[0:10] = "foo"
1712 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1713 del a[0:10]
1714 self.assertEqual(a.delitem, (slice(0, 10)))
1715
1716 def test_methods(self):
1717 # Testing methods...
1718 class C(object):
1719 def __init__(self, x):
1720 self.x = x
1721 def foo(self):
1722 return self.x
1723 c1 = C(1)
1724 self.assertEqual(c1.foo(), 1)
1725 class D(C):
1726 boo = C.foo
1727 goo = c1.foo
1728 d2 = D(2)
1729 self.assertEqual(d2.foo(), 2)
1730 self.assertEqual(d2.boo(), 2)
1731 self.assertEqual(d2.goo(), 1)
1732 class E(object):
1733 foo = C.foo
1734 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001735 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001736
Benjamin Peterson224205f2009-05-08 03:25:19 +00001737 def test_special_method_lookup(self):
1738 # The lookup of special methods bypasses __getattr__ and
1739 # __getattribute__, but they still can be descriptors.
1740
1741 def run_context(manager):
1742 with manager:
1743 pass
1744 def iden(self):
1745 return self
1746 def hello(self):
1747 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001748 def empty_seq(self):
1749 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001750 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001751 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001752 def complex_num(self):
1753 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001754 def stop(self):
1755 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001756 def return_true(self, thing=None):
1757 return True
1758 def do_isinstance(obj):
1759 return isinstance(int, obj)
1760 def do_issubclass(obj):
1761 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001762 def do_dict_missing(checker):
1763 class DictSub(checker.__class__, dict):
1764 pass
1765 self.assertEqual(DictSub()["hi"], 4)
1766 def some_number(self_, key):
1767 self.assertEqual(key, "hi")
1768 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001769 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001770 def format_impl(self, spec):
1771 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001772
1773 # It would be nice to have every special method tested here, but I'm
1774 # only listing the ones I can remember outside of typeobject.c, since it
1775 # does it right.
1776 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001777 ("__bytes__", bytes, hello, set(), {}),
1778 ("__reversed__", reversed, empty_seq, set(), {}),
1779 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001780 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001781 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1782 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001783 ("__missing__", do_dict_missing, some_number,
1784 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001785 ("__subclasscheck__", do_issubclass, return_true,
1786 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001787 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1788 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001789 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001790 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001791 ("__floor__", math.floor, zero, set(), {}),
1792 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001793 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001794 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001795 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001796 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001797 ]
1798
1799 class Checker(object):
1800 def __getattr__(self, attr, test=self):
1801 test.fail("__getattr__ called with {0}".format(attr))
1802 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001803 if attr not in ok:
1804 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001805 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001806 class SpecialDescr(object):
1807 def __init__(self, impl):
1808 self.impl = impl
1809 def __get__(self, obj, owner):
1810 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001811 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001812 class MyException(Exception):
1813 pass
1814 class ErrDescr(object):
1815 def __get__(self, obj, owner):
1816 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001817
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001818 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001819 class X(Checker):
1820 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001821 for attr, obj in env.items():
1822 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001823 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001824 runner(X())
1825
1826 record = []
1827 class X(Checker):
1828 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001829 for attr, obj in env.items():
1830 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001831 setattr(X, name, SpecialDescr(meth_impl))
1832 runner(X())
1833 self.assertEqual(record, [1], name)
1834
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001835 class X(Checker):
1836 pass
1837 for attr, obj in env.items():
1838 setattr(X, attr, obj)
1839 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001840 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001841
Georg Brandl479a7e72008-02-05 18:13:15 +00001842 def test_specials(self):
1843 # Testing special operators...
1844 # Test operators like __hash__ for which a built-in default exists
1845
1846 # Test the default behavior for static classes
1847 class C(object):
1848 def __getitem__(self, i):
1849 if 0 <= i < 10: return i
1850 raise IndexError
1851 c1 = C()
1852 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001853 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001854 self.assertNotEqual(id(c1), id(c2))
1855 hash(c1)
1856 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001857 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001858 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001859 self.assertFalse(c1 != c1)
1860 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001861 # Note that the module name appears in str/repr, and that varies
1862 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001863 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001864 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001865 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001866 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001867 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001868 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001869 # Test the default behavior for dynamic classes
1870 class D(object):
1871 def __getitem__(self, i):
1872 if 0 <= i < 10: return i
1873 raise IndexError
1874 d1 = D()
1875 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001876 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001877 self.assertNotEqual(id(d1), id(d2))
1878 hash(d1)
1879 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001880 self.assertEqual(d1, d1)
1881 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001882 self.assertFalse(d1 != d1)
1883 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001884 # Note that the module name appears in str/repr, and that varies
1885 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001886 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001887 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001888 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001889 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001890 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001891 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001892 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001893 class Proxy(object):
1894 def __init__(self, x):
1895 self.x = x
1896 def __bool__(self):
1897 return not not self.x
1898 def __hash__(self):
1899 return hash(self.x)
1900 def __eq__(self, other):
1901 return self.x == other
1902 def __ne__(self, other):
1903 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001904 def __ge__(self, other):
1905 return self.x >= other
1906 def __gt__(self, other):
1907 return self.x > other
1908 def __le__(self, other):
1909 return self.x <= other
1910 def __lt__(self, other):
1911 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001912 def __str__(self):
1913 return "Proxy:%s" % self.x
1914 def __repr__(self):
1915 return "Proxy(%r)" % self.x
1916 def __contains__(self, value):
1917 return value in self.x
1918 p0 = Proxy(0)
1919 p1 = Proxy(1)
1920 p_1 = Proxy(-1)
1921 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001922 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001923 self.assertEqual(hash(p0), hash(0))
1924 self.assertEqual(p0, p0)
1925 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001926 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001927 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001928 self.assertTrue(p0 < p1)
1929 self.assertTrue(p0 <= p1)
1930 self.assertTrue(p1 > p0)
1931 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001932 self.assertEqual(str(p0), "Proxy:0")
1933 self.assertEqual(repr(p0), "Proxy(0)")
1934 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001935 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001936 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001937 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001938 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001939
Georg Brandl479a7e72008-02-05 18:13:15 +00001940 def test_weakrefs(self):
1941 # Testing weak references...
1942 import weakref
1943 class C(object):
1944 pass
1945 c = C()
1946 r = weakref.ref(c)
1947 self.assertEqual(r(), c)
1948 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001949 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001950 self.assertEqual(r(), None)
1951 del r
1952 class NoWeak(object):
1953 __slots__ = ['foo']
1954 no = NoWeak()
1955 try:
1956 weakref.ref(no)
1957 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001958 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00001959 else:
1960 self.fail("weakref.ref(no) should be illegal")
1961 class Weak(object):
1962 __slots__ = ['foo', '__weakref__']
1963 yes = Weak()
1964 r = weakref.ref(yes)
1965 self.assertEqual(r(), yes)
1966 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001967 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001968 self.assertEqual(r(), None)
1969 del r
1970
1971 def test_properties(self):
1972 # Testing property...
1973 class C(object):
1974 def getx(self):
1975 return self.__x
1976 def setx(self, value):
1977 self.__x = value
1978 def delx(self):
1979 del self.__x
1980 x = property(getx, setx, delx, doc="I'm the x property.")
1981 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001982 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001983 a.x = 42
1984 self.assertEqual(a._C__x, 42)
1985 self.assertEqual(a.x, 42)
1986 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001987 self.assertNotHasAttr(a, "x")
1988 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001989 C.x.__set__(a, 100)
1990 self.assertEqual(C.x.__get__(a), 100)
1991 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001992 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001993
1994 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001995 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001996
1997 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001998 self.assertIn("__doc__", attrs)
1999 self.assertIn("fget", attrs)
2000 self.assertIn("fset", attrs)
2001 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002002
2003 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002004 self.assertIs(raw.fget, C.__dict__['getx'])
2005 self.assertIs(raw.fset, C.__dict__['setx'])
2006 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002007
2008 for attr in "__doc__", "fget", "fset", "fdel":
2009 try:
2010 setattr(raw, attr, 42)
2011 except AttributeError as msg:
2012 if str(msg).find('readonly') < 0:
2013 self.fail("when setting readonly attr %r on a property, "
2014 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2015 else:
2016 self.fail("expected AttributeError from trying to set readonly %r "
2017 "attr on a property" % attr)
2018
2019 class D(object):
2020 __getitem__ = property(lambda s: 1/0)
2021
2022 d = D()
2023 try:
2024 for i in d:
2025 str(i)
2026 except ZeroDivisionError:
2027 pass
2028 else:
2029 self.fail("expected ZeroDivisionError from bad property")
2030
R. David Murray378c0cf2010-02-24 01:46:21 +00002031 @unittest.skipIf(sys.flags.optimize >= 2,
2032 "Docstrings are omitted with -O2 and above")
2033 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002034 class E(object):
2035 def getter(self):
2036 "getter method"
2037 return 0
2038 def setter(self_, value):
2039 "setter method"
2040 pass
2041 prop = property(getter)
2042 self.assertEqual(prop.__doc__, "getter method")
2043 prop2 = property(fset=setter)
2044 self.assertEqual(prop2.__doc__, None)
2045
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002046 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002047 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002048 # this segfaulted in 2.5b2
2049 try:
2050 import _testcapi
2051 except ImportError:
2052 pass
2053 else:
2054 class X(object):
2055 p = property(_testcapi.test_with_docstring)
2056
2057 def test_properties_plus(self):
2058 class C(object):
2059 foo = property(doc="hello")
2060 @foo.getter
2061 def foo(self):
2062 return self._foo
2063 @foo.setter
2064 def foo(self, value):
2065 self._foo = abs(value)
2066 @foo.deleter
2067 def foo(self):
2068 del self._foo
2069 c = C()
2070 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002071 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002072 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002073 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002074 self.assertEqual(c._foo, 42)
2075 self.assertEqual(c.foo, 42)
2076 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002077 self.assertNotHasAttr(c, '_foo')
2078 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002079
2080 class D(C):
2081 @C.foo.deleter
2082 def foo(self):
2083 try:
2084 del self._foo
2085 except AttributeError:
2086 pass
2087 d = D()
2088 d.foo = 24
2089 self.assertEqual(d.foo, 24)
2090 del d.foo
2091 del d.foo
2092
2093 class E(object):
2094 @property
2095 def foo(self):
2096 return self._foo
2097 @foo.setter
2098 def foo(self, value):
2099 raise RuntimeError
2100 @foo.setter
2101 def foo(self, value):
2102 self._foo = abs(value)
2103 @foo.deleter
2104 def foo(self, value=None):
2105 del self._foo
2106
2107 e = E()
2108 e.foo = -42
2109 self.assertEqual(e.foo, 42)
2110 del e.foo
2111
2112 class F(E):
2113 @E.foo.deleter
2114 def foo(self):
2115 del self._foo
2116 @foo.setter
2117 def foo(self, value):
2118 self._foo = max(0, value)
2119 f = F()
2120 f.foo = -10
2121 self.assertEqual(f.foo, 0)
2122 del f.foo
2123
2124 def test_dict_constructors(self):
2125 # Testing dict constructor ...
2126 d = dict()
2127 self.assertEqual(d, {})
2128 d = dict({})
2129 self.assertEqual(d, {})
2130 d = dict({1: 2, 'a': 'b'})
2131 self.assertEqual(d, {1: 2, 'a': 'b'})
2132 self.assertEqual(d, dict(list(d.items())))
2133 self.assertEqual(d, dict(iter(d.items())))
2134 d = dict({'one':1, 'two':2})
2135 self.assertEqual(d, dict(one=1, two=2))
2136 self.assertEqual(d, dict(**d))
2137 self.assertEqual(d, dict({"one": 1}, two=2))
2138 self.assertEqual(d, dict([("two", 2)], one=1))
2139 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2140 self.assertEqual(d, dict(**d))
2141
2142 for badarg in 0, 0, 0j, "0", [0], (0,):
2143 try:
2144 dict(badarg)
2145 except TypeError:
2146 pass
2147 except ValueError:
2148 if badarg == "0":
2149 # It's a sequence, and its elements are also sequences (gotta
2150 # love strings <wink>), but they aren't of length 2, so this
2151 # one seemed better as a ValueError than a TypeError.
2152 pass
2153 else:
2154 self.fail("no TypeError from dict(%r)" % badarg)
2155 else:
2156 self.fail("no TypeError from dict(%r)" % badarg)
2157
2158 try:
2159 dict({}, {})
2160 except TypeError:
2161 pass
2162 else:
2163 self.fail("no TypeError from dict({}, {})")
2164
2165 class Mapping:
2166 # Lacks a .keys() method; will be added later.
2167 dict = {1:2, 3:4, 'a':1j}
2168
2169 try:
2170 dict(Mapping())
2171 except TypeError:
2172 pass
2173 else:
2174 self.fail("no TypeError from dict(incomplete mapping)")
2175
2176 Mapping.keys = lambda self: list(self.dict.keys())
2177 Mapping.__getitem__ = lambda self, i: self.dict[i]
2178 d = dict(Mapping())
2179 self.assertEqual(d, Mapping.dict)
2180
2181 # Init from sequence of iterable objects, each producing a 2-sequence.
2182 class AddressBookEntry:
2183 def __init__(self, first, last):
2184 self.first = first
2185 self.last = last
2186 def __iter__(self):
2187 return iter([self.first, self.last])
2188
2189 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2190 AddressBookEntry('Barry', 'Peters'),
2191 AddressBookEntry('Tim', 'Peters'),
2192 AddressBookEntry('Barry', 'Warsaw')])
2193 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2194
2195 d = dict(zip(range(4), range(1, 5)))
2196 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2197
2198 # Bad sequence lengths.
2199 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2200 try:
2201 dict(bad)
2202 except ValueError:
2203 pass
2204 else:
2205 self.fail("no ValueError from dict(%r)" % bad)
2206
2207 def test_dir(self):
2208 # Testing dir() ...
2209 junk = 12
2210 self.assertEqual(dir(), ['junk', 'self'])
2211 del junk
2212
2213 # Just make sure these don't blow up!
2214 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2215 dir(arg)
2216
2217 # Test dir on new-style classes. Since these have object as a
2218 # base class, a lot more gets sucked in.
2219 def interesting(strings):
2220 return [s for s in strings if not s.startswith('_')]
2221
2222 class C(object):
2223 Cdata = 1
2224 def Cmethod(self): pass
2225
2226 cstuff = ['Cdata', 'Cmethod']
2227 self.assertEqual(interesting(dir(C)), cstuff)
2228
2229 c = C()
2230 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002231 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002232
2233 c.cdata = 2
2234 c.cmethod = lambda self: 0
2235 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002236 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002237
2238 class A(C):
2239 Adata = 1
2240 def Amethod(self): pass
2241
2242 astuff = ['Adata', 'Amethod'] + cstuff
2243 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002244 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002245 a = A()
2246 self.assertEqual(interesting(dir(a)), astuff)
2247 a.adata = 42
2248 a.amethod = lambda self: 3
2249 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002250 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002251
2252 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002253 class M(type(sys)):
2254 pass
2255 minstance = M("m")
2256 minstance.b = 2
2257 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002258 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002259 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002260 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002261 self.assertEqual(names, ['a', 'b'])
2262
2263 class M2(M):
2264 def getdict(self):
2265 return "Not a dict!"
2266 __dict__ = property(getdict)
2267
2268 m2instance = M2("m2")
2269 m2instance.b = 2
2270 m2instance.a = 1
2271 self.assertEqual(m2instance.__dict__, "Not a dict!")
2272 try:
2273 dir(m2instance)
2274 except TypeError:
2275 pass
2276
2277 # Two essentially featureless objects, just inheriting stuff from
2278 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002279 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002280
2281 # Nasty test case for proxied objects
2282 class Wrapper(object):
2283 def __init__(self, obj):
2284 self.__obj = obj
2285 def __repr__(self):
2286 return "Wrapper(%s)" % repr(self.__obj)
2287 def __getitem__(self, key):
2288 return Wrapper(self.__obj[key])
2289 def __len__(self):
2290 return len(self.__obj)
2291 def __getattr__(self, name):
2292 return Wrapper(getattr(self.__obj, name))
2293
2294 class C(object):
2295 def __getclass(self):
2296 return Wrapper(type(self))
2297 __class__ = property(__getclass)
2298
2299 dir(C()) # This used to segfault
2300
2301 def test_supers(self):
2302 # Testing super...
2303
2304 class A(object):
2305 def meth(self, a):
2306 return "A(%r)" % a
2307
2308 self.assertEqual(A().meth(1), "A(1)")
2309
2310 class B(A):
2311 def __init__(self):
2312 self.__super = super(B, self)
2313 def meth(self, a):
2314 return "B(%r)" % a + self.__super.meth(a)
2315
2316 self.assertEqual(B().meth(2), "B(2)A(2)")
2317
2318 class C(A):
2319 def meth(self, a):
2320 return "C(%r)" % a + self.__super.meth(a)
2321 C._C__super = super(C)
2322
2323 self.assertEqual(C().meth(3), "C(3)A(3)")
2324
2325 class D(C, B):
2326 def meth(self, a):
2327 return "D(%r)" % a + super(D, self).meth(a)
2328
2329 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2330
2331 # Test for subclassing super
2332
2333 class mysuper(super):
2334 def __init__(self, *args):
2335 return super(mysuper, self).__init__(*args)
2336
2337 class E(D):
2338 def meth(self, a):
2339 return "E(%r)" % a + mysuper(E, self).meth(a)
2340
2341 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2342
2343 class F(E):
2344 def meth(self, a):
2345 s = self.__super # == mysuper(F, self)
2346 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2347 F._F__super = mysuper(F)
2348
2349 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2350
2351 # Make sure certain errors are raised
2352
2353 try:
2354 super(D, 42)
2355 except TypeError:
2356 pass
2357 else:
2358 self.fail("shouldn't allow super(D, 42)")
2359
2360 try:
2361 super(D, C())
2362 except TypeError:
2363 pass
2364 else:
2365 self.fail("shouldn't allow super(D, C())")
2366
2367 try:
2368 super(D).__get__(12)
2369 except TypeError:
2370 pass
2371 else:
2372 self.fail("shouldn't allow super(D).__get__(12)")
2373
2374 try:
2375 super(D).__get__(C())
2376 except TypeError:
2377 pass
2378 else:
2379 self.fail("shouldn't allow super(D).__get__(C())")
2380
2381 # Make sure data descriptors can be overridden and accessed via super
2382 # (new feature in Python 2.3)
2383
2384 class DDbase(object):
2385 def getx(self): return 42
2386 x = property(getx)
2387
2388 class DDsub(DDbase):
2389 def getx(self): return "hello"
2390 x = property(getx)
2391
2392 dd = DDsub()
2393 self.assertEqual(dd.x, "hello")
2394 self.assertEqual(super(DDsub, dd).x, 42)
2395
2396 # Ensure that super() lookup of descriptor from classmethod
2397 # works (SF ID# 743627)
2398
2399 class Base(object):
2400 aProp = property(lambda self: "foo")
2401
2402 class Sub(Base):
2403 @classmethod
2404 def test(klass):
2405 return super(Sub,klass).aProp
2406
2407 self.assertEqual(Sub.test(), Base.aProp)
2408
2409 # Verify that super() doesn't allow keyword args
2410 try:
2411 super(Base, kw=1)
2412 except TypeError:
2413 pass
2414 else:
2415 self.assertEqual("super shouldn't accept keyword args")
2416
2417 def test_basic_inheritance(self):
2418 # Testing inheritance from basic types...
2419
2420 class hexint(int):
2421 def __repr__(self):
2422 return hex(self)
2423 def __add__(self, other):
2424 return hexint(int.__add__(self, other))
2425 # (Note that overriding __radd__ doesn't work,
2426 # because the int type gets first dibs.)
2427 self.assertEqual(repr(hexint(7) + 9), "0x10")
2428 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2429 a = hexint(12345)
2430 self.assertEqual(a, 12345)
2431 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002432 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002433 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002434 self.assertIs((+a).__class__, int)
2435 self.assertIs((a >> 0).__class__, int)
2436 self.assertIs((a << 0).__class__, int)
2437 self.assertIs((hexint(0) << 12).__class__, int)
2438 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439
2440 class octlong(int):
2441 __slots__ = []
2442 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002443 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002444 def __add__(self, other):
2445 return self.__class__(super(octlong, self).__add__(other))
2446 __radd__ = __add__
2447 self.assertEqual(str(octlong(3) + 5), "0o10")
2448 # (Note that overriding __radd__ here only seems to work
2449 # because the example uses a short int left argument.)
2450 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2451 a = octlong(12345)
2452 self.assertEqual(a, 12345)
2453 self.assertEqual(int(a), 12345)
2454 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002455 self.assertIs(int(a).__class__, int)
2456 self.assertIs((+a).__class__, int)
2457 self.assertIs((-a).__class__, int)
2458 self.assertIs((-octlong(0)).__class__, int)
2459 self.assertIs((a >> 0).__class__, int)
2460 self.assertIs((a << 0).__class__, int)
2461 self.assertIs((a - 0).__class__, int)
2462 self.assertIs((a * 1).__class__, int)
2463 self.assertIs((a ** 1).__class__, int)
2464 self.assertIs((a // 1).__class__, int)
2465 self.assertIs((1 * a).__class__, int)
2466 self.assertIs((a | 0).__class__, int)
2467 self.assertIs((a ^ 0).__class__, int)
2468 self.assertIs((a & -1).__class__, int)
2469 self.assertIs((octlong(0) << 12).__class__, int)
2470 self.assertIs((octlong(0) >> 12).__class__, int)
2471 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002472
2473 # Because octlong overrides __add__, we can't check the absence of +0
2474 # optimizations using octlong.
2475 class longclone(int):
2476 pass
2477 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002478 self.assertIs((a + 0).__class__, int)
2479 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002480
2481 # Check that negative clones don't segfault
2482 a = longclone(-1)
2483 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002484 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002485
2486 class precfloat(float):
2487 __slots__ = ['prec']
2488 def __init__(self, value=0.0, prec=12):
2489 self.prec = int(prec)
2490 def __repr__(self):
2491 return "%.*g" % (self.prec, self)
2492 self.assertEqual(repr(precfloat(1.1)), "1.1")
2493 a = precfloat(12345)
2494 self.assertEqual(a, 12345.0)
2495 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002496 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002497 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002498 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002499
2500 class madcomplex(complex):
2501 def __repr__(self):
2502 return "%.17gj%+.17g" % (self.imag, self.real)
2503 a = madcomplex(-3, 4)
2504 self.assertEqual(repr(a), "4j-3")
2505 base = complex(-3, 4)
2506 self.assertEqual(base.__class__, complex)
2507 self.assertEqual(a, base)
2508 self.assertEqual(complex(a), base)
2509 self.assertEqual(complex(a).__class__, complex)
2510 a = madcomplex(a) # just trying another form of the constructor
2511 self.assertEqual(repr(a), "4j-3")
2512 self.assertEqual(a, base)
2513 self.assertEqual(complex(a), base)
2514 self.assertEqual(complex(a).__class__, complex)
2515 self.assertEqual(hash(a), hash(base))
2516 self.assertEqual((+a).__class__, complex)
2517 self.assertEqual((a + 0).__class__, complex)
2518 self.assertEqual(a + 0, base)
2519 self.assertEqual((a - 0).__class__, complex)
2520 self.assertEqual(a - 0, base)
2521 self.assertEqual((a * 1).__class__, complex)
2522 self.assertEqual(a * 1, base)
2523 self.assertEqual((a / 1).__class__, complex)
2524 self.assertEqual(a / 1, base)
2525
2526 class madtuple(tuple):
2527 _rev = None
2528 def rev(self):
2529 if self._rev is not None:
2530 return self._rev
2531 L = list(self)
2532 L.reverse()
2533 self._rev = self.__class__(L)
2534 return self._rev
2535 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2536 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2537 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2538 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2539 for i in range(512):
2540 t = madtuple(range(i))
2541 u = t.rev()
2542 v = u.rev()
2543 self.assertEqual(v, t)
2544 a = madtuple((1,2,3,4,5))
2545 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002546 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002547 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002548 self.assertIs(a[:].__class__, tuple)
2549 self.assertIs((a * 1).__class__, tuple)
2550 self.assertIs((a * 0).__class__, tuple)
2551 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002552 a = madtuple(())
2553 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002554 self.assertIs(tuple(a).__class__, tuple)
2555 self.assertIs((a + a).__class__, tuple)
2556 self.assertIs((a * 0).__class__, tuple)
2557 self.assertIs((a * 1).__class__, tuple)
2558 self.assertIs((a * 2).__class__, tuple)
2559 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002560
2561 class madstring(str):
2562 _rev = None
2563 def rev(self):
2564 if self._rev is not None:
2565 return self._rev
2566 L = list(self)
2567 L.reverse()
2568 self._rev = self.__class__("".join(L))
2569 return self._rev
2570 s = madstring("abcdefghijklmnopqrstuvwxyz")
2571 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2572 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2573 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2574 for i in range(256):
2575 s = madstring("".join(map(chr, range(i))))
2576 t = s.rev()
2577 u = t.rev()
2578 self.assertEqual(u, s)
2579 s = madstring("12345")
2580 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002581 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582
2583 base = "\x00" * 5
2584 s = madstring(base)
2585 self.assertEqual(s, base)
2586 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002587 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002588 self.assertEqual(hash(s), hash(base))
2589 self.assertEqual({s: 1}[base], 1)
2590 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002591 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002592 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002593 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002594 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002595 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002596 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002597 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002598 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002599 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002600 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002601 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002602 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002603 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002604 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002605 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002606 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002607 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002608 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002609 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002610 self.assertEqual(s.rstrip(), base)
2611 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002612 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002613 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002614 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002615 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002616 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002618 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002619 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002620 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002622 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002623 self.assertEqual(s.lower(), base)
2624
2625 class madunicode(str):
2626 _rev = None
2627 def rev(self):
2628 if self._rev is not None:
2629 return self._rev
2630 L = list(self)
2631 L.reverse()
2632 self._rev = self.__class__("".join(L))
2633 return self._rev
2634 u = madunicode("ABCDEF")
2635 self.assertEqual(u, "ABCDEF")
2636 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2637 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2638 base = "12345"
2639 u = madunicode(base)
2640 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002641 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002642 self.assertEqual(hash(u), hash(base))
2643 self.assertEqual({u: 1}[base], 1)
2644 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002645 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002646 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002647 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002649 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002651 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002652 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002653 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002654 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002655 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002656 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002657 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002658 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002659 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002660 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002661 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002662 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002663 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002664 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002665 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002666 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002667 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002668 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002669 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002670 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002671 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002672 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002673 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002674 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002675 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002676 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002677 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002678 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002679 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002680 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002681 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682 self.assertEqual(u[0:0], "")
2683
2684 class sublist(list):
2685 pass
2686 a = sublist(range(5))
2687 self.assertEqual(a, list(range(5)))
2688 a.append("hello")
2689 self.assertEqual(a, list(range(5)) + ["hello"])
2690 a[5] = 5
2691 self.assertEqual(a, list(range(6)))
2692 a.extend(range(6, 20))
2693 self.assertEqual(a, list(range(20)))
2694 a[-5:] = []
2695 self.assertEqual(a, list(range(15)))
2696 del a[10:15]
2697 self.assertEqual(len(a), 10)
2698 self.assertEqual(a, list(range(10)))
2699 self.assertEqual(list(a), list(range(10)))
2700 self.assertEqual(a[0], 0)
2701 self.assertEqual(a[9], 9)
2702 self.assertEqual(a[-10], 0)
2703 self.assertEqual(a[-1], 9)
2704 self.assertEqual(a[:5], list(range(5)))
2705
2706 ## class CountedInput(file):
2707 ## """Counts lines read by self.readline().
2708 ##
2709 ## self.lineno is the 0-based ordinal of the last line read, up to
2710 ## a maximum of one greater than the number of lines in the file.
2711 ##
2712 ## self.ateof is true if and only if the final "" line has been read,
2713 ## at which point self.lineno stops incrementing, and further calls
2714 ## to readline() continue to return "".
2715 ## """
2716 ##
2717 ## lineno = 0
2718 ## ateof = 0
2719 ## def readline(self):
2720 ## if self.ateof:
2721 ## return ""
2722 ## s = file.readline(self)
2723 ## # Next line works too.
2724 ## # s = super(CountedInput, self).readline()
2725 ## self.lineno += 1
2726 ## if s == "":
2727 ## self.ateof = 1
2728 ## return s
2729 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002730 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002731 ## lines = ['a\n', 'b\n', 'c\n']
2732 ## try:
2733 ## f.writelines(lines)
2734 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002735 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002736 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2737 ## got = f.readline()
2738 ## self.assertEqual(expected, got)
2739 ## self.assertEqual(f.lineno, i)
2740 ## self.assertEqual(f.ateof, (i > len(lines)))
2741 ## f.close()
2742 ## finally:
2743 ## try:
2744 ## f.close()
2745 ## except:
2746 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002747 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002748
2749 def test_keywords(self):
2750 # Testing keyword args to basic type constructors ...
2751 self.assertEqual(int(x=1), 1)
2752 self.assertEqual(float(x=2), 2.0)
2753 self.assertEqual(int(x=3), 3)
2754 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2755 self.assertEqual(str(object=500), '500')
2756 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2757 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2758 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2759 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2760
2761 for constructor in (int, float, int, complex, str, str,
2762 tuple, list):
2763 try:
2764 constructor(bogus_keyword_arg=1)
2765 except TypeError:
2766 pass
2767 else:
2768 self.fail("expected TypeError from bogus keyword argument to %r"
2769 % constructor)
2770
2771 def test_str_subclass_as_dict_key(self):
2772 # Testing a str subclass used as dict key ..
2773
2774 class cistr(str):
2775 """Sublcass of str that computes __eq__ case-insensitively.
2776
2777 Also computes a hash code of the string in canonical form.
2778 """
2779
2780 def __init__(self, value):
2781 self.canonical = value.lower()
2782 self.hashcode = hash(self.canonical)
2783
2784 def __eq__(self, other):
2785 if not isinstance(other, cistr):
2786 other = cistr(other)
2787 return self.canonical == other.canonical
2788
2789 def __hash__(self):
2790 return self.hashcode
2791
2792 self.assertEqual(cistr('ABC'), 'abc')
2793 self.assertEqual('aBc', cistr('ABC'))
2794 self.assertEqual(str(cistr('ABC')), 'ABC')
2795
2796 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2797 self.assertEqual(d[cistr('one')], 1)
2798 self.assertEqual(d[cistr('tWo')], 2)
2799 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002800 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002801 self.assertEqual(d.get(cistr('thrEE')), 3)
2802
2803 def test_classic_comparisons(self):
2804 # Testing classic comparisons...
2805 class classic:
2806 pass
2807
2808 for base in (classic, int, object):
2809 class C(base):
2810 def __init__(self, value):
2811 self.value = int(value)
2812 def __eq__(self, other):
2813 if isinstance(other, C):
2814 return self.value == other.value
2815 if isinstance(other, int) or isinstance(other, int):
2816 return self.value == other
2817 return NotImplemented
2818 def __ne__(self, other):
2819 if isinstance(other, C):
2820 return self.value != other.value
2821 if isinstance(other, int) or isinstance(other, int):
2822 return self.value != other
2823 return NotImplemented
2824 def __lt__(self, other):
2825 if isinstance(other, C):
2826 return self.value < other.value
2827 if isinstance(other, int) or isinstance(other, int):
2828 return self.value < other
2829 return NotImplemented
2830 def __le__(self, other):
2831 if isinstance(other, C):
2832 return self.value <= other.value
2833 if isinstance(other, int) or isinstance(other, int):
2834 return self.value <= other
2835 return NotImplemented
2836 def __gt__(self, other):
2837 if isinstance(other, C):
2838 return self.value > other.value
2839 if isinstance(other, int) or isinstance(other, int):
2840 return self.value > other
2841 return NotImplemented
2842 def __ge__(self, other):
2843 if isinstance(other, C):
2844 return self.value >= other.value
2845 if isinstance(other, int) or isinstance(other, int):
2846 return self.value >= other
2847 return NotImplemented
2848
2849 c1 = C(1)
2850 c2 = C(2)
2851 c3 = C(3)
2852 self.assertEqual(c1, 1)
2853 c = {1: c1, 2: c2, 3: c3}
2854 for x in 1, 2, 3:
2855 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002856 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002858 eval("x %s y" % op),
2859 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002860 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002861 eval("x %s y" % op),
2862 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002864 eval("x %s y" % op),
2865 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002866
2867 def test_rich_comparisons(self):
2868 # Testing rich comparisons...
2869 class Z(complex):
2870 pass
2871 z = Z(1)
2872 self.assertEqual(z, 1+0j)
2873 self.assertEqual(1+0j, z)
2874 class ZZ(complex):
2875 def __eq__(self, other):
2876 try:
2877 return abs(self - other) <= 1e-6
2878 except:
2879 return NotImplemented
2880 zz = ZZ(1.0000003)
2881 self.assertEqual(zz, 1+0j)
2882 self.assertEqual(1+0j, zz)
2883
2884 class classic:
2885 pass
2886 for base in (classic, int, object, list):
2887 class C(base):
2888 def __init__(self, value):
2889 self.value = int(value)
2890 def __cmp__(self_, other):
2891 self.fail("shouldn't call __cmp__")
2892 def __eq__(self, other):
2893 if isinstance(other, C):
2894 return self.value == other.value
2895 if isinstance(other, int) or isinstance(other, int):
2896 return self.value == other
2897 return NotImplemented
2898 def __ne__(self, other):
2899 if isinstance(other, C):
2900 return self.value != other.value
2901 if isinstance(other, int) or isinstance(other, int):
2902 return self.value != other
2903 return NotImplemented
2904 def __lt__(self, other):
2905 if isinstance(other, C):
2906 return self.value < other.value
2907 if isinstance(other, int) or isinstance(other, int):
2908 return self.value < other
2909 return NotImplemented
2910 def __le__(self, other):
2911 if isinstance(other, C):
2912 return self.value <= other.value
2913 if isinstance(other, int) or isinstance(other, int):
2914 return self.value <= other
2915 return NotImplemented
2916 def __gt__(self, other):
2917 if isinstance(other, C):
2918 return self.value > other.value
2919 if isinstance(other, int) or isinstance(other, int):
2920 return self.value > other
2921 return NotImplemented
2922 def __ge__(self, other):
2923 if isinstance(other, C):
2924 return self.value >= other.value
2925 if isinstance(other, int) or isinstance(other, int):
2926 return self.value >= other
2927 return NotImplemented
2928 c1 = C(1)
2929 c2 = C(2)
2930 c3 = C(3)
2931 self.assertEqual(c1, 1)
2932 c = {1: c1, 2: c2, 3: c3}
2933 for x in 1, 2, 3:
2934 for y in 1, 2, 3:
2935 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002936 self.assertEqual(eval("c[x] %s c[y]" % op),
2937 eval("x %s y" % op),
2938 "x=%d, y=%d" % (x, y))
2939 self.assertEqual(eval("c[x] %s y" % op),
2940 eval("x %s y" % op),
2941 "x=%d, y=%d" % (x, y))
2942 self.assertEqual(eval("x %s c[y]" % op),
2943 eval("x %s y" % op),
2944 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002945
2946 def test_descrdoc(self):
2947 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002948 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002949 def check(descr, what):
2950 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002951 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002952 check(complex.real, "the real part of a complex number") # member descriptor
2953
2954 def test_doc_descriptor(self):
2955 # Testing __doc__ descriptor...
2956 # SF bug 542984
2957 class DocDescr(object):
2958 def __get__(self, object, otype):
2959 if object:
2960 object = object.__class__.__name__ + ' instance'
2961 if otype:
2962 otype = otype.__name__
2963 return 'object=%s; type=%s' % (object, otype)
2964 class OldClass:
2965 __doc__ = DocDescr()
2966 class NewClass(object):
2967 __doc__ = DocDescr()
2968 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2969 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2970 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2971 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2972
2973 def test_set_class(self):
2974 # Testing __class__ assignment...
2975 class C(object): pass
2976 class D(object): pass
2977 class E(object): pass
2978 class F(D, E): pass
2979 for cls in C, D, E, F:
2980 for cls2 in C, D, E, F:
2981 x = cls()
2982 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002983 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002984 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002985 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002986 def cant(x, C):
2987 try:
2988 x.__class__ = C
2989 except TypeError:
2990 pass
2991 else:
2992 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2993 try:
2994 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002995 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002996 pass
2997 else:
2998 self.fail("shouldn't allow del %r.__class__" % x)
2999 cant(C(), list)
3000 cant(list(), C)
3001 cant(C(), 1)
3002 cant(C(), object)
3003 cant(object(), list)
3004 cant(list(), object)
3005 class Int(int): __slots__ = []
3006 cant(2, Int)
3007 cant(Int(), int)
3008 cant(True, int)
3009 cant(2, bool)
3010 o = object()
3011 cant(o, type(1))
3012 cant(o, type(None))
3013 del o
3014 class G(object):
3015 __slots__ = ["a", "b"]
3016 class H(object):
3017 __slots__ = ["b", "a"]
3018 class I(object):
3019 __slots__ = ["a", "b"]
3020 class J(object):
3021 __slots__ = ["c", "b"]
3022 class K(object):
3023 __slots__ = ["a", "b", "d"]
3024 class L(H):
3025 __slots__ = ["e"]
3026 class M(I):
3027 __slots__ = ["e"]
3028 class N(J):
3029 __slots__ = ["__weakref__"]
3030 class P(J):
3031 __slots__ = ["__dict__"]
3032 class Q(J):
3033 pass
3034 class R(J):
3035 __slots__ = ["__dict__", "__weakref__"]
3036
3037 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3038 x = cls()
3039 x.a = 1
3040 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003041 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003042 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3043 self.assertEqual(x.a, 1)
3044 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003045 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003046 "assigning %r as __class__ for %r silently failed" % (cls, x))
3047 self.assertEqual(x.a, 1)
3048 for cls in G, J, K, L, M, N, P, R, list, Int:
3049 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3050 if cls is cls2:
3051 continue
3052 cant(cls(), cls2)
3053
Benjamin Peterson193152c2009-04-25 01:08:45 +00003054 # Issue5283: when __class__ changes in __del__, the wrong
3055 # type gets DECREF'd.
3056 class O(object):
3057 pass
3058 class A(object):
3059 def __del__(self):
3060 self.__class__ = O
3061 l = [A() for x in range(100)]
3062 del l
3063
Georg Brandl479a7e72008-02-05 18:13:15 +00003064 def test_set_dict(self):
3065 # Testing __dict__ assignment...
3066 class C(object): pass
3067 a = C()
3068 a.__dict__ = {'b': 1}
3069 self.assertEqual(a.b, 1)
3070 def cant(x, dict):
3071 try:
3072 x.__dict__ = dict
3073 except (AttributeError, TypeError):
3074 pass
3075 else:
3076 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3077 cant(a, None)
3078 cant(a, [])
3079 cant(a, 1)
3080 del a.__dict__ # Deleting __dict__ is allowed
3081
3082 class Base(object):
3083 pass
3084 def verify_dict_readonly(x):
3085 """
3086 x has to be an instance of a class inheriting from Base.
3087 """
3088 cant(x, {})
3089 try:
3090 del x.__dict__
3091 except (AttributeError, TypeError):
3092 pass
3093 else:
3094 self.fail("shouldn't allow del %r.__dict__" % x)
3095 dict_descr = Base.__dict__["__dict__"]
3096 try:
3097 dict_descr.__set__(x, {})
3098 except (AttributeError, TypeError):
3099 pass
3100 else:
3101 self.fail("dict_descr allowed access to %r's dict" % x)
3102
3103 # Classes don't allow __dict__ assignment and have readonly dicts
3104 class Meta1(type, Base):
3105 pass
3106 class Meta2(Base, type):
3107 pass
3108 class D(object, metaclass=Meta1):
3109 pass
3110 class E(object, metaclass=Meta2):
3111 pass
3112 for cls in C, D, E:
3113 verify_dict_readonly(cls)
3114 class_dict = cls.__dict__
3115 try:
3116 class_dict["spam"] = "eggs"
3117 except TypeError:
3118 pass
3119 else:
3120 self.fail("%r's __dict__ can be modified" % cls)
3121
3122 # Modules also disallow __dict__ assignment
3123 class Module1(types.ModuleType, Base):
3124 pass
3125 class Module2(Base, types.ModuleType):
3126 pass
3127 for ModuleType in Module1, Module2:
3128 mod = ModuleType("spam")
3129 verify_dict_readonly(mod)
3130 mod.__dict__["spam"] = "eggs"
3131
3132 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003133 # (at least not any more than regular exception's __dict__ can
3134 # be deleted; on CPython it is not the case, whereas on PyPy they
3135 # can, just like any other new-style instance's __dict__.)
3136 def can_delete_dict(e):
3137 try:
3138 del e.__dict__
3139 except (TypeError, AttributeError):
3140 return False
3141 else:
3142 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003143 class Exception1(Exception, Base):
3144 pass
3145 class Exception2(Base, Exception):
3146 pass
3147 for ExceptionType in Exception, Exception1, Exception2:
3148 e = ExceptionType()
3149 e.__dict__ = {"a": 1}
3150 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003151 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003152
Georg Brandl479a7e72008-02-05 18:13:15 +00003153 def test_binary_operator_override(self):
3154 # Testing overrides of binary operations...
3155 class I(int):
3156 def __repr__(self):
3157 return "I(%r)" % int(self)
3158 def __add__(self, other):
3159 return I(int(self) + int(other))
3160 __radd__ = __add__
3161 def __pow__(self, other, mod=None):
3162 if mod is None:
3163 return I(pow(int(self), int(other)))
3164 else:
3165 return I(pow(int(self), int(other), int(mod)))
3166 def __rpow__(self, other, mod=None):
3167 if mod is None:
3168 return I(pow(int(other), int(self), mod))
3169 else:
3170 return I(pow(int(other), int(self), int(mod)))
3171
3172 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3173 self.assertEqual(repr(I(1) + 2), "I(3)")
3174 self.assertEqual(repr(1 + I(2)), "I(3)")
3175 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3176 self.assertEqual(repr(2 ** I(3)), "I(8)")
3177 self.assertEqual(repr(I(2) ** 3), "I(8)")
3178 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3179 class S(str):
3180 def __eq__(self, other):
3181 return self.lower() == other.lower()
3182
3183 def test_subclass_propagation(self):
3184 # Testing propagation of slot functions to subclasses...
3185 class A(object):
3186 pass
3187 class B(A):
3188 pass
3189 class C(A):
3190 pass
3191 class D(B, C):
3192 pass
3193 d = D()
3194 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3195 A.__hash__ = lambda self: 42
3196 self.assertEqual(hash(d), 42)
3197 C.__hash__ = lambda self: 314
3198 self.assertEqual(hash(d), 314)
3199 B.__hash__ = lambda self: 144
3200 self.assertEqual(hash(d), 144)
3201 D.__hash__ = lambda self: 100
3202 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003203 D.__hash__ = None
3204 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003205 del D.__hash__
3206 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003207 B.__hash__ = None
3208 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003209 del B.__hash__
3210 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003211 C.__hash__ = None
3212 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003213 del C.__hash__
3214 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003215 A.__hash__ = None
3216 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003217 del A.__hash__
3218 self.assertEqual(hash(d), orig_hash)
3219 d.foo = 42
3220 d.bar = 42
3221 self.assertEqual(d.foo, 42)
3222 self.assertEqual(d.bar, 42)
3223 def __getattribute__(self, name):
3224 if name == "foo":
3225 return 24
3226 return object.__getattribute__(self, name)
3227 A.__getattribute__ = __getattribute__
3228 self.assertEqual(d.foo, 24)
3229 self.assertEqual(d.bar, 42)
3230 def __getattr__(self, name):
3231 if name in ("spam", "foo", "bar"):
3232 return "hello"
3233 raise AttributeError(name)
3234 B.__getattr__ = __getattr__
3235 self.assertEqual(d.spam, "hello")
3236 self.assertEqual(d.foo, 24)
3237 self.assertEqual(d.bar, 42)
3238 del A.__getattribute__
3239 self.assertEqual(d.foo, 42)
3240 del d.foo
3241 self.assertEqual(d.foo, "hello")
3242 self.assertEqual(d.bar, 42)
3243 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003244 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003245 d.foo
3246 except AttributeError:
3247 pass
3248 else:
3249 self.fail("d.foo should be undefined now")
3250
3251 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003252 class A(object):
3253 pass
3254 class B(A):
3255 pass
3256 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003257 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003258 A.__setitem__ = lambda *a: None # crash
3259
3260 def test_buffer_inheritance(self):
3261 # Testing that buffer interface is inherited ...
3262
3263 import binascii
3264 # SF bug [#470040] ParseTuple t# vs subclasses.
3265
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003266 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003267 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003268 base = b'abc'
3269 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003270 # b2a_hex uses the buffer interface to get its argument's value, via
3271 # PyArg_ParseTuple 't#' code.
3272 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3273
Georg Brandl479a7e72008-02-05 18:13:15 +00003274 class MyInt(int):
3275 pass
3276 m = MyInt(42)
3277 try:
3278 binascii.b2a_hex(m)
3279 self.fail('subclass of int should not have a buffer interface')
3280 except TypeError:
3281 pass
3282
3283 def test_str_of_str_subclass(self):
3284 # Testing __str__ defined in subclass of str ...
3285 import binascii
3286 import io
3287
3288 class octetstring(str):
3289 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003290 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003291 def __repr__(self):
3292 return self + " repr"
3293
3294 o = octetstring('A')
3295 self.assertEqual(type(o), octetstring)
3296 self.assertEqual(type(str(o)), str)
3297 self.assertEqual(type(repr(o)), str)
3298 self.assertEqual(ord(o), 0x41)
3299 self.assertEqual(str(o), '41')
3300 self.assertEqual(repr(o), 'A repr')
3301 self.assertEqual(o.__str__(), '41')
3302 self.assertEqual(o.__repr__(), 'A repr')
3303
3304 capture = io.StringIO()
3305 # Calling str() or not exercises different internal paths.
3306 print(o, file=capture)
3307 print(str(o), file=capture)
3308 self.assertEqual(capture.getvalue(), '41\n41\n')
3309 capture.close()
3310
3311 def test_keyword_arguments(self):
3312 # Testing keyword arguments to __init__, __call__...
3313 def f(a): return a
3314 self.assertEqual(f.__call__(a=42), 42)
3315 a = []
3316 list.__init__(a, sequence=[0, 1, 2])
3317 self.assertEqual(a, [0, 1, 2])
3318
3319 def test_recursive_call(self):
3320 # Testing recursive __call__() by setting to instance of class...
3321 class A(object):
3322 pass
3323
3324 A.__call__ = A()
3325 try:
3326 A()()
3327 except RuntimeError:
3328 pass
3329 else:
3330 self.fail("Recursion limit should have been reached for __call__()")
3331
3332 def test_delete_hook(self):
3333 # Testing __del__ hook...
3334 log = []
3335 class C(object):
3336 def __del__(self):
3337 log.append(1)
3338 c = C()
3339 self.assertEqual(log, [])
3340 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003341 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003342 self.assertEqual(log, [1])
3343
3344 class D(object): pass
3345 d = D()
3346 try: del d[0]
3347 except TypeError: pass
3348 else: self.fail("invalid del() didn't raise TypeError")
3349
3350 def test_hash_inheritance(self):
3351 # Testing hash of mutable subclasses...
3352
3353 class mydict(dict):
3354 pass
3355 d = mydict()
3356 try:
3357 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003358 except TypeError:
3359 pass
3360 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003361 self.fail("hash() of dict subclass should fail")
3362
3363 class mylist(list):
3364 pass
3365 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003366 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003367 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003368 except TypeError:
3369 pass
3370 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003371 self.fail("hash() of list subclass should fail")
3372
3373 def test_str_operations(self):
3374 try: 'a' + 5
3375 except TypeError: pass
3376 else: self.fail("'' + 5 doesn't raise TypeError")
3377
3378 try: ''.split('')
3379 except ValueError: pass
3380 else: self.fail("''.split('') doesn't raise ValueError")
3381
3382 try: ''.join([0])
3383 except TypeError: pass
3384 else: self.fail("''.join([0]) doesn't raise TypeError")
3385
3386 try: ''.rindex('5')
3387 except ValueError: pass
3388 else: self.fail("''.rindex('5') doesn't raise ValueError")
3389
3390 try: '%(n)s' % None
3391 except TypeError: pass
3392 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3393
3394 try: '%(n' % {}
3395 except ValueError: pass
3396 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3397
3398 try: '%*s' % ('abc')
3399 except TypeError: pass
3400 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3401
3402 try: '%*.*s' % ('abc', 5)
3403 except TypeError: pass
3404 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3405
3406 try: '%s' % (1, 2)
3407 except TypeError: pass
3408 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3409
3410 try: '%' % None
3411 except ValueError: pass
3412 else: self.fail("'%' % None doesn't raise ValueError")
3413
3414 self.assertEqual('534253'.isdigit(), 1)
3415 self.assertEqual('534253x'.isdigit(), 0)
3416 self.assertEqual('%c' % 5, '\x05')
3417 self.assertEqual('%c' % '5', '5')
3418
3419 def test_deepcopy_recursive(self):
3420 # Testing deepcopy of recursive objects...
3421 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003422 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003423 a = Node()
3424 b = Node()
3425 a.b = b
3426 b.a = a
3427 z = deepcopy(a) # This blew up before
3428
3429 def test_unintialized_modules(self):
3430 # Testing uninitialized module objects...
3431 from types import ModuleType as M
3432 m = M.__new__(M)
3433 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003434 self.assertNotHasAttr(m, "__name__")
3435 self.assertNotHasAttr(m, "__file__")
3436 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003437 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003438 m.foo = 1
3439 self.assertEqual(m.__dict__, {"foo": 1})
3440
3441 def test_funny_new(self):
3442 # Testing __new__ returning something unexpected...
3443 class C(object):
3444 def __new__(cls, arg):
3445 if isinstance(arg, str): return [1, 2, 3]
3446 elif isinstance(arg, int): return object.__new__(D)
3447 else: return object.__new__(cls)
3448 class D(C):
3449 def __init__(self, arg):
3450 self.foo = arg
3451 self.assertEqual(C("1"), [1, 2, 3])
3452 self.assertEqual(D("1"), [1, 2, 3])
3453 d = D(None)
3454 self.assertEqual(d.foo, None)
3455 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003456 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003457 self.assertEqual(d.foo, 1)
3458 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003459 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003460 self.assertEqual(d.foo, 1)
3461
3462 def test_imul_bug(self):
3463 # Testing for __imul__ problems...
3464 # SF bug 544647
3465 class C(object):
3466 def __imul__(self, other):
3467 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003468 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003469 y = x
3470 y *= 1.0
3471 self.assertEqual(y, (x, 1.0))
3472 y = x
3473 y *= 2
3474 self.assertEqual(y, (x, 2))
3475 y = x
3476 y *= 3
3477 self.assertEqual(y, (x, 3))
3478 y = x
3479 y *= 1<<100
3480 self.assertEqual(y, (x, 1<<100))
3481 y = x
3482 y *= None
3483 self.assertEqual(y, (x, None))
3484 y = x
3485 y *= "foo"
3486 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003487
Georg Brandl479a7e72008-02-05 18:13:15 +00003488 def test_copy_setstate(self):
3489 # Testing that copy.*copy() correctly uses __setstate__...
3490 import copy
3491 class C(object):
3492 def __init__(self, foo=None):
3493 self.foo = foo
3494 self.__foo = foo
3495 def setfoo(self, foo=None):
3496 self.foo = foo
3497 def getfoo(self):
3498 return self.__foo
3499 def __getstate__(self):
3500 return [self.foo]
3501 def __setstate__(self_, lst):
3502 self.assertEqual(len(lst), 1)
3503 self_.__foo = self_.foo = lst[0]
3504 a = C(42)
3505 a.setfoo(24)
3506 self.assertEqual(a.foo, 24)
3507 self.assertEqual(a.getfoo(), 42)
3508 b = copy.copy(a)
3509 self.assertEqual(b.foo, 24)
3510 self.assertEqual(b.getfoo(), 24)
3511 b = copy.deepcopy(a)
3512 self.assertEqual(b.foo, 24)
3513 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003514
Georg Brandl479a7e72008-02-05 18:13:15 +00003515 def test_slices(self):
3516 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003517
Georg Brandl479a7e72008-02-05 18:13:15 +00003518 # Strings
3519 self.assertEqual("hello"[:4], "hell")
3520 self.assertEqual("hello"[slice(4)], "hell")
3521 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3522 class S(str):
3523 def __getitem__(self, x):
3524 return str.__getitem__(self, x)
3525 self.assertEqual(S("hello")[:4], "hell")
3526 self.assertEqual(S("hello")[slice(4)], "hell")
3527 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3528 # Tuples
3529 self.assertEqual((1,2,3)[:2], (1,2))
3530 self.assertEqual((1,2,3)[slice(2)], (1,2))
3531 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3532 class T(tuple):
3533 def __getitem__(self, x):
3534 return tuple.__getitem__(self, x)
3535 self.assertEqual(T((1,2,3))[:2], (1,2))
3536 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3537 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3538 # Lists
3539 self.assertEqual([1,2,3][:2], [1,2])
3540 self.assertEqual([1,2,3][slice(2)], [1,2])
3541 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3542 class L(list):
3543 def __getitem__(self, x):
3544 return list.__getitem__(self, x)
3545 self.assertEqual(L([1,2,3])[:2], [1,2])
3546 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3547 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3548 # Now do lists and __setitem__
3549 a = L([1,2,3])
3550 a[slice(1, 3)] = [3,2]
3551 self.assertEqual(a, [1,3,2])
3552 a[slice(0, 2, 1)] = [3,1]
3553 self.assertEqual(a, [3,1,2])
3554 a.__setitem__(slice(1, 3), [2,1])
3555 self.assertEqual(a, [3,2,1])
3556 a.__setitem__(slice(0, 2, 1), [2,3])
3557 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003558
Georg Brandl479a7e72008-02-05 18:13:15 +00003559 def test_subtype_resurrection(self):
3560 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003561
Georg Brandl479a7e72008-02-05 18:13:15 +00003562 class C(object):
3563 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003564
Georg Brandl479a7e72008-02-05 18:13:15 +00003565 def __del__(self):
3566 # resurrect the instance
3567 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003568
Georg Brandl479a7e72008-02-05 18:13:15 +00003569 c = C()
3570 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003571
Benjamin Petersone549ead2009-03-28 21:42:05 +00003572 # The most interesting thing here is whether this blows up, due to
3573 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3574 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003575 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003576
Benjamin Petersone549ead2009-03-28 21:42:05 +00003577 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003578 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003579
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 # Make c mortal again, so that the test framework with -l doesn't report
3581 # it as a leak.
3582 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003583
Georg Brandl479a7e72008-02-05 18:13:15 +00003584 def test_slots_trash(self):
3585 # Testing slot trash...
3586 # Deallocating deeply nested slotted trash caused stack overflows
3587 class trash(object):
3588 __slots__ = ['x']
3589 def __init__(self, x):
3590 self.x = x
3591 o = None
3592 for i in range(50000):
3593 o = trash(o)
3594 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003595
Georg Brandl479a7e72008-02-05 18:13:15 +00003596 def test_slots_multiple_inheritance(self):
3597 # SF bug 575229, multiple inheritance w/ slots dumps core
3598 class A(object):
3599 __slots__=()
3600 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003601 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003602 class C(A,B) :
3603 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003604 if support.check_impl_detail():
3605 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003606 self.assertHasAttr(C, '__dict__')
3607 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003608 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003609
Georg Brandl479a7e72008-02-05 18:13:15 +00003610 def test_rmul(self):
3611 # Testing correct invocation of __rmul__...
3612 # SF patch 592646
3613 class C(object):
3614 def __mul__(self, other):
3615 return "mul"
3616 def __rmul__(self, other):
3617 return "rmul"
3618 a = C()
3619 self.assertEqual(a*2, "mul")
3620 self.assertEqual(a*2.2, "mul")
3621 self.assertEqual(2*a, "rmul")
3622 self.assertEqual(2.2*a, "rmul")
3623
3624 def test_ipow(self):
3625 # Testing correct invocation of __ipow__...
3626 # [SF bug 620179]
3627 class C(object):
3628 def __ipow__(self, other):
3629 pass
3630 a = C()
3631 a **= 2
3632
3633 def test_mutable_bases(self):
3634 # Testing mutable bases...
3635
3636 # stuff that should work:
3637 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003638 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003639 class C2(object):
3640 def __getattribute__(self, attr):
3641 if attr == 'a':
3642 return 2
3643 else:
3644 return super(C2, self).__getattribute__(attr)
3645 def meth(self):
3646 return 1
3647 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003648 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003649 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003650 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003651 d = D()
3652 e = E()
3653 D.__bases__ = (C,)
3654 D.__bases__ = (C2,)
3655 self.assertEqual(d.meth(), 1)
3656 self.assertEqual(e.meth(), 1)
3657 self.assertEqual(d.a, 2)
3658 self.assertEqual(e.a, 2)
3659 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003660
Georg Brandl479a7e72008-02-05 18:13:15 +00003661 try:
3662 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003663 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003664 pass
3665 else:
3666 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003667
Georg Brandl479a7e72008-02-05 18:13:15 +00003668 try:
3669 D.__bases__ = ()
3670 except TypeError as msg:
3671 if str(msg) == "a new-style class can't have only classic bases":
3672 self.fail("wrong error message for .__bases__ = ()")
3673 else:
3674 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003675
Georg Brandl479a7e72008-02-05 18:13:15 +00003676 try:
3677 D.__bases__ = (D,)
3678 except TypeError:
3679 pass
3680 else:
3681 # actually, we'll have crashed by here...
3682 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003683
Georg Brandl479a7e72008-02-05 18:13:15 +00003684 try:
3685 D.__bases__ = (C, C)
3686 except TypeError:
3687 pass
3688 else:
3689 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003690
Georg Brandl479a7e72008-02-05 18:13:15 +00003691 try:
3692 D.__bases__ = (E,)
3693 except TypeError:
3694 pass
3695 else:
3696 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003697
Benjamin Petersonae937c02009-04-18 20:54:08 +00003698 def test_builtin_bases(self):
3699 # Make sure all the builtin types can have their base queried without
3700 # segfaulting. See issue #5787.
3701 builtin_types = [tp for tp in builtins.__dict__.values()
3702 if isinstance(tp, type)]
3703 for tp in builtin_types:
3704 object.__getattribute__(tp, "__bases__")
3705 if tp is not object:
3706 self.assertEqual(len(tp.__bases__), 1, tp)
3707
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003708 class L(list):
3709 pass
3710
3711 class C(object):
3712 pass
3713
3714 class D(C):
3715 pass
3716
3717 try:
3718 L.__bases__ = (dict,)
3719 except TypeError:
3720 pass
3721 else:
3722 self.fail("shouldn't turn list subclass into dict subclass")
3723
3724 try:
3725 list.__bases__ = (dict,)
3726 except TypeError:
3727 pass
3728 else:
3729 self.fail("shouldn't be able to assign to list.__bases__")
3730
3731 try:
3732 D.__bases__ = (C, list)
3733 except TypeError:
3734 pass
3735 else:
3736 assert 0, "best_base calculation found wanting"
3737
Benjamin Petersonbd6c41a2015-10-06 19:36:54 -07003738 def test_unsubclassable_types(self):
3739 with self.assertRaises(TypeError):
3740 class X(type(None)):
3741 pass
3742 with self.assertRaises(TypeError):
3743 class X(object, type(None)):
3744 pass
3745 with self.assertRaises(TypeError):
3746 class X(type(None), object):
3747 pass
3748 class O(object):
3749 pass
3750 with self.assertRaises(TypeError):
3751 class X(O, type(None)):
3752 pass
3753 with self.assertRaises(TypeError):
3754 class X(type(None), O):
3755 pass
3756
3757 class X(object):
3758 pass
3759 with self.assertRaises(TypeError):
3760 X.__bases__ = type(None),
3761 with self.assertRaises(TypeError):
3762 X.__bases__ = object, type(None)
3763 with self.assertRaises(TypeError):
3764 X.__bases__ = type(None), object
3765 with self.assertRaises(TypeError):
3766 X.__bases__ = O, type(None)
3767 with self.assertRaises(TypeError):
3768 X.__bases__ = type(None), O
Benjamin Petersonae937c02009-04-18 20:54:08 +00003769
Georg Brandl479a7e72008-02-05 18:13:15 +00003770 def test_mutable_bases_with_failing_mro(self):
3771 # Testing mutable bases with failing mro...
3772 class WorkOnce(type):
3773 def __new__(self, name, bases, ns):
3774 self.flag = 0
3775 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3776 def mro(self):
3777 if self.flag > 0:
3778 raise RuntimeError("bozo")
3779 else:
3780 self.flag += 1
3781 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003782
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 class WorkAlways(type):
3784 def mro(self):
3785 # this is here to make sure that .mro()s aren't called
3786 # with an exception set (which was possible at one point).
3787 # An error message will be printed in a debug build.
3788 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003789 return type.mro(self)
3790
Georg Brandl479a7e72008-02-05 18:13:15 +00003791 class C(object):
3792 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003793
Georg Brandl479a7e72008-02-05 18:13:15 +00003794 class C2(object):
3795 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003796
Georg Brandl479a7e72008-02-05 18:13:15 +00003797 class D(C):
3798 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003799
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 class E(D):
3801 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003802
Georg Brandl479a7e72008-02-05 18:13:15 +00003803 class F(D, metaclass=WorkOnce):
3804 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003805
Georg Brandl479a7e72008-02-05 18:13:15 +00003806 class G(D, metaclass=WorkAlways):
3807 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003808
Georg Brandl479a7e72008-02-05 18:13:15 +00003809 # Immediate subclasses have their mro's adjusted in alphabetical
3810 # order, so E's will get adjusted before adjusting F's fails. We
3811 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003812
Georg Brandl479a7e72008-02-05 18:13:15 +00003813 E_mro_before = E.__mro__
3814 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003815
Armin Rigofd163f92005-12-29 15:59:19 +00003816 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003817 D.__bases__ = (C2,)
3818 except RuntimeError:
3819 self.assertEqual(E.__mro__, E_mro_before)
3820 self.assertEqual(D.__mro__, D_mro_before)
3821 else:
3822 self.fail("exception not propagated")
3823
3824 def test_mutable_bases_catch_mro_conflict(self):
3825 # Testing mutable bases catch mro conflict...
3826 class A(object):
3827 pass
3828
3829 class B(object):
3830 pass
3831
3832 class C(A, B):
3833 pass
3834
3835 class D(A, B):
3836 pass
3837
3838 class E(C, D):
3839 pass
3840
3841 try:
3842 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003843 except TypeError:
3844 pass
3845 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003846 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003847
Georg Brandl479a7e72008-02-05 18:13:15 +00003848 def test_mutable_names(self):
3849 # Testing mutable names...
3850 class C(object):
3851 pass
3852
3853 # C.__module__ could be 'test_descr' or '__main__'
3854 mod = C.__module__
3855
3856 C.__name__ = 'D'
3857 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3858
3859 C.__name__ = 'D.E'
3860 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3861
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003862 def test_evil_type_name(self):
3863 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3864 # execution while the type structure was not in a sane state, and a
3865 # possible segmentation fault as a result. See bug #16447.
3866 class Nasty(str):
3867 def __del__(self):
3868 C.__name__ = "other"
3869
3870 class C:
3871 pass
3872
3873 C.__name__ = Nasty("abc")
3874 C.__name__ = "normal"
3875
Georg Brandl479a7e72008-02-05 18:13:15 +00003876 def test_subclass_right_op(self):
3877 # Testing correct dispatch of subclass overloading __r<op>__...
3878
3879 # This code tests various cases where right-dispatch of a subclass
3880 # should be preferred over left-dispatch of a base class.
3881
3882 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3883
3884 class B(int):
3885 def __floordiv__(self, other):
3886 return "B.__floordiv__"
3887 def __rfloordiv__(self, other):
3888 return "B.__rfloordiv__"
3889
3890 self.assertEqual(B(1) // 1, "B.__floordiv__")
3891 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3892
3893 # Case 2: subclass of object; this is just the baseline for case 3
3894
3895 class C(object):
3896 def __floordiv__(self, other):
3897 return "C.__floordiv__"
3898 def __rfloordiv__(self, other):
3899 return "C.__rfloordiv__"
3900
3901 self.assertEqual(C() // 1, "C.__floordiv__")
3902 self.assertEqual(1 // C(), "C.__rfloordiv__")
3903
3904 # Case 3: subclass of new-style class; here it gets interesting
3905
3906 class D(C):
3907 def __floordiv__(self, other):
3908 return "D.__floordiv__"
3909 def __rfloordiv__(self, other):
3910 return "D.__rfloordiv__"
3911
3912 self.assertEqual(D() // C(), "D.__floordiv__")
3913 self.assertEqual(C() // D(), "D.__rfloordiv__")
3914
3915 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3916
3917 class E(C):
3918 pass
3919
3920 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3921
3922 self.assertEqual(E() // 1, "C.__floordiv__")
3923 self.assertEqual(1 // E(), "C.__rfloordiv__")
3924 self.assertEqual(E() // C(), "C.__floordiv__")
3925 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3926
Benjamin Petersone549ead2009-03-28 21:42:05 +00003927 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003928 def test_meth_class_get(self):
3929 # Testing __get__ method of METH_CLASS C methods...
3930 # Full coverage of descrobject.c::classmethod_get()
3931
3932 # Baseline
3933 arg = [1, 2, 3]
3934 res = {1: None, 2: None, 3: None}
3935 self.assertEqual(dict.fromkeys(arg), res)
3936 self.assertEqual({}.fromkeys(arg), res)
3937
3938 # Now get the descriptor
3939 descr = dict.__dict__["fromkeys"]
3940
3941 # More baseline using the descriptor directly
3942 self.assertEqual(descr.__get__(None, dict)(arg), res)
3943 self.assertEqual(descr.__get__({})(arg), res)
3944
3945 # Now check various error cases
3946 try:
3947 descr.__get__(None, None)
3948 except TypeError:
3949 pass
3950 else:
3951 self.fail("shouldn't have allowed descr.__get__(None, None)")
3952 try:
3953 descr.__get__(42)
3954 except TypeError:
3955 pass
3956 else:
3957 self.fail("shouldn't have allowed descr.__get__(42)")
3958 try:
3959 descr.__get__(None, 42)
3960 except TypeError:
3961 pass
3962 else:
3963 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3964 try:
3965 descr.__get__(None, int)
3966 except TypeError:
3967 pass
3968 else:
3969 self.fail("shouldn't have allowed descr.__get__(None, int)")
3970
3971 def test_isinst_isclass(self):
3972 # Testing proxy isinstance() and isclass()...
3973 class Proxy(object):
3974 def __init__(self, obj):
3975 self.__obj = obj
3976 def __getattribute__(self, name):
3977 if name.startswith("_Proxy__"):
3978 return object.__getattribute__(self, name)
3979 else:
3980 return getattr(self.__obj, name)
3981 # Test with a classic class
3982 class C:
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 classic 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 # Test with a new-style class
3996 class C(object):
3997 pass
3998 a = C()
3999 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004000 self.assertIsInstance(a, C) # Baseline
4001 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004002 # Test with a new-style subclass
4003 class D(C):
4004 pass
4005 a = D()
4006 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004007 self.assertIsInstance(a, C) # Baseline
4008 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004009
4010 def test_proxy_super(self):
4011 # Testing super() for a proxy object...
4012 class Proxy(object):
4013 def __init__(self, obj):
4014 self.__obj = obj
4015 def __getattribute__(self, name):
4016 if name.startswith("_Proxy__"):
4017 return object.__getattribute__(self, name)
4018 else:
4019 return getattr(self.__obj, name)
4020
4021 class B(object):
4022 def f(self):
4023 return "B.f"
4024
4025 class C(B):
4026 def f(self):
4027 return super(C, self).f() + "->C.f"
4028
4029 obj = C()
4030 p = Proxy(obj)
4031 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4032
4033 def test_carloverre(self):
4034 # Testing prohibition of Carlo Verre's hack...
4035 try:
4036 object.__setattr__(str, "foo", 42)
4037 except TypeError:
4038 pass
4039 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004040 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004041 try:
4042 object.__delattr__(str, "lower")
4043 except TypeError:
4044 pass
4045 else:
4046 self.fail("Carlo Verre __delattr__ succeeded!")
4047
4048 def test_weakref_segfault(self):
4049 # Testing weakref segfault...
4050 # SF 742911
4051 import weakref
4052
4053 class Provoker:
4054 def __init__(self, referrent):
4055 self.ref = weakref.ref(referrent)
4056
4057 def __del__(self):
4058 x = self.ref()
4059
4060 class Oops(object):
4061 pass
4062
4063 o = Oops()
4064 o.whatever = Provoker(o)
4065 del o
4066
4067 def test_wrapper_segfault(self):
4068 # SF 927248: deeply nested wrappers could cause stack overflow
4069 f = lambda:None
4070 for i in range(1000000):
4071 f = f.__call__
4072 f = None
4073
4074 def test_file_fault(self):
4075 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004076 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004077 class StdoutGuard:
4078 def __getattr__(self, attr):
4079 sys.stdout = sys.__stdout__
4080 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4081 sys.stdout = StdoutGuard()
4082 try:
4083 print("Oops!")
4084 except RuntimeError:
4085 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004086 finally:
4087 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004088
4089 def test_vicious_descriptor_nonsense(self):
4090 # Testing vicious_descriptor_nonsense...
4091
4092 # A potential segfault spotted by Thomas Wouters in mail to
4093 # python-dev 2003-04-17, turned into an example & fixed by Michael
4094 # Hudson just less than four months later...
4095
4096 class Evil(object):
4097 def __hash__(self):
4098 return hash('attr')
4099 def __eq__(self, other):
4100 del C.attr
4101 return 0
4102
4103 class Descr(object):
4104 def __get__(self, ob, type=None):
4105 return 1
4106
4107 class C(object):
4108 attr = Descr()
4109
4110 c = C()
4111 c.__dict__[Evil()] = 0
4112
4113 self.assertEqual(c.attr, 1)
4114 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004115 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004116 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004117
4118 def test_init(self):
4119 # SF 1155938
4120 class Foo(object):
4121 def __init__(self):
4122 return 10
4123 try:
4124 Foo()
4125 except TypeError:
4126 pass
4127 else:
4128 self.fail("did not test __init__() for None return")
4129
4130 def test_method_wrapper(self):
4131 # Testing method-wrapper objects...
4132 # <type 'method-wrapper'> did not support any reflection before 2.5
4133
Mark Dickinson211c6252009-02-01 10:28:51 +00004134 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004135
4136 l = []
4137 self.assertEqual(l.__add__, l.__add__)
4138 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004139 self.assertNotEqual(l.__add__, [5].__add__)
4140 self.assertNotEqual(l.__add__, l.__mul__)
4141 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004142 if hasattr(l.__add__, '__self__'):
4143 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004144 self.assertIs(l.__add__.__self__, l)
4145 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004146 else:
4147 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004148 self.assertIs(l.__add__.im_self, l)
4149 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004150 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4151 try:
4152 hash(l.__add__)
4153 except TypeError:
4154 pass
4155 else:
4156 self.fail("no TypeError from hash([].__add__)")
4157
4158 t = ()
4159 t += (7,)
4160 self.assertEqual(t.__add__, (7,).__add__)
4161 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4162
4163 def test_not_implemented(self):
4164 # Testing NotImplemented...
4165 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004166 import operator
4167
4168 def specialmethod(self, other):
4169 return NotImplemented
4170
4171 def check(expr, x, y):
4172 try:
4173 exec(expr, {'x': x, 'y': y, 'operator': operator})
4174 except TypeError:
4175 pass
4176 else:
4177 self.fail("no TypeError from %r" % (expr,))
4178
4179 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4180 # TypeErrors
4181 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4182 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004183 for name, expr, iexpr in [
4184 ('__add__', 'x + y', 'x += y'),
4185 ('__sub__', 'x - y', 'x -= y'),
4186 ('__mul__', 'x * y', 'x *= y'),
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004187 ('__truediv__', 'x / y', 'x /= y'),
4188 ('__floordiv__', 'x // y', 'x //= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004189 ('__mod__', 'x % y', 'x %= y'),
4190 ('__divmod__', 'divmod(x, y)', None),
4191 ('__pow__', 'x ** y', 'x **= y'),
4192 ('__lshift__', 'x << y', 'x <<= y'),
4193 ('__rshift__', 'x >> y', 'x >>= y'),
4194 ('__and__', 'x & y', 'x &= y'),
4195 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004196 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004197 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004198 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004199 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004200 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004201 check(expr, a, N1)
4202 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004203 if iexpr:
4204 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004205 check(iexpr, a, N1)
4206 check(iexpr, a, N2)
4207 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004208 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004209 c = C()
4210 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004211 check(iexpr, c, N1)
4212 check(iexpr, c, N2)
4213
Georg Brandl479a7e72008-02-05 18:13:15 +00004214 def test_assign_slice(self):
4215 # ceval.c's assign_slice used to check for
4216 # tp->tp_as_sequence->sq_slice instead of
4217 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004218
Georg Brandl479a7e72008-02-05 18:13:15 +00004219 class C(object):
4220 def __setitem__(self, idx, value):
4221 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004222
Georg Brandl479a7e72008-02-05 18:13:15 +00004223 c = C()
4224 c[1:2] = 3
4225 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004226
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004227 def test_set_and_no_get(self):
4228 # See
4229 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4230 class Descr(object):
4231
4232 def __init__(self, name):
4233 self.name = name
4234
4235 def __set__(self, obj, value):
4236 obj.__dict__[self.name] = value
4237 descr = Descr("a")
4238
4239 class X(object):
4240 a = descr
4241
4242 x = X()
4243 self.assertIs(x.a, descr)
4244 x.a = 42
4245 self.assertEqual(x.a, 42)
4246
Benjamin Peterson21896a32010-03-21 22:03:03 +00004247 # Also check type_getattro for correctness.
4248 class Meta(type):
4249 pass
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02004250 class X(metaclass=Meta):
4251 pass
Benjamin Peterson21896a32010-03-21 22:03:03 +00004252 X.a = 42
4253 Meta.a = Descr("a")
4254 self.assertEqual(X.a, 42)
4255
Benjamin Peterson9262b842008-11-17 22:45:50 +00004256 def test_getattr_hooks(self):
4257 # issue 4230
4258
4259 class Descriptor(object):
4260 counter = 0
4261 def __get__(self, obj, objtype=None):
4262 def getter(name):
4263 self.counter += 1
4264 raise AttributeError(name)
4265 return getter
4266
4267 descr = Descriptor()
4268 class A(object):
4269 __getattribute__ = descr
4270 class B(object):
4271 __getattr__ = descr
4272 class C(object):
4273 __getattribute__ = descr
4274 __getattr__ = descr
4275
4276 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004277 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004278 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004279 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004280 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004281 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004282
Benjamin Peterson9262b842008-11-17 22:45:50 +00004283 class EvilGetattribute(object):
4284 # This used to segfault
4285 def __getattr__(self, name):
4286 raise AttributeError(name)
4287 def __getattribute__(self, name):
4288 del EvilGetattribute.__getattr__
4289 for i in range(5):
4290 gc.collect()
4291 raise AttributeError(name)
4292
4293 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4294
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004295 def test_type___getattribute__(self):
4296 self.assertRaises(TypeError, type.__getattribute__, list, type)
4297
Benjamin Peterson477ba912011-01-12 15:34:01 +00004298 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004299 # type pretends not to have __abstractmethods__.
4300 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4301 class meta(type):
4302 pass
4303 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004304 class X(object):
4305 pass
4306 with self.assertRaises(AttributeError):
4307 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004308
Victor Stinner3249dec2011-05-01 23:19:15 +02004309 def test_proxy_call(self):
4310 class FakeStr:
4311 __class__ = str
4312
4313 fake_str = FakeStr()
4314 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004315 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004316
4317 # call a method descriptor
4318 with self.assertRaises(TypeError):
4319 str.split(fake_str)
4320
4321 # call a slot wrapper descriptor
4322 with self.assertRaises(TypeError):
4323 str.__add__(fake_str, "abc")
4324
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004325 def test_repr_as_str(self):
4326 # Issue #11603: crash or infinite loop when rebinding __str__ as
4327 # __repr__.
4328 class Foo:
4329 pass
4330 Foo.__repr__ = Foo.__str__
4331 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004332 self.assertRaises(RuntimeError, str, foo)
4333 self.assertRaises(RuntimeError, repr, foo)
4334
4335 def test_mixing_slot_wrappers(self):
4336 class X(dict):
4337 __setattr__ = dict.__setitem__
4338 x = X()
4339 x.y = 42
4340 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004341
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004342 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004343 with self.assertRaises(ValueError) as cm:
4344 class X:
4345 __slots__ = ["foo"]
4346 foo = None
4347 m = str(cm.exception)
4348 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4349
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004350 def test_set_doc(self):
4351 class X:
4352 "elephant"
4353 X.__doc__ = "banana"
4354 self.assertEqual(X.__doc__, "banana")
4355 with self.assertRaises(TypeError) as cm:
4356 type(list).__dict__["__doc__"].__set__(list, "blah")
4357 self.assertIn("can't set list.__doc__", str(cm.exception))
4358 with self.assertRaises(TypeError) as cm:
4359 type(X).__dict__["__doc__"].__delete__(X)
4360 self.assertIn("can't delete X.__doc__", str(cm.exception))
4361 self.assertEqual(X.__doc__, "banana")
4362
Antoine Pitrou9d574812011-12-12 13:47:25 +01004363 def test_qualname(self):
4364 descriptors = [str.lower, complex.real, float.real, int.__add__]
4365 types = ['method', 'member', 'getset', 'wrapper']
4366
4367 # make sure we have an example of each type of descriptor
4368 for d, n in zip(descriptors, types):
4369 self.assertEqual(type(d).__name__, n + '_descriptor')
4370
4371 for d in descriptors:
4372 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4373 self.assertEqual(d.__qualname__, qualname)
4374
4375 self.assertEqual(str.lower.__qualname__, 'str.lower')
4376 self.assertEqual(complex.real.__qualname__, 'complex.real')
4377 self.assertEqual(float.real.__qualname__, 'float.real')
4378 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4379
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004380 class X:
4381 pass
4382 with self.assertRaises(TypeError):
4383 del X.__qualname__
4384
4385 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4386 str, 'Oink')
4387
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004388 global Y
4389 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004390 class Inside:
4391 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004392 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004393 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004394
Victor Stinner6f738742012-02-25 01:22:36 +01004395 def test_qualname_dict(self):
4396 ns = {'__qualname__': 'some.name'}
4397 tp = type('Foo', (), ns)
4398 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004399 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004400 self.assertEqual(ns, {'__qualname__': 'some.name'})
4401
4402 ns = {'__qualname__': 1}
4403 self.assertRaises(TypeError, type, 'Foo', (), ns)
4404
Benjamin Peterson52c42432012-03-07 18:41:11 -06004405 def test_cycle_through_dict(self):
4406 # See bug #1469629
4407 class X(dict):
4408 def __init__(self):
4409 dict.__init__(self)
4410 self.__dict__ = self
4411 x = X()
4412 x.attr = 42
4413 wr = weakref.ref(x)
4414 del x
4415 support.gc_collect()
4416 self.assertIsNone(wr())
4417 for o in gc.get_objects():
4418 self.assertIsNot(type(o), X)
4419
Benjamin Peterson96384b92012-03-17 00:05:44 -05004420 def test_object_new_and_init_with_parameters(self):
4421 # See issue #1683368
4422 class OverrideNeither:
4423 pass
4424 self.assertRaises(TypeError, OverrideNeither, 1)
4425 self.assertRaises(TypeError, OverrideNeither, kw=1)
4426 class OverrideNew:
4427 def __new__(cls, foo, kw=0, *args, **kwds):
4428 return object.__new__(cls, *args, **kwds)
4429 class OverrideInit:
4430 def __init__(self, foo, kw=0, *args, **kwargs):
4431 return object.__init__(self, *args, **kwargs)
4432 class OverrideBoth(OverrideNew, OverrideInit):
4433 pass
4434 for case in OverrideNew, OverrideInit, OverrideBoth:
4435 case(1)
4436 case(1, kw=2)
4437 self.assertRaises(TypeError, case, 1, 2, 3)
4438 self.assertRaises(TypeError, case, 1, 2, foo=3)
4439
Benjamin Petersondf813792014-03-17 15:57:17 -05004440 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4441 class Base:
4442 pass
4443 class Sub(Base):
4444 pass
4445 self.assertIn("__dict__", Base.__dict__)
4446 self.assertNotIn("__dict__", Sub.__dict__)
4447
Antoine Pitrou9d574812011-12-12 13:47:25 +01004448
Georg Brandl479a7e72008-02-05 18:13:15 +00004449class DictProxyTests(unittest.TestCase):
4450 def setUp(self):
4451 class C(object):
4452 def meth(self):
4453 pass
4454 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004455
Brett Cannon7a540732011-02-22 03:04:06 +00004456 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4457 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004458 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004459 # Testing dict-proxy keys...
4460 it = self.C.__dict__.keys()
4461 self.assertNotIsInstance(it, list)
4462 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004463 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004464 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004465 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004466
Brett Cannon7a540732011-02-22 03:04:06 +00004467 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4468 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004469 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004470 # Testing dict-proxy values...
4471 it = self.C.__dict__.values()
4472 self.assertNotIsInstance(it, list)
4473 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004474 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004475
Brett Cannon7a540732011-02-22 03:04:06 +00004476 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4477 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004478 def test_iter_items(self):
4479 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004480 it = self.C.__dict__.items()
4481 self.assertNotIsInstance(it, list)
4482 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004483 keys.sort()
4484 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004485 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004486
Georg Brandl479a7e72008-02-05 18:13:15 +00004487 def test_dict_type_with_metaclass(self):
4488 # Testing type of __dict__ when metaclass set...
4489 class B(object):
4490 pass
4491 class M(type):
4492 pass
4493 class C(metaclass=M):
4494 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4495 pass
4496 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004497
Ezio Melottiac53ab62010-12-18 14:59:43 +00004498 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004499 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004500 # We can't blindly compare with the repr of another dict as ordering
4501 # of keys and values is arbitrary and may differ.
4502 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004503 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004504 self.assertTrue(r.endswith(')'), r)
4505 for k, v in self.C.__dict__.items():
4506 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004507
Christian Heimesbbffeb62008-01-24 09:42:52 +00004508
Georg Brandl479a7e72008-02-05 18:13:15 +00004509class PTypesLongInitTest(unittest.TestCase):
4510 # This is in its own TestCase so that it can be run before any other tests.
4511 def test_pytype_long_ready(self):
4512 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004513
Georg Brandl479a7e72008-02-05 18:13:15 +00004514 # This dumps core when SF bug 551412 isn't fixed --
4515 # but only when test_descr.py is run separately.
4516 # (That can't be helped -- as soon as PyType_Ready()
4517 # is called for PyLong_Type, the bug is gone.)
4518 class UserLong(object):
4519 def __pow__(self, *args):
4520 pass
4521 try:
4522 pow(0, UserLong(), 0)
4523 except:
4524 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004525
Georg Brandl479a7e72008-02-05 18:13:15 +00004526 # Another segfault only when run early
4527 # (before PyType_Ready(tuple) is called)
4528 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004529
4530
Victor Stinnerd74782b2012-03-09 00:39:08 +01004531class MiscTests(unittest.TestCase):
4532 def test_type_lookup_mro_reference(self):
4533 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4534 # the type MRO because it may be modified during the lookup, if
4535 # __bases__ is set during the lookup for example.
4536 class MyKey(object):
4537 def __hash__(self):
4538 return hash('mykey')
4539
4540 def __eq__(self, other):
4541 X.__bases__ = (Base2,)
4542
4543 class Base(object):
4544 mykey = 'from Base'
4545 mykey2 = 'from Base'
4546
4547 class Base2(object):
4548 mykey = 'from Base2'
4549 mykey2 = 'from Base2'
4550
4551 X = type('X', (Base,), {MyKey(): 5})
4552 # mykey is read from Base
4553 self.assertEqual(X.mykey, 'from Base')
4554 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4555 self.assertEqual(X.mykey2, 'from Base2')
4556
4557
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004558class PicklingTests(unittest.TestCase):
4559
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004560 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004561 listitems=None, dictitems=None):
4562 if proto >= 4:
4563 reduce_value = obj.__reduce_ex__(proto)
4564 self.assertEqual(reduce_value[:3],
4565 (copyreg.__newobj_ex__,
4566 (type(obj), args, kwargs),
4567 state))
4568 if listitems is not None:
4569 self.assertListEqual(list(reduce_value[3]), listitems)
4570 else:
4571 self.assertIsNone(reduce_value[3])
4572 if dictitems is not None:
4573 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4574 else:
4575 self.assertIsNone(reduce_value[4])
4576 elif proto >= 2:
4577 reduce_value = obj.__reduce_ex__(proto)
4578 self.assertEqual(reduce_value[:3],
4579 (copyreg.__newobj__,
4580 (type(obj),) + args,
4581 state))
4582 if listitems is not None:
4583 self.assertListEqual(list(reduce_value[3]), listitems)
4584 else:
4585 self.assertIsNone(reduce_value[3])
4586 if dictitems is not None:
4587 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4588 else:
4589 self.assertIsNone(reduce_value[4])
4590 else:
4591 base_type = type(obj).__base__
4592 reduce_value = (copyreg._reconstructor,
4593 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004594 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004595 None if base_type is object else base_type(obj)))
4596 if state is not None:
4597 reduce_value += (state,)
4598 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4599 self.assertEqual(obj.__reduce__(), reduce_value)
4600
4601 def test_reduce(self):
4602 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4603 args = (-101, "spam")
4604 kwargs = {'bacon': -201, 'fish': -301}
4605 state = {'cheese': -401}
4606
4607 class C1:
4608 def __getnewargs__(self):
4609 return args
4610 obj = C1()
4611 for proto in protocols:
4612 self._check_reduce(proto, obj, args)
4613
4614 for name, value in state.items():
4615 setattr(obj, name, value)
4616 for proto in protocols:
4617 self._check_reduce(proto, obj, args, state=state)
4618
4619 class C2:
4620 def __getnewargs__(self):
4621 return "bad args"
4622 obj = C2()
4623 for proto in protocols:
4624 if proto >= 2:
4625 with self.assertRaises(TypeError):
4626 obj.__reduce_ex__(proto)
4627
4628 class C3:
4629 def __getnewargs_ex__(self):
4630 return (args, kwargs)
4631 obj = C3()
4632 for proto in protocols:
4633 if proto >= 4:
4634 self._check_reduce(proto, obj, args, kwargs)
4635 elif proto >= 2:
4636 with self.assertRaises(ValueError):
4637 obj.__reduce_ex__(proto)
4638
4639 class C4:
4640 def __getnewargs_ex__(self):
4641 return (args, "bad dict")
4642 class C5:
4643 def __getnewargs_ex__(self):
4644 return ("bad tuple", kwargs)
4645 class C6:
4646 def __getnewargs_ex__(self):
4647 return ()
4648 class C7:
4649 def __getnewargs_ex__(self):
4650 return "bad args"
4651 for proto in protocols:
4652 for cls in C4, C5, C6, C7:
4653 obj = cls()
4654 if proto >= 2:
4655 with self.assertRaises((TypeError, ValueError)):
4656 obj.__reduce_ex__(proto)
4657
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004658 class C9:
4659 def __getnewargs_ex__(self):
4660 return (args, {})
4661 obj = C9()
4662 for proto in protocols:
4663 self._check_reduce(proto, obj, args)
4664
4665 class C10:
4666 def __getnewargs_ex__(self):
4667 raise IndexError
4668 obj = C10()
4669 for proto in protocols:
4670 if proto >= 2:
4671 with self.assertRaises(IndexError):
4672 obj.__reduce_ex__(proto)
4673
4674 class C11:
4675 def __getstate__(self):
4676 return state
4677 obj = C11()
4678 for proto in protocols:
4679 self._check_reduce(proto, obj, state=state)
4680
4681 class C12:
4682 def __getstate__(self):
4683 return "not dict"
4684 obj = C12()
4685 for proto in protocols:
4686 self._check_reduce(proto, obj, state="not dict")
4687
4688 class C13:
4689 def __getstate__(self):
4690 raise IndexError
4691 obj = C13()
4692 for proto in protocols:
4693 with self.assertRaises(IndexError):
4694 obj.__reduce_ex__(proto)
4695 if proto < 2:
4696 with self.assertRaises(IndexError):
4697 obj.__reduce__()
4698
4699 class C14:
4700 __slots__ = tuple(state)
4701 def __init__(self):
4702 for name, value in state.items():
4703 setattr(self, name, value)
4704
4705 obj = C14()
4706 for proto in protocols:
4707 if proto >= 2:
4708 self._check_reduce(proto, obj, state=(None, state))
4709 else:
4710 with self.assertRaises(TypeError):
4711 obj.__reduce_ex__(proto)
4712 with self.assertRaises(TypeError):
4713 obj.__reduce__()
4714
4715 class C15(dict):
4716 pass
4717 obj = C15({"quebec": -601})
4718 for proto in protocols:
4719 self._check_reduce(proto, obj, dictitems=dict(obj))
4720
4721 class C16(list):
4722 pass
4723 obj = C16(["yukon"])
4724 for proto in protocols:
4725 self._check_reduce(proto, obj, listitems=list(obj))
4726
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004727 def test_special_method_lookup(self):
4728 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4729 class Picky:
4730 def __getstate__(self):
4731 return {}
4732
4733 def __getattr__(self, attr):
4734 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4735 raise AssertionError(attr)
4736 return None
4737 for protocol in protocols:
4738 state = {} if protocol >= 2 else None
4739 self._check_reduce(protocol, Picky(), state=state)
4740
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004741 def _assert_is_copy(self, obj, objcopy, msg=None):
4742 """Utility method to verify if two objects are copies of each others.
4743 """
4744 if msg is None:
4745 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4746 if type(obj).__repr__ is object.__repr__:
4747 # We have this limitation for now because we use the object's repr
4748 # to help us verify that the two objects are copies. This allows
4749 # us to delegate the non-generic verification logic to the objects
4750 # themselves.
4751 raise ValueError("object passed to _assert_is_copy must " +
4752 "override the __repr__ method.")
4753 self.assertIsNot(obj, objcopy, msg=msg)
4754 self.assertIs(type(obj), type(objcopy), msg=msg)
4755 if hasattr(obj, '__dict__'):
4756 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4757 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4758 if hasattr(obj, '__slots__'):
4759 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4760 for slot in obj.__slots__:
4761 self.assertEqual(
4762 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4763 self.assertEqual(getattr(obj, slot, None),
4764 getattr(objcopy, slot, None), msg=msg)
4765 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4766
4767 @staticmethod
4768 def _generate_pickle_copiers():
4769 """Utility method to generate the many possible pickle configurations.
4770 """
4771 class PickleCopier:
4772 "This class copies object using pickle."
4773 def __init__(self, proto, dumps, loads):
4774 self.proto = proto
4775 self.dumps = dumps
4776 self.loads = loads
4777 def copy(self, obj):
4778 return self.loads(self.dumps(obj, self.proto))
4779 def __repr__(self):
4780 # We try to be as descriptive as possible here since this is
4781 # the string which we will allow us to tell the pickle
4782 # configuration we are using during debugging.
4783 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4784 .format(self.proto,
4785 self.dumps.__module__, self.dumps.__qualname__,
4786 self.loads.__module__, self.loads.__qualname__))
4787 return (PickleCopier(*args) for args in
4788 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4789 {pickle.dumps, pickle._dumps},
4790 {pickle.loads, pickle._loads}))
4791
4792 def test_pickle_slots(self):
4793 # Tests pickling of classes with __slots__.
4794
4795 # Pickling of classes with __slots__ but without __getstate__ should
4796 # fail (if using protocol 0 or 1)
4797 global C
4798 class C:
4799 __slots__ = ['a']
4800 with self.assertRaises(TypeError):
4801 pickle.dumps(C(), 0)
4802
4803 global D
4804 class D(C):
4805 pass
4806 with self.assertRaises(TypeError):
4807 pickle.dumps(D(), 0)
4808
4809 class C:
4810 "A class with __getstate__ and __setstate__ implemented."
4811 __slots__ = ['a']
4812 def __getstate__(self):
4813 state = getattr(self, '__dict__', {}).copy()
4814 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004815 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004816 try:
4817 state[slot] = getattr(self, slot)
4818 except AttributeError:
4819 pass
4820 return state
4821 def __setstate__(self, state):
4822 for k, v in state.items():
4823 setattr(self, k, v)
4824 def __repr__(self):
4825 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4826
4827 class D(C):
4828 "A subclass of a class with slots."
4829 pass
4830
4831 global E
4832 class E(C):
4833 "A subclass with an extra slot."
4834 __slots__ = ['b']
4835
4836 # Now it should work
4837 for pickle_copier in self._generate_pickle_copiers():
4838 with self.subTest(pickle_copier=pickle_copier):
4839 x = C()
4840 y = pickle_copier.copy(x)
4841 self._assert_is_copy(x, y)
4842
4843 x.a = 42
4844 y = pickle_copier.copy(x)
4845 self._assert_is_copy(x, y)
4846
4847 x = D()
4848 x.a = 42
4849 x.b = 100
4850 y = pickle_copier.copy(x)
4851 self._assert_is_copy(x, y)
4852
4853 x = E()
4854 x.a = 42
4855 x.b = "foo"
4856 y = pickle_copier.copy(x)
4857 self._assert_is_copy(x, y)
4858
4859 def test_reduce_copying(self):
4860 # Tests pickling and copying new-style classes and objects.
4861 global C1
4862 class C1:
4863 "The state of this class is copyable via its instance dict."
4864 ARGS = (1, 2)
4865 NEED_DICT_COPYING = True
4866 def __init__(self, a, b):
4867 super().__init__()
4868 self.a = a
4869 self.b = b
4870 def __repr__(self):
4871 return "C1(%r, %r)" % (self.a, self.b)
4872
4873 global C2
4874 class C2(list):
4875 "A list subclass copyable via __getnewargs__."
4876 ARGS = (1, 2)
4877 NEED_DICT_COPYING = False
4878 def __new__(cls, a, b):
4879 self = super().__new__(cls)
4880 self.a = a
4881 self.b = b
4882 return self
4883 def __init__(self, *args):
4884 super().__init__()
4885 # This helps testing that __init__ is not called during the
4886 # unpickling process, which would cause extra appends.
4887 self.append("cheese")
4888 @classmethod
4889 def __getnewargs__(cls):
4890 return cls.ARGS
4891 def __repr__(self):
4892 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
4893
4894 global C3
4895 class C3(list):
4896 "A list subclass copyable via __getstate__."
4897 ARGS = (1, 2)
4898 NEED_DICT_COPYING = False
4899 def __init__(self, a, b):
4900 self.a = a
4901 self.b = b
4902 # This helps testing that __init__ is not called during the
4903 # unpickling process, which would cause extra appends.
4904 self.append("cheese")
4905 @classmethod
4906 def __getstate__(cls):
4907 return cls.ARGS
4908 def __setstate__(self, state):
4909 a, b = state
4910 self.a = a
4911 self.b = b
4912 def __repr__(self):
4913 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
4914
4915 global C4
4916 class C4(int):
4917 "An int subclass copyable via __getnewargs__."
4918 ARGS = ("hello", "world", 1)
4919 NEED_DICT_COPYING = False
4920 def __new__(cls, a, b, value):
4921 self = super().__new__(cls, value)
4922 self.a = a
4923 self.b = b
4924 return self
4925 @classmethod
4926 def __getnewargs__(cls):
4927 return cls.ARGS
4928 def __repr__(self):
4929 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
4930
4931 global C5
4932 class C5(int):
4933 "An int subclass copyable via __getnewargs_ex__."
4934 ARGS = (1, 2)
4935 KWARGS = {'value': 3}
4936 NEED_DICT_COPYING = False
4937 def __new__(cls, a, b, *, value=0):
4938 self = super().__new__(cls, value)
4939 self.a = a
4940 self.b = b
4941 return self
4942 @classmethod
4943 def __getnewargs_ex__(cls):
4944 return (cls.ARGS, cls.KWARGS)
4945 def __repr__(self):
4946 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
4947
4948 test_classes = (C1, C2, C3, C4, C5)
4949 # Testing copying through pickle
4950 pickle_copiers = self._generate_pickle_copiers()
4951 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
4952 with self.subTest(cls=cls, pickle_copier=pickle_copier):
4953 kwargs = getattr(cls, 'KWARGS', {})
4954 obj = cls(*cls.ARGS, **kwargs)
4955 proto = pickle_copier.proto
4956 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
4957 with self.assertRaises(ValueError):
4958 pickle_copier.dumps(obj, proto)
4959 continue
4960 objcopy = pickle_copier.copy(obj)
4961 self._assert_is_copy(obj, objcopy)
4962 # For test classes that supports this, make sure we didn't go
4963 # around the reduce protocol by simply copying the attribute
4964 # dictionary. We clear attributes using the previous copy to
4965 # not mutate the original argument.
4966 if proto >= 2 and not cls.NEED_DICT_COPYING:
4967 objcopy.__dict__.clear()
4968 objcopy2 = pickle_copier.copy(objcopy)
4969 self._assert_is_copy(obj, objcopy2)
4970
4971 # Testing copying through copy.deepcopy()
4972 for cls in test_classes:
4973 with self.subTest(cls=cls):
4974 kwargs = getattr(cls, 'KWARGS', {})
4975 obj = cls(*cls.ARGS, **kwargs)
4976 # XXX: We need to modify the copy module to support PEP 3154's
4977 # reduce protocol 4.
4978 if hasattr(cls, '__getnewargs_ex__'):
4979 continue
4980 objcopy = deepcopy(obj)
4981 self._assert_is_copy(obj, objcopy)
4982 # For test classes that supports this, make sure we didn't go
4983 # around the reduce protocol by simply copying the attribute
4984 # dictionary. We clear attributes using the previous copy to
4985 # not mutate the original argument.
4986 if not cls.NEED_DICT_COPYING:
4987 objcopy.__dict__.clear()
4988 objcopy2 = deepcopy(objcopy)
4989 self._assert_is_copy(obj, objcopy2)
4990
4991
Benjamin Peterson2a605342014-03-17 16:20:12 -05004992class SharedKeyTests(unittest.TestCase):
4993
4994 @support.cpython_only
4995 def test_subclasses(self):
4996 # Verify that subclasses can share keys (per PEP 412)
4997 class A:
4998 pass
4999 class B(A):
5000 pass
5001
5002 a, b = A(), B()
5003 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5004 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5005 a.x, a.y, a.z, a.w = range(4)
5006 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5007 a2 = A()
5008 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5009 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5010 b.u, b.v, b.w, b.t = range(4)
5011 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5012
5013
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005014class DebugHelperMeta(type):
5015 """
5016 Sets default __doc__ and simplifies repr() output.
5017 """
5018 def __new__(mcls, name, bases, attrs):
5019 if attrs.get('__doc__') is None:
5020 attrs['__doc__'] = name # helps when debugging with gdb
5021 return type.__new__(mcls, name, bases, attrs)
5022 def __repr__(cls):
5023 return repr(cls.__name__)
5024
5025
5026class MroTest(unittest.TestCase):
5027 """
5028 Regressions for some bugs revealed through
5029 mcsl.mro() customization (typeobject.c: mro_internal()) and
5030 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5031 """
5032
5033 def setUp(self):
5034 self.step = 0
5035 self.ready = False
5036
5037 def step_until(self, limit):
5038 ret = (self.step < limit)
5039 if ret:
5040 self.step += 1
5041 return ret
5042
5043 def test_incomplete_set_bases_on_self(self):
5044 """
5045 type_set_bases must be aware that type->tp_mro can be NULL.
5046 """
5047 class M(DebugHelperMeta):
5048 def mro(cls):
5049 if self.step_until(1):
5050 assert cls.__mro__ is None
5051 cls.__bases__ += ()
5052
5053 return type.mro(cls)
5054
5055 class A(metaclass=M):
5056 pass
5057
5058 def test_reent_set_bases_on_base(self):
5059 """
5060 Deep reentrancy must not over-decref old_mro.
5061 """
5062 class M(DebugHelperMeta):
5063 def mro(cls):
5064 if cls.__mro__ is not None and cls.__name__ == 'B':
5065 # 4-5 steps are usually enough to make it crash somewhere
5066 if self.step_until(10):
5067 A.__bases__ += ()
5068
5069 return type.mro(cls)
5070
5071 class A(metaclass=M):
5072 pass
5073 class B(A):
5074 pass
5075 B.__bases__ += ()
5076
5077 def test_reent_set_bases_on_direct_base(self):
5078 """
5079 Similar to test_reent_set_bases_on_base, but may crash differently.
5080 """
5081 class M(DebugHelperMeta):
5082 def mro(cls):
5083 base = cls.__bases__[0]
5084 if base is not object:
5085 if self.step_until(5):
5086 base.__bases__ += ()
5087
5088 return type.mro(cls)
5089
5090 class A(metaclass=M):
5091 pass
5092 class B(A):
5093 pass
5094 class C(B):
5095 pass
5096
5097 def test_reent_set_bases_tp_base_cycle(self):
5098 """
5099 type_set_bases must check for an inheritance cycle not only through
5100 MRO of the type, which may be not yet updated in case of reentrance,
5101 but also through tp_base chain, which is assigned before diving into
5102 inner calls to mro().
5103
5104 Otherwise, the following snippet can loop forever:
5105 do {
5106 // ...
5107 type = type->tp_base;
5108 } while (type != NULL);
5109
5110 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5111 would not be happy in that case, causing a stack overflow.
5112 """
5113 class M(DebugHelperMeta):
5114 def mro(cls):
5115 if self.ready:
5116 if cls.__name__ == 'B1':
5117 B2.__bases__ = (B1,)
5118 if cls.__name__ == 'B2':
5119 B1.__bases__ = (B2,)
5120 return type.mro(cls)
5121
5122 class A(metaclass=M):
5123 pass
5124 class B1(A):
5125 pass
5126 class B2(A):
5127 pass
5128
5129 self.ready = True
5130 with self.assertRaises(TypeError):
5131 B1.__bases__ += ()
5132
5133 def test_tp_subclasses_cycle_in_update_slots(self):
5134 """
5135 type_set_bases must check for reentrancy upon finishing its job
5136 by updating tp_subclasses of old/new bases of the type.
5137 Otherwise, an implicit inheritance cycle through tp_subclasses
5138 can break functions that recurse on elements of that field
5139 (like recurse_down_subclasses and mro_hierarchy) eventually
5140 leading to a stack overflow.
5141 """
5142 class M(DebugHelperMeta):
5143 def mro(cls):
5144 if self.ready and cls.__name__ == 'C':
5145 self.ready = False
5146 C.__bases__ = (B2,)
5147 return type.mro(cls)
5148
5149 class A(metaclass=M):
5150 pass
5151 class B1(A):
5152 pass
5153 class B2(A):
5154 pass
5155 class C(A):
5156 pass
5157
5158 self.ready = True
5159 C.__bases__ = (B1,)
5160 B1.__bases__ = (C,)
5161
5162 self.assertEqual(C.__bases__, (B2,))
5163 self.assertEqual(B2.__subclasses__(), [C])
5164 self.assertEqual(B1.__subclasses__(), [])
5165
5166 self.assertEqual(B1.__bases__, (C,))
5167 self.assertEqual(C.__subclasses__(), [B1])
5168
5169 def test_tp_subclasses_cycle_error_return_path(self):
5170 """
5171 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5172 a code path executed on error (goto bail).
5173 """
5174 class E(Exception):
5175 pass
5176 class M(DebugHelperMeta):
5177 def mro(cls):
5178 if self.ready and cls.__name__ == 'C':
5179 if C.__bases__ == (B2,):
5180 self.ready = False
5181 else:
5182 C.__bases__ = (B2,)
5183 raise E
5184 return type.mro(cls)
5185
5186 class A(metaclass=M):
5187 pass
5188 class B1(A):
5189 pass
5190 class B2(A):
5191 pass
5192 class C(A):
5193 pass
5194
5195 self.ready = True
5196 with self.assertRaises(E):
5197 C.__bases__ = (B1,)
5198 B1.__bases__ = (C,)
5199
5200 self.assertEqual(C.__bases__, (B2,))
5201 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5202
5203 def test_incomplete_extend(self):
5204 """
5205 Extending an unitialized type with type->tp_mro == NULL must
5206 throw a reasonable TypeError exception, instead of failing
5207 with PyErr_BadInternalCall.
5208 """
5209 class M(DebugHelperMeta):
5210 def mro(cls):
5211 if cls.__mro__ is None and cls.__name__ != 'X':
5212 with self.assertRaises(TypeError):
5213 class X(cls):
5214 pass
5215
5216 return type.mro(cls)
5217
5218 class A(metaclass=M):
5219 pass
5220
5221 def test_incomplete_super(self):
5222 """
5223 Attrubute lookup on a super object must be aware that
5224 its target type can be uninitialized (type->tp_mro == NULL).
5225 """
5226 class M(DebugHelperMeta):
5227 def mro(cls):
5228 if cls.__mro__ is None:
5229 with self.assertRaises(AttributeError):
5230 super(cls, cls).xxx
5231
5232 return type.mro(cls)
5233
5234 class A(metaclass=M):
5235 pass
5236
5237
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005238def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00005239 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005240 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01005241 ClassPropertiesAndMethods, DictProxyTests,
Benjamin Peterson104b9e02015-02-05 22:29:14 -05005242 MiscTests, PicklingTests, SharedKeyTests,
5243 MroTest)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244
Guido van Rossuma56b42b2001-09-20 21:39:07 +00005245if __name__ == "__main__":
5246 test_main()