blob: f08a3d2bf613c40f989d0463f20e12554ea4cb74 [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
R. David Murray378c0cf2010-02-24 01:46:21 +00002053 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002054 # this segfaulted in 2.5b2
2055 try:
2056 import _testcapi
2057 except ImportError:
2058 pass
2059 else:
2060 class X(object):
2061 p = property(_testcapi.test_with_docstring)
2062
2063 def test_properties_plus(self):
2064 class C(object):
2065 foo = property(doc="hello")
2066 @foo.getter
2067 def foo(self):
2068 return self._foo
2069 @foo.setter
2070 def foo(self, value):
2071 self._foo = abs(value)
2072 @foo.deleter
2073 def foo(self):
2074 del self._foo
2075 c = C()
2076 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002077 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002078 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002079 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002080 self.assertEqual(c._foo, 42)
2081 self.assertEqual(c.foo, 42)
2082 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002083 self.assertNotHasAttr(c, '_foo')
2084 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002085
2086 class D(C):
2087 @C.foo.deleter
2088 def foo(self):
2089 try:
2090 del self._foo
2091 except AttributeError:
2092 pass
2093 d = D()
2094 d.foo = 24
2095 self.assertEqual(d.foo, 24)
2096 del d.foo
2097 del d.foo
2098
2099 class E(object):
2100 @property
2101 def foo(self):
2102 return self._foo
2103 @foo.setter
2104 def foo(self, value):
2105 raise RuntimeError
2106 @foo.setter
2107 def foo(self, value):
2108 self._foo = abs(value)
2109 @foo.deleter
2110 def foo(self, value=None):
2111 del self._foo
2112
2113 e = E()
2114 e.foo = -42
2115 self.assertEqual(e.foo, 42)
2116 del e.foo
2117
2118 class F(E):
2119 @E.foo.deleter
2120 def foo(self):
2121 del self._foo
2122 @foo.setter
2123 def foo(self, value):
2124 self._foo = max(0, value)
2125 f = F()
2126 f.foo = -10
2127 self.assertEqual(f.foo, 0)
2128 del f.foo
2129
2130 def test_dict_constructors(self):
2131 # Testing dict constructor ...
2132 d = dict()
2133 self.assertEqual(d, {})
2134 d = dict({})
2135 self.assertEqual(d, {})
2136 d = dict({1: 2, 'a': 'b'})
2137 self.assertEqual(d, {1: 2, 'a': 'b'})
2138 self.assertEqual(d, dict(list(d.items())))
2139 self.assertEqual(d, dict(iter(d.items())))
2140 d = dict({'one':1, 'two':2})
2141 self.assertEqual(d, dict(one=1, two=2))
2142 self.assertEqual(d, dict(**d))
2143 self.assertEqual(d, dict({"one": 1}, two=2))
2144 self.assertEqual(d, dict([("two", 2)], one=1))
2145 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2146 self.assertEqual(d, dict(**d))
2147
2148 for badarg in 0, 0, 0j, "0", [0], (0,):
2149 try:
2150 dict(badarg)
2151 except TypeError:
2152 pass
2153 except ValueError:
2154 if badarg == "0":
2155 # It's a sequence, and its elements are also sequences (gotta
2156 # love strings <wink>), but they aren't of length 2, so this
2157 # one seemed better as a ValueError than a TypeError.
2158 pass
2159 else:
2160 self.fail("no TypeError from dict(%r)" % badarg)
2161 else:
2162 self.fail("no TypeError from dict(%r)" % badarg)
2163
2164 try:
2165 dict({}, {})
2166 except TypeError:
2167 pass
2168 else:
2169 self.fail("no TypeError from dict({}, {})")
2170
2171 class Mapping:
2172 # Lacks a .keys() method; will be added later.
2173 dict = {1:2, 3:4, 'a':1j}
2174
2175 try:
2176 dict(Mapping())
2177 except TypeError:
2178 pass
2179 else:
2180 self.fail("no TypeError from dict(incomplete mapping)")
2181
2182 Mapping.keys = lambda self: list(self.dict.keys())
2183 Mapping.__getitem__ = lambda self, i: self.dict[i]
2184 d = dict(Mapping())
2185 self.assertEqual(d, Mapping.dict)
2186
2187 # Init from sequence of iterable objects, each producing a 2-sequence.
2188 class AddressBookEntry:
2189 def __init__(self, first, last):
2190 self.first = first
2191 self.last = last
2192 def __iter__(self):
2193 return iter([self.first, self.last])
2194
2195 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2196 AddressBookEntry('Barry', 'Peters'),
2197 AddressBookEntry('Tim', 'Peters'),
2198 AddressBookEntry('Barry', 'Warsaw')])
2199 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2200
2201 d = dict(zip(range(4), range(1, 5)))
2202 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2203
2204 # Bad sequence lengths.
2205 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2206 try:
2207 dict(bad)
2208 except ValueError:
2209 pass
2210 else:
2211 self.fail("no ValueError from dict(%r)" % bad)
2212
2213 def test_dir(self):
2214 # Testing dir() ...
2215 junk = 12
2216 self.assertEqual(dir(), ['junk', 'self'])
2217 del junk
2218
2219 # Just make sure these don't blow up!
2220 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2221 dir(arg)
2222
2223 # Test dir on new-style classes. Since these have object as a
2224 # base class, a lot more gets sucked in.
2225 def interesting(strings):
2226 return [s for s in strings if not s.startswith('_')]
2227
2228 class C(object):
2229 Cdata = 1
2230 def Cmethod(self): pass
2231
2232 cstuff = ['Cdata', 'Cmethod']
2233 self.assertEqual(interesting(dir(C)), cstuff)
2234
2235 c = C()
2236 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002237 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002238
2239 c.cdata = 2
2240 c.cmethod = lambda self: 0
2241 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002242 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002243
2244 class A(C):
2245 Adata = 1
2246 def Amethod(self): pass
2247
2248 astuff = ['Adata', 'Amethod'] + cstuff
2249 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002250 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002251 a = A()
2252 self.assertEqual(interesting(dir(a)), astuff)
2253 a.adata = 42
2254 a.amethod = lambda self: 3
2255 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002256 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002257
2258 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002259 class M(type(sys)):
2260 pass
2261 minstance = M("m")
2262 minstance.b = 2
2263 minstance.a = 1
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002264 default_attributes = ['__name__', '__doc__', '__package__',
Eric Snowb523f842013-11-22 09:05:39 -07002265 '__loader__', '__spec__']
Brett Cannon4c14b5d2013-05-04 13:56:58 -04002266 names = [x for x in dir(minstance) if x not in default_attributes]
Georg Brandl479a7e72008-02-05 18:13:15 +00002267 self.assertEqual(names, ['a', 'b'])
2268
2269 class M2(M):
2270 def getdict(self):
2271 return "Not a dict!"
2272 __dict__ = property(getdict)
2273
2274 m2instance = M2("m2")
2275 m2instance.b = 2
2276 m2instance.a = 1
2277 self.assertEqual(m2instance.__dict__, "Not a dict!")
2278 try:
2279 dir(m2instance)
2280 except TypeError:
2281 pass
2282
2283 # Two essentially featureless objects, just inheriting stuff from
2284 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002285 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002286
2287 # Nasty test case for proxied objects
2288 class Wrapper(object):
2289 def __init__(self, obj):
2290 self.__obj = obj
2291 def __repr__(self):
2292 return "Wrapper(%s)" % repr(self.__obj)
2293 def __getitem__(self, key):
2294 return Wrapper(self.__obj[key])
2295 def __len__(self):
2296 return len(self.__obj)
2297 def __getattr__(self, name):
2298 return Wrapper(getattr(self.__obj, name))
2299
2300 class C(object):
2301 def __getclass(self):
2302 return Wrapper(type(self))
2303 __class__ = property(__getclass)
2304
2305 dir(C()) # This used to segfault
2306
2307 def test_supers(self):
2308 # Testing super...
2309
2310 class A(object):
2311 def meth(self, a):
2312 return "A(%r)" % a
2313
2314 self.assertEqual(A().meth(1), "A(1)")
2315
2316 class B(A):
2317 def __init__(self):
2318 self.__super = super(B, self)
2319 def meth(self, a):
2320 return "B(%r)" % a + self.__super.meth(a)
2321
2322 self.assertEqual(B().meth(2), "B(2)A(2)")
2323
2324 class C(A):
2325 def meth(self, a):
2326 return "C(%r)" % a + self.__super.meth(a)
2327 C._C__super = super(C)
2328
2329 self.assertEqual(C().meth(3), "C(3)A(3)")
2330
2331 class D(C, B):
2332 def meth(self, a):
2333 return "D(%r)" % a + super(D, self).meth(a)
2334
2335 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2336
2337 # Test for subclassing super
2338
2339 class mysuper(super):
2340 def __init__(self, *args):
2341 return super(mysuper, self).__init__(*args)
2342
2343 class E(D):
2344 def meth(self, a):
2345 return "E(%r)" % a + mysuper(E, self).meth(a)
2346
2347 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2348
2349 class F(E):
2350 def meth(self, a):
2351 s = self.__super # == mysuper(F, self)
2352 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2353 F._F__super = mysuper(F)
2354
2355 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2356
2357 # Make sure certain errors are raised
2358
2359 try:
2360 super(D, 42)
2361 except TypeError:
2362 pass
2363 else:
2364 self.fail("shouldn't allow super(D, 42)")
2365
2366 try:
2367 super(D, C())
2368 except TypeError:
2369 pass
2370 else:
2371 self.fail("shouldn't allow super(D, C())")
2372
2373 try:
2374 super(D).__get__(12)
2375 except TypeError:
2376 pass
2377 else:
2378 self.fail("shouldn't allow super(D).__get__(12)")
2379
2380 try:
2381 super(D).__get__(C())
2382 except TypeError:
2383 pass
2384 else:
2385 self.fail("shouldn't allow super(D).__get__(C())")
2386
2387 # Make sure data descriptors can be overridden and accessed via super
2388 # (new feature in Python 2.3)
2389
2390 class DDbase(object):
2391 def getx(self): return 42
2392 x = property(getx)
2393
2394 class DDsub(DDbase):
2395 def getx(self): return "hello"
2396 x = property(getx)
2397
2398 dd = DDsub()
2399 self.assertEqual(dd.x, "hello")
2400 self.assertEqual(super(DDsub, dd).x, 42)
2401
2402 # Ensure that super() lookup of descriptor from classmethod
2403 # works (SF ID# 743627)
2404
2405 class Base(object):
2406 aProp = property(lambda self: "foo")
2407
2408 class Sub(Base):
2409 @classmethod
2410 def test(klass):
2411 return super(Sub,klass).aProp
2412
2413 self.assertEqual(Sub.test(), Base.aProp)
2414
2415 # Verify that super() doesn't allow keyword args
2416 try:
2417 super(Base, kw=1)
2418 except TypeError:
2419 pass
2420 else:
2421 self.assertEqual("super shouldn't accept keyword args")
2422
2423 def test_basic_inheritance(self):
2424 # Testing inheritance from basic types...
2425
2426 class hexint(int):
2427 def __repr__(self):
2428 return hex(self)
2429 def __add__(self, other):
2430 return hexint(int.__add__(self, other))
2431 # (Note that overriding __radd__ doesn't work,
2432 # because the int type gets first dibs.)
2433 self.assertEqual(repr(hexint(7) + 9), "0x10")
2434 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2435 a = hexint(12345)
2436 self.assertEqual(a, 12345)
2437 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002438 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002440 self.assertIs((+a).__class__, int)
2441 self.assertIs((a >> 0).__class__, int)
2442 self.assertIs((a << 0).__class__, int)
2443 self.assertIs((hexint(0) << 12).__class__, int)
2444 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002445
2446 class octlong(int):
2447 __slots__ = []
2448 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002449 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002450 def __add__(self, other):
2451 return self.__class__(super(octlong, self).__add__(other))
2452 __radd__ = __add__
2453 self.assertEqual(str(octlong(3) + 5), "0o10")
2454 # (Note that overriding __radd__ here only seems to work
2455 # because the example uses a short int left argument.)
2456 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2457 a = octlong(12345)
2458 self.assertEqual(a, 12345)
2459 self.assertEqual(int(a), 12345)
2460 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002461 self.assertIs(int(a).__class__, int)
2462 self.assertIs((+a).__class__, int)
2463 self.assertIs((-a).__class__, int)
2464 self.assertIs((-octlong(0)).__class__, int)
2465 self.assertIs((a >> 0).__class__, int)
2466 self.assertIs((a << 0).__class__, int)
2467 self.assertIs((a - 0).__class__, int)
2468 self.assertIs((a * 1).__class__, int)
2469 self.assertIs((a ** 1).__class__, int)
2470 self.assertIs((a // 1).__class__, int)
2471 self.assertIs((1 * a).__class__, int)
2472 self.assertIs((a | 0).__class__, int)
2473 self.assertIs((a ^ 0).__class__, int)
2474 self.assertIs((a & -1).__class__, int)
2475 self.assertIs((octlong(0) << 12).__class__, int)
2476 self.assertIs((octlong(0) >> 12).__class__, int)
2477 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002478
2479 # Because octlong overrides __add__, we can't check the absence of +0
2480 # optimizations using octlong.
2481 class longclone(int):
2482 pass
2483 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002484 self.assertIs((a + 0).__class__, int)
2485 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002486
2487 # Check that negative clones don't segfault
2488 a = longclone(-1)
2489 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002490 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002491
2492 class precfloat(float):
2493 __slots__ = ['prec']
2494 def __init__(self, value=0.0, prec=12):
2495 self.prec = int(prec)
2496 def __repr__(self):
2497 return "%.*g" % (self.prec, self)
2498 self.assertEqual(repr(precfloat(1.1)), "1.1")
2499 a = precfloat(12345)
2500 self.assertEqual(a, 12345.0)
2501 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002502 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002503 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002504 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002505
2506 class madcomplex(complex):
2507 def __repr__(self):
2508 return "%.17gj%+.17g" % (self.imag, self.real)
2509 a = madcomplex(-3, 4)
2510 self.assertEqual(repr(a), "4j-3")
2511 base = complex(-3, 4)
2512 self.assertEqual(base.__class__, complex)
2513 self.assertEqual(a, base)
2514 self.assertEqual(complex(a), base)
2515 self.assertEqual(complex(a).__class__, complex)
2516 a = madcomplex(a) # just trying another form of the constructor
2517 self.assertEqual(repr(a), "4j-3")
2518 self.assertEqual(a, base)
2519 self.assertEqual(complex(a), base)
2520 self.assertEqual(complex(a).__class__, complex)
2521 self.assertEqual(hash(a), hash(base))
2522 self.assertEqual((+a).__class__, complex)
2523 self.assertEqual((a + 0).__class__, complex)
2524 self.assertEqual(a + 0, base)
2525 self.assertEqual((a - 0).__class__, complex)
2526 self.assertEqual(a - 0, base)
2527 self.assertEqual((a * 1).__class__, complex)
2528 self.assertEqual(a * 1, base)
2529 self.assertEqual((a / 1).__class__, complex)
2530 self.assertEqual(a / 1, base)
2531
2532 class madtuple(tuple):
2533 _rev = None
2534 def rev(self):
2535 if self._rev is not None:
2536 return self._rev
2537 L = list(self)
2538 L.reverse()
2539 self._rev = self.__class__(L)
2540 return self._rev
2541 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2542 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2543 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2544 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2545 for i in range(512):
2546 t = madtuple(range(i))
2547 u = t.rev()
2548 v = u.rev()
2549 self.assertEqual(v, t)
2550 a = madtuple((1,2,3,4,5))
2551 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002552 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002553 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002554 self.assertIs(a[:].__class__, tuple)
2555 self.assertIs((a * 1).__class__, tuple)
2556 self.assertIs((a * 0).__class__, tuple)
2557 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002558 a = madtuple(())
2559 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002560 self.assertIs(tuple(a).__class__, tuple)
2561 self.assertIs((a + a).__class__, tuple)
2562 self.assertIs((a * 0).__class__, tuple)
2563 self.assertIs((a * 1).__class__, tuple)
2564 self.assertIs((a * 2).__class__, tuple)
2565 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002566
2567 class madstring(str):
2568 _rev = None
2569 def rev(self):
2570 if self._rev is not None:
2571 return self._rev
2572 L = list(self)
2573 L.reverse()
2574 self._rev = self.__class__("".join(L))
2575 return self._rev
2576 s = madstring("abcdefghijklmnopqrstuvwxyz")
2577 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2578 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2579 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2580 for i in range(256):
2581 s = madstring("".join(map(chr, range(i))))
2582 t = s.rev()
2583 u = t.rev()
2584 self.assertEqual(u, s)
2585 s = madstring("12345")
2586 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002587 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002588
2589 base = "\x00" * 5
2590 s = madstring(base)
2591 self.assertEqual(s, base)
2592 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002593 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002594 self.assertEqual(hash(s), hash(base))
2595 self.assertEqual({s: 1}[base], 1)
2596 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002597 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002598 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002599 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002600 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002601 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002602 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002603 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002604 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002605 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002606 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002607 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002608 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002609 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002610 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002611 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002612 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002613 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002614 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002615 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002616 self.assertEqual(s.rstrip(), base)
2617 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002618 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002619 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002620 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002622 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002623 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002624 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002625 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002626 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002627 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002628 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002629 self.assertEqual(s.lower(), base)
2630
2631 class madunicode(str):
2632 _rev = None
2633 def rev(self):
2634 if self._rev is not None:
2635 return self._rev
2636 L = list(self)
2637 L.reverse()
2638 self._rev = self.__class__("".join(L))
2639 return self._rev
2640 u = madunicode("ABCDEF")
2641 self.assertEqual(u, "ABCDEF")
2642 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2643 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2644 base = "12345"
2645 u = madunicode(base)
2646 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002647 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 self.assertEqual(hash(u), hash(base))
2649 self.assertEqual({u: 1}[base], 1)
2650 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002651 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002652 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002653 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002654 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002655 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002656 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002657 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002658 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002659 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002660 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002661 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002662 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002663 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002664 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002665 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002666 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002667 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002668 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002669 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002670 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002671 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002672 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002673 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002674 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002675 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002676 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002677 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002678 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002679 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002680 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002681 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002683 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002684 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002685 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002686 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002687 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002688 self.assertEqual(u[0:0], "")
2689
2690 class sublist(list):
2691 pass
2692 a = sublist(range(5))
2693 self.assertEqual(a, list(range(5)))
2694 a.append("hello")
2695 self.assertEqual(a, list(range(5)) + ["hello"])
2696 a[5] = 5
2697 self.assertEqual(a, list(range(6)))
2698 a.extend(range(6, 20))
2699 self.assertEqual(a, list(range(20)))
2700 a[-5:] = []
2701 self.assertEqual(a, list(range(15)))
2702 del a[10:15]
2703 self.assertEqual(len(a), 10)
2704 self.assertEqual(a, list(range(10)))
2705 self.assertEqual(list(a), list(range(10)))
2706 self.assertEqual(a[0], 0)
2707 self.assertEqual(a[9], 9)
2708 self.assertEqual(a[-10], 0)
2709 self.assertEqual(a[-1], 9)
2710 self.assertEqual(a[:5], list(range(5)))
2711
2712 ## class CountedInput(file):
2713 ## """Counts lines read by self.readline().
2714 ##
2715 ## self.lineno is the 0-based ordinal of the last line read, up to
2716 ## a maximum of one greater than the number of lines in the file.
2717 ##
2718 ## self.ateof is true if and only if the final "" line has been read,
2719 ## at which point self.lineno stops incrementing, and further calls
2720 ## to readline() continue to return "".
2721 ## """
2722 ##
2723 ## lineno = 0
2724 ## ateof = 0
2725 ## def readline(self):
2726 ## if self.ateof:
2727 ## return ""
2728 ## s = file.readline(self)
2729 ## # Next line works too.
2730 ## # s = super(CountedInput, self).readline()
2731 ## self.lineno += 1
2732 ## if s == "":
2733 ## self.ateof = 1
2734 ## return s
2735 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002736 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002737 ## lines = ['a\n', 'b\n', 'c\n']
2738 ## try:
2739 ## f.writelines(lines)
2740 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002741 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002742 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2743 ## got = f.readline()
2744 ## self.assertEqual(expected, got)
2745 ## self.assertEqual(f.lineno, i)
2746 ## self.assertEqual(f.ateof, (i > len(lines)))
2747 ## f.close()
2748 ## finally:
2749 ## try:
2750 ## f.close()
2751 ## except:
2752 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002753 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002754
2755 def test_keywords(self):
2756 # Testing keyword args to basic type constructors ...
2757 self.assertEqual(int(x=1), 1)
2758 self.assertEqual(float(x=2), 2.0)
2759 self.assertEqual(int(x=3), 3)
2760 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2761 self.assertEqual(str(object=500), '500')
2762 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2763 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2764 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2765 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2766
2767 for constructor in (int, float, int, complex, str, str,
2768 tuple, list):
2769 try:
2770 constructor(bogus_keyword_arg=1)
2771 except TypeError:
2772 pass
2773 else:
2774 self.fail("expected TypeError from bogus keyword argument to %r"
2775 % constructor)
2776
2777 def test_str_subclass_as_dict_key(self):
2778 # Testing a str subclass used as dict key ..
2779
2780 class cistr(str):
2781 """Sublcass of str that computes __eq__ case-insensitively.
2782
2783 Also computes a hash code of the string in canonical form.
2784 """
2785
2786 def __init__(self, value):
2787 self.canonical = value.lower()
2788 self.hashcode = hash(self.canonical)
2789
2790 def __eq__(self, other):
2791 if not isinstance(other, cistr):
2792 other = cistr(other)
2793 return self.canonical == other.canonical
2794
2795 def __hash__(self):
2796 return self.hashcode
2797
2798 self.assertEqual(cistr('ABC'), 'abc')
2799 self.assertEqual('aBc', cistr('ABC'))
2800 self.assertEqual(str(cistr('ABC')), 'ABC')
2801
2802 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2803 self.assertEqual(d[cistr('one')], 1)
2804 self.assertEqual(d[cistr('tWo')], 2)
2805 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002806 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002807 self.assertEqual(d.get(cistr('thrEE')), 3)
2808
2809 def test_classic_comparisons(self):
2810 # Testing classic comparisons...
2811 class classic:
2812 pass
2813
2814 for base in (classic, int, object):
2815 class C(base):
2816 def __init__(self, value):
2817 self.value = int(value)
2818 def __eq__(self, other):
2819 if isinstance(other, C):
2820 return self.value == other.value
2821 if isinstance(other, int) or isinstance(other, int):
2822 return self.value == other
2823 return NotImplemented
2824 def __ne__(self, other):
2825 if isinstance(other, C):
2826 return self.value != other.value
2827 if isinstance(other, int) or isinstance(other, int):
2828 return self.value != other
2829 return NotImplemented
2830 def __lt__(self, other):
2831 if isinstance(other, C):
2832 return self.value < other.value
2833 if isinstance(other, int) or isinstance(other, int):
2834 return self.value < other
2835 return NotImplemented
2836 def __le__(self, other):
2837 if isinstance(other, C):
2838 return self.value <= other.value
2839 if isinstance(other, int) or isinstance(other, int):
2840 return self.value <= other
2841 return NotImplemented
2842 def __gt__(self, other):
2843 if isinstance(other, C):
2844 return self.value > other.value
2845 if isinstance(other, int) or isinstance(other, int):
2846 return self.value > other
2847 return NotImplemented
2848 def __ge__(self, other):
2849 if isinstance(other, C):
2850 return self.value >= other.value
2851 if isinstance(other, int) or isinstance(other, int):
2852 return self.value >= other
2853 return NotImplemented
2854
2855 c1 = C(1)
2856 c2 = C(2)
2857 c3 = C(3)
2858 self.assertEqual(c1, 1)
2859 c = {1: c1, 2: c2, 3: c3}
2860 for x in 1, 2, 3:
2861 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002862 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002864 eval("x %s y" % op),
2865 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002866 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002867 eval("x %s y" % op),
2868 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002869 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002870 eval("x %s y" % op),
2871 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002872
2873 def test_rich_comparisons(self):
2874 # Testing rich comparisons...
2875 class Z(complex):
2876 pass
2877 z = Z(1)
2878 self.assertEqual(z, 1+0j)
2879 self.assertEqual(1+0j, z)
2880 class ZZ(complex):
2881 def __eq__(self, other):
2882 try:
2883 return abs(self - other) <= 1e-6
2884 except:
2885 return NotImplemented
2886 zz = ZZ(1.0000003)
2887 self.assertEqual(zz, 1+0j)
2888 self.assertEqual(1+0j, zz)
2889
2890 class classic:
2891 pass
2892 for base in (classic, int, object, list):
2893 class C(base):
2894 def __init__(self, value):
2895 self.value = int(value)
2896 def __cmp__(self_, other):
2897 self.fail("shouldn't call __cmp__")
2898 def __eq__(self, other):
2899 if isinstance(other, C):
2900 return self.value == other.value
2901 if isinstance(other, int) or isinstance(other, int):
2902 return self.value == other
2903 return NotImplemented
2904 def __ne__(self, other):
2905 if isinstance(other, C):
2906 return self.value != other.value
2907 if isinstance(other, int) or isinstance(other, int):
2908 return self.value != other
2909 return NotImplemented
2910 def __lt__(self, other):
2911 if isinstance(other, C):
2912 return self.value < other.value
2913 if isinstance(other, int) or isinstance(other, int):
2914 return self.value < other
2915 return NotImplemented
2916 def __le__(self, other):
2917 if isinstance(other, C):
2918 return self.value <= other.value
2919 if isinstance(other, int) or isinstance(other, int):
2920 return self.value <= other
2921 return NotImplemented
2922 def __gt__(self, other):
2923 if isinstance(other, C):
2924 return self.value > other.value
2925 if isinstance(other, int) or isinstance(other, int):
2926 return self.value > other
2927 return NotImplemented
2928 def __ge__(self, other):
2929 if isinstance(other, C):
2930 return self.value >= other.value
2931 if isinstance(other, int) or isinstance(other, int):
2932 return self.value >= other
2933 return NotImplemented
2934 c1 = C(1)
2935 c2 = C(2)
2936 c3 = C(3)
2937 self.assertEqual(c1, 1)
2938 c = {1: c1, 2: c2, 3: c3}
2939 for x in 1, 2, 3:
2940 for y in 1, 2, 3:
2941 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002942 self.assertEqual(eval("c[x] %s c[y]" % op),
2943 eval("x %s y" % op),
2944 "x=%d, y=%d" % (x, y))
2945 self.assertEqual(eval("c[x] %s y" % op),
2946 eval("x %s y" % op),
2947 "x=%d, y=%d" % (x, y))
2948 self.assertEqual(eval("x %s c[y]" % op),
2949 eval("x %s y" % op),
2950 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002951
2952 def test_descrdoc(self):
2953 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002954 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002955 def check(descr, what):
2956 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002957 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002958 check(complex.real, "the real part of a complex number") # member descriptor
2959
2960 def test_doc_descriptor(self):
2961 # Testing __doc__ descriptor...
2962 # SF bug 542984
2963 class DocDescr(object):
2964 def __get__(self, object, otype):
2965 if object:
2966 object = object.__class__.__name__ + ' instance'
2967 if otype:
2968 otype = otype.__name__
2969 return 'object=%s; type=%s' % (object, otype)
2970 class OldClass:
2971 __doc__ = DocDescr()
2972 class NewClass(object):
2973 __doc__ = DocDescr()
2974 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2975 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2976 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2977 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2978
2979 def test_set_class(self):
2980 # Testing __class__ assignment...
2981 class C(object): pass
2982 class D(object): pass
2983 class E(object): pass
2984 class F(D, E): pass
2985 for cls in C, D, E, F:
2986 for cls2 in C, D, E, F:
2987 x = cls()
2988 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002989 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002990 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002991 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002992 def cant(x, C):
2993 try:
2994 x.__class__ = C
2995 except TypeError:
2996 pass
2997 else:
2998 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2999 try:
3000 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003001 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003002 pass
3003 else:
3004 self.fail("shouldn't allow del %r.__class__" % x)
3005 cant(C(), list)
3006 cant(list(), C)
3007 cant(C(), 1)
3008 cant(C(), object)
3009 cant(object(), list)
3010 cant(list(), object)
3011 class Int(int): __slots__ = []
3012 cant(2, Int)
3013 cant(Int(), int)
3014 cant(True, int)
3015 cant(2, bool)
3016 o = object()
3017 cant(o, type(1))
3018 cant(o, type(None))
3019 del o
3020 class G(object):
3021 __slots__ = ["a", "b"]
3022 class H(object):
3023 __slots__ = ["b", "a"]
3024 class I(object):
3025 __slots__ = ["a", "b"]
3026 class J(object):
3027 __slots__ = ["c", "b"]
3028 class K(object):
3029 __slots__ = ["a", "b", "d"]
3030 class L(H):
3031 __slots__ = ["e"]
3032 class M(I):
3033 __slots__ = ["e"]
3034 class N(J):
3035 __slots__ = ["__weakref__"]
3036 class P(J):
3037 __slots__ = ["__dict__"]
3038 class Q(J):
3039 pass
3040 class R(J):
3041 __slots__ = ["__dict__", "__weakref__"]
3042
3043 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3044 x = cls()
3045 x.a = 1
3046 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003047 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003048 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3049 self.assertEqual(x.a, 1)
3050 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003051 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003052 "assigning %r as __class__ for %r silently failed" % (cls, x))
3053 self.assertEqual(x.a, 1)
3054 for cls in G, J, K, L, M, N, P, R, list, Int:
3055 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3056 if cls is cls2:
3057 continue
3058 cant(cls(), cls2)
3059
Benjamin Peterson193152c2009-04-25 01:08:45 +00003060 # Issue5283: when __class__ changes in __del__, the wrong
3061 # type gets DECREF'd.
3062 class O(object):
3063 pass
3064 class A(object):
3065 def __del__(self):
3066 self.__class__ = O
3067 l = [A() for x in range(100)]
3068 del l
3069
Georg Brandl479a7e72008-02-05 18:13:15 +00003070 def test_set_dict(self):
3071 # Testing __dict__ assignment...
3072 class C(object): pass
3073 a = C()
3074 a.__dict__ = {'b': 1}
3075 self.assertEqual(a.b, 1)
3076 def cant(x, dict):
3077 try:
3078 x.__dict__ = dict
3079 except (AttributeError, TypeError):
3080 pass
3081 else:
3082 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3083 cant(a, None)
3084 cant(a, [])
3085 cant(a, 1)
3086 del a.__dict__ # Deleting __dict__ is allowed
3087
3088 class Base(object):
3089 pass
3090 def verify_dict_readonly(x):
3091 """
3092 x has to be an instance of a class inheriting from Base.
3093 """
3094 cant(x, {})
3095 try:
3096 del x.__dict__
3097 except (AttributeError, TypeError):
3098 pass
3099 else:
3100 self.fail("shouldn't allow del %r.__dict__" % x)
3101 dict_descr = Base.__dict__["__dict__"]
3102 try:
3103 dict_descr.__set__(x, {})
3104 except (AttributeError, TypeError):
3105 pass
3106 else:
3107 self.fail("dict_descr allowed access to %r's dict" % x)
3108
3109 # Classes don't allow __dict__ assignment and have readonly dicts
3110 class Meta1(type, Base):
3111 pass
3112 class Meta2(Base, type):
3113 pass
3114 class D(object, metaclass=Meta1):
3115 pass
3116 class E(object, metaclass=Meta2):
3117 pass
3118 for cls in C, D, E:
3119 verify_dict_readonly(cls)
3120 class_dict = cls.__dict__
3121 try:
3122 class_dict["spam"] = "eggs"
3123 except TypeError:
3124 pass
3125 else:
3126 self.fail("%r's __dict__ can be modified" % cls)
3127
3128 # Modules also disallow __dict__ assignment
3129 class Module1(types.ModuleType, Base):
3130 pass
3131 class Module2(Base, types.ModuleType):
3132 pass
3133 for ModuleType in Module1, Module2:
3134 mod = ModuleType("spam")
3135 verify_dict_readonly(mod)
3136 mod.__dict__["spam"] = "eggs"
3137
3138 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003139 # (at least not any more than regular exception's __dict__ can
3140 # be deleted; on CPython it is not the case, whereas on PyPy they
3141 # can, just like any other new-style instance's __dict__.)
3142 def can_delete_dict(e):
3143 try:
3144 del e.__dict__
3145 except (TypeError, AttributeError):
3146 return False
3147 else:
3148 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003149 class Exception1(Exception, Base):
3150 pass
3151 class Exception2(Base, Exception):
3152 pass
3153 for ExceptionType in Exception, Exception1, Exception2:
3154 e = ExceptionType()
3155 e.__dict__ = {"a": 1}
3156 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003157 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003158
Georg Brandl479a7e72008-02-05 18:13:15 +00003159 def test_binary_operator_override(self):
3160 # Testing overrides of binary operations...
3161 class I(int):
3162 def __repr__(self):
3163 return "I(%r)" % int(self)
3164 def __add__(self, other):
3165 return I(int(self) + int(other))
3166 __radd__ = __add__
3167 def __pow__(self, other, mod=None):
3168 if mod is None:
3169 return I(pow(int(self), int(other)))
3170 else:
3171 return I(pow(int(self), int(other), int(mod)))
3172 def __rpow__(self, other, mod=None):
3173 if mod is None:
3174 return I(pow(int(other), int(self), mod))
3175 else:
3176 return I(pow(int(other), int(self), int(mod)))
3177
3178 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3179 self.assertEqual(repr(I(1) + 2), "I(3)")
3180 self.assertEqual(repr(1 + I(2)), "I(3)")
3181 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3182 self.assertEqual(repr(2 ** I(3)), "I(8)")
3183 self.assertEqual(repr(I(2) ** 3), "I(8)")
3184 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3185 class S(str):
3186 def __eq__(self, other):
3187 return self.lower() == other.lower()
3188
3189 def test_subclass_propagation(self):
3190 # Testing propagation of slot functions to subclasses...
3191 class A(object):
3192 pass
3193 class B(A):
3194 pass
3195 class C(A):
3196 pass
3197 class D(B, C):
3198 pass
3199 d = D()
3200 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3201 A.__hash__ = lambda self: 42
3202 self.assertEqual(hash(d), 42)
3203 C.__hash__ = lambda self: 314
3204 self.assertEqual(hash(d), 314)
3205 B.__hash__ = lambda self: 144
3206 self.assertEqual(hash(d), 144)
3207 D.__hash__ = lambda self: 100
3208 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003209 D.__hash__ = None
3210 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003211 del D.__hash__
3212 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003213 B.__hash__ = None
3214 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003215 del B.__hash__
3216 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003217 C.__hash__ = None
3218 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003219 del C.__hash__
3220 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003221 A.__hash__ = None
3222 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003223 del A.__hash__
3224 self.assertEqual(hash(d), orig_hash)
3225 d.foo = 42
3226 d.bar = 42
3227 self.assertEqual(d.foo, 42)
3228 self.assertEqual(d.bar, 42)
3229 def __getattribute__(self, name):
3230 if name == "foo":
3231 return 24
3232 return object.__getattribute__(self, name)
3233 A.__getattribute__ = __getattribute__
3234 self.assertEqual(d.foo, 24)
3235 self.assertEqual(d.bar, 42)
3236 def __getattr__(self, name):
3237 if name in ("spam", "foo", "bar"):
3238 return "hello"
3239 raise AttributeError(name)
3240 B.__getattr__ = __getattr__
3241 self.assertEqual(d.spam, "hello")
3242 self.assertEqual(d.foo, 24)
3243 self.assertEqual(d.bar, 42)
3244 del A.__getattribute__
3245 self.assertEqual(d.foo, 42)
3246 del d.foo
3247 self.assertEqual(d.foo, "hello")
3248 self.assertEqual(d.bar, 42)
3249 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003250 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003251 d.foo
3252 except AttributeError:
3253 pass
3254 else:
3255 self.fail("d.foo should be undefined now")
3256
3257 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003258 class A(object):
3259 pass
3260 class B(A):
3261 pass
3262 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003263 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003264 A.__setitem__ = lambda *a: None # crash
3265
3266 def test_buffer_inheritance(self):
3267 # Testing that buffer interface is inherited ...
3268
3269 import binascii
3270 # SF bug [#470040] ParseTuple t# vs subclasses.
3271
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003272 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003273 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003274 base = b'abc'
3275 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003276 # b2a_hex uses the buffer interface to get its argument's value, via
3277 # PyArg_ParseTuple 't#' code.
3278 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3279
Georg Brandl479a7e72008-02-05 18:13:15 +00003280 class MyInt(int):
3281 pass
3282 m = MyInt(42)
3283 try:
3284 binascii.b2a_hex(m)
3285 self.fail('subclass of int should not have a buffer interface')
3286 except TypeError:
3287 pass
3288
3289 def test_str_of_str_subclass(self):
3290 # Testing __str__ defined in subclass of str ...
3291 import binascii
3292 import io
3293
3294 class octetstring(str):
3295 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003296 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003297 def __repr__(self):
3298 return self + " repr"
3299
3300 o = octetstring('A')
3301 self.assertEqual(type(o), octetstring)
3302 self.assertEqual(type(str(o)), str)
3303 self.assertEqual(type(repr(o)), str)
3304 self.assertEqual(ord(o), 0x41)
3305 self.assertEqual(str(o), '41')
3306 self.assertEqual(repr(o), 'A repr')
3307 self.assertEqual(o.__str__(), '41')
3308 self.assertEqual(o.__repr__(), 'A repr')
3309
3310 capture = io.StringIO()
3311 # Calling str() or not exercises different internal paths.
3312 print(o, file=capture)
3313 print(str(o), file=capture)
3314 self.assertEqual(capture.getvalue(), '41\n41\n')
3315 capture.close()
3316
3317 def test_keyword_arguments(self):
3318 # Testing keyword arguments to __init__, __call__...
3319 def f(a): return a
3320 self.assertEqual(f.__call__(a=42), 42)
3321 a = []
3322 list.__init__(a, sequence=[0, 1, 2])
3323 self.assertEqual(a, [0, 1, 2])
3324
3325 def test_recursive_call(self):
3326 # Testing recursive __call__() by setting to instance of class...
3327 class A(object):
3328 pass
3329
3330 A.__call__ = A()
3331 try:
3332 A()()
3333 except RuntimeError:
3334 pass
3335 else:
3336 self.fail("Recursion limit should have been reached for __call__()")
3337
3338 def test_delete_hook(self):
3339 # Testing __del__ hook...
3340 log = []
3341 class C(object):
3342 def __del__(self):
3343 log.append(1)
3344 c = C()
3345 self.assertEqual(log, [])
3346 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003347 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003348 self.assertEqual(log, [1])
3349
3350 class D(object): pass
3351 d = D()
3352 try: del d[0]
3353 except TypeError: pass
3354 else: self.fail("invalid del() didn't raise TypeError")
3355
3356 def test_hash_inheritance(self):
3357 # Testing hash of mutable subclasses...
3358
3359 class mydict(dict):
3360 pass
3361 d = mydict()
3362 try:
3363 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003364 except TypeError:
3365 pass
3366 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003367 self.fail("hash() of dict subclass should fail")
3368
3369 class mylist(list):
3370 pass
3371 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003372 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003373 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003374 except TypeError:
3375 pass
3376 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003377 self.fail("hash() of list subclass should fail")
3378
3379 def test_str_operations(self):
3380 try: 'a' + 5
3381 except TypeError: pass
3382 else: self.fail("'' + 5 doesn't raise TypeError")
3383
3384 try: ''.split('')
3385 except ValueError: pass
3386 else: self.fail("''.split('') doesn't raise ValueError")
3387
3388 try: ''.join([0])
3389 except TypeError: pass
3390 else: self.fail("''.join([0]) doesn't raise TypeError")
3391
3392 try: ''.rindex('5')
3393 except ValueError: pass
3394 else: self.fail("''.rindex('5') doesn't raise ValueError")
3395
3396 try: '%(n)s' % None
3397 except TypeError: pass
3398 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3399
3400 try: '%(n' % {}
3401 except ValueError: pass
3402 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3403
3404 try: '%*s' % ('abc')
3405 except TypeError: pass
3406 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3407
3408 try: '%*.*s' % ('abc', 5)
3409 except TypeError: pass
3410 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3411
3412 try: '%s' % (1, 2)
3413 except TypeError: pass
3414 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3415
3416 try: '%' % None
3417 except ValueError: pass
3418 else: self.fail("'%' % None doesn't raise ValueError")
3419
3420 self.assertEqual('534253'.isdigit(), 1)
3421 self.assertEqual('534253x'.isdigit(), 0)
3422 self.assertEqual('%c' % 5, '\x05')
3423 self.assertEqual('%c' % '5', '5')
3424
3425 def test_deepcopy_recursive(self):
3426 # Testing deepcopy of recursive objects...
3427 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003428 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003429 a = Node()
3430 b = Node()
3431 a.b = b
3432 b.a = a
3433 z = deepcopy(a) # This blew up before
3434
3435 def test_unintialized_modules(self):
3436 # Testing uninitialized module objects...
3437 from types import ModuleType as M
3438 m = M.__new__(M)
3439 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003440 self.assertNotHasAttr(m, "__name__")
3441 self.assertNotHasAttr(m, "__file__")
3442 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003443 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003444 m.foo = 1
3445 self.assertEqual(m.__dict__, {"foo": 1})
3446
3447 def test_funny_new(self):
3448 # Testing __new__ returning something unexpected...
3449 class C(object):
3450 def __new__(cls, arg):
3451 if isinstance(arg, str): return [1, 2, 3]
3452 elif isinstance(arg, int): return object.__new__(D)
3453 else: return object.__new__(cls)
3454 class D(C):
3455 def __init__(self, arg):
3456 self.foo = arg
3457 self.assertEqual(C("1"), [1, 2, 3])
3458 self.assertEqual(D("1"), [1, 2, 3])
3459 d = D(None)
3460 self.assertEqual(d.foo, None)
3461 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003462 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003463 self.assertEqual(d.foo, 1)
3464 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003465 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003466 self.assertEqual(d.foo, 1)
3467
3468 def test_imul_bug(self):
3469 # Testing for __imul__ problems...
3470 # SF bug 544647
3471 class C(object):
3472 def __imul__(self, other):
3473 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003474 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003475 y = x
3476 y *= 1.0
3477 self.assertEqual(y, (x, 1.0))
3478 y = x
3479 y *= 2
3480 self.assertEqual(y, (x, 2))
3481 y = x
3482 y *= 3
3483 self.assertEqual(y, (x, 3))
3484 y = x
3485 y *= 1<<100
3486 self.assertEqual(y, (x, 1<<100))
3487 y = x
3488 y *= None
3489 self.assertEqual(y, (x, None))
3490 y = x
3491 y *= "foo"
3492 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003493
Georg Brandl479a7e72008-02-05 18:13:15 +00003494 def test_copy_setstate(self):
3495 # Testing that copy.*copy() correctly uses __setstate__...
3496 import copy
3497 class C(object):
3498 def __init__(self, foo=None):
3499 self.foo = foo
3500 self.__foo = foo
3501 def setfoo(self, foo=None):
3502 self.foo = foo
3503 def getfoo(self):
3504 return self.__foo
3505 def __getstate__(self):
3506 return [self.foo]
3507 def __setstate__(self_, lst):
3508 self.assertEqual(len(lst), 1)
3509 self_.__foo = self_.foo = lst[0]
3510 a = C(42)
3511 a.setfoo(24)
3512 self.assertEqual(a.foo, 24)
3513 self.assertEqual(a.getfoo(), 42)
3514 b = copy.copy(a)
3515 self.assertEqual(b.foo, 24)
3516 self.assertEqual(b.getfoo(), 24)
3517 b = copy.deepcopy(a)
3518 self.assertEqual(b.foo, 24)
3519 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003520
Georg Brandl479a7e72008-02-05 18:13:15 +00003521 def test_slices(self):
3522 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003523
Georg Brandl479a7e72008-02-05 18:13:15 +00003524 # Strings
3525 self.assertEqual("hello"[:4], "hell")
3526 self.assertEqual("hello"[slice(4)], "hell")
3527 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3528 class S(str):
3529 def __getitem__(self, x):
3530 return str.__getitem__(self, x)
3531 self.assertEqual(S("hello")[:4], "hell")
3532 self.assertEqual(S("hello")[slice(4)], "hell")
3533 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3534 # Tuples
3535 self.assertEqual((1,2,3)[:2], (1,2))
3536 self.assertEqual((1,2,3)[slice(2)], (1,2))
3537 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3538 class T(tuple):
3539 def __getitem__(self, x):
3540 return tuple.__getitem__(self, x)
3541 self.assertEqual(T((1,2,3))[:2], (1,2))
3542 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3543 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3544 # Lists
3545 self.assertEqual([1,2,3][:2], [1,2])
3546 self.assertEqual([1,2,3][slice(2)], [1,2])
3547 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3548 class L(list):
3549 def __getitem__(self, x):
3550 return list.__getitem__(self, x)
3551 self.assertEqual(L([1,2,3])[:2], [1,2])
3552 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3553 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3554 # Now do lists and __setitem__
3555 a = L([1,2,3])
3556 a[slice(1, 3)] = [3,2]
3557 self.assertEqual(a, [1,3,2])
3558 a[slice(0, 2, 1)] = [3,1]
3559 self.assertEqual(a, [3,1,2])
3560 a.__setitem__(slice(1, 3), [2,1])
3561 self.assertEqual(a, [3,2,1])
3562 a.__setitem__(slice(0, 2, 1), [2,3])
3563 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003564
Georg Brandl479a7e72008-02-05 18:13:15 +00003565 def test_subtype_resurrection(self):
3566 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003567
Georg Brandl479a7e72008-02-05 18:13:15 +00003568 class C(object):
3569 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003570
Georg Brandl479a7e72008-02-05 18:13:15 +00003571 def __del__(self):
3572 # resurrect the instance
3573 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003574
Georg Brandl479a7e72008-02-05 18:13:15 +00003575 c = C()
3576 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003577
Benjamin Petersone549ead2009-03-28 21:42:05 +00003578 # The most interesting thing here is whether this blows up, due to
3579 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3580 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003581 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003582
Benjamin Petersone549ead2009-03-28 21:42:05 +00003583 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003584 self.assertEqual(len(C.container), 1)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003585
Georg Brandl479a7e72008-02-05 18:13:15 +00003586 # Make c mortal again, so that the test framework with -l doesn't report
3587 # it as a leak.
3588 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003589
Georg Brandl479a7e72008-02-05 18:13:15 +00003590 def test_slots_trash(self):
3591 # Testing slot trash...
3592 # Deallocating deeply nested slotted trash caused stack overflows
3593 class trash(object):
3594 __slots__ = ['x']
3595 def __init__(self, x):
3596 self.x = x
3597 o = None
3598 for i in range(50000):
3599 o = trash(o)
3600 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003601
Georg Brandl479a7e72008-02-05 18:13:15 +00003602 def test_slots_multiple_inheritance(self):
3603 # SF bug 575229, multiple inheritance w/ slots dumps core
3604 class A(object):
3605 __slots__=()
3606 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003607 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003608 class C(A,B) :
3609 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003610 if support.check_impl_detail():
3611 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003612 self.assertHasAttr(C, '__dict__')
3613 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003614 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003615
Georg Brandl479a7e72008-02-05 18:13:15 +00003616 def test_rmul(self):
3617 # Testing correct invocation of __rmul__...
3618 # SF patch 592646
3619 class C(object):
3620 def __mul__(self, other):
3621 return "mul"
3622 def __rmul__(self, other):
3623 return "rmul"
3624 a = C()
3625 self.assertEqual(a*2, "mul")
3626 self.assertEqual(a*2.2, "mul")
3627 self.assertEqual(2*a, "rmul")
3628 self.assertEqual(2.2*a, "rmul")
3629
3630 def test_ipow(self):
3631 # Testing correct invocation of __ipow__...
3632 # [SF bug 620179]
3633 class C(object):
3634 def __ipow__(self, other):
3635 pass
3636 a = C()
3637 a **= 2
3638
3639 def test_mutable_bases(self):
3640 # Testing mutable bases...
3641
3642 # stuff that should work:
3643 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003644 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003645 class C2(object):
3646 def __getattribute__(self, attr):
3647 if attr == 'a':
3648 return 2
3649 else:
3650 return super(C2, self).__getattribute__(attr)
3651 def meth(self):
3652 return 1
3653 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003654 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003655 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003656 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003657 d = D()
3658 e = E()
3659 D.__bases__ = (C,)
3660 D.__bases__ = (C2,)
3661 self.assertEqual(d.meth(), 1)
3662 self.assertEqual(e.meth(), 1)
3663 self.assertEqual(d.a, 2)
3664 self.assertEqual(e.a, 2)
3665 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003666
Georg Brandl479a7e72008-02-05 18:13:15 +00003667 try:
3668 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003669 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003670 pass
3671 else:
3672 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003673
Georg Brandl479a7e72008-02-05 18:13:15 +00003674 try:
3675 D.__bases__ = ()
3676 except TypeError as msg:
3677 if str(msg) == "a new-style class can't have only classic bases":
3678 self.fail("wrong error message for .__bases__ = ()")
3679 else:
3680 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003681
Georg Brandl479a7e72008-02-05 18:13:15 +00003682 try:
3683 D.__bases__ = (D,)
3684 except TypeError:
3685 pass
3686 else:
3687 # actually, we'll have crashed by here...
3688 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003689
Georg Brandl479a7e72008-02-05 18:13:15 +00003690 try:
3691 D.__bases__ = (C, C)
3692 except TypeError:
3693 pass
3694 else:
3695 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003696
Georg Brandl479a7e72008-02-05 18:13:15 +00003697 try:
3698 D.__bases__ = (E,)
3699 except TypeError:
3700 pass
3701 else:
3702 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003703
Benjamin Petersonae937c02009-04-18 20:54:08 +00003704 def test_builtin_bases(self):
3705 # Make sure all the builtin types can have their base queried without
3706 # segfaulting. See issue #5787.
3707 builtin_types = [tp for tp in builtins.__dict__.values()
3708 if isinstance(tp, type)]
3709 for tp in builtin_types:
3710 object.__getattribute__(tp, "__bases__")
3711 if tp is not object:
3712 self.assertEqual(len(tp.__bases__), 1, tp)
3713
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003714 class L(list):
3715 pass
3716
3717 class C(object):
3718 pass
3719
3720 class D(C):
3721 pass
3722
3723 try:
3724 L.__bases__ = (dict,)
3725 except TypeError:
3726 pass
3727 else:
3728 self.fail("shouldn't turn list subclass into dict subclass")
3729
3730 try:
3731 list.__bases__ = (dict,)
3732 except TypeError:
3733 pass
3734 else:
3735 self.fail("shouldn't be able to assign to list.__bases__")
3736
3737 try:
3738 D.__bases__ = (C, list)
3739 except TypeError:
3740 pass
3741 else:
3742 assert 0, "best_base calculation found wanting"
3743
Benjamin Petersonae937c02009-04-18 20:54:08 +00003744
Georg Brandl479a7e72008-02-05 18:13:15 +00003745 def test_mutable_bases_with_failing_mro(self):
3746 # Testing mutable bases with failing mro...
3747 class WorkOnce(type):
3748 def __new__(self, name, bases, ns):
3749 self.flag = 0
3750 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3751 def mro(self):
3752 if self.flag > 0:
3753 raise RuntimeError("bozo")
3754 else:
3755 self.flag += 1
3756 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003757
Georg Brandl479a7e72008-02-05 18:13:15 +00003758 class WorkAlways(type):
3759 def mro(self):
3760 # this is here to make sure that .mro()s aren't called
3761 # with an exception set (which was possible at one point).
3762 # An error message will be printed in a debug build.
3763 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003764 return type.mro(self)
3765
Georg Brandl479a7e72008-02-05 18:13:15 +00003766 class C(object):
3767 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003768
Georg Brandl479a7e72008-02-05 18:13:15 +00003769 class C2(object):
3770 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003771
Georg Brandl479a7e72008-02-05 18:13:15 +00003772 class D(C):
3773 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003774
Georg Brandl479a7e72008-02-05 18:13:15 +00003775 class E(D):
3776 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003777
Georg Brandl479a7e72008-02-05 18:13:15 +00003778 class F(D, metaclass=WorkOnce):
3779 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003780
Georg Brandl479a7e72008-02-05 18:13:15 +00003781 class G(D, metaclass=WorkAlways):
3782 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003783
Georg Brandl479a7e72008-02-05 18:13:15 +00003784 # Immediate subclasses have their mro's adjusted in alphabetical
3785 # order, so E's will get adjusted before adjusting F's fails. We
3786 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003787
Georg Brandl479a7e72008-02-05 18:13:15 +00003788 E_mro_before = E.__mro__
3789 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003790
Armin Rigofd163f92005-12-29 15:59:19 +00003791 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003792 D.__bases__ = (C2,)
3793 except RuntimeError:
3794 self.assertEqual(E.__mro__, E_mro_before)
3795 self.assertEqual(D.__mro__, D_mro_before)
3796 else:
3797 self.fail("exception not propagated")
3798
3799 def test_mutable_bases_catch_mro_conflict(self):
3800 # Testing mutable bases catch mro conflict...
3801 class A(object):
3802 pass
3803
3804 class B(object):
3805 pass
3806
3807 class C(A, B):
3808 pass
3809
3810 class D(A, B):
3811 pass
3812
3813 class E(C, D):
3814 pass
3815
3816 try:
3817 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003818 except TypeError:
3819 pass
3820 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003821 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003822
Georg Brandl479a7e72008-02-05 18:13:15 +00003823 def test_mutable_names(self):
3824 # Testing mutable names...
3825 class C(object):
3826 pass
3827
3828 # C.__module__ could be 'test_descr' or '__main__'
3829 mod = C.__module__
3830
3831 C.__name__ = 'D'
3832 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3833
3834 C.__name__ = 'D.E'
3835 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3836
Mark Dickinson64aafeb2013-04-13 15:26:58 +01003837 def test_evil_type_name(self):
3838 # A badly placed Py_DECREF in type_set_name led to arbitrary code
3839 # execution while the type structure was not in a sane state, and a
3840 # possible segmentation fault as a result. See bug #16447.
3841 class Nasty(str):
3842 def __del__(self):
3843 C.__name__ = "other"
3844
3845 class C:
3846 pass
3847
3848 C.__name__ = Nasty("abc")
3849 C.__name__ = "normal"
3850
Georg Brandl479a7e72008-02-05 18:13:15 +00003851 def test_subclass_right_op(self):
3852 # Testing correct dispatch of subclass overloading __r<op>__...
3853
3854 # This code tests various cases where right-dispatch of a subclass
3855 # should be preferred over left-dispatch of a base class.
3856
3857 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3858
3859 class B(int):
3860 def __floordiv__(self, other):
3861 return "B.__floordiv__"
3862 def __rfloordiv__(self, other):
3863 return "B.__rfloordiv__"
3864
3865 self.assertEqual(B(1) // 1, "B.__floordiv__")
3866 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3867
3868 # Case 2: subclass of object; this is just the baseline for case 3
3869
3870 class C(object):
3871 def __floordiv__(self, other):
3872 return "C.__floordiv__"
3873 def __rfloordiv__(self, other):
3874 return "C.__rfloordiv__"
3875
3876 self.assertEqual(C() // 1, "C.__floordiv__")
3877 self.assertEqual(1 // C(), "C.__rfloordiv__")
3878
3879 # Case 3: subclass of new-style class; here it gets interesting
3880
3881 class D(C):
3882 def __floordiv__(self, other):
3883 return "D.__floordiv__"
3884 def __rfloordiv__(self, other):
3885 return "D.__rfloordiv__"
3886
3887 self.assertEqual(D() // C(), "D.__floordiv__")
3888 self.assertEqual(C() // D(), "D.__rfloordiv__")
3889
3890 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3891
3892 class E(C):
3893 pass
3894
3895 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3896
3897 self.assertEqual(E() // 1, "C.__floordiv__")
3898 self.assertEqual(1 // E(), "C.__rfloordiv__")
3899 self.assertEqual(E() // C(), "C.__floordiv__")
3900 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3901
Benjamin Petersone549ead2009-03-28 21:42:05 +00003902 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003903 def test_meth_class_get(self):
3904 # Testing __get__ method of METH_CLASS C methods...
3905 # Full coverage of descrobject.c::classmethod_get()
3906
3907 # Baseline
3908 arg = [1, 2, 3]
3909 res = {1: None, 2: None, 3: None}
3910 self.assertEqual(dict.fromkeys(arg), res)
3911 self.assertEqual({}.fromkeys(arg), res)
3912
3913 # Now get the descriptor
3914 descr = dict.__dict__["fromkeys"]
3915
3916 # More baseline using the descriptor directly
3917 self.assertEqual(descr.__get__(None, dict)(arg), res)
3918 self.assertEqual(descr.__get__({})(arg), res)
3919
3920 # Now check various error cases
3921 try:
3922 descr.__get__(None, None)
3923 except TypeError:
3924 pass
3925 else:
3926 self.fail("shouldn't have allowed descr.__get__(None, None)")
3927 try:
3928 descr.__get__(42)
3929 except TypeError:
3930 pass
3931 else:
3932 self.fail("shouldn't have allowed descr.__get__(42)")
3933 try:
3934 descr.__get__(None, 42)
3935 except TypeError:
3936 pass
3937 else:
3938 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3939 try:
3940 descr.__get__(None, int)
3941 except TypeError:
3942 pass
3943 else:
3944 self.fail("shouldn't have allowed descr.__get__(None, int)")
3945
3946 def test_isinst_isclass(self):
3947 # Testing proxy isinstance() and isclass()...
3948 class Proxy(object):
3949 def __init__(self, obj):
3950 self.__obj = obj
3951 def __getattribute__(self, name):
3952 if name.startswith("_Proxy__"):
3953 return object.__getattribute__(self, name)
3954 else:
3955 return getattr(self.__obj, name)
3956 # Test with a classic class
3957 class C:
3958 pass
3959 a = C()
3960 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003961 self.assertIsInstance(a, C) # Baseline
3962 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003963 # Test with a classic subclass
3964 class D(C):
3965 pass
3966 a = D()
3967 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003968 self.assertIsInstance(a, C) # Baseline
3969 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003970 # Test with a new-style class
3971 class C(object):
3972 pass
3973 a = C()
3974 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003975 self.assertIsInstance(a, C) # Baseline
3976 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003977 # Test with a new-style subclass
3978 class D(C):
3979 pass
3980 a = D()
3981 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003982 self.assertIsInstance(a, C) # Baseline
3983 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003984
3985 def test_proxy_super(self):
3986 # Testing super() for a proxy object...
3987 class Proxy(object):
3988 def __init__(self, obj):
3989 self.__obj = obj
3990 def __getattribute__(self, name):
3991 if name.startswith("_Proxy__"):
3992 return object.__getattribute__(self, name)
3993 else:
3994 return getattr(self.__obj, name)
3995
3996 class B(object):
3997 def f(self):
3998 return "B.f"
3999
4000 class C(B):
4001 def f(self):
4002 return super(C, self).f() + "->C.f"
4003
4004 obj = C()
4005 p = Proxy(obj)
4006 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4007
4008 def test_carloverre(self):
4009 # Testing prohibition of Carlo Verre's hack...
4010 try:
4011 object.__setattr__(str, "foo", 42)
4012 except TypeError:
4013 pass
4014 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004015 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004016 try:
4017 object.__delattr__(str, "lower")
4018 except TypeError:
4019 pass
4020 else:
4021 self.fail("Carlo Verre __delattr__ succeeded!")
4022
4023 def test_weakref_segfault(self):
4024 # Testing weakref segfault...
4025 # SF 742911
4026 import weakref
4027
4028 class Provoker:
4029 def __init__(self, referrent):
4030 self.ref = weakref.ref(referrent)
4031
4032 def __del__(self):
4033 x = self.ref()
4034
4035 class Oops(object):
4036 pass
4037
4038 o = Oops()
4039 o.whatever = Provoker(o)
4040 del o
4041
4042 def test_wrapper_segfault(self):
4043 # SF 927248: deeply nested wrappers could cause stack overflow
4044 f = lambda:None
4045 for i in range(1000000):
4046 f = f.__call__
4047 f = None
4048
4049 def test_file_fault(self):
4050 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004051 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004052 class StdoutGuard:
4053 def __getattr__(self, attr):
4054 sys.stdout = sys.__stdout__
4055 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4056 sys.stdout = StdoutGuard()
4057 try:
4058 print("Oops!")
4059 except RuntimeError:
4060 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004061 finally:
4062 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004063
4064 def test_vicious_descriptor_nonsense(self):
4065 # Testing vicious_descriptor_nonsense...
4066
4067 # A potential segfault spotted by Thomas Wouters in mail to
4068 # python-dev 2003-04-17, turned into an example & fixed by Michael
4069 # Hudson just less than four months later...
4070
4071 class Evil(object):
4072 def __hash__(self):
4073 return hash('attr')
4074 def __eq__(self, other):
4075 del C.attr
4076 return 0
4077
4078 class Descr(object):
4079 def __get__(self, ob, type=None):
4080 return 1
4081
4082 class C(object):
4083 attr = Descr()
4084
4085 c = C()
4086 c.__dict__[Evil()] = 0
4087
4088 self.assertEqual(c.attr, 1)
4089 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004090 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004091 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004092
4093 def test_init(self):
4094 # SF 1155938
4095 class Foo(object):
4096 def __init__(self):
4097 return 10
4098 try:
4099 Foo()
4100 except TypeError:
4101 pass
4102 else:
4103 self.fail("did not test __init__() for None return")
4104
4105 def test_method_wrapper(self):
4106 # Testing method-wrapper objects...
4107 # <type 'method-wrapper'> did not support any reflection before 2.5
4108
Mark Dickinson211c6252009-02-01 10:28:51 +00004109 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004110
4111 l = []
4112 self.assertEqual(l.__add__, l.__add__)
4113 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004114 self.assertNotEqual(l.__add__, [5].__add__)
4115 self.assertNotEqual(l.__add__, l.__mul__)
4116 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004117 if hasattr(l.__add__, '__self__'):
4118 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004119 self.assertIs(l.__add__.__self__, l)
4120 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004121 else:
4122 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004123 self.assertIs(l.__add__.im_self, l)
4124 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004125 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4126 try:
4127 hash(l.__add__)
4128 except TypeError:
4129 pass
4130 else:
4131 self.fail("no TypeError from hash([].__add__)")
4132
4133 t = ()
4134 t += (7,)
4135 self.assertEqual(t.__add__, (7,).__add__)
4136 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4137
4138 def test_not_implemented(self):
4139 # Testing NotImplemented...
4140 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004141 import operator
4142
4143 def specialmethod(self, other):
4144 return NotImplemented
4145
4146 def check(expr, x, y):
4147 try:
4148 exec(expr, {'x': x, 'y': y, 'operator': operator})
4149 except TypeError:
4150 pass
4151 else:
4152 self.fail("no TypeError from %r" % (expr,))
4153
4154 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4155 # TypeErrors
4156 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4157 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004158 for name, expr, iexpr in [
4159 ('__add__', 'x + y', 'x += y'),
4160 ('__sub__', 'x - y', 'x -= y'),
4161 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004162 ('__truediv__', 'operator.truediv(x, y)', None),
4163 ('__floordiv__', 'operator.floordiv(x, y)', None),
4164 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004165 ('__mod__', 'x % y', 'x %= y'),
4166 ('__divmod__', 'divmod(x, y)', None),
4167 ('__pow__', 'x ** y', 'x **= y'),
4168 ('__lshift__', 'x << y', 'x <<= y'),
4169 ('__rshift__', 'x >> y', 'x >>= y'),
4170 ('__and__', 'x & y', 'x &= y'),
4171 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004172 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004173 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004174 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004175 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004176 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004177 check(expr, a, N1)
4178 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004179 if iexpr:
4180 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004181 check(iexpr, a, N1)
4182 check(iexpr, a, N2)
4183 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004184 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004185 c = C()
4186 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004187 check(iexpr, c, N1)
4188 check(iexpr, c, N2)
4189
Georg Brandl479a7e72008-02-05 18:13:15 +00004190 def test_assign_slice(self):
4191 # ceval.c's assign_slice used to check for
4192 # tp->tp_as_sequence->sq_slice instead of
4193 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004194
Georg Brandl479a7e72008-02-05 18:13:15 +00004195 class C(object):
4196 def __setitem__(self, idx, value):
4197 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004198
Georg Brandl479a7e72008-02-05 18:13:15 +00004199 c = C()
4200 c[1:2] = 3
4201 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004202
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004203 def test_set_and_no_get(self):
4204 # See
4205 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4206 class Descr(object):
4207
4208 def __init__(self, name):
4209 self.name = name
4210
4211 def __set__(self, obj, value):
4212 obj.__dict__[self.name] = value
4213 descr = Descr("a")
4214
4215 class X(object):
4216 a = descr
4217
4218 x = X()
4219 self.assertIs(x.a, descr)
4220 x.a = 42
4221 self.assertEqual(x.a, 42)
4222
Benjamin Peterson21896a32010-03-21 22:03:03 +00004223 # Also check type_getattro for correctness.
4224 class Meta(type):
4225 pass
4226 class X(object):
4227 __metaclass__ = Meta
4228 X.a = 42
4229 Meta.a = Descr("a")
4230 self.assertEqual(X.a, 42)
4231
Benjamin Peterson9262b842008-11-17 22:45:50 +00004232 def test_getattr_hooks(self):
4233 # issue 4230
4234
4235 class Descriptor(object):
4236 counter = 0
4237 def __get__(self, obj, objtype=None):
4238 def getter(name):
4239 self.counter += 1
4240 raise AttributeError(name)
4241 return getter
4242
4243 descr = Descriptor()
4244 class A(object):
4245 __getattribute__ = descr
4246 class B(object):
4247 __getattr__ = descr
4248 class C(object):
4249 __getattribute__ = descr
4250 __getattr__ = descr
4251
4252 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004253 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004254 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004255 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004256 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004257 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004258
Benjamin Peterson9262b842008-11-17 22:45:50 +00004259 class EvilGetattribute(object):
4260 # This used to segfault
4261 def __getattr__(self, name):
4262 raise AttributeError(name)
4263 def __getattribute__(self, name):
4264 del EvilGetattribute.__getattr__
4265 for i in range(5):
4266 gc.collect()
4267 raise AttributeError(name)
4268
4269 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4270
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004271 def test_type___getattribute__(self):
4272 self.assertRaises(TypeError, type.__getattribute__, list, type)
4273
Benjamin Peterson477ba912011-01-12 15:34:01 +00004274 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004275 # type pretends not to have __abstractmethods__.
4276 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4277 class meta(type):
4278 pass
4279 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004280 class X(object):
4281 pass
4282 with self.assertRaises(AttributeError):
4283 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004284
Victor Stinner3249dec2011-05-01 23:19:15 +02004285 def test_proxy_call(self):
4286 class FakeStr:
4287 __class__ = str
4288
4289 fake_str = FakeStr()
4290 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004291 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004292
4293 # call a method descriptor
4294 with self.assertRaises(TypeError):
4295 str.split(fake_str)
4296
4297 # call a slot wrapper descriptor
4298 with self.assertRaises(TypeError):
4299 str.__add__(fake_str, "abc")
4300
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004301 def test_repr_as_str(self):
4302 # Issue #11603: crash or infinite loop when rebinding __str__ as
4303 # __repr__.
4304 class Foo:
4305 pass
4306 Foo.__repr__ = Foo.__str__
4307 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004308 self.assertRaises(RuntimeError, str, foo)
4309 self.assertRaises(RuntimeError, repr, foo)
4310
4311 def test_mixing_slot_wrappers(self):
4312 class X(dict):
4313 __setattr__ = dict.__setitem__
4314 x = X()
4315 x.y = 42
4316 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004317
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004318 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004319 with self.assertRaises(ValueError) as cm:
4320 class X:
4321 __slots__ = ["foo"]
4322 foo = None
4323 m = str(cm.exception)
4324 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4325
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004326 def test_set_doc(self):
4327 class X:
4328 "elephant"
4329 X.__doc__ = "banana"
4330 self.assertEqual(X.__doc__, "banana")
4331 with self.assertRaises(TypeError) as cm:
4332 type(list).__dict__["__doc__"].__set__(list, "blah")
4333 self.assertIn("can't set list.__doc__", str(cm.exception))
4334 with self.assertRaises(TypeError) as cm:
4335 type(X).__dict__["__doc__"].__delete__(X)
4336 self.assertIn("can't delete X.__doc__", str(cm.exception))
4337 self.assertEqual(X.__doc__, "banana")
4338
Antoine Pitrou9d574812011-12-12 13:47:25 +01004339 def test_qualname(self):
4340 descriptors = [str.lower, complex.real, float.real, int.__add__]
4341 types = ['method', 'member', 'getset', 'wrapper']
4342
4343 # make sure we have an example of each type of descriptor
4344 for d, n in zip(descriptors, types):
4345 self.assertEqual(type(d).__name__, n + '_descriptor')
4346
4347 for d in descriptors:
4348 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4349 self.assertEqual(d.__qualname__, qualname)
4350
4351 self.assertEqual(str.lower.__qualname__, 'str.lower')
4352 self.assertEqual(complex.real.__qualname__, 'complex.real')
4353 self.assertEqual(float.real.__qualname__, 'float.real')
4354 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4355
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004356 class X:
4357 pass
4358 with self.assertRaises(TypeError):
4359 del X.__qualname__
4360
4361 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4362 str, 'Oink')
4363
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004364 global Y
4365 class Y:
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004366 class Inside:
4367 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004368 self.assertEqual(Y.__qualname__, 'Y')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004369 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04004370
Victor Stinner6f738742012-02-25 01:22:36 +01004371 def test_qualname_dict(self):
4372 ns = {'__qualname__': 'some.name'}
4373 tp = type('Foo', (), ns)
4374 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004375 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004376 self.assertEqual(ns, {'__qualname__': 'some.name'})
4377
4378 ns = {'__qualname__': 1}
4379 self.assertRaises(TypeError, type, 'Foo', (), ns)
4380
Benjamin Peterson52c42432012-03-07 18:41:11 -06004381 def test_cycle_through_dict(self):
4382 # See bug #1469629
4383 class X(dict):
4384 def __init__(self):
4385 dict.__init__(self)
4386 self.__dict__ = self
4387 x = X()
4388 x.attr = 42
4389 wr = weakref.ref(x)
4390 del x
4391 support.gc_collect()
4392 self.assertIsNone(wr())
4393 for o in gc.get_objects():
4394 self.assertIsNot(type(o), X)
4395
Benjamin Peterson96384b92012-03-17 00:05:44 -05004396 def test_object_new_and_init_with_parameters(self):
4397 # See issue #1683368
4398 class OverrideNeither:
4399 pass
4400 self.assertRaises(TypeError, OverrideNeither, 1)
4401 self.assertRaises(TypeError, OverrideNeither, kw=1)
4402 class OverrideNew:
4403 def __new__(cls, foo, kw=0, *args, **kwds):
4404 return object.__new__(cls, *args, **kwds)
4405 class OverrideInit:
4406 def __init__(self, foo, kw=0, *args, **kwargs):
4407 return object.__init__(self, *args, **kwargs)
4408 class OverrideBoth(OverrideNew, OverrideInit):
4409 pass
4410 for case in OverrideNew, OverrideInit, OverrideBoth:
4411 case(1)
4412 case(1, kw=2)
4413 self.assertRaises(TypeError, case, 1, 2, 3)
4414 self.assertRaises(TypeError, case, 1, 2, foo=3)
4415
Antoine Pitrou9d574812011-12-12 13:47:25 +01004416
Georg Brandl479a7e72008-02-05 18:13:15 +00004417class DictProxyTests(unittest.TestCase):
4418 def setUp(self):
4419 class C(object):
4420 def meth(self):
4421 pass
4422 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004423
Brett Cannon7a540732011-02-22 03:04:06 +00004424 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4425 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004426 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004427 # Testing dict-proxy keys...
4428 it = self.C.__dict__.keys()
4429 self.assertNotIsInstance(it, list)
4430 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004431 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004432 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004433 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004434
Brett Cannon7a540732011-02-22 03:04:06 +00004435 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4436 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004437 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004438 # Testing dict-proxy values...
4439 it = self.C.__dict__.values()
4440 self.assertNotIsInstance(it, list)
4441 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004442 self.assertEqual(len(values), 5)
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_items(self):
4447 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004448 it = self.C.__dict__.items()
4449 self.assertNotIsInstance(it, list)
4450 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004451 keys.sort()
4452 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004453 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004454
Georg Brandl479a7e72008-02-05 18:13:15 +00004455 def test_dict_type_with_metaclass(self):
4456 # Testing type of __dict__ when metaclass set...
4457 class B(object):
4458 pass
4459 class M(type):
4460 pass
4461 class C(metaclass=M):
4462 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4463 pass
4464 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004465
Ezio Melottiac53ab62010-12-18 14:59:43 +00004466 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004467 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004468 # We can't blindly compare with the repr of another dict as ordering
4469 # of keys and values is arbitrary and may differ.
4470 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004471 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004472 self.assertTrue(r.endswith(')'), r)
4473 for k, v in self.C.__dict__.items():
4474 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004475
Christian Heimesbbffeb62008-01-24 09:42:52 +00004476
Georg Brandl479a7e72008-02-05 18:13:15 +00004477class PTypesLongInitTest(unittest.TestCase):
4478 # This is in its own TestCase so that it can be run before any other tests.
4479 def test_pytype_long_ready(self):
4480 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004481
Georg Brandl479a7e72008-02-05 18:13:15 +00004482 # This dumps core when SF bug 551412 isn't fixed --
4483 # but only when test_descr.py is run separately.
4484 # (That can't be helped -- as soon as PyType_Ready()
4485 # is called for PyLong_Type, the bug is gone.)
4486 class UserLong(object):
4487 def __pow__(self, *args):
4488 pass
4489 try:
4490 pow(0, UserLong(), 0)
4491 except:
4492 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004493
Georg Brandl479a7e72008-02-05 18:13:15 +00004494 # Another segfault only when run early
4495 # (before PyType_Ready(tuple) is called)
4496 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004497
4498
Victor Stinnerd74782b2012-03-09 00:39:08 +01004499class MiscTests(unittest.TestCase):
4500 def test_type_lookup_mro_reference(self):
4501 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4502 # the type MRO because it may be modified during the lookup, if
4503 # __bases__ is set during the lookup for example.
4504 class MyKey(object):
4505 def __hash__(self):
4506 return hash('mykey')
4507
4508 def __eq__(self, other):
4509 X.__bases__ = (Base2,)
4510
4511 class Base(object):
4512 mykey = 'from Base'
4513 mykey2 = 'from Base'
4514
4515 class Base2(object):
4516 mykey = 'from Base2'
4517 mykey2 = 'from Base2'
4518
4519 X = type('X', (Base,), {MyKey(): 5})
4520 # mykey is read from Base
4521 self.assertEqual(X.mykey, 'from Base')
4522 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4523 self.assertEqual(X.mykey2, 'from Base2')
4524
4525
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004526class PicklingTests(unittest.TestCase):
4527
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004528 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004529 listitems=None, dictitems=None):
4530 if proto >= 4:
4531 reduce_value = obj.__reduce_ex__(proto)
4532 self.assertEqual(reduce_value[:3],
4533 (copyreg.__newobj_ex__,
4534 (type(obj), args, kwargs),
4535 state))
4536 if listitems is not None:
4537 self.assertListEqual(list(reduce_value[3]), listitems)
4538 else:
4539 self.assertIsNone(reduce_value[3])
4540 if dictitems is not None:
4541 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4542 else:
4543 self.assertIsNone(reduce_value[4])
4544 elif proto >= 2:
4545 reduce_value = obj.__reduce_ex__(proto)
4546 self.assertEqual(reduce_value[:3],
4547 (copyreg.__newobj__,
4548 (type(obj),) + args,
4549 state))
4550 if listitems is not None:
4551 self.assertListEqual(list(reduce_value[3]), listitems)
4552 else:
4553 self.assertIsNone(reduce_value[3])
4554 if dictitems is not None:
4555 self.assertDictEqual(dict(reduce_value[4]), dictitems)
4556 else:
4557 self.assertIsNone(reduce_value[4])
4558 else:
4559 base_type = type(obj).__base__
4560 reduce_value = (copyreg._reconstructor,
4561 (type(obj),
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004562 base_type,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004563 None if base_type is object else base_type(obj)))
4564 if state is not None:
4565 reduce_value += (state,)
4566 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4567 self.assertEqual(obj.__reduce__(), reduce_value)
4568
4569 def test_reduce(self):
4570 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4571 args = (-101, "spam")
4572 kwargs = {'bacon': -201, 'fish': -301}
4573 state = {'cheese': -401}
4574
4575 class C1:
4576 def __getnewargs__(self):
4577 return args
4578 obj = C1()
4579 for proto in protocols:
4580 self._check_reduce(proto, obj, args)
4581
4582 for name, value in state.items():
4583 setattr(obj, name, value)
4584 for proto in protocols:
4585 self._check_reduce(proto, obj, args, state=state)
4586
4587 class C2:
4588 def __getnewargs__(self):
4589 return "bad args"
4590 obj = C2()
4591 for proto in protocols:
4592 if proto >= 2:
4593 with self.assertRaises(TypeError):
4594 obj.__reduce_ex__(proto)
4595
4596 class C3:
4597 def __getnewargs_ex__(self):
4598 return (args, kwargs)
4599 obj = C3()
4600 for proto in protocols:
4601 if proto >= 4:
4602 self._check_reduce(proto, obj, args, kwargs)
4603 elif proto >= 2:
4604 with self.assertRaises(ValueError):
4605 obj.__reduce_ex__(proto)
4606
4607 class C4:
4608 def __getnewargs_ex__(self):
4609 return (args, "bad dict")
4610 class C5:
4611 def __getnewargs_ex__(self):
4612 return ("bad tuple", kwargs)
4613 class C6:
4614 def __getnewargs_ex__(self):
4615 return ()
4616 class C7:
4617 def __getnewargs_ex__(self):
4618 return "bad args"
4619 for proto in protocols:
4620 for cls in C4, C5, C6, C7:
4621 obj = cls()
4622 if proto >= 2:
4623 with self.assertRaises((TypeError, ValueError)):
4624 obj.__reduce_ex__(proto)
4625
4626 class C8:
4627 def __getnewargs_ex__(self):
4628 return (args, kwargs)
4629 obj = C8()
4630 for proto in protocols:
4631 if 2 <= proto < 4:
4632 with self.assertRaises(ValueError):
4633 obj.__reduce_ex__(proto)
4634 class C9:
4635 def __getnewargs_ex__(self):
4636 return (args, {})
4637 obj = C9()
4638 for proto in protocols:
4639 self._check_reduce(proto, obj, args)
4640
4641 class C10:
4642 def __getnewargs_ex__(self):
4643 raise IndexError
4644 obj = C10()
4645 for proto in protocols:
4646 if proto >= 2:
4647 with self.assertRaises(IndexError):
4648 obj.__reduce_ex__(proto)
4649
4650 class C11:
4651 def __getstate__(self):
4652 return state
4653 obj = C11()
4654 for proto in protocols:
4655 self._check_reduce(proto, obj, state=state)
4656
4657 class C12:
4658 def __getstate__(self):
4659 return "not dict"
4660 obj = C12()
4661 for proto in protocols:
4662 self._check_reduce(proto, obj, state="not dict")
4663
4664 class C13:
4665 def __getstate__(self):
4666 raise IndexError
4667 obj = C13()
4668 for proto in protocols:
4669 with self.assertRaises(IndexError):
4670 obj.__reduce_ex__(proto)
4671 if proto < 2:
4672 with self.assertRaises(IndexError):
4673 obj.__reduce__()
4674
4675 class C14:
4676 __slots__ = tuple(state)
4677 def __init__(self):
4678 for name, value in state.items():
4679 setattr(self, name, value)
4680
4681 obj = C14()
4682 for proto in protocols:
4683 if proto >= 2:
4684 self._check_reduce(proto, obj, state=(None, state))
4685 else:
4686 with self.assertRaises(TypeError):
4687 obj.__reduce_ex__(proto)
4688 with self.assertRaises(TypeError):
4689 obj.__reduce__()
4690
4691 class C15(dict):
4692 pass
4693 obj = C15({"quebec": -601})
4694 for proto in protocols:
4695 self._check_reduce(proto, obj, dictitems=dict(obj))
4696
4697 class C16(list):
4698 pass
4699 obj = C16(["yukon"])
4700 for proto in protocols:
4701 self._check_reduce(proto, obj, listitems=list(obj))
4702
4703 def _assert_is_copy(self, obj, objcopy, msg=None):
4704 """Utility method to verify if two objects are copies of each others.
4705 """
4706 if msg is None:
4707 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4708 if type(obj).__repr__ is object.__repr__:
4709 # We have this limitation for now because we use the object's repr
4710 # to help us verify that the two objects are copies. This allows
4711 # us to delegate the non-generic verification logic to the objects
4712 # themselves.
4713 raise ValueError("object passed to _assert_is_copy must " +
4714 "override the __repr__ method.")
4715 self.assertIsNot(obj, objcopy, msg=msg)
4716 self.assertIs(type(obj), type(objcopy), msg=msg)
4717 if hasattr(obj, '__dict__'):
4718 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4719 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4720 if hasattr(obj, '__slots__'):
4721 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4722 for slot in obj.__slots__:
4723 self.assertEqual(
4724 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4725 self.assertEqual(getattr(obj, slot, None),
4726 getattr(objcopy, slot, None), msg=msg)
4727 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4728
4729 @staticmethod
4730 def _generate_pickle_copiers():
4731 """Utility method to generate the many possible pickle configurations.
4732 """
4733 class PickleCopier:
4734 "This class copies object using pickle."
4735 def __init__(self, proto, dumps, loads):
4736 self.proto = proto
4737 self.dumps = dumps
4738 self.loads = loads
4739 def copy(self, obj):
4740 return self.loads(self.dumps(obj, self.proto))
4741 def __repr__(self):
4742 # We try to be as descriptive as possible here since this is
4743 # the string which we will allow us to tell the pickle
4744 # configuration we are using during debugging.
4745 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4746 .format(self.proto,
4747 self.dumps.__module__, self.dumps.__qualname__,
4748 self.loads.__module__, self.loads.__qualname__))
4749 return (PickleCopier(*args) for args in
4750 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4751 {pickle.dumps, pickle._dumps},
4752 {pickle.loads, pickle._loads}))
4753
4754 def test_pickle_slots(self):
4755 # Tests pickling of classes with __slots__.
4756
4757 # Pickling of classes with __slots__ but without __getstate__ should
4758 # fail (if using protocol 0 or 1)
4759 global C
4760 class C:
4761 __slots__ = ['a']
4762 with self.assertRaises(TypeError):
4763 pickle.dumps(C(), 0)
4764
4765 global D
4766 class D(C):
4767 pass
4768 with self.assertRaises(TypeError):
4769 pickle.dumps(D(), 0)
4770
4771 class C:
4772 "A class with __getstate__ and __setstate__ implemented."
4773 __slots__ = ['a']
4774 def __getstate__(self):
4775 state = getattr(self, '__dict__', {}).copy()
4776 for cls in type(self).__mro__:
Antoine Pitrou7cd9fbe2013-11-23 19:01:36 +01004777 for slot in cls.__dict__.get('__slots__', ()):
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004778 try:
4779 state[slot] = getattr(self, slot)
4780 except AttributeError:
4781 pass
4782 return state
4783 def __setstate__(self, state):
4784 for k, v in state.items():
4785 setattr(self, k, v)
4786 def __repr__(self):
4787 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
4788
4789 class D(C):
4790 "A subclass of a class with slots."
4791 pass
4792
4793 global E
4794 class E(C):
4795 "A subclass with an extra slot."
4796 __slots__ = ['b']
4797
4798 # Now it should work
4799 for pickle_copier in self._generate_pickle_copiers():
4800 with self.subTest(pickle_copier=pickle_copier):
4801 x = C()
4802 y = pickle_copier.copy(x)
4803 self._assert_is_copy(x, y)
4804
4805 x.a = 42
4806 y = pickle_copier.copy(x)
4807 self._assert_is_copy(x, y)
4808
4809 x = D()
4810 x.a = 42
4811 x.b = 100
4812 y = pickle_copier.copy(x)
4813 self._assert_is_copy(x, y)
4814
4815 x = E()
4816 x.a = 42
4817 x.b = "foo"
4818 y = pickle_copier.copy(x)
4819 self._assert_is_copy(x, y)
4820
4821 def test_reduce_copying(self):
4822 # Tests pickling and copying new-style classes and objects.
4823 global C1
4824 class C1:
4825 "The state of this class is copyable via its instance dict."
4826 ARGS = (1, 2)
4827 NEED_DICT_COPYING = True
4828 def __init__(self, a, b):
4829 super().__init__()
4830 self.a = a
4831 self.b = b
4832 def __repr__(self):
4833 return "C1(%r, %r)" % (self.a, self.b)
4834
4835 global C2
4836 class C2(list):
4837 "A list subclass copyable via __getnewargs__."
4838 ARGS = (1, 2)
4839 NEED_DICT_COPYING = False
4840 def __new__(cls, a, b):
4841 self = super().__new__(cls)
4842 self.a = a
4843 self.b = b
4844 return self
4845 def __init__(self, *args):
4846 super().__init__()
4847 # This helps testing that __init__ is not called during the
4848 # unpickling process, which would cause extra appends.
4849 self.append("cheese")
4850 @classmethod
4851 def __getnewargs__(cls):
4852 return cls.ARGS
4853 def __repr__(self):
4854 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
4855
4856 global C3
4857 class C3(list):
4858 "A list subclass copyable via __getstate__."
4859 ARGS = (1, 2)
4860 NEED_DICT_COPYING = False
4861 def __init__(self, a, b):
4862 self.a = a
4863 self.b = b
4864 # This helps testing that __init__ is not called during the
4865 # unpickling process, which would cause extra appends.
4866 self.append("cheese")
4867 @classmethod
4868 def __getstate__(cls):
4869 return cls.ARGS
4870 def __setstate__(self, state):
4871 a, b = state
4872 self.a = a
4873 self.b = b
4874 def __repr__(self):
4875 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
4876
4877 global C4
4878 class C4(int):
4879 "An int subclass copyable via __getnewargs__."
4880 ARGS = ("hello", "world", 1)
4881 NEED_DICT_COPYING = False
4882 def __new__(cls, a, b, value):
4883 self = super().__new__(cls, value)
4884 self.a = a
4885 self.b = b
4886 return self
4887 @classmethod
4888 def __getnewargs__(cls):
4889 return cls.ARGS
4890 def __repr__(self):
4891 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
4892
4893 global C5
4894 class C5(int):
4895 "An int subclass copyable via __getnewargs_ex__."
4896 ARGS = (1, 2)
4897 KWARGS = {'value': 3}
4898 NEED_DICT_COPYING = False
4899 def __new__(cls, a, b, *, value=0):
4900 self = super().__new__(cls, value)
4901 self.a = a
4902 self.b = b
4903 return self
4904 @classmethod
4905 def __getnewargs_ex__(cls):
4906 return (cls.ARGS, cls.KWARGS)
4907 def __repr__(self):
4908 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
4909
4910 test_classes = (C1, C2, C3, C4, C5)
4911 # Testing copying through pickle
4912 pickle_copiers = self._generate_pickle_copiers()
4913 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
4914 with self.subTest(cls=cls, pickle_copier=pickle_copier):
4915 kwargs = getattr(cls, 'KWARGS', {})
4916 obj = cls(*cls.ARGS, **kwargs)
4917 proto = pickle_copier.proto
4918 if 2 <= proto < 4 and hasattr(cls, '__getnewargs_ex__'):
4919 with self.assertRaises(ValueError):
4920 pickle_copier.dumps(obj, proto)
4921 continue
4922 objcopy = pickle_copier.copy(obj)
4923 self._assert_is_copy(obj, objcopy)
4924 # For test classes that supports this, make sure we didn't go
4925 # around the reduce protocol by simply copying the attribute
4926 # dictionary. We clear attributes using the previous copy to
4927 # not mutate the original argument.
4928 if proto >= 2 and not cls.NEED_DICT_COPYING:
4929 objcopy.__dict__.clear()
4930 objcopy2 = pickle_copier.copy(objcopy)
4931 self._assert_is_copy(obj, objcopy2)
4932
4933 # Testing copying through copy.deepcopy()
4934 for cls in test_classes:
4935 with self.subTest(cls=cls):
4936 kwargs = getattr(cls, 'KWARGS', {})
4937 obj = cls(*cls.ARGS, **kwargs)
4938 # XXX: We need to modify the copy module to support PEP 3154's
4939 # reduce protocol 4.
4940 if hasattr(cls, '__getnewargs_ex__'):
4941 continue
4942 objcopy = deepcopy(obj)
4943 self._assert_is_copy(obj, objcopy)
4944 # For test classes that supports this, make sure we didn't go
4945 # around the reduce protocol by simply copying the attribute
4946 # dictionary. We clear attributes using the previous copy to
4947 # not mutate the original argument.
4948 if not cls.NEED_DICT_COPYING:
4949 objcopy.__dict__.clear()
4950 objcopy2 = deepcopy(objcopy)
4951 self._assert_is_copy(obj, objcopy2)
4952
4953
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004954def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004955 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004956 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01004957 ClassPropertiesAndMethods, DictProxyTests,
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +01004958 MiscTests, PicklingTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004960if __name__ == "__main__":
4961 test_main()