blob: 71d8609ab8c0a167f36d2a7d5620537439411985 [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': '*',
24 'div': '/',
25 'divmod': 'divmod',
26 'pow': '**',
27 'lshift': '<<',
28 'rshift': '>>',
29 'and': '&',
30 'xor': '^',
31 'or': '|',
32 'cmp': 'cmp',
33 'lt': '<',
34 'le': '<=',
35 'eq': '==',
36 'ne': '!=',
37 'gt': '>',
38 'ge': '>=',
39 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000040
Georg Brandl479a7e72008-02-05 18:13:15 +000041 for name, expr in list(self.binops.items()):
42 if expr.islower():
43 expr = expr + "(a, b)"
44 else:
45 expr = 'a %s b' % expr
46 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000047
Georg Brandl479a7e72008-02-05 18:13:15 +000048 self.unops = {
49 'pos': '+',
50 'neg': '-',
51 'abs': 'abs',
52 'invert': '~',
53 'int': 'int',
54 'float': 'float',
55 'oct': 'oct',
56 'hex': 'hex',
57 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000058
Georg Brandl479a7e72008-02-05 18:13:15 +000059 for name, expr in list(self.unops.items()):
60 if expr.islower():
61 expr = expr + "(a)"
62 else:
63 expr = '%s a' % expr
64 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000065
Georg Brandl479a7e72008-02-05 18:13:15 +000066 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
67 d = {'a': a}
68 self.assertEqual(eval(expr, d), res)
69 t = type(a)
70 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000071
Georg Brandl479a7e72008-02-05 18:13:15 +000072 # Find method in parent class
73 while meth not in t.__dict__:
74 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000075 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
76 # method object; the getattr() below obtains its underlying function.
77 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000078 self.assertEqual(m(a), res)
79 bm = getattr(a, meth)
80 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000081
Georg Brandl479a7e72008-02-05 18:13:15 +000082 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
83 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000084
Georg Brandl479a7e72008-02-05 18:13:15 +000085 # XXX Hack so this passes before 2.3 when -Qnew is specified.
86 if meth == "__div__" and 1/2 == 0.5:
87 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000088
Georg Brandl479a7e72008-02-05 18:13:15 +000089 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000090
Georg Brandl479a7e72008-02-05 18:13:15 +000091 self.assertEqual(eval(expr, d), res)
92 t = type(a)
93 m = getattr(t, meth)
94 while meth not in t.__dict__:
95 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000096 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
97 # method object; the getattr() below obtains its underlying function.
98 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000099 self.assertEqual(m(a, b), res)
100 bm = getattr(a, meth)
101 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000102
Georg Brandl479a7e72008-02-05 18:13:15 +0000103 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
104 d = {'a': a, 'b': b, 'c': c}
105 self.assertEqual(eval(expr, d), res)
106 t = type(a)
107 m = getattr(t, meth)
108 while meth not in t.__dict__:
109 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000110 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
111 # method object; the getattr() below obtains its underlying function.
112 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000113 self.assertEqual(m(a, slice(b, c)), res)
114 bm = getattr(a, meth)
115 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000116
Georg Brandl479a7e72008-02-05 18:13:15 +0000117 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
118 d = {'a': deepcopy(a), 'b': b}
119 exec(stmt, d)
120 self.assertEqual(d['a'], res)
121 t = type(a)
122 m = getattr(t, meth)
123 while meth not in t.__dict__:
124 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000125 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
126 # method object; the getattr() below obtains its underlying function.
127 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000128 d['a'] = deepcopy(a)
129 m(d['a'], b)
130 self.assertEqual(d['a'], res)
131 d['a'] = deepcopy(a)
132 bm = getattr(d['a'], meth)
133 bm(b)
134 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000135
Georg Brandl479a7e72008-02-05 18:13:15 +0000136 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
137 d = {'a': deepcopy(a), 'b': b, 'c': c}
138 exec(stmt, d)
139 self.assertEqual(d['a'], res)
140 t = type(a)
141 m = getattr(t, meth)
142 while meth not in t.__dict__:
143 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000144 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
145 # method object; the getattr() below obtains its underlying function.
146 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000147 d['a'] = deepcopy(a)
148 m(d['a'], b, c)
149 self.assertEqual(d['a'], res)
150 d['a'] = deepcopy(a)
151 bm = getattr(d['a'], meth)
152 bm(b, c)
153 self.assertEqual(d['a'], res)
154
155 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
156 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
157 exec(stmt, dictionary)
158 self.assertEqual(dictionary['a'], res)
159 t = type(a)
160 while meth not in t.__dict__:
161 t = t.__bases__[0]
162 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000163 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
164 # method object; the getattr() below obtains its underlying function.
165 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000166 dictionary['a'] = deepcopy(a)
167 m(dictionary['a'], slice(b, c), d)
168 self.assertEqual(dictionary['a'], res)
169 dictionary['a'] = deepcopy(a)
170 bm = getattr(dictionary['a'], meth)
171 bm(slice(b, c), d)
172 self.assertEqual(dictionary['a'], res)
173
174 def test_lists(self):
175 # Testing list operations...
176 # Asserts are within individual test methods
177 self.binop_test([1], [2], [1,2], "a+b", "__add__")
178 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
179 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
180 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
181 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
182 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
183 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
184 self.unop_test([1,2,3], 3, "len(a)", "__len__")
185 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
186 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
187 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
188 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
189 "__setitem__")
190
191 def test_dicts(self):
192 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000193 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
194 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
195 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
196
197 d = {1:2, 3:4}
198 l1 = []
199 for i in list(d.keys()):
200 l1.append(i)
201 l = []
202 for i in iter(d):
203 l.append(i)
204 self.assertEqual(l, l1)
205 l = []
206 for i in d.__iter__():
207 l.append(i)
208 self.assertEqual(l, l1)
209 l = []
210 for i in dict.__iter__(d):
211 l.append(i)
212 self.assertEqual(l, l1)
213 d = {1:2, 3:4}
214 self.unop_test(d, 2, "len(a)", "__len__")
215 self.assertEqual(eval(repr(d), {}), d)
216 self.assertEqual(eval(d.__repr__(), {}), d)
217 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
218 "__setitem__")
219
220 # Tests for unary and binary operators
221 def number_operators(self, a, b, skip=[]):
222 dict = {'a': a, 'b': b}
223
224 for name, expr in list(self.binops.items()):
225 if name not in skip:
226 name = "__%s__" % name
227 if hasattr(a, name):
228 res = eval(expr, dict)
229 self.binop_test(a, b, res, expr, name)
230
231 for name, expr in list(self.unops.items()):
232 if name not in skip:
233 name = "__%s__" % name
234 if hasattr(a, name):
235 res = eval(expr, dict)
236 self.unop_test(a, res, expr, name)
237
238 def test_ints(self):
239 # Testing int operations...
240 self.number_operators(100, 3)
241 # The following crashes in Python 2.2
242 self.assertEqual((1).__bool__(), 1)
243 self.assertEqual((0).__bool__(), 0)
244 # This returns 'NotImplemented' in Python 2.2
245 class C(int):
246 def __add__(self, other):
247 return NotImplemented
248 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000249 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000250 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000251 except TypeError:
252 pass
253 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000254 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000255
Georg Brandl479a7e72008-02-05 18:13:15 +0000256 def test_floats(self):
257 # Testing float operations...
258 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000259
Georg Brandl479a7e72008-02-05 18:13:15 +0000260 def test_complexes(self):
261 # Testing complex operations...
262 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000263 'int', 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +0000264 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000265
Georg Brandl479a7e72008-02-05 18:13:15 +0000266 class Number(complex):
267 __slots__ = ['prec']
268 def __new__(cls, *args, **kwds):
269 result = complex.__new__(cls, *args)
270 result.prec = kwds.get('prec', 12)
271 return result
272 def __repr__(self):
273 prec = self.prec
274 if self.imag == 0.0:
275 return "%.*g" % (prec, self.real)
276 if self.real == 0.0:
277 return "%.*gj" % (prec, self.imag)
278 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
279 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000280
Georg Brandl479a7e72008-02-05 18:13:15 +0000281 a = Number(3.14, prec=6)
282 self.assertEqual(repr(a), "3.14")
283 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000284
Georg Brandl479a7e72008-02-05 18:13:15 +0000285 a = Number(a, prec=2)
286 self.assertEqual(repr(a), "3.1")
287 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000288
Georg Brandl479a7e72008-02-05 18:13:15 +0000289 a = Number(234.5)
290 self.assertEqual(repr(a), "234.5")
291 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000292
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000293 def test_explicit_reverse_methods(self):
294 # see issue 9930
295 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
296 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
297
Benjamin Petersone549ead2009-03-28 21:42:05 +0000298 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000299 def test_spam_lists(self):
300 # Testing spamlist operations...
301 import copy, xxsubtype as spam
302
303 def spamlist(l, memo=None):
304 import xxsubtype as spam
305 return spam.spamlist(l)
306
307 # This is an ugly hack:
308 copy._deepcopy_dispatch[spam.spamlist] = spamlist
309
310 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
311 "__add__")
312 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
313 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
314 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
315 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
316 "__getitem__")
317 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
318 "__iadd__")
319 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
320 "__imul__")
321 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
322 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
323 "__mul__")
324 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
325 "__rmul__")
326 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
327 "__setitem__")
328 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
329 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
330 # Test subclassing
331 class C(spam.spamlist):
332 def foo(self): return 1
333 a = C()
334 self.assertEqual(a, [])
335 self.assertEqual(a.foo(), 1)
336 a.append(100)
337 self.assertEqual(a, [100])
338 self.assertEqual(a.getstate(), 0)
339 a.setstate(42)
340 self.assertEqual(a.getstate(), 42)
341
Benjamin Petersone549ead2009-03-28 21:42:05 +0000342 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000343 def test_spam_dicts(self):
344 # Testing spamdict operations...
345 import copy, xxsubtype as spam
346 def spamdict(d, memo=None):
347 import xxsubtype as spam
348 sd = spam.spamdict()
349 for k, v in list(d.items()):
350 sd[k] = v
351 return sd
352 # This is an ugly hack:
353 copy._deepcopy_dispatch[spam.spamdict] = spamdict
354
Georg Brandl479a7e72008-02-05 18:13:15 +0000355 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
356 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
357 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
358 d = spamdict({1:2,3:4})
359 l1 = []
360 for i in list(d.keys()):
361 l1.append(i)
362 l = []
363 for i in iter(d):
364 l.append(i)
365 self.assertEqual(l, l1)
366 l = []
367 for i in d.__iter__():
368 l.append(i)
369 self.assertEqual(l, l1)
370 l = []
371 for i in type(spamdict({})).__iter__(d):
372 l.append(i)
373 self.assertEqual(l, l1)
374 straightd = {1:2, 3:4}
375 spamd = spamdict(straightd)
376 self.unop_test(spamd, 2, "len(a)", "__len__")
377 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
378 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
379 "a[b]=c", "__setitem__")
380 # Test subclassing
381 class C(spam.spamdict):
382 def foo(self): return 1
383 a = C()
384 self.assertEqual(list(a.items()), [])
385 self.assertEqual(a.foo(), 1)
386 a['foo'] = 'bar'
387 self.assertEqual(list(a.items()), [('foo', 'bar')])
388 self.assertEqual(a.getstate(), 0)
389 a.setstate(100)
390 self.assertEqual(a.getstate(), 100)
391
392class ClassPropertiesAndMethods(unittest.TestCase):
393
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200394 def assertHasAttr(self, obj, name):
395 self.assertTrue(hasattr(obj, name),
396 '%r has no attribute %r' % (obj, name))
397
398 def assertNotHasAttr(self, obj, name):
399 self.assertFalse(hasattr(obj, name),
400 '%r has unexpected attribute %r' % (obj, name))
401
Georg Brandl479a7e72008-02-05 18:13:15 +0000402 def test_python_dicts(self):
403 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000404 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000405 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000406 d = dict()
407 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200408 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000409 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000410 class C(dict):
411 state = -1
412 def __init__(self_local, *a, **kw):
413 if a:
414 self.assertEqual(len(a), 1)
415 self_local.state = a[0]
416 if kw:
417 for k, v in list(kw.items()):
418 self_local[v] = k
419 def __getitem__(self, key):
420 return self.get(key, 0)
421 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000422 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000423 dict.__setitem__(self_local, key, value)
424 def setstate(self, state):
425 self.state = state
426 def getstate(self):
427 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000428 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000429 a1 = C(12)
430 self.assertEqual(a1.state, 12)
431 a2 = C(foo=1, bar=2)
432 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
433 a = C()
434 self.assertEqual(a.state, -1)
435 self.assertEqual(a.getstate(), -1)
436 a.setstate(0)
437 self.assertEqual(a.state, 0)
438 self.assertEqual(a.getstate(), 0)
439 a.setstate(10)
440 self.assertEqual(a.state, 10)
441 self.assertEqual(a.getstate(), 10)
442 self.assertEqual(a[42], 0)
443 a[42] = 24
444 self.assertEqual(a[42], 24)
445 N = 50
446 for i in range(N):
447 a[i] = C()
448 for j in range(N):
449 a[i][j] = i*j
450 for i in range(N):
451 for j in range(N):
452 self.assertEqual(a[i][j], i*j)
453
454 def test_python_lists(self):
455 # Testing Python subclass of list...
456 class C(list):
457 def __getitem__(self, i):
458 if isinstance(i, slice):
459 return i.start, i.stop
460 return list.__getitem__(self, i) + 100
461 a = C()
462 a.extend([0,1,2])
463 self.assertEqual(a[0], 100)
464 self.assertEqual(a[1], 101)
465 self.assertEqual(a[2], 102)
466 self.assertEqual(a[100:200], (100,200))
467
468 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000469 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000470 class C(metaclass=type):
471 def __init__(self):
472 self.__state = 0
473 def getstate(self):
474 return self.__state
475 def setstate(self, state):
476 self.__state = state
477 a = C()
478 self.assertEqual(a.getstate(), 0)
479 a.setstate(10)
480 self.assertEqual(a.getstate(), 10)
481 class _metaclass(type):
482 def myself(cls): return cls
483 class D(metaclass=_metaclass):
484 pass
485 self.assertEqual(D.myself(), D)
486 d = D()
487 self.assertEqual(d.__class__, D)
488 class M1(type):
489 def __new__(cls, name, bases, dict):
490 dict['__spam__'] = 1
491 return type.__new__(cls, name, bases, dict)
492 class C(metaclass=M1):
493 pass
494 self.assertEqual(C.__spam__, 1)
495 c = C()
496 self.assertEqual(c.__spam__, 1)
497
498 class _instance(object):
499 pass
500 class M2(object):
501 @staticmethod
502 def __new__(cls, name, bases, dict):
503 self = object.__new__(cls)
504 self.name = name
505 self.bases = bases
506 self.dict = dict
507 return self
508 def __call__(self):
509 it = _instance()
510 # Early binding of methods
511 for key in self.dict:
512 if key.startswith("__"):
513 continue
514 setattr(it, key, self.dict[key].__get__(it, self))
515 return it
516 class C(metaclass=M2):
517 def spam(self):
518 return 42
519 self.assertEqual(C.name, 'C')
520 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000521 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000522 c = C()
523 self.assertEqual(c.spam(), 42)
524
525 # More metaclass examples
526
527 class autosuper(type):
528 # Automatically add __super to the class
529 # This trick only works for dynamic classes
530 def __new__(metaclass, name, bases, dict):
531 cls = super(autosuper, metaclass).__new__(metaclass,
532 name, bases, dict)
533 # Name mangling for __super removes leading underscores
534 while name[:1] == "_":
535 name = name[1:]
536 if name:
537 name = "_%s__super" % name
538 else:
539 name = "__super"
540 setattr(cls, name, super(cls))
541 return cls
542 class A(metaclass=autosuper):
543 def meth(self):
544 return "A"
545 class B(A):
546 def meth(self):
547 return "B" + self.__super.meth()
548 class C(A):
549 def meth(self):
550 return "C" + self.__super.meth()
551 class D(C, B):
552 def meth(self):
553 return "D" + self.__super.meth()
554 self.assertEqual(D().meth(), "DCBA")
555 class E(B, C):
556 def meth(self):
557 return "E" + self.__super.meth()
558 self.assertEqual(E().meth(), "EBCA")
559
560 class autoproperty(type):
561 # Automatically create property attributes when methods
562 # named _get_x and/or _set_x are found
563 def __new__(metaclass, name, bases, dict):
564 hits = {}
565 for key, val in dict.items():
566 if key.startswith("_get_"):
567 key = key[5:]
568 get, set = hits.get(key, (None, None))
569 get = val
570 hits[key] = get, set
571 elif key.startswith("_set_"):
572 key = key[5:]
573 get, set = hits.get(key, (None, None))
574 set = val
575 hits[key] = get, set
576 for key, (get, set) in hits.items():
577 dict[key] = property(get, set)
578 return super(autoproperty, metaclass).__new__(metaclass,
579 name, bases, dict)
580 class A(metaclass=autoproperty):
581 def _get_x(self):
582 return -self.__x
583 def _set_x(self, x):
584 self.__x = -x
585 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200586 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000587 a.x = 12
588 self.assertEqual(a.x, 12)
589 self.assertEqual(a._A__x, -12)
590
591 class multimetaclass(autoproperty, autosuper):
592 # Merge of multiple cooperating metaclasses
593 pass
594 class A(metaclass=multimetaclass):
595 def _get_x(self):
596 return "A"
597 class B(A):
598 def _get_x(self):
599 return "B" + self.__super._get_x()
600 class C(A):
601 def _get_x(self):
602 return "C" + self.__super._get_x()
603 class D(C, B):
604 def _get_x(self):
605 return "D" + self.__super._get_x()
606 self.assertEqual(D().x, "DCBA")
607
608 # Make sure type(x) doesn't call x.__class__.__init__
609 class T(type):
610 counter = 0
611 def __init__(self, *args):
612 T.counter += 1
613 class C(metaclass=T):
614 pass
615 self.assertEqual(T.counter, 1)
616 a = C()
617 self.assertEqual(type(a), C)
618 self.assertEqual(T.counter, 1)
619
620 class C(object): pass
621 c = C()
622 try: c()
623 except TypeError: pass
624 else: self.fail("calling object w/o call method should raise "
625 "TypeError")
626
627 # Testing code to find most derived baseclass
628 class A(type):
629 def __new__(*args, **kwargs):
630 return type.__new__(*args, **kwargs)
631
632 class B(object):
633 pass
634
635 class C(object, metaclass=A):
636 pass
637
638 # The most derived metaclass of D is A rather than type.
639 class D(B, C):
640 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000641 self.assertIs(A, type(D))
642
643 # issue1294232: correct metaclass calculation
644 new_calls = [] # to check the order of __new__ calls
645 class AMeta(type):
646 @staticmethod
647 def __new__(mcls, name, bases, ns):
648 new_calls.append('AMeta')
649 return super().__new__(mcls, name, bases, ns)
650 @classmethod
651 def __prepare__(mcls, name, bases):
652 return {}
653
654 class BMeta(AMeta):
655 @staticmethod
656 def __new__(mcls, name, bases, ns):
657 new_calls.append('BMeta')
658 return super().__new__(mcls, name, bases, ns)
659 @classmethod
660 def __prepare__(mcls, name, bases):
661 ns = super().__prepare__(name, bases)
662 ns['BMeta_was_here'] = True
663 return ns
664
665 class A(metaclass=AMeta):
666 pass
667 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000668 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000669
670 class B(metaclass=BMeta):
671 pass
672 # BMeta.__new__ calls AMeta.__new__ with super:
673 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000674 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000675
676 class C(A, B):
677 pass
678 # The most derived metaclass is BMeta:
679 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000680 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000681 # BMeta.__prepare__ should've been called:
682 self.assertIn('BMeta_was_here', C.__dict__)
683
684 # The order of the bases shouldn't matter:
685 class C2(B, A):
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', C2.__dict__)
690
691 # Check correct metaclass calculation when a metaclass is declared:
692 class D(C, metaclass=type):
693 pass
694 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000695 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000696 self.assertIn('BMeta_was_here', D.__dict__)
697
698 class E(C, metaclass=AMeta):
699 pass
700 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000701 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000702 self.assertIn('BMeta_was_here', E.__dict__)
703
704 # Special case: the given metaclass isn't a class,
705 # so there is no metaclass calculation.
706 marker = object()
707 def func(*args, **kwargs):
708 return marker
709 class X(metaclass=func):
710 pass
711 class Y(object, metaclass=func):
712 pass
713 class Z(D, metaclass=func):
714 pass
715 self.assertIs(marker, X)
716 self.assertIs(marker, Y)
717 self.assertIs(marker, Z)
718
719 # The given metaclass is a class,
720 # but not a descendant of type.
721 prepare_calls = [] # to track __prepare__ calls
722 class ANotMeta:
723 def __new__(mcls, *args, **kwargs):
724 new_calls.append('ANotMeta')
725 return super().__new__(mcls)
726 @classmethod
727 def __prepare__(mcls, name, bases):
728 prepare_calls.append('ANotMeta')
729 return {}
730 class BNotMeta(ANotMeta):
731 def __new__(mcls, *args, **kwargs):
732 new_calls.append('BNotMeta')
733 return super().__new__(mcls)
734 @classmethod
735 def __prepare__(mcls, name, bases):
736 prepare_calls.append('BNotMeta')
737 return super().__prepare__(name, bases)
738
739 class A(metaclass=ANotMeta):
740 pass
741 self.assertIs(ANotMeta, type(A))
742 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000743 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000744 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000745 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000746
747 class B(metaclass=BNotMeta):
748 pass
749 self.assertIs(BNotMeta, type(B))
750 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000751 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000752 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000753 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000754
755 class C(A, B):
756 pass
757 self.assertIs(BNotMeta, type(C))
758 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000759 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000760 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000761 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000762
763 class C2(B, A):
764 pass
765 self.assertIs(BNotMeta, type(C2))
766 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000767 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000768 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000769 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000770
771 # This is a TypeError, because of a metaclass conflict:
772 # BNotMeta is neither a subclass, nor a superclass of type
773 with self.assertRaises(TypeError):
774 class D(C, metaclass=type):
775 pass
776
777 class E(C, metaclass=ANotMeta):
778 pass
779 self.assertIs(BNotMeta, type(E))
780 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000781 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000782 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000783 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000784
785 class F(object(), C):
786 pass
787 self.assertIs(BNotMeta, type(F))
788 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000789 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000790 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000791 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000792
793 class F2(C, object()):
794 pass
795 self.assertIs(BNotMeta, type(F2))
796 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000797 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000798 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000799 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000800
801 # TypeError: BNotMeta is neither a
802 # subclass, nor a superclass of int
803 with self.assertRaises(TypeError):
804 class X(C, int()):
805 pass
806 with self.assertRaises(TypeError):
807 class X(int(), C):
808 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000809
810 def test_module_subclasses(self):
811 # Testing Python subclass of module...
812 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000813 MT = type(sys)
814 class MM(MT):
815 def __init__(self, name):
816 MT.__init__(self, name)
817 def __getattribute__(self, name):
818 log.append(("getattr", name))
819 return MT.__getattribute__(self, name)
820 def __setattr__(self, name, value):
821 log.append(("setattr", name, value))
822 MT.__setattr__(self, name, value)
823 def __delattr__(self, name):
824 log.append(("delattr", name))
825 MT.__delattr__(self, name)
826 a = MM("a")
827 a.foo = 12
828 x = a.foo
829 del a.foo
830 self.assertEqual(log, [("setattr", "foo", 12),
831 ("getattr", "foo"),
832 ("delattr", "foo")])
833
834 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000835 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000836 class Module(types.ModuleType, str):
837 pass
838 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000839 pass
840 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000841 self.fail("inheriting from ModuleType and str at the same time "
842 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000843
Georg Brandl479a7e72008-02-05 18:13:15 +0000844 def test_multiple_inheritance(self):
845 # Testing multiple inheritance...
846 class C(object):
847 def __init__(self):
848 self.__state = 0
849 def getstate(self):
850 return self.__state
851 def setstate(self, state):
852 self.__state = state
853 a = C()
854 self.assertEqual(a.getstate(), 0)
855 a.setstate(10)
856 self.assertEqual(a.getstate(), 10)
857 class D(dict, C):
858 def __init__(self):
859 type({}).__init__(self)
860 C.__init__(self)
861 d = D()
862 self.assertEqual(list(d.keys()), [])
863 d["hello"] = "world"
864 self.assertEqual(list(d.items()), [("hello", "world")])
865 self.assertEqual(d["hello"], "world")
866 self.assertEqual(d.getstate(), 0)
867 d.setstate(10)
868 self.assertEqual(d.getstate(), 10)
869 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000870
Georg Brandl479a7e72008-02-05 18:13:15 +0000871 # SF bug #442833
872 class Node(object):
873 def __int__(self):
874 return int(self.foo())
875 def foo(self):
876 return "23"
877 class Frag(Node, list):
878 def foo(self):
879 return "42"
880 self.assertEqual(Node().__int__(), 23)
881 self.assertEqual(int(Node()), 23)
882 self.assertEqual(Frag().__int__(), 42)
883 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000884
Georg Brandl479a7e72008-02-05 18:13:15 +0000885 def test_diamond_inheritence(self):
886 # Testing multiple inheritance special cases...
887 class A(object):
888 def spam(self): return "A"
889 self.assertEqual(A().spam(), "A")
890 class B(A):
891 def boo(self): return "B"
892 def spam(self): return "B"
893 self.assertEqual(B().spam(), "B")
894 self.assertEqual(B().boo(), "B")
895 class C(A):
896 def boo(self): return "C"
897 self.assertEqual(C().spam(), "A")
898 self.assertEqual(C().boo(), "C")
899 class D(B, C): pass
900 self.assertEqual(D().spam(), "B")
901 self.assertEqual(D().boo(), "B")
902 self.assertEqual(D.__mro__, (D, B, C, A, object))
903 class E(C, B): pass
904 self.assertEqual(E().spam(), "B")
905 self.assertEqual(E().boo(), "C")
906 self.assertEqual(E.__mro__, (E, C, B, A, object))
907 # MRO order disagreement
908 try:
909 class F(D, E): pass
910 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000911 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000912 else:
913 self.fail("expected MRO order disagreement (F)")
914 try:
915 class G(E, D): pass
916 except TypeError:
917 pass
918 else:
919 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000920
Georg Brandl479a7e72008-02-05 18:13:15 +0000921 # see thread python-dev/2002-October/029035.html
922 def test_ex5_from_c3_switch(self):
923 # Testing ex5 from C3 switch discussion...
924 class A(object): pass
925 class B(object): pass
926 class C(object): pass
927 class X(A): pass
928 class Y(A): pass
929 class Z(X,B,Y,C): pass
930 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931
Georg Brandl479a7e72008-02-05 18:13:15 +0000932 # see "A Monotonic Superclass Linearization for Dylan",
933 # by Kim Barrett et al. (OOPSLA 1996)
934 def test_monotonicity(self):
935 # Testing MRO monotonicity...
936 class Boat(object): pass
937 class DayBoat(Boat): pass
938 class WheelBoat(Boat): pass
939 class EngineLess(DayBoat): pass
940 class SmallMultihull(DayBoat): pass
941 class PedalWheelBoat(EngineLess,WheelBoat): pass
942 class SmallCatamaran(SmallMultihull): pass
943 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000944
Georg Brandl479a7e72008-02-05 18:13:15 +0000945 self.assertEqual(PedalWheelBoat.__mro__,
946 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
947 self.assertEqual(SmallCatamaran.__mro__,
948 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
949 self.assertEqual(Pedalo.__mro__,
950 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
951 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000952
Georg Brandl479a7e72008-02-05 18:13:15 +0000953 # see "A Monotonic Superclass Linearization for Dylan",
954 # by Kim Barrett et al. (OOPSLA 1996)
955 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200956 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000957 class Pane(object): pass
958 class ScrollingMixin(object): pass
959 class EditingMixin(object): pass
960 class ScrollablePane(Pane,ScrollingMixin): pass
961 class EditablePane(Pane,EditingMixin): pass
962 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000963
Georg Brandl479a7e72008-02-05 18:13:15 +0000964 self.assertEqual(EditableScrollablePane.__mro__,
965 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
966 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000967
Georg Brandl479a7e72008-02-05 18:13:15 +0000968 def test_mro_disagreement(self):
969 # Testing error messages for MRO disagreement...
970 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000971order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000972
Georg Brandl479a7e72008-02-05 18:13:15 +0000973 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000974 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000975 callable(*args)
976 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000977 # the exact msg is generally considered an impl detail
978 if support.check_impl_detail():
979 if not str(msg).startswith(expected):
980 self.fail("Message %r, expected %r" %
981 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000982 else:
983 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000984
Georg Brandl479a7e72008-02-05 18:13:15 +0000985 class A(object): pass
986 class B(A): pass
987 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000988
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 # Test some very simple errors
990 raises(TypeError, "duplicate base class A",
991 type, "X", (A, A), {})
992 raises(TypeError, mro_err_msg,
993 type, "X", (A, B), {})
994 raises(TypeError, mro_err_msg,
995 type, "X", (A, C, B), {})
996 # Test a slightly more complex error
997 class GridLayout(object): pass
998 class HorizontalGrid(GridLayout): pass
999 class VerticalGrid(GridLayout): pass
1000 class HVGrid(HorizontalGrid, VerticalGrid): pass
1001 class VHGrid(VerticalGrid, HorizontalGrid): pass
1002 raises(TypeError, mro_err_msg,
1003 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +00001004
Georg Brandl479a7e72008-02-05 18:13:15 +00001005 def test_object_class(self):
1006 # Testing object class...
1007 a = object()
1008 self.assertEqual(a.__class__, object)
1009 self.assertEqual(type(a), object)
1010 b = object()
1011 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001012 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001013 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001014 a.foo = 12
1015 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001016 pass
1017 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001019 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001020
Georg Brandl479a7e72008-02-05 18:13:15 +00001021 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001022 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001023 x = Cdict()
1024 self.assertEqual(x.__dict__, {})
1025 x.foo = 1
1026 self.assertEqual(x.foo, 1)
1027 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028
Georg Brandl479a7e72008-02-05 18:13:15 +00001029 def test_slots(self):
1030 # Testing __slots__...
1031 class C0(object):
1032 __slots__ = []
1033 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001034 self.assertNotHasAttr(x, "__dict__")
1035 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001036
1037 class C1(object):
1038 __slots__ = ['a']
1039 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001040 self.assertNotHasAttr(x, "__dict__")
1041 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001043 self.assertEqual(x.a, 1)
1044 x.a = None
1045 self.assertEqual(x.a, None)
1046 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001047 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001048
Georg Brandl479a7e72008-02-05 18:13:15 +00001049 class C3(object):
1050 __slots__ = ['a', 'b', 'c']
1051 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001052 self.assertNotHasAttr(x, "__dict__")
1053 self.assertNotHasAttr(x, 'a')
1054 self.assertNotHasAttr(x, 'b')
1055 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001056 x.a = 1
1057 x.b = 2
1058 x.c = 3
1059 self.assertEqual(x.a, 1)
1060 self.assertEqual(x.b, 2)
1061 self.assertEqual(x.c, 3)
1062
1063 class C4(object):
1064 """Validate name mangling"""
1065 __slots__ = ['__a']
1066 def __init__(self, value):
1067 self.__a = value
1068 def get(self):
1069 return self.__a
1070 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001071 self.assertNotHasAttr(x, '__dict__')
1072 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001073 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001074 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001075 x.__a = 6
1076 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001077 pass
1078 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001079 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001080
Georg Brandl479a7e72008-02-05 18:13:15 +00001081 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001082 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001083 class C(object):
1084 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001085 except TypeError:
1086 pass
1087 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001088 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001089 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001090 class C(object):
1091 __slots__ = ["foo bar"]
1092 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001093 pass
1094 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001095 self.fail("['foo bar'] slots not caught")
1096 try:
1097 class C(object):
1098 __slots__ = ["foo\0bar"]
1099 except TypeError:
1100 pass
1101 else:
1102 self.fail("['foo\\0bar'] slots not caught")
1103 try:
1104 class C(object):
1105 __slots__ = ["1"]
1106 except TypeError:
1107 pass
1108 else:
1109 self.fail("['1'] slots not caught")
1110 try:
1111 class C(object):
1112 __slots__ = [""]
1113 except TypeError:
1114 pass
1115 else:
1116 self.fail("[''] slots not caught")
1117 class C(object):
1118 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1119 # XXX(nnorwitz): was there supposed to be something tested
1120 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001121
Georg Brandl479a7e72008-02-05 18:13:15 +00001122 # Test a single string is not expanded as a sequence.
1123 class C(object):
1124 __slots__ = "abc"
1125 c = C()
1126 c.abc = 5
1127 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001128
Georg Brandl479a7e72008-02-05 18:13:15 +00001129 # Test unicode slot names
1130 # Test a single unicode string is not expanded as a sequence.
1131 class C(object):
1132 __slots__ = "abc"
1133 c = C()
1134 c.abc = 5
1135 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001136
Georg Brandl479a7e72008-02-05 18:13:15 +00001137 # _unicode_to_string used to modify slots in certain circumstances
1138 slots = ("foo", "bar")
1139 class C(object):
1140 __slots__ = slots
1141 x = C()
1142 x.foo = 5
1143 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001144 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001145 # this used to leak references
1146 try:
1147 class C(object):
1148 __slots__ = [chr(128)]
1149 except (TypeError, UnicodeEncodeError):
1150 pass
1151 else:
1152 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001153
Georg Brandl479a7e72008-02-05 18:13:15 +00001154 # Test leaks
1155 class Counted(object):
1156 counter = 0 # counts the number of instances alive
1157 def __init__(self):
1158 Counted.counter += 1
1159 def __del__(self):
1160 Counted.counter -= 1
1161 class C(object):
1162 __slots__ = ['a', 'b', 'c']
1163 x = C()
1164 x.a = Counted()
1165 x.b = Counted()
1166 x.c = Counted()
1167 self.assertEqual(Counted.counter, 3)
1168 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001169 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001170 self.assertEqual(Counted.counter, 0)
1171 class D(C):
1172 pass
1173 x = D()
1174 x.a = Counted()
1175 x.z = Counted()
1176 self.assertEqual(Counted.counter, 2)
1177 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001178 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001179 self.assertEqual(Counted.counter, 0)
1180 class E(D):
1181 __slots__ = ['e']
1182 x = E()
1183 x.a = Counted()
1184 x.z = Counted()
1185 x.e = Counted()
1186 self.assertEqual(Counted.counter, 3)
1187 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001188 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001189 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001190
Georg Brandl479a7e72008-02-05 18:13:15 +00001191 # Test cyclical leaks [SF bug 519621]
1192 class F(object):
1193 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001194 s = F()
1195 s.a = [Counted(), s]
1196 self.assertEqual(Counted.counter, 1)
1197 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001198 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001199 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001200
Georg Brandl479a7e72008-02-05 18:13:15 +00001201 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001202 if hasattr(gc, 'get_objects'):
1203 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001204 def __eq__(self, other):
1205 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001206 g = G()
1207 orig_objects = len(gc.get_objects())
1208 for i in range(10):
1209 g==g
1210 new_objects = len(gc.get_objects())
1211 self.assertEqual(orig_objects, new_objects)
1212
Georg Brandl479a7e72008-02-05 18:13:15 +00001213 class H(object):
1214 __slots__ = ['a', 'b']
1215 def __init__(self):
1216 self.a = 1
1217 self.b = 2
1218 def __del__(self_):
1219 self.assertEqual(self_.a, 1)
1220 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001221 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001222 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001223 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001224 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001225
Benjamin Petersond12362a2009-12-30 19:44:54 +00001226 class X(object):
1227 __slots__ = "a"
1228 with self.assertRaises(AttributeError):
1229 del X().a
1230
Georg Brandl479a7e72008-02-05 18:13:15 +00001231 def test_slots_special(self):
1232 # Testing __dict__ and __weakref__ in __slots__...
1233 class D(object):
1234 __slots__ = ["__dict__"]
1235 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001236 self.assertHasAttr(a, "__dict__")
1237 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001238 a.foo = 42
1239 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001240
Georg Brandl479a7e72008-02-05 18:13:15 +00001241 class W(object):
1242 __slots__ = ["__weakref__"]
1243 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001244 self.assertHasAttr(a, "__weakref__")
1245 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001246 try:
1247 a.foo = 42
1248 except AttributeError:
1249 pass
1250 else:
1251 self.fail("shouldn't be allowed to set a.foo")
1252
1253 class C1(W, D):
1254 __slots__ = []
1255 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001256 self.assertHasAttr(a, "__dict__")
1257 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001258 a.foo = 42
1259 self.assertEqual(a.__dict__, {"foo": 42})
1260
1261 class C2(D, W):
1262 __slots__ = []
1263 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001264 self.assertHasAttr(a, "__dict__")
1265 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001266 a.foo = 42
1267 self.assertEqual(a.__dict__, {"foo": 42})
1268
Christian Heimesa156e092008-02-16 07:38:31 +00001269 def test_slots_descriptor(self):
1270 # Issue2115: slot descriptors did not correctly check
1271 # the type of the given object
1272 import abc
1273 class MyABC(metaclass=abc.ABCMeta):
1274 __slots__ = "a"
1275
1276 class Unrelated(object):
1277 pass
1278 MyABC.register(Unrelated)
1279
1280 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001281 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001282
1283 # This used to crash
1284 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1285
Georg Brandl479a7e72008-02-05 18:13:15 +00001286 def test_dynamics(self):
1287 # Testing class attribute propagation...
1288 class D(object):
1289 pass
1290 class E(D):
1291 pass
1292 class F(D):
1293 pass
1294 D.foo = 1
1295 self.assertEqual(D.foo, 1)
1296 # Test that dynamic attributes are inherited
1297 self.assertEqual(E.foo, 1)
1298 self.assertEqual(F.foo, 1)
1299 # Test dynamic instances
1300 class C(object):
1301 pass
1302 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001303 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001304 C.foobar = 2
1305 self.assertEqual(a.foobar, 2)
1306 C.method = lambda self: 42
1307 self.assertEqual(a.method(), 42)
1308 C.__repr__ = lambda self: "C()"
1309 self.assertEqual(repr(a), "C()")
1310 C.__int__ = lambda self: 100
1311 self.assertEqual(int(a), 100)
1312 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001313 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001314 def mygetattr(self, name):
1315 if name == "spam":
1316 return "spam"
1317 raise AttributeError
1318 C.__getattr__ = mygetattr
1319 self.assertEqual(a.spam, "spam")
1320 a.new = 12
1321 self.assertEqual(a.new, 12)
1322 def mysetattr(self, name, value):
1323 if name == "spam":
1324 raise AttributeError
1325 return object.__setattr__(self, name, value)
1326 C.__setattr__ = mysetattr
1327 try:
1328 a.spam = "not spam"
1329 except AttributeError:
1330 pass
1331 else:
1332 self.fail("expected AttributeError")
1333 self.assertEqual(a.spam, "spam")
1334 class D(C):
1335 pass
1336 d = D()
1337 d.foo = 1
1338 self.assertEqual(d.foo, 1)
1339
1340 # Test handling of int*seq and seq*int
1341 class I(int):
1342 pass
1343 self.assertEqual("a"*I(2), "aa")
1344 self.assertEqual(I(2)*"a", "aa")
1345 self.assertEqual(2*I(3), 6)
1346 self.assertEqual(I(3)*2, 6)
1347 self.assertEqual(I(3)*I(2), 6)
1348
Georg Brandl479a7e72008-02-05 18:13:15 +00001349 # Test comparison of classes with dynamic metaclasses
1350 class dynamicmetaclass(type):
1351 pass
1352 class someclass(metaclass=dynamicmetaclass):
1353 pass
1354 self.assertNotEqual(someclass, object)
1355
1356 def test_errors(self):
1357 # Testing errors...
1358 try:
1359 class C(list, dict):
1360 pass
1361 except TypeError:
1362 pass
1363 else:
1364 self.fail("inheritance from both list and dict should be illegal")
1365
1366 try:
1367 class C(object, None):
1368 pass
1369 except TypeError:
1370 pass
1371 else:
1372 self.fail("inheritance from non-type should be illegal")
1373 class Classic:
1374 pass
1375
1376 try:
1377 class C(type(len)):
1378 pass
1379 except TypeError:
1380 pass
1381 else:
1382 self.fail("inheritance from CFunction should be illegal")
1383
1384 try:
1385 class C(object):
1386 __slots__ = 1
1387 except TypeError:
1388 pass
1389 else:
1390 self.fail("__slots__ = 1 should be illegal")
1391
1392 try:
1393 class C(object):
1394 __slots__ = [1]
1395 except TypeError:
1396 pass
1397 else:
1398 self.fail("__slots__ = [1] should be illegal")
1399
1400 class M1(type):
1401 pass
1402 class M2(type):
1403 pass
1404 class A1(object, metaclass=M1):
1405 pass
1406 class A2(object, metaclass=M2):
1407 pass
1408 try:
1409 class B(A1, A2):
1410 pass
1411 except TypeError:
1412 pass
1413 else:
1414 self.fail("finding the most derived metaclass should have failed")
1415
1416 def test_classmethods(self):
1417 # Testing class methods...
1418 class C(object):
1419 def foo(*a): return a
1420 goo = classmethod(foo)
1421 c = C()
1422 self.assertEqual(C.goo(1), (C, 1))
1423 self.assertEqual(c.goo(1), (C, 1))
1424 self.assertEqual(c.foo(1), (c, 1))
1425 class D(C):
1426 pass
1427 d = D()
1428 self.assertEqual(D.goo(1), (D, 1))
1429 self.assertEqual(d.goo(1), (D, 1))
1430 self.assertEqual(d.foo(1), (d, 1))
1431 self.assertEqual(D.foo(d, 1), (d, 1))
1432 # Test for a specific crash (SF bug 528132)
1433 def f(cls, arg): return (cls, arg)
1434 ff = classmethod(f)
1435 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1436 self.assertEqual(ff.__get__(0)(42), (int, 42))
1437
1438 # Test super() with classmethods (SF bug 535444)
1439 self.assertEqual(C.goo.__self__, C)
1440 self.assertEqual(D.goo.__self__, D)
1441 self.assertEqual(super(D,D).goo.__self__, D)
1442 self.assertEqual(super(D,d).goo.__self__, D)
1443 self.assertEqual(super(D,D).goo(), (D,))
1444 self.assertEqual(super(D,d).goo(), (D,))
1445
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001446 # Verify that a non-callable will raise
1447 meth = classmethod(1).__get__(1)
1448 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001449
1450 # Verify that classmethod() doesn't allow keyword args
1451 try:
1452 classmethod(f, kw=1)
1453 except TypeError:
1454 pass
1455 else:
1456 self.fail("classmethod shouldn't accept keyword args")
1457
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001458 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001459 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001460 cm.x = 42
1461 self.assertEqual(cm.x, 42)
1462 self.assertEqual(cm.__dict__, {"x" : 42})
1463 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001464 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001465
Benjamin Petersone549ead2009-03-28 21:42:05 +00001466 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001467 def test_classmethods_in_c(self):
1468 # Testing C-based class methods...
1469 import xxsubtype as spam
1470 a = (1, 2, 3)
1471 d = {'abc': 123}
1472 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1473 self.assertEqual(x, spam.spamlist)
1474 self.assertEqual(a, a1)
1475 self.assertEqual(d, d1)
1476 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1477 self.assertEqual(x, spam.spamlist)
1478 self.assertEqual(a, a1)
1479 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001480 spam_cm = spam.spamlist.__dict__['classmeth']
1481 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1482 self.assertEqual(x2, spam.spamlist)
1483 self.assertEqual(a2, a1)
1484 self.assertEqual(d2, d1)
1485 class SubSpam(spam.spamlist): pass
1486 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1487 self.assertEqual(x2, SubSpam)
1488 self.assertEqual(a2, a1)
1489 self.assertEqual(d2, d1)
1490 with self.assertRaises(TypeError):
1491 spam_cm()
1492 with self.assertRaises(TypeError):
1493 spam_cm(spam.spamlist())
1494 with self.assertRaises(TypeError):
1495 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001496
1497 def test_staticmethods(self):
1498 # Testing static methods...
1499 class C(object):
1500 def foo(*a): return a
1501 goo = staticmethod(foo)
1502 c = C()
1503 self.assertEqual(C.goo(1), (1,))
1504 self.assertEqual(c.goo(1), (1,))
1505 self.assertEqual(c.foo(1), (c, 1,))
1506 class D(C):
1507 pass
1508 d = D()
1509 self.assertEqual(D.goo(1), (1,))
1510 self.assertEqual(d.goo(1), (1,))
1511 self.assertEqual(d.foo(1), (d, 1))
1512 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001513 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001514 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001515 sm.x = 42
1516 self.assertEqual(sm.x, 42)
1517 self.assertEqual(sm.__dict__, {"x" : 42})
1518 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001519 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001520
Benjamin Petersone549ead2009-03-28 21:42:05 +00001521 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001522 def test_staticmethods_in_c(self):
1523 # Testing C-based static methods...
1524 import xxsubtype as spam
1525 a = (1, 2, 3)
1526 d = {"abc": 123}
1527 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1528 self.assertEqual(x, None)
1529 self.assertEqual(a, a1)
1530 self.assertEqual(d, d1)
1531 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1532 self.assertEqual(x, None)
1533 self.assertEqual(a, a1)
1534 self.assertEqual(d, d1)
1535
1536 def test_classic(self):
1537 # Testing classic classes...
1538 class C:
1539 def foo(*a): return a
1540 goo = classmethod(foo)
1541 c = C()
1542 self.assertEqual(C.goo(1), (C, 1))
1543 self.assertEqual(c.goo(1), (C, 1))
1544 self.assertEqual(c.foo(1), (c, 1))
1545 class D(C):
1546 pass
1547 d = D()
1548 self.assertEqual(D.goo(1), (D, 1))
1549 self.assertEqual(d.goo(1), (D, 1))
1550 self.assertEqual(d.foo(1), (d, 1))
1551 self.assertEqual(D.foo(d, 1), (d, 1))
1552 class E: # *not* subclassing from C
1553 foo = C.foo
1554 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001555 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001556
1557 def test_compattr(self):
1558 # Testing computed attributes...
1559 class C(object):
1560 class computed_attribute(object):
1561 def __init__(self, get, set=None, delete=None):
1562 self.__get = get
1563 self.__set = set
1564 self.__delete = delete
1565 def __get__(self, obj, type=None):
1566 return self.__get(obj)
1567 def __set__(self, obj, value):
1568 return self.__set(obj, value)
1569 def __delete__(self, obj):
1570 return self.__delete(obj)
1571 def __init__(self):
1572 self.__x = 0
1573 def __get_x(self):
1574 x = self.__x
1575 self.__x = x+1
1576 return x
1577 def __set_x(self, x):
1578 self.__x = x
1579 def __delete_x(self):
1580 del self.__x
1581 x = computed_attribute(__get_x, __set_x, __delete_x)
1582 a = C()
1583 self.assertEqual(a.x, 0)
1584 self.assertEqual(a.x, 1)
1585 a.x = 10
1586 self.assertEqual(a.x, 10)
1587 self.assertEqual(a.x, 11)
1588 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001589 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001590
1591 def test_newslots(self):
1592 # Testing __new__ slot override...
1593 class C(list):
1594 def __new__(cls):
1595 self = list.__new__(cls)
1596 self.foo = 1
1597 return self
1598 def __init__(self):
1599 self.foo = self.foo + 2
1600 a = C()
1601 self.assertEqual(a.foo, 3)
1602 self.assertEqual(a.__class__, C)
1603 class D(C):
1604 pass
1605 b = D()
1606 self.assertEqual(b.foo, 3)
1607 self.assertEqual(b.__class__, D)
1608
1609 def test_altmro(self):
1610 # Testing mro() and overriding it...
1611 class A(object):
1612 def f(self): return "A"
1613 class B(A):
1614 pass
1615 class C(A):
1616 def f(self): return "C"
1617 class D(B, C):
1618 pass
1619 self.assertEqual(D.mro(), [D, B, C, A, object])
1620 self.assertEqual(D.__mro__, (D, B, C, A, object))
1621 self.assertEqual(D().f(), "C")
1622
1623 class PerverseMetaType(type):
1624 def mro(cls):
1625 L = type.mro(cls)
1626 L.reverse()
1627 return L
1628 class X(D,B,C,A, metaclass=PerverseMetaType):
1629 pass
1630 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1631 self.assertEqual(X().f(), "A")
1632
1633 try:
1634 class _metaclass(type):
1635 def mro(self):
1636 return [self, dict, object]
1637 class X(object, metaclass=_metaclass):
1638 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001639 # In CPython, the class creation above already raises
1640 # TypeError, as a protection against the fact that
1641 # instances of X would segfault it. In other Python
1642 # implementations it would be ok to let the class X
1643 # be created, but instead get a clean TypeError on the
1644 # __setitem__ below.
1645 x = object.__new__(X)
1646 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001647 except TypeError:
1648 pass
1649 else:
1650 self.fail("devious mro() return not caught")
1651
1652 try:
1653 class _metaclass(type):
1654 def mro(self):
1655 return [1]
1656 class X(object, metaclass=_metaclass):
1657 pass
1658 except TypeError:
1659 pass
1660 else:
1661 self.fail("non-class mro() return not caught")
1662
1663 try:
1664 class _metaclass(type):
1665 def mro(self):
1666 return 1
1667 class X(object, metaclass=_metaclass):
1668 pass
1669 except TypeError:
1670 pass
1671 else:
1672 self.fail("non-sequence mro() return not caught")
1673
1674 def test_overloading(self):
1675 # Testing operator overloading...
1676
1677 class B(object):
1678 "Intermediate class because object doesn't have a __setattr__"
1679
1680 class C(B):
1681 def __getattr__(self, name):
1682 if name == "foo":
1683 return ("getattr", name)
1684 else:
1685 raise AttributeError
1686 def __setattr__(self, name, value):
1687 if name == "foo":
1688 self.setattr = (name, value)
1689 else:
1690 return B.__setattr__(self, name, value)
1691 def __delattr__(self, name):
1692 if name == "foo":
1693 self.delattr = name
1694 else:
1695 return B.__delattr__(self, name)
1696
1697 def __getitem__(self, key):
1698 return ("getitem", key)
1699 def __setitem__(self, key, value):
1700 self.setitem = (key, value)
1701 def __delitem__(self, key):
1702 self.delitem = key
1703
1704 a = C()
1705 self.assertEqual(a.foo, ("getattr", "foo"))
1706 a.foo = 12
1707 self.assertEqual(a.setattr, ("foo", 12))
1708 del a.foo
1709 self.assertEqual(a.delattr, "foo")
1710
1711 self.assertEqual(a[12], ("getitem", 12))
1712 a[12] = 21
1713 self.assertEqual(a.setitem, (12, 21))
1714 del a[12]
1715 self.assertEqual(a.delitem, 12)
1716
1717 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1718 a[0:10] = "foo"
1719 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1720 del a[0:10]
1721 self.assertEqual(a.delitem, (slice(0, 10)))
1722
1723 def test_methods(self):
1724 # Testing methods...
1725 class C(object):
1726 def __init__(self, x):
1727 self.x = x
1728 def foo(self):
1729 return self.x
1730 c1 = C(1)
1731 self.assertEqual(c1.foo(), 1)
1732 class D(C):
1733 boo = C.foo
1734 goo = c1.foo
1735 d2 = D(2)
1736 self.assertEqual(d2.foo(), 2)
1737 self.assertEqual(d2.boo(), 2)
1738 self.assertEqual(d2.goo(), 1)
1739 class E(object):
1740 foo = C.foo
1741 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001742 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001743
Benjamin Peterson224205f2009-05-08 03:25:19 +00001744 def test_special_method_lookup(self):
1745 # The lookup of special methods bypasses __getattr__ and
1746 # __getattribute__, but they still can be descriptors.
1747
1748 def run_context(manager):
1749 with manager:
1750 pass
1751 def iden(self):
1752 return self
1753 def hello(self):
1754 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001755 def empty_seq(self):
1756 return []
Benjamin Peterson71557592013-04-13 17:20:36 -04001757 def zero(self):
Benjamin Petersona5758c02009-05-09 18:15:04 +00001758 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001759 def complex_num(self):
1760 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001761 def stop(self):
1762 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001763 def return_true(self, thing=None):
1764 return True
1765 def do_isinstance(obj):
1766 return isinstance(int, obj)
1767 def do_issubclass(obj):
1768 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001769 def do_dict_missing(checker):
1770 class DictSub(checker.__class__, dict):
1771 pass
1772 self.assertEqual(DictSub()["hi"], 4)
1773 def some_number(self_, key):
1774 self.assertEqual(key, "hi")
1775 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001776 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001777 def format_impl(self, spec):
1778 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001779
1780 # It would be nice to have every special method tested here, but I'm
1781 # only listing the ones I can remember outside of typeobject.c, since it
1782 # does it right.
1783 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001784 ("__bytes__", bytes, hello, set(), {}),
1785 ("__reversed__", reversed, empty_seq, set(), {}),
1786 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001787 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001788 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1789 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001790 ("__missing__", do_dict_missing, some_number,
1791 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001792 ("__subclasscheck__", do_issubclass, return_true,
1793 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001794 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1795 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001796 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001797 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001798 ("__floor__", math.floor, zero, set(), {}),
1799 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001800 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001801 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001802 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001803 ("__round__", round, zero, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001804 ]
1805
1806 class Checker(object):
1807 def __getattr__(self, attr, test=self):
1808 test.fail("__getattr__ called with {0}".format(attr))
1809 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001810 if attr not in ok:
1811 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001812 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001813 class SpecialDescr(object):
1814 def __init__(self, impl):
1815 self.impl = impl
1816 def __get__(self, obj, owner):
1817 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001818 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001819 class MyException(Exception):
1820 pass
1821 class ErrDescr(object):
1822 def __get__(self, obj, owner):
1823 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001824
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001825 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001826 class X(Checker):
1827 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001828 for attr, obj in env.items():
1829 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001830 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001831 runner(X())
1832
1833 record = []
1834 class X(Checker):
1835 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001836 for attr, obj in env.items():
1837 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001838 setattr(X, name, SpecialDescr(meth_impl))
1839 runner(X())
1840 self.assertEqual(record, [1], name)
1841
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001842 class X(Checker):
1843 pass
1844 for attr, obj in env.items():
1845 setattr(X, attr, obj)
1846 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001847 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001848
Georg Brandl479a7e72008-02-05 18:13:15 +00001849 def test_specials(self):
1850 # Testing special operators...
1851 # Test operators like __hash__ for which a built-in default exists
1852
1853 # Test the default behavior for static classes
1854 class C(object):
1855 def __getitem__(self, i):
1856 if 0 <= i < 10: return i
1857 raise IndexError
1858 c1 = C()
1859 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001860 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001861 self.assertNotEqual(id(c1), id(c2))
1862 hash(c1)
1863 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001864 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001865 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001866 self.assertFalse(c1 != c1)
1867 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001868 # Note that the module name appears in str/repr, and that varies
1869 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001870 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001871 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001872 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001873 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001874 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001875 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001876 # Test the default behavior for dynamic classes
1877 class D(object):
1878 def __getitem__(self, i):
1879 if 0 <= i < 10: return i
1880 raise IndexError
1881 d1 = D()
1882 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001883 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001884 self.assertNotEqual(id(d1), id(d2))
1885 hash(d1)
1886 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001887 self.assertEqual(d1, d1)
1888 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001889 self.assertFalse(d1 != d1)
1890 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001891 # Note that the module name appears in str/repr, and that varies
1892 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001893 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001894 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001895 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001896 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001897 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001898 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001899 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001900 class Proxy(object):
1901 def __init__(self, x):
1902 self.x = x
1903 def __bool__(self):
1904 return not not self.x
1905 def __hash__(self):
1906 return hash(self.x)
1907 def __eq__(self, other):
1908 return self.x == other
1909 def __ne__(self, other):
1910 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001911 def __ge__(self, other):
1912 return self.x >= other
1913 def __gt__(self, other):
1914 return self.x > other
1915 def __le__(self, other):
1916 return self.x <= other
1917 def __lt__(self, other):
1918 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001919 def __str__(self):
1920 return "Proxy:%s" % self.x
1921 def __repr__(self):
1922 return "Proxy(%r)" % self.x
1923 def __contains__(self, value):
1924 return value in self.x
1925 p0 = Proxy(0)
1926 p1 = Proxy(1)
1927 p_1 = Proxy(-1)
1928 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001929 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001930 self.assertEqual(hash(p0), hash(0))
1931 self.assertEqual(p0, p0)
1932 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001933 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001934 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001935 self.assertTrue(p0 < p1)
1936 self.assertTrue(p0 <= p1)
1937 self.assertTrue(p1 > p0)
1938 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001939 self.assertEqual(str(p0), "Proxy:0")
1940 self.assertEqual(repr(p0), "Proxy(0)")
1941 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001942 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001943 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001944 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001945 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001946
Georg Brandl479a7e72008-02-05 18:13:15 +00001947 def test_weakrefs(self):
1948 # Testing weak references...
1949 import weakref
1950 class C(object):
1951 pass
1952 c = C()
1953 r = weakref.ref(c)
1954 self.assertEqual(r(), c)
1955 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001956 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001957 self.assertEqual(r(), None)
1958 del r
1959 class NoWeak(object):
1960 __slots__ = ['foo']
1961 no = NoWeak()
1962 try:
1963 weakref.ref(no)
1964 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001965 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00001966 else:
1967 self.fail("weakref.ref(no) should be illegal")
1968 class Weak(object):
1969 __slots__ = ['foo', '__weakref__']
1970 yes = Weak()
1971 r = weakref.ref(yes)
1972 self.assertEqual(r(), yes)
1973 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001974 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001975 self.assertEqual(r(), None)
1976 del r
1977
1978 def test_properties(self):
1979 # Testing property...
1980 class C(object):
1981 def getx(self):
1982 return self.__x
1983 def setx(self, value):
1984 self.__x = value
1985 def delx(self):
1986 del self.__x
1987 x = property(getx, setx, delx, doc="I'm the x property.")
1988 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001989 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001990 a.x = 42
1991 self.assertEqual(a._C__x, 42)
1992 self.assertEqual(a.x, 42)
1993 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001994 self.assertNotHasAttr(a, "x")
1995 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001996 C.x.__set__(a, 100)
1997 self.assertEqual(C.x.__get__(a), 100)
1998 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001999 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00002000
2001 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00002002 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00002003
2004 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002005 self.assertIn("__doc__", attrs)
2006 self.assertIn("fget", attrs)
2007 self.assertIn("fset", attrs)
2008 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002009
2010 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002011 self.assertIs(raw.fget, C.__dict__['getx'])
2012 self.assertIs(raw.fset, C.__dict__['setx'])
2013 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002014
2015 for attr in "__doc__", "fget", "fset", "fdel":
2016 try:
2017 setattr(raw, attr, 42)
2018 except AttributeError as msg:
2019 if str(msg).find('readonly') < 0:
2020 self.fail("when setting readonly attr %r on a property, "
2021 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2022 else:
2023 self.fail("expected AttributeError from trying to set readonly %r "
2024 "attr on a property" % attr)
2025
2026 class D(object):
2027 __getitem__ = property(lambda s: 1/0)
2028
2029 d = D()
2030 try:
2031 for i in d:
2032 str(i)
2033 except ZeroDivisionError:
2034 pass
2035 else:
2036 self.fail("expected ZeroDivisionError from bad property")
2037
R. David Murray378c0cf2010-02-24 01:46:21 +00002038 @unittest.skipIf(sys.flags.optimize >= 2,
2039 "Docstrings are omitted with -O2 and above")
2040 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002041 class E(object):
2042 def getter(self):
2043 "getter method"
2044 return 0
2045 def setter(self_, value):
2046 "setter method"
2047 pass
2048 prop = property(getter)
2049 self.assertEqual(prop.__doc__, "getter method")
2050 prop2 = property(fset=setter)
2051 self.assertEqual(prop2.__doc__, None)
2052
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002053 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002054 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002055 # this segfaulted in 2.5b2
2056 try:
2057 import _testcapi
2058 except ImportError:
2059 pass
2060 else:
2061 class X(object):
2062 p = property(_testcapi.test_with_docstring)
2063
2064 def test_properties_plus(self):
2065 class C(object):
2066 foo = property(doc="hello")
2067 @foo.getter
2068 def foo(self):
2069 return self._foo
2070 @foo.setter
2071 def foo(self, value):
2072 self._foo = abs(value)
2073 @foo.deleter
2074 def foo(self):
2075 del self._foo
2076 c = C()
2077 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002078 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002079 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002080 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002081 self.assertEqual(c._foo, 42)
2082 self.assertEqual(c.foo, 42)
2083 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002084 self.assertNotHasAttr(c, '_foo')
2085 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002086
2087 class D(C):
2088 @C.foo.deleter
2089 def foo(self):
2090 try:
2091 del self._foo
2092 except AttributeError:
2093 pass
2094 d = D()
2095 d.foo = 24
2096 self.assertEqual(d.foo, 24)
2097 del d.foo
2098 del d.foo
2099
2100 class E(object):
2101 @property
2102 def foo(self):
2103 return self._foo
2104 @foo.setter
2105 def foo(self, value):
2106 raise RuntimeError
2107 @foo.setter
2108 def foo(self, value):
2109 self._foo = abs(value)
2110 @foo.deleter
2111 def foo(self, value=None):
2112 del self._foo
2113
2114 e = E()
2115 e.foo = -42
2116 self.assertEqual(e.foo, 42)
2117 del e.foo
2118
2119 class F(E):
2120 @E.foo.deleter
2121 def foo(self):
2122 del self._foo
2123 @foo.setter
2124 def foo(self, value):
2125 self._foo = max(0, value)
2126 f = F()
2127 f.foo = -10
2128 self.assertEqual(f.foo, 0)
2129 del f.foo
2130
2131 def test_dict_constructors(self):
2132 # Testing dict constructor ...
2133 d = dict()
2134 self.assertEqual(d, {})
2135 d = dict({})
2136 self.assertEqual(d, {})
2137 d = dict({1: 2, 'a': 'b'})
2138 self.assertEqual(d, {1: 2, 'a': 'b'})
2139 self.assertEqual(d, dict(list(d.items())))
2140 self.assertEqual(d, dict(iter(d.items())))
2141 d = dict({'one':1, 'two':2})
2142 self.assertEqual(d, dict(one=1, two=2))
2143 self.assertEqual(d, dict(**d))
2144 self.assertEqual(d, dict({"one": 1}, two=2))
2145 self.assertEqual(d, dict([("two", 2)], one=1))
2146 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2147 self.assertEqual(d, dict(**d))
2148
2149 for badarg in 0, 0, 0j, "0", [0], (0,):
2150 try:
2151 dict(badarg)
2152 except TypeError:
2153 pass
2154 except ValueError:
2155 if badarg == "0":
2156 # It's a sequence, and its elements are also sequences (gotta
2157 # love strings <wink>), but they aren't of length 2, so this
2158 # one seemed better as a ValueError than a TypeError.
2159 pass
2160 else:
2161 self.fail("no TypeError from dict(%r)" % badarg)
2162 else:
2163 self.fail("no TypeError from dict(%r)" % badarg)
2164
2165 try:
2166 dict({}, {})
2167 except TypeError:
2168 pass
2169 else:
2170 self.fail("no TypeError from dict({}, {})")
2171
2172 class Mapping:
2173 # Lacks a .keys() method; will be added later.
2174 dict = {1:2, 3:4, 'a':1j}
2175
2176 try:
2177 dict(Mapping())
2178 except TypeError:
2179 pass
2180 else:
2181 self.fail("no TypeError from dict(incomplete mapping)")
2182
2183 Mapping.keys = lambda self: list(self.dict.keys())
2184 Mapping.__getitem__ = lambda self, i: self.dict[i]
2185 d = dict(Mapping())
2186 self.assertEqual(d, Mapping.dict)
2187
2188 # Init from sequence of iterable objects, each producing a 2-sequence.
2189 class AddressBookEntry:
2190 def __init__(self, first, last):
2191 self.first = first
2192 self.last = last
2193 def __iter__(self):
2194 return iter([self.first, self.last])
2195
2196 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2197 AddressBookEntry('Barry', 'Peters'),
2198 AddressBookEntry('Tim', 'Peters'),
2199 AddressBookEntry('Barry', 'Warsaw')])
2200 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2201
2202 d = dict(zip(range(4), range(1, 5)))
2203 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2204
2205 # Bad sequence lengths.
2206 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2207 try:
2208 dict(bad)
2209 except ValueError:
2210 pass
2211 else:
2212 self.fail("no ValueError from dict(%r)" % bad)
2213
2214 def test_dir(self):
2215 # Testing dir() ...
2216 junk = 12
2217 self.assertEqual(dir(), ['junk', 'self'])
2218 del junk
2219
2220 # Just make sure these don't blow up!
2221 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2222 dir(arg)
2223
2224 # Test dir on new-style classes. Since these have object as a
2225 # base class, a lot more gets sucked in.
2226 def interesting(strings):
2227 return [s for s in strings if not s.startswith('_')]
2228
2229 class C(object):
2230 Cdata = 1
2231 def Cmethod(self): pass
2232
2233 cstuff = ['Cdata', 'Cmethod']
2234 self.assertEqual(interesting(dir(C)), cstuff)
2235
2236 c = C()
2237 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002238 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002239
2240 c.cdata = 2
2241 c.cmethod = lambda self: 0
2242 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002243 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002244
2245 class A(C):
2246 Adata = 1
2247 def Amethod(self): pass
2248
2249 astuff = ['Adata', 'Amethod'] + cstuff
2250 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002251 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002252 a = A()
2253 self.assertEqual(interesting(dir(a)), astuff)
2254 a.adata = 42
2255 a.amethod = lambda self: 3
2256 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002257 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002258
2259 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002260 class M(type(sys)):
2261 pass
2262 minstance = M("m")
2263 minstance.b = 2
2264 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002265 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002266 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002267 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002268 self.assertEqual(names, ['a', 'b'])
2269
2270 class M2(M):
2271 def getdict(self):
2272 return "Not a dict!"
2273 __dict__ = property(getdict)
2274
2275 m2instance = M2("m2")
2276 m2instance.b = 2
2277 m2instance.a = 1
2278 self.assertEqual(m2instance.__dict__, "Not a dict!")
2279 try:
2280 dir(m2instance)
2281 except TypeError:
2282 pass
2283
2284 # Two essentially featureless objects, just inheriting stuff from
2285 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002286 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002287
2288 # Nasty test case for proxied objects
2289 class Wrapper(object):
2290 def __init__(self, obj):
2291 self.__obj = obj
2292 def __repr__(self):
2293 return "Wrapper(%s)" % repr(self.__obj)
2294 def __getitem__(self, key):
2295 return Wrapper(self.__obj[key])
2296 def __len__(self):
2297 return len(self.__obj)
2298 def __getattr__(self, name):
2299 return Wrapper(getattr(self.__obj, name))
2300
2301 class C(object):
2302 def __getclass(self):
2303 return Wrapper(type(self))
2304 __class__ = property(__getclass)
2305
2306 dir(C()) # This used to segfault
2307
2308 def test_supers(self):
2309 # Testing super...
2310
2311 class A(object):
2312 def meth(self, a):
2313 return "A(%r)" % a
2314
2315 self.assertEqual(A().meth(1), "A(1)")
2316
2317 class B(A):
2318 def __init__(self):
2319 self.__super = super(B, self)
2320 def meth(self, a):
2321 return "B(%r)" % a + self.__super.meth(a)
2322
2323 self.assertEqual(B().meth(2), "B(2)A(2)")
2324
2325 class C(A):
2326 def meth(self, a):
2327 return "C(%r)" % a + self.__super.meth(a)
2328 C._C__super = super(C)
2329
2330 self.assertEqual(C().meth(3), "C(3)A(3)")
2331
2332 class D(C, B):
2333 def meth(self, a):
2334 return "D(%r)" % a + super(D, self).meth(a)
2335
2336 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2337
2338 # Test for subclassing super
2339
2340 class mysuper(super):
2341 def __init__(self, *args):
2342 return super(mysuper, self).__init__(*args)
2343
2344 class E(D):
2345 def meth(self, a):
2346 return "E(%r)" % a + mysuper(E, self).meth(a)
2347
2348 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2349
2350 class F(E):
2351 def meth(self, a):
2352 s = self.__super # == mysuper(F, self)
2353 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2354 F._F__super = mysuper(F)
2355
2356 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2357
2358 # Make sure certain errors are raised
2359
2360 try:
2361 super(D, 42)
2362 except TypeError:
2363 pass
2364 else:
2365 self.fail("shouldn't allow super(D, 42)")
2366
2367 try:
2368 super(D, C())
2369 except TypeError:
2370 pass
2371 else:
2372 self.fail("shouldn't allow super(D, C())")
2373
2374 try:
2375 super(D).__get__(12)
2376 except TypeError:
2377 pass
2378 else:
2379 self.fail("shouldn't allow super(D).__get__(12)")
2380
2381 try:
2382 super(D).__get__(C())
2383 except TypeError:
2384 pass
2385 else:
2386 self.fail("shouldn't allow super(D).__get__(C())")
2387
2388 # Make sure data descriptors can be overridden and accessed via super
2389 # (new feature in Python 2.3)
2390
2391 class DDbase(object):
2392 def getx(self): return 42
2393 x = property(getx)
2394
2395 class DDsub(DDbase):
2396 def getx(self): return "hello"
2397 x = property(getx)
2398
2399 dd = DDsub()
2400 self.assertEqual(dd.x, "hello")
2401 self.assertEqual(super(DDsub, dd).x, 42)
2402
2403 # Ensure that super() lookup of descriptor from classmethod
2404 # works (SF ID# 743627)
2405
2406 class Base(object):
2407 aProp = property(lambda self: "foo")
2408
2409 class Sub(Base):
2410 @classmethod
2411 def test(klass):
2412 return super(Sub,klass).aProp
2413
2414 self.assertEqual(Sub.test(), Base.aProp)
2415
2416 # Verify that super() doesn't allow keyword args
2417 try:
2418 super(Base, kw=1)
2419 except TypeError:
2420 pass
2421 else:
2422 self.assertEqual("super shouldn't accept keyword args")
2423
2424 def test_basic_inheritance(self):
2425 # Testing inheritance from basic types...
2426
2427 class hexint(int):
2428 def __repr__(self):
2429 return hex(self)
2430 def __add__(self, other):
2431 return hexint(int.__add__(self, other))
2432 # (Note that overriding __radd__ doesn't work,
2433 # because the int type gets first dibs.)
2434 self.assertEqual(repr(hexint(7) + 9), "0x10")
2435 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2436 a = hexint(12345)
2437 self.assertEqual(a, 12345)
2438 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002439 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002440 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002441 self.assertIs((+a).__class__, int)
2442 self.assertIs((a >> 0).__class__, int)
2443 self.assertIs((a << 0).__class__, int)
2444 self.assertIs((hexint(0) << 12).__class__, int)
2445 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002446
2447 class octlong(int):
2448 __slots__ = []
2449 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002450 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002451 def __add__(self, other):
2452 return self.__class__(super(octlong, self).__add__(other))
2453 __radd__ = __add__
2454 self.assertEqual(str(octlong(3) + 5), "0o10")
2455 # (Note that overriding __radd__ here only seems to work
2456 # because the example uses a short int left argument.)
2457 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2458 a = octlong(12345)
2459 self.assertEqual(a, 12345)
2460 self.assertEqual(int(a), 12345)
2461 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002462 self.assertIs(int(a).__class__, int)
2463 self.assertIs((+a).__class__, int)
2464 self.assertIs((-a).__class__, int)
2465 self.assertIs((-octlong(0)).__class__, int)
2466 self.assertIs((a >> 0).__class__, int)
2467 self.assertIs((a << 0).__class__, int)
2468 self.assertIs((a - 0).__class__, int)
2469 self.assertIs((a * 1).__class__, int)
2470 self.assertIs((a ** 1).__class__, int)
2471 self.assertIs((a // 1).__class__, int)
2472 self.assertIs((1 * a).__class__, int)
2473 self.assertIs((a | 0).__class__, int)
2474 self.assertIs((a ^ 0).__class__, int)
2475 self.assertIs((a & -1).__class__, int)
2476 self.assertIs((octlong(0) << 12).__class__, int)
2477 self.assertIs((octlong(0) >> 12).__class__, int)
2478 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002479
2480 # Because octlong overrides __add__, we can't check the absence of +0
2481 # optimizations using octlong.
2482 class longclone(int):
2483 pass
2484 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002485 self.assertIs((a + 0).__class__, int)
2486 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002487
2488 # Check that negative clones don't segfault
2489 a = longclone(-1)
2490 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002491 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002492
2493 class precfloat(float):
2494 __slots__ = ['prec']
2495 def __init__(self, value=0.0, prec=12):
2496 self.prec = int(prec)
2497 def __repr__(self):
2498 return "%.*g" % (self.prec, self)
2499 self.assertEqual(repr(precfloat(1.1)), "1.1")
2500 a = precfloat(12345)
2501 self.assertEqual(a, 12345.0)
2502 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002503 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002504 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002505 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002506
2507 class madcomplex(complex):
2508 def __repr__(self):
2509 return "%.17gj%+.17g" % (self.imag, self.real)
2510 a = madcomplex(-3, 4)
2511 self.assertEqual(repr(a), "4j-3")
2512 base = complex(-3, 4)
2513 self.assertEqual(base.__class__, complex)
2514 self.assertEqual(a, base)
2515 self.assertEqual(complex(a), base)
2516 self.assertEqual(complex(a).__class__, complex)
2517 a = madcomplex(a) # just trying another form of the constructor
2518 self.assertEqual(repr(a), "4j-3")
2519 self.assertEqual(a, base)
2520 self.assertEqual(complex(a), base)
2521 self.assertEqual(complex(a).__class__, complex)
2522 self.assertEqual(hash(a), hash(base))
2523 self.assertEqual((+a).__class__, complex)
2524 self.assertEqual((a + 0).__class__, complex)
2525 self.assertEqual(a + 0, base)
2526 self.assertEqual((a - 0).__class__, complex)
2527 self.assertEqual(a - 0, base)
2528 self.assertEqual((a * 1).__class__, complex)
2529 self.assertEqual(a * 1, base)
2530 self.assertEqual((a / 1).__class__, complex)
2531 self.assertEqual(a / 1, base)
2532
2533 class madtuple(tuple):
2534 _rev = None
2535 def rev(self):
2536 if self._rev is not None:
2537 return self._rev
2538 L = list(self)
2539 L.reverse()
2540 self._rev = self.__class__(L)
2541 return self._rev
2542 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2543 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2544 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2545 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2546 for i in range(512):
2547 t = madtuple(range(i))
2548 u = t.rev()
2549 v = u.rev()
2550 self.assertEqual(v, t)
2551 a = madtuple((1,2,3,4,5))
2552 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002553 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002554 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002555 self.assertIs(a[:].__class__, tuple)
2556 self.assertIs((a * 1).__class__, tuple)
2557 self.assertIs((a * 0).__class__, tuple)
2558 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002559 a = madtuple(())
2560 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002561 self.assertIs(tuple(a).__class__, tuple)
2562 self.assertIs((a + a).__class__, tuple)
2563 self.assertIs((a * 0).__class__, tuple)
2564 self.assertIs((a * 1).__class__, tuple)
2565 self.assertIs((a * 2).__class__, tuple)
2566 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002567
2568 class madstring(str):
2569 _rev = None
2570 def rev(self):
2571 if self._rev is not None:
2572 return self._rev
2573 L = list(self)
2574 L.reverse()
2575 self._rev = self.__class__("".join(L))
2576 return self._rev
2577 s = madstring("abcdefghijklmnopqrstuvwxyz")
2578 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2579 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2580 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2581 for i in range(256):
2582 s = madstring("".join(map(chr, range(i))))
2583 t = s.rev()
2584 u = t.rev()
2585 self.assertEqual(u, s)
2586 s = madstring("12345")
2587 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002588 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002589
2590 base = "\x00" * 5
2591 s = madstring(base)
2592 self.assertEqual(s, base)
2593 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002594 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002595 self.assertEqual(hash(s), hash(base))
2596 self.assertEqual({s: 1}[base], 1)
2597 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002598 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002599 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002600 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002601 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002602 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002603 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002604 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002605 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002606 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002607 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002608 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002609 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002610 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002611 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002612 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002613 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002614 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002615 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002616 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 self.assertEqual(s.rstrip(), base)
2618 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002619 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002620 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002621 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002622 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002623 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002624 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002625 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002626 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002627 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002628 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002629 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002630 self.assertEqual(s.lower(), base)
2631
2632 class madunicode(str):
2633 _rev = None
2634 def rev(self):
2635 if self._rev is not None:
2636 return self._rev
2637 L = list(self)
2638 L.reverse()
2639 self._rev = self.__class__("".join(L))
2640 return self._rev
2641 u = madunicode("ABCDEF")
2642 self.assertEqual(u, "ABCDEF")
2643 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2644 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2645 base = "12345"
2646 u = madunicode(base)
2647 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002648 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002649 self.assertEqual(hash(u), hash(base))
2650 self.assertEqual({u: 1}[base], 1)
2651 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002652 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002653 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002654 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002655 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002656 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002657 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002658 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002659 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002660 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002661 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002662 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002663 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002664 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002665 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002666 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002667 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002668 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002669 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002670 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002671 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002672 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002673 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002674 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002675 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002676 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002677 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002678 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002679 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002680 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002681 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002682 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002683 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002684 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002685 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002686 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002687 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002688 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002689 self.assertEqual(u[0:0], "")
2690
2691 class sublist(list):
2692 pass
2693 a = sublist(range(5))
2694 self.assertEqual(a, list(range(5)))
2695 a.append("hello")
2696 self.assertEqual(a, list(range(5)) + ["hello"])
2697 a[5] = 5
2698 self.assertEqual(a, list(range(6)))
2699 a.extend(range(6, 20))
2700 self.assertEqual(a, list(range(20)))
2701 a[-5:] = []
2702 self.assertEqual(a, list(range(15)))
2703 del a[10:15]
2704 self.assertEqual(len(a), 10)
2705 self.assertEqual(a, list(range(10)))
2706 self.assertEqual(list(a), list(range(10)))
2707 self.assertEqual(a[0], 0)
2708 self.assertEqual(a[9], 9)
2709 self.assertEqual(a[-10], 0)
2710 self.assertEqual(a[-1], 9)
2711 self.assertEqual(a[:5], list(range(5)))
2712
2713 ## class CountedInput(file):
2714 ## """Counts lines read by self.readline().
2715 ##
2716 ## self.lineno is the 0-based ordinal of the last line read, up to
2717 ## a maximum of one greater than the number of lines in the file.
2718 ##
2719 ## self.ateof is true if and only if the final "" line has been read,
2720 ## at which point self.lineno stops incrementing, and further calls
2721 ## to readline() continue to return "".
2722 ## """
2723 ##
2724 ## lineno = 0
2725 ## ateof = 0
2726 ## def readline(self):
2727 ## if self.ateof:
2728 ## return ""
2729 ## s = file.readline(self)
2730 ## # Next line works too.
2731 ## # s = super(CountedInput, self).readline()
2732 ## self.lineno += 1
2733 ## if s == "":
2734 ## self.ateof = 1
2735 ## return s
2736 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002737 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002738 ## lines = ['a\n', 'b\n', 'c\n']
2739 ## try:
2740 ## f.writelines(lines)
2741 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002742 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002743 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2744 ## got = f.readline()
2745 ## self.assertEqual(expected, got)
2746 ## self.assertEqual(f.lineno, i)
2747 ## self.assertEqual(f.ateof, (i > len(lines)))
2748 ## f.close()
2749 ## finally:
2750 ## try:
2751 ## f.close()
2752 ## except:
2753 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002754 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002755
2756 def test_keywords(self):
2757 # Testing keyword args to basic type constructors ...
2758 self.assertEqual(int(x=1), 1)
2759 self.assertEqual(float(x=2), 2.0)
2760 self.assertEqual(int(x=3), 3)
2761 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2762 self.assertEqual(str(object=500), '500')
2763 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2764 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2765 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2766 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2767
2768 for constructor in (int, float, int, complex, str, str,
2769 tuple, list):
2770 try:
2771 constructor(bogus_keyword_arg=1)
2772 except TypeError:
2773 pass
2774 else:
2775 self.fail("expected TypeError from bogus keyword argument to %r"
2776 % constructor)
2777
2778 def test_str_subclass_as_dict_key(self):
2779 # Testing a str subclass used as dict key ..
2780
2781 class cistr(str):
2782 """Sublcass of str that computes __eq__ case-insensitively.
2783
2784 Also computes a hash code of the string in canonical form.
2785 """
2786
2787 def __init__(self, value):
2788 self.canonical = value.lower()
2789 self.hashcode = hash(self.canonical)
2790
2791 def __eq__(self, other):
2792 if not isinstance(other, cistr):
2793 other = cistr(other)
2794 return self.canonical == other.canonical
2795
2796 def __hash__(self):
2797 return self.hashcode
2798
2799 self.assertEqual(cistr('ABC'), 'abc')
2800 self.assertEqual('aBc', cistr('ABC'))
2801 self.assertEqual(str(cistr('ABC')), 'ABC')
2802
2803 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2804 self.assertEqual(d[cistr('one')], 1)
2805 self.assertEqual(d[cistr('tWo')], 2)
2806 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002807 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002808 self.assertEqual(d.get(cistr('thrEE')), 3)
2809
2810 def test_classic_comparisons(self):
2811 # Testing classic comparisons...
2812 class classic:
2813 pass
2814
2815 for base in (classic, int, object):
2816 class C(base):
2817 def __init__(self, value):
2818 self.value = int(value)
2819 def __eq__(self, other):
2820 if isinstance(other, C):
2821 return self.value == other.value
2822 if isinstance(other, int) or isinstance(other, int):
2823 return self.value == other
2824 return NotImplemented
2825 def __ne__(self, other):
2826 if isinstance(other, C):
2827 return self.value != other.value
2828 if isinstance(other, int) or isinstance(other, int):
2829 return self.value != other
2830 return NotImplemented
2831 def __lt__(self, other):
2832 if isinstance(other, C):
2833 return self.value < other.value
2834 if isinstance(other, int) or isinstance(other, int):
2835 return self.value < other
2836 return NotImplemented
2837 def __le__(self, other):
2838 if isinstance(other, C):
2839 return self.value <= other.value
2840 if isinstance(other, int) or isinstance(other, int):
2841 return self.value <= other
2842 return NotImplemented
2843 def __gt__(self, other):
2844 if isinstance(other, C):
2845 return self.value > other.value
2846 if isinstance(other, int) or isinstance(other, int):
2847 return self.value > other
2848 return NotImplemented
2849 def __ge__(self, other):
2850 if isinstance(other, C):
2851 return self.value >= other.value
2852 if isinstance(other, int) or isinstance(other, int):
2853 return self.value >= other
2854 return NotImplemented
2855
2856 c1 = C(1)
2857 c2 = C(2)
2858 c3 = C(3)
2859 self.assertEqual(c1, 1)
2860 c = {1: c1, 2: c2, 3: c3}
2861 for x in 1, 2, 3:
2862 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002863 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002864 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002865 eval("x %s y" % op),
2866 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002867 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002868 eval("x %s y" % op),
2869 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002870 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002871 eval("x %s y" % op),
2872 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002873
2874 def test_rich_comparisons(self):
2875 # Testing rich comparisons...
2876 class Z(complex):
2877 pass
2878 z = Z(1)
2879 self.assertEqual(z, 1+0j)
2880 self.assertEqual(1+0j, z)
2881 class ZZ(complex):
2882 def __eq__(self, other):
2883 try:
2884 return abs(self - other) <= 1e-6
2885 except:
2886 return NotImplemented
2887 zz = ZZ(1.0000003)
2888 self.assertEqual(zz, 1+0j)
2889 self.assertEqual(1+0j, zz)
2890
2891 class classic:
2892 pass
2893 for base in (classic, int, object, list):
2894 class C(base):
2895 def __init__(self, value):
2896 self.value = int(value)
2897 def __cmp__(self_, other):
2898 self.fail("shouldn't call __cmp__")
2899 def __eq__(self, other):
2900 if isinstance(other, C):
2901 return self.value == other.value
2902 if isinstance(other, int) or isinstance(other, int):
2903 return self.value == other
2904 return NotImplemented
2905 def __ne__(self, other):
2906 if isinstance(other, C):
2907 return self.value != other.value
2908 if isinstance(other, int) or isinstance(other, int):
2909 return self.value != other
2910 return NotImplemented
2911 def __lt__(self, other):
2912 if isinstance(other, C):
2913 return self.value < other.value
2914 if isinstance(other, int) or isinstance(other, int):
2915 return self.value < other
2916 return NotImplemented
2917 def __le__(self, other):
2918 if isinstance(other, C):
2919 return self.value <= other.value
2920 if isinstance(other, int) or isinstance(other, int):
2921 return self.value <= other
2922 return NotImplemented
2923 def __gt__(self, other):
2924 if isinstance(other, C):
2925 return self.value > other.value
2926 if isinstance(other, int) or isinstance(other, int):
2927 return self.value > other
2928 return NotImplemented
2929 def __ge__(self, other):
2930 if isinstance(other, C):
2931 return self.value >= other.value
2932 if isinstance(other, int) or isinstance(other, int):
2933 return self.value >= other
2934 return NotImplemented
2935 c1 = C(1)
2936 c2 = C(2)
2937 c3 = C(3)
2938 self.assertEqual(c1, 1)
2939 c = {1: c1, 2: c2, 3: c3}
2940 for x in 1, 2, 3:
2941 for y in 1, 2, 3:
2942 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002943 self.assertEqual(eval("c[x] %s c[y]" % op),
2944 eval("x %s y" % op),
2945 "x=%d, y=%d" % (x, y))
2946 self.assertEqual(eval("c[x] %s y" % op),
2947 eval("x %s y" % op),
2948 "x=%d, y=%d" % (x, y))
2949 self.assertEqual(eval("x %s c[y]" % op),
2950 eval("x %s y" % op),
2951 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002952
2953 def test_descrdoc(self):
2954 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002955 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002956 def check(descr, what):
2957 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002958 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002959 check(complex.real, "the real part of a complex number") # member descriptor
2960
2961 def test_doc_descriptor(self):
2962 # Testing __doc__ descriptor...
2963 # SF bug 542984
2964 class DocDescr(object):
2965 def __get__(self, object, otype):
2966 if object:
2967 object = object.__class__.__name__ + ' instance'
2968 if otype:
2969 otype = otype.__name__
2970 return 'object=%s; type=%s' % (object, otype)
2971 class OldClass:
2972 __doc__ = DocDescr()
2973 class NewClass(object):
2974 __doc__ = DocDescr()
2975 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2976 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2977 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2978 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2979
2980 def test_set_class(self):
2981 # Testing __class__ assignment...
2982 class C(object): pass
2983 class D(object): pass
2984 class E(object): pass
2985 class F(D, E): pass
2986 for cls in C, D, E, F:
2987 for cls2 in C, D, E, F:
2988 x = cls()
2989 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002990 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002991 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002992 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002993 def cant(x, C):
2994 try:
2995 x.__class__ = C
2996 except TypeError:
2997 pass
2998 else:
2999 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3000 try:
3001 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003002 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003003 pass
3004 else:
3005 self.fail("shouldn't allow del %r.__class__" % x)
3006 cant(C(), list)
3007 cant(list(), C)
3008 cant(C(), 1)
3009 cant(C(), object)
3010 cant(object(), list)
3011 cant(list(), object)
3012 class Int(int): __slots__ = []
3013 cant(2, Int)
3014 cant(Int(), int)
3015 cant(True, int)
3016 cant(2, bool)
3017 o = object()
3018 cant(o, type(1))
3019 cant(o, type(None))
3020 del o
3021 class G(object):
3022 __slots__ = ["a", "b"]
3023 class H(object):
3024 __slots__ = ["b", "a"]
3025 class I(object):
3026 __slots__ = ["a", "b"]
3027 class J(object):
3028 __slots__ = ["c", "b"]
3029 class K(object):
3030 __slots__ = ["a", "b", "d"]
3031 class L(H):
3032 __slots__ = ["e"]
3033 class M(I):
3034 __slots__ = ["e"]
3035 class N(J):
3036 __slots__ = ["__weakref__"]
3037 class P(J):
3038 __slots__ = ["__dict__"]
3039 class Q(J):
3040 pass
3041 class R(J):
3042 __slots__ = ["__dict__", "__weakref__"]
3043
3044 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3045 x = cls()
3046 x.a = 1
3047 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003048 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003049 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3050 self.assertEqual(x.a, 1)
3051 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003052 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003053 "assigning %r as __class__ for %r silently failed" % (cls, x))
3054 self.assertEqual(x.a, 1)
3055 for cls in G, J, K, L, M, N, P, R, list, Int:
3056 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3057 if cls is cls2:
3058 continue
3059 cant(cls(), cls2)
3060
Benjamin Peterson193152c2009-04-25 01:08:45 +00003061 # Issue5283: when __class__ changes in __del__, the wrong
3062 # type gets DECREF'd.
3063 class O(object):
3064 pass
3065 class A(object):
3066 def __del__(self):
3067 self.__class__ = O
3068 l = [A() for x in range(100)]
3069 del l
3070
Georg Brandl479a7e72008-02-05 18:13:15 +00003071 def test_set_dict(self):
3072 # Testing __dict__ assignment...
3073 class C(object): pass
3074 a = C()
3075 a.__dict__ = {'b': 1}
3076 self.assertEqual(a.b, 1)
3077 def cant(x, dict):
3078 try:
3079 x.__dict__ = dict
3080 except (AttributeError, TypeError):
3081 pass
3082 else:
3083 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3084 cant(a, None)
3085 cant(a, [])
3086 cant(a, 1)
3087 del a.__dict__ # Deleting __dict__ is allowed
3088
3089 class Base(object):
3090 pass
3091 def verify_dict_readonly(x):
3092 """
3093 x has to be an instance of a class inheriting from Base.
3094 """
3095 cant(x, {})
3096 try:
3097 del x.__dict__
3098 except (AttributeError, TypeError):
3099 pass
3100 else:
3101 self.fail("shouldn't allow del %r.__dict__" % x)
3102 dict_descr = Base.__dict__["__dict__"]
3103 try:
3104 dict_descr.__set__(x, {})
3105 except (AttributeError, TypeError):
3106 pass
3107 else:
3108 self.fail("dict_descr allowed access to %r's dict" % x)
3109
3110 # Classes don't allow __dict__ assignment and have readonly dicts
3111 class Meta1(type, Base):
3112 pass
3113 class Meta2(Base, type):
3114 pass
3115 class D(object, metaclass=Meta1):
3116 pass
3117 class E(object, metaclass=Meta2):
3118 pass
3119 for cls in C, D, E:
3120 verify_dict_readonly(cls)
3121 class_dict = cls.__dict__
3122 try:
3123 class_dict["spam"] = "eggs"
3124 except TypeError:
3125 pass
3126 else:
3127 self.fail("%r's __dict__ can be modified" % cls)
3128
3129 # Modules also disallow __dict__ assignment
3130 class Module1(types.ModuleType, Base):
3131 pass
3132 class Module2(Base, types.ModuleType):
3133 pass
3134 for ModuleType in Module1, Module2:
3135 mod = ModuleType("spam")
3136 verify_dict_readonly(mod)
3137 mod.__dict__["spam"] = "eggs"
3138
3139 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003140 # (at least not any more than regular exception's __dict__ can
3141 # be deleted; on CPython it is not the case, whereas on PyPy they
3142 # can, just like any other new-style instance's __dict__.)
3143 def can_delete_dict(e):
3144 try:
3145 del e.__dict__
3146 except (TypeError, AttributeError):
3147 return False
3148 else:
3149 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003150 class Exception1(Exception, Base):
3151 pass
3152 class Exception2(Base, Exception):
3153 pass
3154 for ExceptionType in Exception, Exception1, Exception2:
3155 e = ExceptionType()
3156 e.__dict__ = {"a": 1}
3157 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003158 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003159
Georg Brandl479a7e72008-02-05 18:13:15 +00003160 def test_binary_operator_override(self):
3161 # Testing overrides of binary operations...
3162 class I(int):
3163 def __repr__(self):
3164 return "I(%r)" % int(self)
3165 def __add__(self, other):
3166 return I(int(self) + int(other))
3167 __radd__ = __add__
3168 def __pow__(self, other, mod=None):
3169 if mod is None:
3170 return I(pow(int(self), int(other)))
3171 else:
3172 return I(pow(int(self), int(other), int(mod)))
3173 def __rpow__(self, other, mod=None):
3174 if mod is None:
3175 return I(pow(int(other), int(self), mod))
3176 else:
3177 return I(pow(int(other), int(self), int(mod)))
3178
3179 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3180 self.assertEqual(repr(I(1) + 2), "I(3)")
3181 self.assertEqual(repr(1 + I(2)), "I(3)")
3182 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3183 self.assertEqual(repr(2 ** I(3)), "I(8)")
3184 self.assertEqual(repr(I(2) ** 3), "I(8)")
3185 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3186 class S(str):
3187 def __eq__(self, other):
3188 return self.lower() == other.lower()
3189
3190 def test_subclass_propagation(self):
3191 # Testing propagation of slot functions to subclasses...
3192 class A(object):
3193 pass
3194 class B(A):
3195 pass
3196 class C(A):
3197 pass
3198 class D(B, C):
3199 pass
3200 d = D()
3201 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3202 A.__hash__ = lambda self: 42
3203 self.assertEqual(hash(d), 42)
3204 C.__hash__ = lambda self: 314
3205 self.assertEqual(hash(d), 314)
3206 B.__hash__ = lambda self: 144
3207 self.assertEqual(hash(d), 144)
3208 D.__hash__ = lambda self: 100
3209 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003210 D.__hash__ = None
3211 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003212 del D.__hash__
3213 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003214 B.__hash__ = None
3215 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003216 del B.__hash__
3217 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003218 C.__hash__ = None
3219 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003220 del C.__hash__
3221 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003222 A.__hash__ = None
3223 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003224 del A.__hash__
3225 self.assertEqual(hash(d), orig_hash)
3226 d.foo = 42
3227 d.bar = 42
3228 self.assertEqual(d.foo, 42)
3229 self.assertEqual(d.bar, 42)
3230 def __getattribute__(self, name):
3231 if name == "foo":
3232 return 24
3233 return object.__getattribute__(self, name)
3234 A.__getattribute__ = __getattribute__
3235 self.assertEqual(d.foo, 24)
3236 self.assertEqual(d.bar, 42)
3237 def __getattr__(self, name):
3238 if name in ("spam", "foo", "bar"):
3239 return "hello"
3240 raise AttributeError(name)
3241 B.__getattr__ = __getattr__
3242 self.assertEqual(d.spam, "hello")
3243 self.assertEqual(d.foo, 24)
3244 self.assertEqual(d.bar, 42)
3245 del A.__getattribute__
3246 self.assertEqual(d.foo, 42)
3247 del d.foo
3248 self.assertEqual(d.foo, "hello")
3249 self.assertEqual(d.bar, 42)
3250 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003251 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003252 d.foo
3253 except AttributeError:
3254 pass
3255 else:
3256 self.fail("d.foo should be undefined now")
3257
3258 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003259 class A(object):
3260 pass
3261 class B(A):
3262 pass
3263 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003264 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003265 A.__setitem__ = lambda *a: None # crash
3266
3267 def test_buffer_inheritance(self):
3268 # Testing that buffer interface is inherited ...
3269
3270 import binascii
3271 # SF bug [#470040] ParseTuple t# vs subclasses.
3272
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003273 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003274 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003275 base = b'abc'
3276 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003277 # b2a_hex uses the buffer interface to get its argument's value, via
3278 # PyArg_ParseTuple 't#' code.
3279 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3280
Georg Brandl479a7e72008-02-05 18:13:15 +00003281 class MyInt(int):
3282 pass
3283 m = MyInt(42)
3284 try:
3285 binascii.b2a_hex(m)
3286 self.fail('subclass of int should not have a buffer interface')
3287 except TypeError:
3288 pass
3289
3290 def test_str_of_str_subclass(self):
3291 # Testing __str__ defined in subclass of str ...
3292 import binascii
3293 import io
3294
3295 class octetstring(str):
3296 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003297 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003298 def __repr__(self):
3299 return self + " repr"
3300
3301 o = octetstring('A')
3302 self.assertEqual(type(o), octetstring)
3303 self.assertEqual(type(str(o)), str)
3304 self.assertEqual(type(repr(o)), str)
3305 self.assertEqual(ord(o), 0x41)
3306 self.assertEqual(str(o), '41')
3307 self.assertEqual(repr(o), 'A repr')
3308 self.assertEqual(o.__str__(), '41')
3309 self.assertEqual(o.__repr__(), 'A repr')
3310
3311 capture = io.StringIO()
3312 # Calling str() or not exercises different internal paths.
3313 print(o, file=capture)
3314 print(str(o), file=capture)
3315 self.assertEqual(capture.getvalue(), '41\n41\n')
3316 capture.close()
3317
3318 def test_keyword_arguments(self):
3319 # Testing keyword arguments to __init__, __call__...
3320 def f(a): return a
3321 self.assertEqual(f.__call__(a=42), 42)
3322 a = []
3323 list.__init__(a, sequence=[0, 1, 2])
3324 self.assertEqual(a, [0, 1, 2])
3325
3326 def test_recursive_call(self):
3327 # Testing recursive __call__() by setting to instance of class...
3328 class A(object):
3329 pass
3330
3331 A.__call__ = A()
3332 try:
3333 A()()
3334 except RuntimeError:
3335 pass
3336 else:
3337 self.fail("Recursion limit should have been reached for __call__()")
3338
3339 def test_delete_hook(self):
3340 # Testing __del__ hook...
3341 log = []
3342 class C(object):
3343 def __del__(self):
3344 log.append(1)
3345 c = C()
3346 self.assertEqual(log, [])
3347 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003348 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003349 self.assertEqual(log, [1])
3350
3351 class D(object): pass
3352 d = D()
3353 try: del d[0]
3354 except TypeError: pass
3355 else: self.fail("invalid del() didn't raise TypeError")
3356
3357 def test_hash_inheritance(self):
3358 # Testing hash of mutable subclasses...
3359
3360 class mydict(dict):
3361 pass
3362 d = mydict()
3363 try:
3364 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003365 except TypeError:
3366 pass
3367 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003368 self.fail("hash() of dict subclass should fail")
3369
3370 class mylist(list):
3371 pass
3372 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003373 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003374 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003375 except TypeError:
3376 pass
3377 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003378 self.fail("hash() of list subclass should fail")
3379
3380 def test_str_operations(self):
3381 try: 'a' + 5
3382 except TypeError: pass
3383 else: self.fail("'' + 5 doesn't raise TypeError")
3384
3385 try: ''.split('')
3386 except ValueError: pass
3387 else: self.fail("''.split('') doesn't raise ValueError")
3388
3389 try: ''.join([0])
3390 except TypeError: pass
3391 else: self.fail("''.join([0]) doesn't raise TypeError")
3392
3393 try: ''.rindex('5')
3394 except ValueError: pass
3395 else: self.fail("''.rindex('5') doesn't raise ValueError")
3396
3397 try: '%(n)s' % None
3398 except TypeError: pass
3399 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3400
3401 try: '%(n' % {}
3402 except ValueError: pass
3403 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3404
3405 try: '%*s' % ('abc')
3406 except TypeError: pass
3407 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3408
3409 try: '%*.*s' % ('abc', 5)
3410 except TypeError: pass
3411 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3412
3413 try: '%s' % (1, 2)
3414 except TypeError: pass
3415 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3416
3417 try: '%' % None
3418 except ValueError: pass
3419 else: self.fail("'%' % None doesn't raise ValueError")
3420
3421 self.assertEqual('534253'.isdigit(), 1)
3422 self.assertEqual('534253x'.isdigit(), 0)
3423 self.assertEqual('%c' % 5, '\x05')
3424 self.assertEqual('%c' % '5', '5')
3425
3426 def test_deepcopy_recursive(self):
3427 # Testing deepcopy of recursive objects...
3428 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003429 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003430 a = Node()
3431 b = Node()
3432 a.b = b
3433 b.a = a
3434 z = deepcopy(a) # This blew up before
3435
3436 def test_unintialized_modules(self):
3437 # Testing uninitialized module objects...
3438 from types import ModuleType as M
3439 m = M.__new__(M)
3440 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003441 self.assertNotHasAttr(m, "__name__")
3442 self.assertNotHasAttr(m, "__file__")
3443 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003444 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003445 m.foo = 1
3446 self.assertEqual(m.__dict__, {"foo": 1})
3447
3448 def test_funny_new(self):
3449 # Testing __new__ returning something unexpected...
3450 class C(object):
3451 def __new__(cls, arg):
3452 if isinstance(arg, str): return [1, 2, 3]
3453 elif isinstance(arg, int): return object.__new__(D)
3454 else: return object.__new__(cls)
3455 class D(C):
3456 def __init__(self, arg):
3457 self.foo = arg
3458 self.assertEqual(C("1"), [1, 2, 3])
3459 self.assertEqual(D("1"), [1, 2, 3])
3460 d = D(None)
3461 self.assertEqual(d.foo, None)
3462 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003463 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003464 self.assertEqual(d.foo, 1)
3465 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003466 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003467 self.assertEqual(d.foo, 1)
3468
3469 def test_imul_bug(self):
3470 # Testing for __imul__ problems...
3471 # SF bug 544647
3472 class C(object):
3473 def __imul__(self, other):
3474 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003475 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003476 y = x
3477 y *= 1.0
3478 self.assertEqual(y, (x, 1.0))
3479 y = x
3480 y *= 2
3481 self.assertEqual(y, (x, 2))
3482 y = x
3483 y *= 3
3484 self.assertEqual(y, (x, 3))
3485 y = x
3486 y *= 1<<100
3487 self.assertEqual(y, (x, 1<<100))
3488 y = x
3489 y *= None
3490 self.assertEqual(y, (x, None))
3491 y = x
3492 y *= "foo"
3493 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003494
Georg Brandl479a7e72008-02-05 18:13:15 +00003495 def test_copy_setstate(self):
3496 # Testing that copy.*copy() correctly uses __setstate__...
3497 import copy
3498 class C(object):
3499 def __init__(self, foo=None):
3500 self.foo = foo
3501 self.__foo = foo
3502 def setfoo(self, foo=None):
3503 self.foo = foo
3504 def getfoo(self):
3505 return self.__foo
3506 def __getstate__(self):
3507 return [self.foo]
3508 def __setstate__(self_, lst):
3509 self.assertEqual(len(lst), 1)
3510 self_.__foo = self_.foo = lst[0]
3511 a = C(42)
3512 a.setfoo(24)
3513 self.assertEqual(a.foo, 24)
3514 self.assertEqual(a.getfoo(), 42)
3515 b = copy.copy(a)
3516 self.assertEqual(b.foo, 24)
3517 self.assertEqual(b.getfoo(), 24)
3518 b = copy.deepcopy(a)
3519 self.assertEqual(b.foo, 24)
3520 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003521
Georg Brandl479a7e72008-02-05 18:13:15 +00003522 def test_slices(self):
3523 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003524
Georg Brandl479a7e72008-02-05 18:13:15 +00003525 # Strings
3526 self.assertEqual("hello"[:4], "hell")
3527 self.assertEqual("hello"[slice(4)], "hell")
3528 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3529 class S(str):
3530 def __getitem__(self, x):
3531 return str.__getitem__(self, x)
3532 self.assertEqual(S("hello")[:4], "hell")
3533 self.assertEqual(S("hello")[slice(4)], "hell")
3534 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3535 # Tuples
3536 self.assertEqual((1,2,3)[:2], (1,2))
3537 self.assertEqual((1,2,3)[slice(2)], (1,2))
3538 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3539 class T(tuple):
3540 def __getitem__(self, x):
3541 return tuple.__getitem__(self, x)
3542 self.assertEqual(T((1,2,3))[:2], (1,2))
3543 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3544 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3545 # Lists
3546 self.assertEqual([1,2,3][:2], [1,2])
3547 self.assertEqual([1,2,3][slice(2)], [1,2])
3548 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3549 class L(list):
3550 def __getitem__(self, x):
3551 return list.__getitem__(self, x)
3552 self.assertEqual(L([1,2,3])[:2], [1,2])
3553 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3554 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3555 # Now do lists and __setitem__
3556 a = L([1,2,3])
3557 a[slice(1, 3)] = [3,2]
3558 self.assertEqual(a, [1,3,2])
3559 a[slice(0, 2, 1)] = [3,1]
3560 self.assertEqual(a, [3,1,2])
3561 a.__setitem__(slice(1, 3), [2,1])
3562 self.assertEqual(a, [3,2,1])
3563 a.__setitem__(slice(0, 2, 1), [2,3])
3564 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003565
Georg Brandl479a7e72008-02-05 18:13:15 +00003566 def test_subtype_resurrection(self):
3567 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003568
Georg Brandl479a7e72008-02-05 18:13:15 +00003569 class C(object):
3570 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003571
Georg Brandl479a7e72008-02-05 18:13:15 +00003572 def __del__(self):
3573 # resurrect the instance
3574 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003575
Georg Brandl479a7e72008-02-05 18:13:15 +00003576 c = C()
3577 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003578
Benjamin Petersone549ead2009-03-28 21:42:05 +00003579 # The most interesting thing here is whether this blows up, due to
3580 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3581 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003582 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003583
Benjamin Petersone549ead2009-03-28 21:42:05 +00003584 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003585 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003586
Georg Brandl479a7e72008-02-05 18:13:15 +00003587 # Make c mortal again, so that the test framework with -l doesn't report
3588 # it as a leak.
3589 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003590
Georg Brandl479a7e72008-02-05 18:13:15 +00003591 def test_slots_trash(self):
3592 # Testing slot trash...
3593 # Deallocating deeply nested slotted trash caused stack overflows
3594 class trash(object):
3595 __slots__ = ['x']
3596 def __init__(self, x):
3597 self.x = x
3598 o = None
3599 for i in range(50000):
3600 o = trash(o)
3601 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003602
Georg Brandl479a7e72008-02-05 18:13:15 +00003603 def test_slots_multiple_inheritance(self):
3604 # SF bug 575229, multiple inheritance w/ slots dumps core
3605 class A(object):
3606 __slots__=()
3607 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003608 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003609 class C(A,B) :
3610 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003611 if support.check_impl_detail():
3612 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003613 self.assertHasAttr(C, '__dict__')
3614 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003615 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003616
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 def test_rmul(self):
3618 # Testing correct invocation of __rmul__...
3619 # SF patch 592646
3620 class C(object):
3621 def __mul__(self, other):
3622 return "mul"
3623 def __rmul__(self, other):
3624 return "rmul"
3625 a = C()
3626 self.assertEqual(a*2, "mul")
3627 self.assertEqual(a*2.2, "mul")
3628 self.assertEqual(2*a, "rmul")
3629 self.assertEqual(2.2*a, "rmul")
3630
3631 def test_ipow(self):
3632 # Testing correct invocation of __ipow__...
3633 # [SF bug 620179]
3634 class C(object):
3635 def __ipow__(self, other):
3636 pass
3637 a = C()
3638 a **= 2
3639
3640 def test_mutable_bases(self):
3641 # Testing mutable bases...
3642
3643 # stuff that should work:
3644 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003645 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003646 class C2(object):
3647 def __getattribute__(self, attr):
3648 if attr == 'a':
3649 return 2
3650 else:
3651 return super(C2, self).__getattribute__(attr)
3652 def meth(self):
3653 return 1
3654 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003655 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003656 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003657 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003658 d = D()
3659 e = E()
3660 D.__bases__ = (C,)
3661 D.__bases__ = (C2,)
3662 self.assertEqual(d.meth(), 1)
3663 self.assertEqual(e.meth(), 1)
3664 self.assertEqual(d.a, 2)
3665 self.assertEqual(e.a, 2)
3666 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003667
Georg Brandl479a7e72008-02-05 18:13:15 +00003668 try:
3669 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003670 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003671 pass
3672 else:
3673 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003674
Georg Brandl479a7e72008-02-05 18:13:15 +00003675 try:
3676 D.__bases__ = ()
3677 except TypeError as msg:
3678 if str(msg) == "a new-style class can't have only classic bases":
3679 self.fail("wrong error message for .__bases__ = ()")
3680 else:
3681 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003682
Georg Brandl479a7e72008-02-05 18:13:15 +00003683 try:
3684 D.__bases__ = (D,)
3685 except TypeError:
3686 pass
3687 else:
3688 # actually, we'll have crashed by here...
3689 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003690
Georg Brandl479a7e72008-02-05 18:13:15 +00003691 try:
3692 D.__bases__ = (C, C)
3693 except TypeError:
3694 pass
3695 else:
3696 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003697
Georg Brandl479a7e72008-02-05 18:13:15 +00003698 try:
3699 D.__bases__ = (E,)
3700 except TypeError:
3701 pass
3702 else:
3703 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003704
Benjamin Petersonae937c02009-04-18 20:54:08 +00003705 def test_builtin_bases(self):
3706 # Make sure all the builtin types can have their base queried without
3707 # segfaulting. See issue #5787.
3708 builtin_types = [tp for tp in builtins.__dict__.values()
3709 if isinstance(tp, type)]
3710 for tp in builtin_types:
3711 object.__getattribute__(tp, "__bases__")
3712 if tp is not object:
3713 self.assertEqual(len(tp.__bases__), 1, tp)
3714
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003715 class L(list):
3716 pass
3717
3718 class C(object):
3719 pass
3720
3721 class D(C):
3722 pass
3723
3724 try:
3725 L.__bases__ = (dict,)
3726 except TypeError:
3727 pass
3728 else:
3729 self.fail("shouldn't turn list subclass into dict subclass")
3730
3731 try:
3732 list.__bases__ = (dict,)
3733 except TypeError:
3734 pass
3735 else:
3736 self.fail("shouldn't be able to assign to list.__bases__")
3737
3738 try:
3739 D.__bases__ = (C, list)
3740 except TypeError:
3741 pass
3742 else:
3743 assert 0, "best_base calculation found wanting"
3744
Benjamin Petersonae937c02009-04-18 20:54:08 +00003745
Georg Brandl479a7e72008-02-05 18:13:15 +00003746 def test_mutable_bases_with_failing_mro(self):
3747 # Testing mutable bases with failing mro...
3748 class WorkOnce(type):
3749 def __new__(self, name, bases, ns):
3750 self.flag = 0
3751 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3752 def mro(self):
3753 if self.flag > 0:
3754 raise RuntimeError("bozo")
3755 else:
3756 self.flag += 1
3757 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003758
Georg Brandl479a7e72008-02-05 18:13:15 +00003759 class WorkAlways(type):
3760 def mro(self):
3761 # this is here to make sure that .mro()s aren't called
3762 # with an exception set (which was possible at one point).
3763 # An error message will be printed in a debug build.
3764 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003765 return type.mro(self)
3766
Georg Brandl479a7e72008-02-05 18:13:15 +00003767 class C(object):
3768 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003769
Georg Brandl479a7e72008-02-05 18:13:15 +00003770 class C2(object):
3771 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003772
Georg Brandl479a7e72008-02-05 18:13:15 +00003773 class D(C):
3774 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003775
Georg Brandl479a7e72008-02-05 18:13:15 +00003776 class E(D):
3777 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003778
Georg Brandl479a7e72008-02-05 18:13:15 +00003779 class F(D, metaclass=WorkOnce):
3780 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003781
Georg Brandl479a7e72008-02-05 18:13:15 +00003782 class G(D, metaclass=WorkAlways):
3783 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003784
Georg Brandl479a7e72008-02-05 18:13:15 +00003785 # Immediate subclasses have their mro's adjusted in alphabetical
3786 # order, so E's will get adjusted before adjusting F's fails. We
3787 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003788
Georg Brandl479a7e72008-02-05 18:13:15 +00003789 E_mro_before = E.__mro__
3790 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003791
Armin Rigofd163f92005-12-29 15:59:19 +00003792 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003793 D.__bases__ = (C2,)
3794 except RuntimeError:
3795 self.assertEqual(E.__mro__, E_mro_before)
3796 self.assertEqual(D.__mro__, D_mro_before)
3797 else:
3798 self.fail("exception not propagated")
3799
3800 def test_mutable_bases_catch_mro_conflict(self):
3801 # Testing mutable bases catch mro conflict...
3802 class A(object):
3803 pass
3804
3805 class B(object):
3806 pass
3807
3808 class C(A, B):
3809 pass
3810
3811 class D(A, B):
3812 pass
3813
3814 class E(C, D):
3815 pass
3816
3817 try:
3818 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003819 except TypeError:
3820 pass
3821 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003822 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003823
Georg Brandl479a7e72008-02-05 18:13:15 +00003824 def test_mutable_names(self):
3825 # Testing mutable names...
3826 class C(object):
3827 pass
3828
3829 # C.__module__ could be 'test_descr' or '__main__'
3830 mod = C.__module__
3831
3832 C.__name__ = 'D'
3833 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3834
3835 C.__name__ = 'D.E'
3836 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3837
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003838 def test_evil_type_name(self):
3839 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3840 # execution while the type structure was not in a sane state, and a
3841 # possible segmentation fault as a result. See bug #16447.
3842 class Nasty(str):
3843 def __del__(self):
3844 C.__name__ = "other"
3845
3846 class C:
3847 pass
3848
3849 C.__name__ = Nasty("abc")
3850 C.__name__ = "normal"
3851
Georg Brandl479a7e72008-02-05 18:13:15 +00003852 def test_subclass_right_op(self):
3853 # Testing correct dispatch of subclass overloading __r<op>__...
3854
3855 # This code tests various cases where right-dispatch of a subclass
3856 # should be preferred over left-dispatch of a base class.
3857
3858 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3859
3860 class B(int):
3861 def __floordiv__(self, other):
3862 return "B.__floordiv__"
3863 def __rfloordiv__(self, other):
3864 return "B.__rfloordiv__"
3865
3866 self.assertEqual(B(1) // 1, "B.__floordiv__")
3867 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3868
3869 # Case 2: subclass of object; this is just the baseline for case 3
3870
3871 class C(object):
3872 def __floordiv__(self, other):
3873 return "C.__floordiv__"
3874 def __rfloordiv__(self, other):
3875 return "C.__rfloordiv__"
3876
3877 self.assertEqual(C() // 1, "C.__floordiv__")
3878 self.assertEqual(1 // C(), "C.__rfloordiv__")
3879
3880 # Case 3: subclass of new-style class; here it gets interesting
3881
3882 class D(C):
3883 def __floordiv__(self, other):
3884 return "D.__floordiv__"
3885 def __rfloordiv__(self, other):
3886 return "D.__rfloordiv__"
3887
3888 self.assertEqual(D() // C(), "D.__floordiv__")
3889 self.assertEqual(C() // D(), "D.__rfloordiv__")
3890
3891 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3892
3893 class E(C):
3894 pass
3895
3896 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3897
3898 self.assertEqual(E() // 1, "C.__floordiv__")
3899 self.assertEqual(1 // E(), "C.__rfloordiv__")
3900 self.assertEqual(E() // C(), "C.__floordiv__")
3901 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3902
Benjamin Petersone549ead2009-03-28 21:42:05 +00003903 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003904 def test_meth_class_get(self):
3905 # Testing __get__ method of METH_CLASS C methods...
3906 # Full coverage of descrobject.c::classmethod_get()
3907
3908 # Baseline
3909 arg = [1, 2, 3]
3910 res = {1: None, 2: None, 3: None}
3911 self.assertEqual(dict.fromkeys(arg), res)
3912 self.assertEqual({}.fromkeys(arg), res)
3913
3914 # Now get the descriptor
3915 descr = dict.__dict__["fromkeys"]
3916
3917 # More baseline using the descriptor directly
3918 self.assertEqual(descr.__get__(None, dict)(arg), res)
3919 self.assertEqual(descr.__get__({})(arg), res)
3920
3921 # Now check various error cases
3922 try:
3923 descr.__get__(None, None)
3924 except TypeError:
3925 pass
3926 else:
3927 self.fail("shouldn't have allowed descr.__get__(None, None)")
3928 try:
3929 descr.__get__(42)
3930 except TypeError:
3931 pass
3932 else:
3933 self.fail("shouldn't have allowed descr.__get__(42)")
3934 try:
3935 descr.__get__(None, 42)
3936 except TypeError:
3937 pass
3938 else:
3939 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3940 try:
3941 descr.__get__(None, int)
3942 except TypeError:
3943 pass
3944 else:
3945 self.fail("shouldn't have allowed descr.__get__(None, int)")
3946
3947 def test_isinst_isclass(self):
3948 # Testing proxy isinstance() and isclass()...
3949 class Proxy(object):
3950 def __init__(self, obj):
3951 self.__obj = obj
3952 def __getattribute__(self, name):
3953 if name.startswith("_Proxy__"):
3954 return object.__getattribute__(self, name)
3955 else:
3956 return getattr(self.__obj, name)
3957 # Test with a classic class
3958 class C:
3959 pass
3960 a = C()
3961 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003962 self.assertIsInstance(a, C) # Baseline
3963 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003964 # Test with a classic subclass
3965 class D(C):
3966 pass
3967 a = D()
3968 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003969 self.assertIsInstance(a, C) # Baseline
3970 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003971 # Test with a new-style class
3972 class C(object):
3973 pass
3974 a = C()
3975 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003976 self.assertIsInstance(a, C) # Baseline
3977 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003978 # Test with a new-style subclass
3979 class D(C):
3980 pass
3981 a = D()
3982 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003983 self.assertIsInstance(a, C) # Baseline
3984 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003985
3986 def test_proxy_super(self):
3987 # Testing super() for a proxy object...
3988 class Proxy(object):
3989 def __init__(self, obj):
3990 self.__obj = obj
3991 def __getattribute__(self, name):
3992 if name.startswith("_Proxy__"):
3993 return object.__getattribute__(self, name)
3994 else:
3995 return getattr(self.__obj, name)
3996
3997 class B(object):
3998 def f(self):
3999 return "B.f"
4000
4001 class C(B):
4002 def f(self):
4003 return super(C, self).f() + "->C.f"
4004
4005 obj = C()
4006 p = Proxy(obj)
4007 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4008
4009 def test_carloverre(self):
4010 # Testing prohibition of Carlo Verre's hack...
4011 try:
4012 object.__setattr__(str, "foo", 42)
4013 except TypeError:
4014 pass
4015 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004016 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004017 try:
4018 object.__delattr__(str, "lower")
4019 except TypeError:
4020 pass
4021 else:
4022 self.fail("Carlo Verre __delattr__ succeeded!")
4023
4024 def test_weakref_segfault(self):
4025 # Testing weakref segfault...
4026 # SF 742911
4027 import weakref
4028
4029 class Provoker:
4030 def __init__(self, referrent):
4031 self.ref = weakref.ref(referrent)
4032
4033 def __del__(self):
4034 x = self.ref()
4035
4036 class Oops(object):
4037 pass
4038
4039 o = Oops()
4040 o.whatever = Provoker(o)
4041 del o
4042
4043 def test_wrapper_segfault(self):
4044 # SF 927248: deeply nested wrappers could cause stack overflow
4045 f = lambda:None
4046 for i in range(1000000):
4047 f = f.__call__
4048 f = None
4049
4050 def test_file_fault(self):
4051 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004052 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004053 class StdoutGuard:
4054 def __getattr__(self, attr):
4055 sys.stdout = sys.__stdout__
4056 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4057 sys.stdout = StdoutGuard()
4058 try:
4059 print("Oops!")
4060 except RuntimeError:
4061 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004062 finally:
4063 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004064
4065 def test_vicious_descriptor_nonsense(self):
4066 # Testing vicious_descriptor_nonsense...
4067
4068 # A potential segfault spotted by Thomas Wouters in mail to
4069 # python-dev 2003-04-17, turned into an example & fixed by Michael
4070 # Hudson just less than four months later...
4071
4072 class Evil(object):
4073 def __hash__(self):
4074 return hash('attr')
4075 def __eq__(self, other):
4076 del C.attr
4077 return 0
4078
4079 class Descr(object):
4080 def __get__(self, ob, type=None):
4081 return 1
4082
4083 class C(object):
4084 attr = Descr()
4085
4086 c = C()
4087 c.__dict__[Evil()] = 0
4088
4089 self.assertEqual(c.attr, 1)
4090 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004091 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004092 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004093
4094 def test_init(self):
4095 # SF 1155938
4096 class Foo(object):
4097 def __init__(self):
4098 return 10
4099 try:
4100 Foo()
4101 except TypeError:
4102 pass
4103 else:
4104 self.fail("did not test __init__() for None return")
4105
4106 def test_method_wrapper(self):
4107 # Testing method-wrapper objects...
4108 # <type 'method-wrapper'> did not support any reflection before 2.5
4109
Mark Dickinson211c6252009-02-01 10:28:51 +00004110 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004111
4112 l = []
4113 self.assertEqual(l.__add__, l.__add__)
4114 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004115 self.assertNotEqual(l.__add__, [5].__add__)
4116 self.assertNotEqual(l.__add__, l.__mul__)
4117 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004118 if hasattr(l.__add__, '__self__'):
4119 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004120 self.assertIs(l.__add__.__self__, l)
4121 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004122 else:
4123 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004124 self.assertIs(l.__add__.im_self, l)
4125 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004126 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4127 try:
4128 hash(l.__add__)
4129 except TypeError:
4130 pass
4131 else:
4132 self.fail("no TypeError from hash([].__add__)")
4133
4134 t = ()
4135 t += (7,)
4136 self.assertEqual(t.__add__, (7,).__add__)
4137 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4138
4139 def test_not_implemented(self):
4140 # Testing NotImplemented...
4141 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004142 import operator
4143
4144 def specialmethod(self, other):
4145 return NotImplemented
4146
4147 def check(expr, x, y):
4148 try:
4149 exec(expr, {'x': x, 'y': y, 'operator': operator})
4150 except TypeError:
4151 pass
4152 else:
4153 self.fail("no TypeError from %r" % (expr,))
4154
4155 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4156 # TypeErrors
4157 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4158 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004159 for name, expr, iexpr in [
4160 ('__add__', 'x + y', 'x += y'),
4161 ('__sub__', 'x - y', 'x -= y'),
4162 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004163 ('__truediv__', 'operator.truediv(x, y)', None),
4164 ('__floordiv__', 'operator.floordiv(x, y)', None),
4165 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004166 ('__mod__', 'x % y', 'x %= y'),
4167 ('__divmod__', 'divmod(x, y)', None),
4168 ('__pow__', 'x ** y', 'x **= y'),
4169 ('__lshift__', 'x << y', 'x <<= y'),
4170 ('__rshift__', 'x >> y', 'x >>= y'),
4171 ('__and__', 'x & y', 'x &= y'),
4172 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004173 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004174 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004175 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004176 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004177 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004178 check(expr, a, N1)
4179 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004180 if iexpr:
4181 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004182 check(iexpr, a, N1)
4183 check(iexpr, a, N2)
4184 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004185 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004186 c = C()
4187 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004188 check(iexpr, c, N1)
4189 check(iexpr, c, N2)
4190
Georg Brandl479a7e72008-02-05 18:13:15 +00004191 def test_assign_slice(self):
4192 # ceval.c's assign_slice used to check for
4193 # tp->tp_as_sequence->sq_slice instead of
4194 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004195
Georg Brandl479a7e72008-02-05 18:13:15 +00004196 class C(object):
4197 def __setitem__(self, idx, value):
4198 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004199
Georg Brandl479a7e72008-02-05 18:13:15 +00004200 c = C()
4201 c[1:2] = 3
4202 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004203
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004204 def test_set_and_no_get(self):
4205 # See
4206 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4207 class Descr(object):
4208
4209 def __init__(self, name):
4210 self.name = name
4211
4212 def __set__(self, obj, value):
4213 obj.__dict__[self.name] = value
4214 descr = Descr("a")
4215
4216 class X(object):
4217 a = descr
4218
4219 x = X()
4220 self.assertIs(x.a, descr)
4221 x.a = 42
4222 self.assertEqual(x.a, 42)
4223
Benjamin Peterson21896a32010-03-21 22:03:03 +00004224 # Also check type_getattro for correctness.
4225 class Meta(type):
4226 pass
4227 class X(object):
4228 __metaclass__ = Meta
4229 X.a = 42
4230 Meta.a = Descr("a")
4231 self.assertEqual(X.a, 42)
4232
Benjamin Peterson9262b842008-11-17 22:45:50 +00004233 def test_getattr_hooks(self):
4234 # issue 4230
4235
4236 class Descriptor(object):
4237 counter = 0
4238 def __get__(self, obj, objtype=None):
4239 def getter(name):
4240 self.counter += 1
4241 raise AttributeError(name)
4242 return getter
4243
4244 descr = Descriptor()
4245 class A(object):
4246 __getattribute__ = descr
4247 class B(object):
4248 __getattr__ = descr
4249 class C(object):
4250 __getattribute__ = descr
4251 __getattr__ = descr
4252
4253 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004254 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004255 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004256 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004257 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004258 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004259
Benjamin Peterson9262b842008-11-17 22:45:50 +00004260 class EvilGetattribute(object):
4261 # This used to segfault
4262 def __getattr__(self, name):
4263 raise AttributeError(name)
4264 def __getattribute__(self, name):
4265 del EvilGetattribute.__getattr__
4266 for i in range(5):
4267 gc.collect()
4268 raise AttributeError(name)
4269
4270 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4271
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004272 def test_type___getattribute__(self):
4273 self.assertRaises(TypeError, type.__getattribute__, list, type)
4274
Benjamin Peterson477ba912011-01-12 15:34:01 +00004275 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004276 # type pretends not to have __abstractmethods__.
4277 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4278 class meta(type):
4279 pass
4280 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004281 class X(object):
4282 pass
4283 with self.assertRaises(AttributeError):
4284 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004285
Victor Stinner3249dec2011-05-01 23:19:15 +02004286 def test_proxy_call(self):
4287 class FakeStr:
4288 __class__ = str
4289
4290 fake_str = FakeStr()
4291 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004292 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004293
4294 # call a method descriptor
4295 with self.assertRaises(TypeError):
4296 str.split(fake_str)
4297
4298 # call a slot wrapper descriptor
4299 with self.assertRaises(TypeError):
4300 str.__add__(fake_str, "abc")
4301
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004302 def test_repr_as_str(self):
4303 # Issue #11603: crash or infinite loop when rebinding __str__ as
4304 # __repr__.
4305 class Foo:
4306 pass
4307 Foo.__repr__ = Foo.__str__
4308 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004309 self.assertRaises(RuntimeError, str, foo)
4310 self.assertRaises(RuntimeError, repr, foo)
4311
4312 def test_mixing_slot_wrappers(self):
4313 class X(dict):
4314 __setattr__ = dict.__setitem__
4315 x = X()
4316 x.y = 42
4317 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004318
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004319 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004320 with self.assertRaises(ValueError) as cm:
4321 class X:
4322 __slots__ = ["foo"]
4323 foo = None
4324 m = str(cm.exception)
4325 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4326
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004327 def test_set_doc(self):
4328 class X:
4329 "elephant"
4330 X.__doc__ = "banana"
4331 self.assertEqual(X.__doc__, "banana")
4332 with self.assertRaises(TypeError) as cm:
4333 type(list).__dict__["__doc__"].__set__(list, "blah")
4334 self.assertIn("can't set list.__doc__", str(cm.exception))
4335 with self.assertRaises(TypeError) as cm:
4336 type(X).__dict__["__doc__"].__delete__(X)
4337 self.assertIn("can't delete X.__doc__", str(cm.exception))
4338 self.assertEqual(X.__doc__, "banana")
4339
Antoine Pitrou9d574812011-12-12 13:47:25 +01004340 def test_qualname(self):
4341 descriptors = [str.lower, complex.real, float.real, int.__add__]
4342 types = ['method', 'member', 'getset', 'wrapper']
4343
4344 # make sure we have an example of each type of descriptor
4345 for d, n in zip(descriptors, types):
4346 self.assertEqual(type(d).__name__, n + '_descriptor')
4347
4348 for d in descriptors:
4349 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4350 self.assertEqual(d.__qualname__, qualname)
4351
4352 self.assertEqual(str.lower.__qualname__, 'str.lower')
4353 self.assertEqual(complex.real.__qualname__, 'complex.real')
4354 self.assertEqual(float.real.__qualname__, 'float.real')
4355 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4356
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004357 class X:
4358 pass
4359 with self.assertRaises(TypeError):
4360 del X.__qualname__
4361
4362 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4363 str, 'Oink')
4364
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004365 global Y
4366 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004367 class Inside:
4368 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004369 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004370 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004371
Victor Stinner6f738742012-02-25 01:22:36 +01004372 def test_qualname_dict(self):
4373 ns = {'__qualname__': 'some.name'}
4374 tp = type('Foo', (), ns)
4375 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004376 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004377 self.assertEqual(ns, {'__qualname__': 'some.name'})
4378
4379 ns = {'__qualname__': 1}
4380 self.assertRaises(TypeError, type, 'Foo', (), ns)
4381
Benjamin Peterson52c42432012-03-07 18:41:11 -06004382 def test_cycle_through_dict(self):
4383 # See bug #1469629
4384 class X(dict):
4385 def __init__(self):
4386 dict.__init__(self)
4387 self.__dict__ = self
4388 x = X()
4389 x.attr = 42
4390 wr = weakref.ref(x)
4391 del x
4392 support.gc_collect()
4393 self.assertIsNone(wr())
4394 for o in gc.get_objects():
4395 self.assertIsNot(type(o), X)
4396
Benjamin Peterson96384b92012-03-17 00:05:44 -05004397 def test_object_new_and_init_with_parameters(self):
4398 # See issue #1683368
4399 class OverrideNeither:
4400 pass
4401 self.assertRaises(TypeError, OverrideNeither, 1)
4402 self.assertRaises(TypeError, OverrideNeither, kw=1)
4403 class OverrideNew:
4404 def __new__(cls, foo, kw=0, *args, **kwds):
4405 return object.__new__(cls, *args, **kwds)
4406 class OverrideInit:
4407 def __init__(self, foo, kw=0, *args, **kwargs):
4408 return object.__init__(self, *args, **kwargs)
4409 class OverrideBoth(OverrideNew, OverrideInit):
4410 pass
4411 for case in OverrideNew, OverrideInit, OverrideBoth:
4412 case(1)
4413 case(1, kw=2)
4414 self.assertRaises(TypeError, case, 1, 2, 3)
4415 self.assertRaises(TypeError, case, 1, 2, foo=3)
4416
Benjamin Petersondf813792014-03-17 15:57:17 -05004417 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4418 class Base:
4419 pass
4420 class Sub(Base):
4421 pass
4422 self.assertIn("__dict__", Base.__dict__)
4423 self.assertNotIn("__dict__", Sub.__dict__)
4424
Antoine Pitrou9d574812011-12-12 13:47:25 +01004425
Georg Brandl479a7e72008-02-05 18:13:15 +00004426class DictProxyTests(unittest.TestCase):
4427 def setUp(self):
4428 class C(object):
4429 def meth(self):
4430 pass
4431 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004432
Brett Cannon7a540732011-02-22 03:04:06 +00004433 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4434 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004435 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004436 # Testing dict-proxy keys...
4437 it = self.C.__dict__.keys()
4438 self.assertNotIsInstance(it, list)
4439 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004440 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004441 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004442 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004443
Brett Cannon7a540732011-02-22 03:04:06 +00004444 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4445 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004446 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004447 # Testing dict-proxy values...
4448 it = self.C.__dict__.values()
4449 self.assertNotIsInstance(it, list)
4450 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004451 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004452
Brett Cannon7a540732011-02-22 03:04:06 +00004453 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4454 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004455 def test_iter_items(self):
4456 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004457 it = self.C.__dict__.items()
4458 self.assertNotIsInstance(it, list)
4459 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004460 keys.sort()
4461 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004462 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004463
Georg Brandl479a7e72008-02-05 18:13:15 +00004464 def test_dict_type_with_metaclass(self):
4465 # Testing type of __dict__ when metaclass set...
4466 class B(object):
4467 pass
4468 class M(type):
4469 pass
4470 class C(metaclass=M):
4471 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4472 pass
4473 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004474
Ezio Melottiac53ab62010-12-18 14:59:43 +00004475 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004476 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004477 # We can't blindly compare with the repr of another dict as ordering
4478 # of keys and values is arbitrary and may differ.
4479 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004480 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004481 self.assertTrue(r.endswith(')'), r)
4482 for k, v in self.C.__dict__.items():
4483 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004484
Christian Heimesbbffeb62008-01-24 09:42:52 +00004485
Georg Brandl479a7e72008-02-05 18:13:15 +00004486class PTypesLongInitTest(unittest.TestCase):
4487 # This is in its own TestCase so that it can be run before any other tests.
4488 def test_pytype_long_ready(self):
4489 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004490
Georg Brandl479a7e72008-02-05 18:13:15 +00004491 # This dumps core when SF bug 551412 isn't fixed --
4492 # but only when test_descr.py is run separately.
4493 # (That can't be helped -- as soon as PyType_Ready()
4494 # is called for PyLong_Type, the bug is gone.)
4495 class UserLong(object):
4496 def __pow__(self, *args):
4497 pass
4498 try:
4499 pow(0, UserLong(), 0)
4500 except:
4501 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004502
Georg Brandl479a7e72008-02-05 18:13:15 +00004503 # Another segfault only when run early
4504 # (before PyType_Ready(tuple) is called)
4505 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004506
4507
Victor Stinnerd74782b2012-03-09 00:39:08 +01004508class MiscTests(unittest.TestCase):
4509 def test_type_lookup_mro_reference(self):
4510 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4511 # the type MRO because it may be modified during the lookup, if
4512 # __bases__ is set during the lookup for example.
4513 class MyKey(object):
4514 def __hash__(self):
4515 return hash('mykey')
4516
4517 def __eq__(self, other):
4518 X.__bases__ = (Base2,)
4519
4520 class Base(object):
4521 mykey = 'from Base'
4522 mykey2 = 'from Base'
4523
4524 class Base2(object):
4525 mykey = 'from Base2'
4526 mykey2 = 'from Base2'
4527
4528 X = type('X', (Base,), {MyKey(): 5})
4529 # mykey is read from Base
4530 self.assertEqual(X.mykey, 'from Base')
4531 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4532 self.assertEqual(X.mykey2, 'from Base2')
4533
4534
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004535class PicklingTests(unittest.TestCase):
4536
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004537 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004538 listitems=None, dictitems=None):
4539 if proto >= 4:
4540 reduce_value = obj.__reduce_ex__(proto)
4541 self.assertEqual(reduce_value[:3],
4542 (copyreg.__newobj_ex__,
4543 (type(obj), args, kwargs),
4544 state))
4545 if listitems is not None:
4546 self.assertListEqual(list(reduce_value[3]), listitems)
4547 else:
4548 self.assertIsNone(reduce_value[3])
4549 if dictitems is not None:
4550 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4551 else:
4552 self.assertIsNone(reduce_value[4])
4553 elif proto >= 2:
4554 reduce_value = obj.__reduce_ex__(proto)
4555 self.assertEqual(reduce_value[:3],
4556 (copyreg.__newobj__,
4557 (type(obj),) + args,
4558 state))
4559 if listitems is not None:
4560 self.assertListEqual(list(reduce_value[3]), listitems)
4561 else:
4562 self.assertIsNone(reduce_value[3])
4563 if dictitems is not None:
4564 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4565 else:
4566 self.assertIsNone(reduce_value[4])
4567 else:
4568 base_type = type(obj).__base__
4569 reduce_value = (copyreg._reconstructor,
4570 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004571 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004572 None if base_type is object else base_type(obj)))
4573 if state is not None:
4574 reduce_value += (state,)
4575 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4576 self.assertEqual(obj.__reduce__(), reduce_value)
4577
4578 def test_reduce(self):
4579 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4580 args = (-101, "spam")
4581 kwargs = {'bacon': -201, 'fish': -301}
4582 state = {'cheese': -401}
4583
4584 class C1:
4585 def __getnewargs__(self):
4586 return args
4587 obj = C1()
4588 for proto in protocols:
4589 self._check_reduce(proto, obj, args)
4590
4591 for name, value in state.items():
4592 setattr(obj, name, value)
4593 for proto in protocols:
4594 self._check_reduce(proto, obj, args, state=state)
4595
4596 class C2:
4597 def __getnewargs__(self):
4598 return "bad args"
4599 obj = C2()
4600 for proto in protocols:
4601 if proto >= 2:
4602 with self.assertRaises(TypeError):
4603 obj.__reduce_ex__(proto)
4604
4605 class C3:
4606 def __getnewargs_ex__(self):
4607 return (args, kwargs)
4608 obj = C3()
4609 for proto in protocols:
4610 if proto >= 4:
4611 self._check_reduce(proto, obj, args, kwargs)
4612 elif proto >= 2:
4613 with self.assertRaises(ValueError):
4614 obj.__reduce_ex__(proto)
4615
4616 class C4:
4617 def __getnewargs_ex__(self):
4618 return (args, "bad dict")
4619 class C5:
4620 def __getnewargs_ex__(self):
4621 return ("bad tuple", kwargs)
4622 class C6:
4623 def __getnewargs_ex__(self):
4624 return ()
4625 class C7:
4626 def __getnewargs_ex__(self):
4627 return "bad args"
4628 for proto in protocols:
4629 for cls in C4, C5, C6, C7:
4630 obj = cls()
4631 if proto >= 2:
4632 with self.assertRaises((TypeError, ValueError)):
4633 obj.__reduce_ex__(proto)
4634
4635 class C8:
4636 def __getnewargs_ex__(self):
4637 return (args, kwargs)
4638 obj = C8()
4639 for proto in protocols:
4640 if 2 <= proto < 4:
4641 with self.assertRaises(ValueError):
4642 obj.__reduce_ex__(proto)
4643 class C9:
4644 def __getnewargs_ex__(self):
4645 return (args, {})
4646 obj = C9()
4647 for proto in protocols:
4648 self._check_reduce(proto, obj, args)
4649
4650 class C10:
4651 def __getnewargs_ex__(self):
4652 raise IndexError
4653 obj = C10()
4654 for proto in protocols:
4655 if proto >= 2:
4656 with self.assertRaises(IndexError):
4657 obj.__reduce_ex__(proto)
4658
4659 class C11:
4660 def __getstate__(self):
4661 return state
4662 obj = C11()
4663 for proto in protocols:
4664 self._check_reduce(proto, obj, state=state)
4665
4666 class C12:
4667 def __getstate__(self):
4668 return "not dict"
4669 obj = C12()
4670 for proto in protocols:
4671 self._check_reduce(proto, obj, state="not dict")
4672
4673 class C13:
4674 def __getstate__(self):
4675 raise IndexError
4676 obj = C13()
4677 for proto in protocols:
4678 with self.assertRaises(IndexError):
4679 obj.__reduce_ex__(proto)
4680 if proto < 2:
4681 with self.assertRaises(IndexError):
4682 obj.__reduce__()
4683
4684 class C14:
4685 __slots__ = tuple(state)
4686 def __init__(self):
4687 for name, value in state.items():
4688 setattr(self, name, value)
4689
4690 obj = C14()
4691 for proto in protocols:
4692 if proto >= 2:
4693 self._check_reduce(proto, obj, state=(None, state))
4694 else:
4695 with self.assertRaises(TypeError):
4696 obj.__reduce_ex__(proto)
4697 with self.assertRaises(TypeError):
4698 obj.__reduce__()
4699
4700 class C15(dict):
4701 pass
4702 obj = C15({"quebec": -601})
4703 for proto in protocols:
4704 self._check_reduce(proto, obj, dictitems=dict(obj))
4705
4706 class C16(list):
4707 pass
4708 obj = C16(["yukon"])
4709 for proto in protocols:
4710 self._check_reduce(proto, obj, listitems=list(obj))
4711
Benjamin Peterson2626fab2014-02-16 13:49:16 -05004712 def test_special_method_lookup(self):
4713 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4714 class Picky:
4715 def __getstate__(self):
4716 return {}
4717
4718 def __getattr__(self, attr):
4719 if attr in ("__getnewargs__", "__getnewargs_ex__"):
4720 raise AssertionError(attr)
4721 return None
4722 for protocol in protocols:
4723 state = {} if protocol >= 2 else None
4724 self._check_reduce(protocol, Picky(), state=state)
4725
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004726 def _assert_is_copy(self, obj, objcopy, msg=None):
4727 """Utility method to verify if two objects are copies of each others.
4728 """
4729 if msg is None:
4730 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4731 if type(obj).__repr__ is object.__repr__:
4732 # We have this limitation for now because we use the object's repr
4733 # to help us verify that the two objects are copies. This allows
4734 # us to delegate the non-generic verification logic to the objects
4735 # themselves.
4736 raise ValueError("object passed to _assert_is_copy must " +
4737 "override the __repr__ method.")
4738 self.assertIsNot(obj, objcopy, msg=msg)
4739 self.assertIs(type(obj), type(objcopy), msg=msg)
4740 if hasattr(obj, '__dict__'):
4741 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4742 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4743 if hasattr(obj, '__slots__'):
4744 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4745 for slot in obj.__slots__:
4746 self.assertEqual(
4747 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4748 self.assertEqual(getattr(obj, slot, None),
4749 getattr(objcopy, slot, None), msg=msg)
4750 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4751
4752 @staticmethod
4753 def _generate_pickle_copiers():
4754 """Utility method to generate the many possible pickle configurations.
4755 """
4756 class PickleCopier:
4757 "This class copies object using pickle."
4758 def __init__(self, proto, dumps, loads):
4759 self.proto = proto
4760 self.dumps = dumps
4761 self.loads = loads
4762 def copy(self, obj):
4763 return self.loads(self.dumps(obj, self.proto))
4764 def __repr__(self):
4765 # We try to be as descriptive as possible here since this is
4766 # the string which we will allow us to tell the pickle
4767 # configuration we are using during debugging.
4768 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4769 .format(self.proto,
4770 self.dumps.__module__, self.dumps.__qualname__,
4771 self.loads.__module__, self.loads.__qualname__))
4772 return (PickleCopier(*args) for args in
4773 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4774 {pickle.dumps, pickle._dumps},
4775 {pickle.loads, pickle._loads}))
4776
4777 def test_pickle_slots(self):
4778 # Tests pickling of classes with __slots__.
4779
4780 # Pickling of classes with __slots__ but without __getstate__ should
4781 # fail (if using protocol 0 or 1)
4782 global C
4783 class C:
4784 __slots__ = ['a']
4785 with self.assertRaises(TypeError):
4786 pickle.dumps(C(), 0)
4787
4788 global D
4789 class D(C):
4790 pass
4791 with self.assertRaises(TypeError):
4792 pickle.dumps(D(), 0)
4793
4794 class C:
4795 "A class with __getstate__ and __setstate__ implemented."
4796 __slots__ = ['a']
4797 def __getstate__(self):
4798 state = getattr(self, '__dict__', {}).copy()
4799 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004800 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004801 try:
4802 state[slot] = getattr(self, slot)
4803 except AttributeError:
4804 pass
4805 return state
4806 def __setstate__(self, state):
4807 for k, v in state.items():
4808 setattr(self, k, v)
4809 def __repr__(self):
4810 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4811
4812 class D(C):
4813 "A subclass of a class with slots."
4814 pass
4815
4816 global E
4817 class E(C):
4818 "A subclass with an extra slot."
4819 __slots__ = ['b']
4820
4821 # Now it should work
4822 for pickle_copier in self._generate_pickle_copiers():
4823 with self.subTest(pickle_copier=pickle_copier):
4824 x = C()
4825 y = pickle_copier.copy(x)
4826 self._assert_is_copy(x, y)
4827
4828 x.a = 42
4829 y = pickle_copier.copy(x)
4830 self._assert_is_copy(x, y)
4831
4832 x = D()
4833 x.a = 42
4834 x.b = 100
4835 y = pickle_copier.copy(x)
4836 self._assert_is_copy(x, y)
4837
4838 x = E()
4839 x.a = 42
4840 x.b = "foo"
4841 y = pickle_copier.copy(x)
4842 self._assert_is_copy(x, y)
4843
4844 def test_reduce_copying(self):
4845 # Tests pickling and copying new-style classes and objects.
4846 global C1
4847 class C1:
4848 "The state of this class is copyable via its instance dict."
4849 ARGS = (1, 2)
4850 NEED_DICT_COPYING = True
4851 def __init__(self, a, b):
4852 super().__init__()
4853 self.a = a
4854 self.b = b
4855 def __repr__(self):
4856 return "C1(%r, %r)" % (self.a, self.b)
4857
4858 global C2
4859 class C2(list):
4860 "A list subclass copyable via __getnewargs__."
4861 ARGS = (1, 2)
4862 NEED_DICT_COPYING = False
4863 def __new__(cls, a, b):
4864 self = super().__new__(cls)
4865 self.a = a
4866 self.b = b
4867 return self
4868 def __init__(self, *args):
4869 super().__init__()
4870 # This helps testing that __init__ is not called during the
4871 # unpickling process, which would cause extra appends.
4872 self.append("cheese")
4873 @classmethod
4874 def __getnewargs__(cls):
4875 return cls.ARGS
4876 def __repr__(self):
4877 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
4878
4879 global C3
4880 class C3(list):
4881 "A list subclass copyable via __getstate__."
4882 ARGS = (1, 2)
4883 NEED_DICT_COPYING = False
4884 def __init__(self, a, b):
4885 self.a = a
4886 self.b = b
4887 # This helps testing that __init__ is not called during the
4888 # unpickling process, which would cause extra appends.
4889 self.append("cheese")
4890 @classmethod
4891 def __getstate__(cls):
4892 return cls.ARGS
4893 def __setstate__(self, state):
4894 a, b = state
4895 self.a = a
4896 self.b = b
4897 def __repr__(self):
4898 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
4899
4900 global C4
4901 class C4(int):
4902 "An int subclass copyable via __getnewargs__."
4903 ARGS = ("hello", "world", 1)
4904 NEED_DICT_COPYING = False
4905 def __new__(cls, a, b, value):
4906 self = super().__new__(cls, value)
4907 self.a = a
4908 self.b = b
4909 return self
4910 @classmethod
4911 def __getnewargs__(cls):
4912 return cls.ARGS
4913 def __repr__(self):
4914 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
4915
4916 global C5
4917 class C5(int):
4918 "An int subclass copyable via __getnewargs_ex__."
4919 ARGS = (1, 2)
4920 KWARGS = {'value': 3}
4921 NEED_DICT_COPYING = False
4922 def __new__(cls, a, b, *, value=0):
4923 self = super().__new__(cls, value)
4924 self.a = a
4925 self.b = b
4926 return self
4927 @classmethod
4928 def __getnewargs_ex__(cls):
4929 return (cls.ARGS, cls.KWARGS)
4930 def __repr__(self):
4931 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
4932
4933 test_classes = (C1, C2, C3, C4, C5)
4934 # Testing copying through pickle
4935 pickle_copiers = self._generate_pickle_copiers()
4936 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
4937 with self.subTest(cls=cls, pickle_copier=pickle_copier):
4938 kwargs = getattr(cls, 'KWARGS', {})
4939 obj = cls(*cls.ARGS, **kwargs)
4940 proto = pickle_copier.proto
4941 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
4942 with self.assertRaises(ValueError):
4943 pickle_copier.dumps(obj, proto)
4944 continue
4945 objcopy = pickle_copier.copy(obj)
4946 self._assert_is_copy(obj, objcopy)
4947 # For test classes that supports this, make sure we didn't go
4948 # around the reduce protocol by simply copying the attribute
4949 # dictionary. We clear attributes using the previous copy to
4950 # not mutate the original argument.
4951 if proto >= 2 and not cls.NEED_DICT_COPYING:
4952 objcopy.__dict__.clear()
4953 objcopy2 = pickle_copier.copy(objcopy)
4954 self._assert_is_copy(obj, objcopy2)
4955
4956 # Testing copying through copy.deepcopy()
4957 for cls in test_classes:
4958 with self.subTest(cls=cls):
4959 kwargs = getattr(cls, 'KWARGS', {})
4960 obj = cls(*cls.ARGS, **kwargs)
4961 # XXX: We need to modify the copy module to support PEP 3154's
4962 # reduce protocol 4.
4963 if hasattr(cls, '__getnewargs_ex__'):
4964 continue
4965 objcopy = deepcopy(obj)
4966 self._assert_is_copy(obj, objcopy)
4967 # For test classes that supports this, make sure we didn't go
4968 # around the reduce protocol by simply copying the attribute
4969 # dictionary. We clear attributes using the previous copy to
4970 # not mutate the original argument.
4971 if not cls.NEED_DICT_COPYING:
4972 objcopy.__dict__.clear()
4973 objcopy2 = deepcopy(objcopy)
4974 self._assert_is_copy(obj, objcopy2)
4975
4976
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004977def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004978 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004979 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01004980 ClassPropertiesAndMethods, DictProxyTests,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004981 MiscTests, PicklingTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004982
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004983if __name__ == "__main__":
4984 test_main()