blob: 8940ae9d54fccc41f8c9990297856378c2e35980 [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Benjamin Peterson52c42432012-03-07 18:41:11 -06002import gc
Benjamin Petersona5758c02009-05-09 18:15:04 +00003import sys
Guido van Rossum360e4b82007-05-14 22:51:27 +00004import types
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00005import math
Georg Brandl479a7e72008-02-05 18:13:15 +00006import unittest
Benjamin Peterson52c42432012-03-07 18:41:11 -06007import weakref
Tim Peters4d9b4662002-04-16 01:59:17 +00008
Georg Brandl479a7e72008-02-05 18:13:15 +00009from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +000011
Tim Peters6d6c1a32001-08-02 04:15:00 +000012
Georg Brandl479a7e72008-02-05 18:13:15 +000013class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000014
Georg Brandl479a7e72008-02-05 18:13:15 +000015 def __init__(self, *args, **kwargs):
16 unittest.TestCase.__init__(self, *args, **kwargs)
17 self.binops = {
18 'add': '+',
19 'sub': '-',
20 'mul': '*',
21 'div': '/',
22 'divmod': 'divmod',
23 'pow': '**',
24 'lshift': '<<',
25 'rshift': '>>',
26 'and': '&',
27 'xor': '^',
28 'or': '|',
29 'cmp': 'cmp',
30 'lt': '<',
31 'le': '<=',
32 'eq': '==',
33 'ne': '!=',
34 'gt': '>',
35 'ge': '>=',
36 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000037
Georg Brandl479a7e72008-02-05 18:13:15 +000038 for name, expr in list(self.binops.items()):
39 if expr.islower():
40 expr = expr + "(a, b)"
41 else:
42 expr = 'a %s b' % expr
43 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000044
Georg Brandl479a7e72008-02-05 18:13:15 +000045 self.unops = {
46 'pos': '+',
47 'neg': '-',
48 'abs': 'abs',
49 'invert': '~',
50 'int': 'int',
51 'float': 'float',
52 'oct': 'oct',
53 'hex': 'hex',
54 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000055
Georg Brandl479a7e72008-02-05 18:13:15 +000056 for name, expr in list(self.unops.items()):
57 if expr.islower():
58 expr = expr + "(a)"
59 else:
60 expr = '%s a' % expr
61 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000062
Georg Brandl479a7e72008-02-05 18:13:15 +000063 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
64 d = {'a': a}
65 self.assertEqual(eval(expr, d), res)
66 t = type(a)
67 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000068
Georg Brandl479a7e72008-02-05 18:13:15 +000069 # Find method in parent class
70 while meth not in t.__dict__:
71 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000072 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
73 # method object; the getattr() below obtains its underlying function.
74 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000075 self.assertEqual(m(a), res)
76 bm = getattr(a, meth)
77 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000078
Georg Brandl479a7e72008-02-05 18:13:15 +000079 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
80 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000081
Georg Brandl479a7e72008-02-05 18:13:15 +000082 # XXX Hack so this passes before 2.3 when -Qnew is specified.
83 if meth == "__div__" and 1/2 == 0.5:
84 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl479a7e72008-02-05 18:13:15 +000086 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000087
Georg Brandl479a7e72008-02-05 18:13:15 +000088 self.assertEqual(eval(expr, d), res)
89 t = type(a)
90 m = getattr(t, meth)
91 while meth not in t.__dict__:
92 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000093 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
94 # method object; the getattr() below obtains its underlying function.
95 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000096 self.assertEqual(m(a, b), res)
97 bm = getattr(a, meth)
98 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000099
Georg Brandl479a7e72008-02-05 18:13:15 +0000100 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
101 d = {'a': a, 'b': b, 'c': c}
102 self.assertEqual(eval(expr, d), res)
103 t = type(a)
104 m = getattr(t, meth)
105 while meth not in t.__dict__:
106 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000107 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
108 # method object; the getattr() below obtains its underlying function.
109 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000110 self.assertEqual(m(a, slice(b, c)), res)
111 bm = getattr(a, meth)
112 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000113
Georg Brandl479a7e72008-02-05 18:13:15 +0000114 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
115 d = {'a': deepcopy(a), 'b': b}
116 exec(stmt, d)
117 self.assertEqual(d['a'], res)
118 t = type(a)
119 m = getattr(t, meth)
120 while meth not in t.__dict__:
121 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000122 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
123 # method object; the getattr() below obtains its underlying function.
124 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000125 d['a'] = deepcopy(a)
126 m(d['a'], b)
127 self.assertEqual(d['a'], res)
128 d['a'] = deepcopy(a)
129 bm = getattr(d['a'], meth)
130 bm(b)
131 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000132
Georg Brandl479a7e72008-02-05 18:13:15 +0000133 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
134 d = {'a': deepcopy(a), 'b': b, 'c': c}
135 exec(stmt, d)
136 self.assertEqual(d['a'], res)
137 t = type(a)
138 m = getattr(t, meth)
139 while meth not in t.__dict__:
140 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000141 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
142 # method object; the getattr() below obtains its underlying function.
143 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000144 d['a'] = deepcopy(a)
145 m(d['a'], b, c)
146 self.assertEqual(d['a'], res)
147 d['a'] = deepcopy(a)
148 bm = getattr(d['a'], meth)
149 bm(b, c)
150 self.assertEqual(d['a'], res)
151
152 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
153 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
154 exec(stmt, dictionary)
155 self.assertEqual(dictionary['a'], res)
156 t = type(a)
157 while meth not in t.__dict__:
158 t = t.__bases__[0]
159 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000160 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
161 # method object; the getattr() below obtains its underlying function.
162 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000163 dictionary['a'] = deepcopy(a)
164 m(dictionary['a'], slice(b, c), d)
165 self.assertEqual(dictionary['a'], res)
166 dictionary['a'] = deepcopy(a)
167 bm = getattr(dictionary['a'], meth)
168 bm(slice(b, c), d)
169 self.assertEqual(dictionary['a'], res)
170
171 def test_lists(self):
172 # Testing list operations...
173 # Asserts are within individual test methods
174 self.binop_test([1], [2], [1,2], "a+b", "__add__")
175 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
176 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
177 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
178 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
179 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
180 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
181 self.unop_test([1,2,3], 3, "len(a)", "__len__")
182 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
183 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
184 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
185 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
186 "__setitem__")
187
188 def test_dicts(self):
189 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000190 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
191 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
192 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
193
194 d = {1:2, 3:4}
195 l1 = []
196 for i in list(d.keys()):
197 l1.append(i)
198 l = []
199 for i in iter(d):
200 l.append(i)
201 self.assertEqual(l, l1)
202 l = []
203 for i in d.__iter__():
204 l.append(i)
205 self.assertEqual(l, l1)
206 l = []
207 for i in dict.__iter__(d):
208 l.append(i)
209 self.assertEqual(l, l1)
210 d = {1:2, 3:4}
211 self.unop_test(d, 2, "len(a)", "__len__")
212 self.assertEqual(eval(repr(d), {}), d)
213 self.assertEqual(eval(d.__repr__(), {}), d)
214 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
215 "__setitem__")
216
217 # Tests for unary and binary operators
218 def number_operators(self, a, b, skip=[]):
219 dict = {'a': a, 'b': b}
220
221 for name, expr in list(self.binops.items()):
222 if name not in skip:
223 name = "__%s__" % name
224 if hasattr(a, name):
225 res = eval(expr, dict)
226 self.binop_test(a, b, res, expr, name)
227
228 for name, expr in list(self.unops.items()):
229 if name not in skip:
230 name = "__%s__" % name
231 if hasattr(a, name):
232 res = eval(expr, dict)
233 self.unop_test(a, res, expr, name)
234
235 def test_ints(self):
236 # Testing int operations...
237 self.number_operators(100, 3)
238 # The following crashes in Python 2.2
239 self.assertEqual((1).__bool__(), 1)
240 self.assertEqual((0).__bool__(), 0)
241 # This returns 'NotImplemented' in Python 2.2
242 class C(int):
243 def __add__(self, other):
244 return NotImplemented
245 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000246 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000247 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000248 except TypeError:
249 pass
250 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000251 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000252
Georg Brandl479a7e72008-02-05 18:13:15 +0000253 def test_floats(self):
254 # Testing float operations...
255 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000256
Georg Brandl479a7e72008-02-05 18:13:15 +0000257 def test_complexes(self):
258 # Testing complex operations...
259 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000260 'int', 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +0000261 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000262
Georg Brandl479a7e72008-02-05 18:13:15 +0000263 class Number(complex):
264 __slots__ = ['prec']
265 def __new__(cls, *args, **kwds):
266 result = complex.__new__(cls, *args)
267 result.prec = kwds.get('prec', 12)
268 return result
269 def __repr__(self):
270 prec = self.prec
271 if self.imag == 0.0:
272 return "%.*g" % (prec, self.real)
273 if self.real == 0.0:
274 return "%.*gj" % (prec, self.imag)
275 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
276 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000277
Georg Brandl479a7e72008-02-05 18:13:15 +0000278 a = Number(3.14, prec=6)
279 self.assertEqual(repr(a), "3.14")
280 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000281
Georg Brandl479a7e72008-02-05 18:13:15 +0000282 a = Number(a, prec=2)
283 self.assertEqual(repr(a), "3.1")
284 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000285
Georg Brandl479a7e72008-02-05 18:13:15 +0000286 a = Number(234.5)
287 self.assertEqual(repr(a), "234.5")
288 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000289
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000290 def test_explicit_reverse_methods(self):
291 # see issue 9930
292 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
293 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
294
Benjamin Petersone549ead2009-03-28 21:42:05 +0000295 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000296 def test_spam_lists(self):
297 # Testing spamlist operations...
298 import copy, xxsubtype as spam
299
300 def spamlist(l, memo=None):
301 import xxsubtype as spam
302 return spam.spamlist(l)
303
304 # This is an ugly hack:
305 copy._deepcopy_dispatch[spam.spamlist] = spamlist
306
307 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
308 "__add__")
309 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
310 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
311 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
312 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
313 "__getitem__")
314 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
315 "__iadd__")
316 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
317 "__imul__")
318 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
319 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
320 "__mul__")
321 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
322 "__rmul__")
323 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
324 "__setitem__")
325 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
326 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
327 # Test subclassing
328 class C(spam.spamlist):
329 def foo(self): return 1
330 a = C()
331 self.assertEqual(a, [])
332 self.assertEqual(a.foo(), 1)
333 a.append(100)
334 self.assertEqual(a, [100])
335 self.assertEqual(a.getstate(), 0)
336 a.setstate(42)
337 self.assertEqual(a.getstate(), 42)
338
Benjamin Petersone549ead2009-03-28 21:42:05 +0000339 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000340 def test_spam_dicts(self):
341 # Testing spamdict operations...
342 import copy, xxsubtype as spam
343 def spamdict(d, memo=None):
344 import xxsubtype as spam
345 sd = spam.spamdict()
346 for k, v in list(d.items()):
347 sd[k] = v
348 return sd
349 # This is an ugly hack:
350 copy._deepcopy_dispatch[spam.spamdict] = spamdict
351
Georg Brandl479a7e72008-02-05 18:13:15 +0000352 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
353 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
354 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
355 d = spamdict({1:2,3:4})
356 l1 = []
357 for i in list(d.keys()):
358 l1.append(i)
359 l = []
360 for i in iter(d):
361 l.append(i)
362 self.assertEqual(l, l1)
363 l = []
364 for i in d.__iter__():
365 l.append(i)
366 self.assertEqual(l, l1)
367 l = []
368 for i in type(spamdict({})).__iter__(d):
369 l.append(i)
370 self.assertEqual(l, l1)
371 straightd = {1:2, 3:4}
372 spamd = spamdict(straightd)
373 self.unop_test(spamd, 2, "len(a)", "__len__")
374 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
375 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
376 "a[b]=c", "__setitem__")
377 # Test subclassing
378 class C(spam.spamdict):
379 def foo(self): return 1
380 a = C()
381 self.assertEqual(list(a.items()), [])
382 self.assertEqual(a.foo(), 1)
383 a['foo'] = 'bar'
384 self.assertEqual(list(a.items()), [('foo', 'bar')])
385 self.assertEqual(a.getstate(), 0)
386 a.setstate(100)
387 self.assertEqual(a.getstate(), 100)
388
389class ClassPropertiesAndMethods(unittest.TestCase):
390
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200391 def assertHasAttr(self, obj, name):
392 self.assertTrue(hasattr(obj, name),
393 '%r has no attribute %r' % (obj, name))
394
395 def assertNotHasAttr(self, obj, name):
396 self.assertFalse(hasattr(obj, name),
397 '%r has unexpected attribute %r' % (obj, name))
398
Georg Brandl479a7e72008-02-05 18:13:15 +0000399 def test_python_dicts(self):
400 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000401 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000402 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000403 d = dict()
404 self.assertEqual(d, {})
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200405 self.assertIs(d.__class__, dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000406 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000407 class C(dict):
408 state = -1
409 def __init__(self_local, *a, **kw):
410 if a:
411 self.assertEqual(len(a), 1)
412 self_local.state = a[0]
413 if kw:
414 for k, v in list(kw.items()):
415 self_local[v] = k
416 def __getitem__(self, key):
417 return self.get(key, 0)
418 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000419 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000420 dict.__setitem__(self_local, key, value)
421 def setstate(self, state):
422 self.state = state
423 def getstate(self):
424 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000425 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000426 a1 = C(12)
427 self.assertEqual(a1.state, 12)
428 a2 = C(foo=1, bar=2)
429 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
430 a = C()
431 self.assertEqual(a.state, -1)
432 self.assertEqual(a.getstate(), -1)
433 a.setstate(0)
434 self.assertEqual(a.state, 0)
435 self.assertEqual(a.getstate(), 0)
436 a.setstate(10)
437 self.assertEqual(a.state, 10)
438 self.assertEqual(a.getstate(), 10)
439 self.assertEqual(a[42], 0)
440 a[42] = 24
441 self.assertEqual(a[42], 24)
442 N = 50
443 for i in range(N):
444 a[i] = C()
445 for j in range(N):
446 a[i][j] = i*j
447 for i in range(N):
448 for j in range(N):
449 self.assertEqual(a[i][j], i*j)
450
451 def test_python_lists(self):
452 # Testing Python subclass of list...
453 class C(list):
454 def __getitem__(self, i):
455 if isinstance(i, slice):
456 return i.start, i.stop
457 return list.__getitem__(self, i) + 100
458 a = C()
459 a.extend([0,1,2])
460 self.assertEqual(a[0], 100)
461 self.assertEqual(a[1], 101)
462 self.assertEqual(a[2], 102)
463 self.assertEqual(a[100:200], (100,200))
464
465 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000466 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000467 class C(metaclass=type):
468 def __init__(self):
469 self.__state = 0
470 def getstate(self):
471 return self.__state
472 def setstate(self, state):
473 self.__state = state
474 a = C()
475 self.assertEqual(a.getstate(), 0)
476 a.setstate(10)
477 self.assertEqual(a.getstate(), 10)
478 class _metaclass(type):
479 def myself(cls): return cls
480 class D(metaclass=_metaclass):
481 pass
482 self.assertEqual(D.myself(), D)
483 d = D()
484 self.assertEqual(d.__class__, D)
485 class M1(type):
486 def __new__(cls, name, bases, dict):
487 dict['__spam__'] = 1
488 return type.__new__(cls, name, bases, dict)
489 class C(metaclass=M1):
490 pass
491 self.assertEqual(C.__spam__, 1)
492 c = C()
493 self.assertEqual(c.__spam__, 1)
494
495 class _instance(object):
496 pass
497 class M2(object):
498 @staticmethod
499 def __new__(cls, name, bases, dict):
500 self = object.__new__(cls)
501 self.name = name
502 self.bases = bases
503 self.dict = dict
504 return self
505 def __call__(self):
506 it = _instance()
507 # Early binding of methods
508 for key in self.dict:
509 if key.startswith("__"):
510 continue
511 setattr(it, key, self.dict[key].__get__(it, self))
512 return it
513 class C(metaclass=M2):
514 def spam(self):
515 return 42
516 self.assertEqual(C.name, 'C')
517 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000518 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000519 c = C()
520 self.assertEqual(c.spam(), 42)
521
522 # More metaclass examples
523
524 class autosuper(type):
525 # Automatically add __super to the class
526 # This trick only works for dynamic classes
527 def __new__(metaclass, name, bases, dict):
528 cls = super(autosuper, metaclass).__new__(metaclass,
529 name, bases, dict)
530 # Name mangling for __super removes leading underscores
531 while name[:1] == "_":
532 name = name[1:]
533 if name:
534 name = "_%s__super" % name
535 else:
536 name = "__super"
537 setattr(cls, name, super(cls))
538 return cls
539 class A(metaclass=autosuper):
540 def meth(self):
541 return "A"
542 class B(A):
543 def meth(self):
544 return "B" + self.__super.meth()
545 class C(A):
546 def meth(self):
547 return "C" + self.__super.meth()
548 class D(C, B):
549 def meth(self):
550 return "D" + self.__super.meth()
551 self.assertEqual(D().meth(), "DCBA")
552 class E(B, C):
553 def meth(self):
554 return "E" + self.__super.meth()
555 self.assertEqual(E().meth(), "EBCA")
556
557 class autoproperty(type):
558 # Automatically create property attributes when methods
559 # named _get_x and/or _set_x are found
560 def __new__(metaclass, name, bases, dict):
561 hits = {}
562 for key, val in dict.items():
563 if key.startswith("_get_"):
564 key = key[5:]
565 get, set = hits.get(key, (None, None))
566 get = val
567 hits[key] = get, set
568 elif key.startswith("_set_"):
569 key = key[5:]
570 get, set = hits.get(key, (None, None))
571 set = val
572 hits[key] = get, set
573 for key, (get, set) in hits.items():
574 dict[key] = property(get, set)
575 return super(autoproperty, metaclass).__new__(metaclass,
576 name, bases, dict)
577 class A(metaclass=autoproperty):
578 def _get_x(self):
579 return -self.__x
580 def _set_x(self, x):
581 self.__x = -x
582 a = A()
Serhiy Storchaka76edd212013-11-17 23:38:50 +0200583 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +0000584 a.x = 12
585 self.assertEqual(a.x, 12)
586 self.assertEqual(a._A__x, -12)
587
588 class multimetaclass(autoproperty, autosuper):
589 # Merge of multiple cooperating metaclasses
590 pass
591 class A(metaclass=multimetaclass):
592 def _get_x(self):
593 return "A"
594 class B(A):
595 def _get_x(self):
596 return "B" + self.__super._get_x()
597 class C(A):
598 def _get_x(self):
599 return "C" + self.__super._get_x()
600 class D(C, B):
601 def _get_x(self):
602 return "D" + self.__super._get_x()
603 self.assertEqual(D().x, "DCBA")
604
605 # Make sure type(x) doesn't call x.__class__.__init__
606 class T(type):
607 counter = 0
608 def __init__(self, *args):
609 T.counter += 1
610 class C(metaclass=T):
611 pass
612 self.assertEqual(T.counter, 1)
613 a = C()
614 self.assertEqual(type(a), C)
615 self.assertEqual(T.counter, 1)
616
617 class C(object): pass
618 c = C()
619 try: c()
620 except TypeError: pass
621 else: self.fail("calling object w/o call method should raise "
622 "TypeError")
623
624 # Testing code to find most derived baseclass
625 class A(type):
626 def __new__(*args, **kwargs):
627 return type.__new__(*args, **kwargs)
628
629 class B(object):
630 pass
631
632 class C(object, metaclass=A):
633 pass
634
635 # The most derived metaclass of D is A rather than type.
636 class D(B, C):
637 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000638 self.assertIs(A, type(D))
639
640 # issue1294232: correct metaclass calculation
641 new_calls = [] # to check the order of __new__ calls
642 class AMeta(type):
643 @staticmethod
644 def __new__(mcls, name, bases, ns):
645 new_calls.append('AMeta')
646 return super().__new__(mcls, name, bases, ns)
647 @classmethod
648 def __prepare__(mcls, name, bases):
649 return {}
650
651 class BMeta(AMeta):
652 @staticmethod
653 def __new__(mcls, name, bases, ns):
654 new_calls.append('BMeta')
655 return super().__new__(mcls, name, bases, ns)
656 @classmethod
657 def __prepare__(mcls, name, bases):
658 ns = super().__prepare__(name, bases)
659 ns['BMeta_was_here'] = True
660 return ns
661
662 class A(metaclass=AMeta):
663 pass
664 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000665 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000666
667 class B(metaclass=BMeta):
668 pass
669 # BMeta.__new__ calls AMeta.__new__ with super:
670 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000671 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000672
673 class C(A, B):
674 pass
675 # The most derived metaclass is BMeta:
676 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000677 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000678 # BMeta.__prepare__ should've been called:
679 self.assertIn('BMeta_was_here', C.__dict__)
680
681 # The order of the bases shouldn't matter:
682 class C2(B, A):
683 pass
684 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000685 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000686 self.assertIn('BMeta_was_here', C2.__dict__)
687
688 # Check correct metaclass calculation when a metaclass is declared:
689 class D(C, metaclass=type):
690 pass
691 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000692 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000693 self.assertIn('BMeta_was_here', D.__dict__)
694
695 class E(C, metaclass=AMeta):
696 pass
697 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000698 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000699 self.assertIn('BMeta_was_here', E.__dict__)
700
701 # Special case: the given metaclass isn't a class,
702 # so there is no metaclass calculation.
703 marker = object()
704 def func(*args, **kwargs):
705 return marker
706 class X(metaclass=func):
707 pass
708 class Y(object, metaclass=func):
709 pass
710 class Z(D, metaclass=func):
711 pass
712 self.assertIs(marker, X)
713 self.assertIs(marker, Y)
714 self.assertIs(marker, Z)
715
716 # The given metaclass is a class,
717 # but not a descendant of type.
718 prepare_calls = [] # to track __prepare__ calls
719 class ANotMeta:
720 def __new__(mcls, *args, **kwargs):
721 new_calls.append('ANotMeta')
722 return super().__new__(mcls)
723 @classmethod
724 def __prepare__(mcls, name, bases):
725 prepare_calls.append('ANotMeta')
726 return {}
727 class BNotMeta(ANotMeta):
728 def __new__(mcls, *args, **kwargs):
729 new_calls.append('BNotMeta')
730 return super().__new__(mcls)
731 @classmethod
732 def __prepare__(mcls, name, bases):
733 prepare_calls.append('BNotMeta')
734 return super().__prepare__(name, bases)
735
736 class A(metaclass=ANotMeta):
737 pass
738 self.assertIs(ANotMeta, type(A))
739 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000740 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000741 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000742 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000743
744 class B(metaclass=BNotMeta):
745 pass
746 self.assertIs(BNotMeta, type(B))
747 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000748 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000749 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000750 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000751
752 class C(A, B):
753 pass
754 self.assertIs(BNotMeta, type(C))
755 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000756 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000757 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000758 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000759
760 class C2(B, A):
761 pass
762 self.assertIs(BNotMeta, type(C2))
763 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000764 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000765 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000766 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000767
768 # This is a TypeError, because of a metaclass conflict:
769 # BNotMeta is neither a subclass, nor a superclass of type
770 with self.assertRaises(TypeError):
771 class D(C, metaclass=type):
772 pass
773
774 class E(C, metaclass=ANotMeta):
775 pass
776 self.assertIs(BNotMeta, type(E))
777 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000778 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000779 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000780 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000781
782 class F(object(), C):
783 pass
784 self.assertIs(BNotMeta, type(F))
785 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000786 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000787 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000788 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000789
790 class F2(C, object()):
791 pass
792 self.assertIs(BNotMeta, type(F2))
793 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000794 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000795 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000796 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000797
798 # TypeError: BNotMeta is neither a
799 # subclass, nor a superclass of int
800 with self.assertRaises(TypeError):
801 class X(C, int()):
802 pass
803 with self.assertRaises(TypeError):
804 class X(int(), C):
805 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000806
807 def test_module_subclasses(self):
808 # Testing Python subclass of module...
809 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000810 MT = type(sys)
811 class MM(MT):
812 def __init__(self, name):
813 MT.__init__(self, name)
814 def __getattribute__(self, name):
815 log.append(("getattr", name))
816 return MT.__getattribute__(self, name)
817 def __setattr__(self, name, value):
818 log.append(("setattr", name, value))
819 MT.__setattr__(self, name, value)
820 def __delattr__(self, name):
821 log.append(("delattr", name))
822 MT.__delattr__(self, name)
823 a = MM("a")
824 a.foo = 12
825 x = a.foo
826 del a.foo
827 self.assertEqual(log, [("setattr", "foo", 12),
828 ("getattr", "foo"),
829 ("delattr", "foo")])
830
831 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000832 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000833 class Module(types.ModuleType, str):
834 pass
835 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000836 pass
837 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000838 self.fail("inheriting from ModuleType and str at the same time "
839 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000840
Georg Brandl479a7e72008-02-05 18:13:15 +0000841 def test_multiple_inheritance(self):
842 # Testing multiple inheritance...
843 class C(object):
844 def __init__(self):
845 self.__state = 0
846 def getstate(self):
847 return self.__state
848 def setstate(self, state):
849 self.__state = state
850 a = C()
851 self.assertEqual(a.getstate(), 0)
852 a.setstate(10)
853 self.assertEqual(a.getstate(), 10)
854 class D(dict, C):
855 def __init__(self):
856 type({}).__init__(self)
857 C.__init__(self)
858 d = D()
859 self.assertEqual(list(d.keys()), [])
860 d["hello"] = "world"
861 self.assertEqual(list(d.items()), [("hello", "world")])
862 self.assertEqual(d["hello"], "world")
863 self.assertEqual(d.getstate(), 0)
864 d.setstate(10)
865 self.assertEqual(d.getstate(), 10)
866 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000867
Georg Brandl479a7e72008-02-05 18:13:15 +0000868 # SF bug #442833
869 class Node(object):
870 def __int__(self):
871 return int(self.foo())
872 def foo(self):
873 return "23"
874 class Frag(Node, list):
875 def foo(self):
876 return "42"
877 self.assertEqual(Node().__int__(), 23)
878 self.assertEqual(int(Node()), 23)
879 self.assertEqual(Frag().__int__(), 42)
880 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000881
Georg Brandl479a7e72008-02-05 18:13:15 +0000882 def test_diamond_inheritence(self):
883 # Testing multiple inheritance special cases...
884 class A(object):
885 def spam(self): return "A"
886 self.assertEqual(A().spam(), "A")
887 class B(A):
888 def boo(self): return "B"
889 def spam(self): return "B"
890 self.assertEqual(B().spam(), "B")
891 self.assertEqual(B().boo(), "B")
892 class C(A):
893 def boo(self): return "C"
894 self.assertEqual(C().spam(), "A")
895 self.assertEqual(C().boo(), "C")
896 class D(B, C): pass
897 self.assertEqual(D().spam(), "B")
898 self.assertEqual(D().boo(), "B")
899 self.assertEqual(D.__mro__, (D, B, C, A, object))
900 class E(C, B): pass
901 self.assertEqual(E().spam(), "B")
902 self.assertEqual(E().boo(), "C")
903 self.assertEqual(E.__mro__, (E, C, B, A, object))
904 # MRO order disagreement
905 try:
906 class F(D, E): pass
907 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000908 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000909 else:
910 self.fail("expected MRO order disagreement (F)")
911 try:
912 class G(E, D): pass
913 except TypeError:
914 pass
915 else:
916 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000917
Georg Brandl479a7e72008-02-05 18:13:15 +0000918 # see thread python-dev/2002-October/029035.html
919 def test_ex5_from_c3_switch(self):
920 # Testing ex5 from C3 switch discussion...
921 class A(object): pass
922 class B(object): pass
923 class C(object): pass
924 class X(A): pass
925 class Y(A): pass
926 class Z(X,B,Y,C): pass
927 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000928
Georg Brandl479a7e72008-02-05 18:13:15 +0000929 # see "A Monotonic Superclass Linearization for Dylan",
930 # by Kim Barrett et al. (OOPSLA 1996)
931 def test_monotonicity(self):
932 # Testing MRO monotonicity...
933 class Boat(object): pass
934 class DayBoat(Boat): pass
935 class WheelBoat(Boat): pass
936 class EngineLess(DayBoat): pass
937 class SmallMultihull(DayBoat): pass
938 class PedalWheelBoat(EngineLess,WheelBoat): pass
939 class SmallCatamaran(SmallMultihull): pass
940 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000941
Georg Brandl479a7e72008-02-05 18:13:15 +0000942 self.assertEqual(PedalWheelBoat.__mro__,
943 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
944 self.assertEqual(SmallCatamaran.__mro__,
945 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
946 self.assertEqual(Pedalo.__mro__,
947 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
948 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000949
Georg Brandl479a7e72008-02-05 18:13:15 +0000950 # see "A Monotonic Superclass Linearization for Dylan",
951 # by Kim Barrett et al. (OOPSLA 1996)
952 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200953 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000954 class Pane(object): pass
955 class ScrollingMixin(object): pass
956 class EditingMixin(object): pass
957 class ScrollablePane(Pane,ScrollingMixin): pass
958 class EditablePane(Pane,EditingMixin): pass
959 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000960
Georg Brandl479a7e72008-02-05 18:13:15 +0000961 self.assertEqual(EditableScrollablePane.__mro__,
962 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
963 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000964
Georg Brandl479a7e72008-02-05 18:13:15 +0000965 def test_mro_disagreement(self):
966 # Testing error messages for MRO disagreement...
967 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000968order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000969
Georg Brandl479a7e72008-02-05 18:13:15 +0000970 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000971 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000972 callable(*args)
973 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000974 # the exact msg is generally considered an impl detail
975 if support.check_impl_detail():
976 if not str(msg).startswith(expected):
977 self.fail("Message %r, expected %r" %
978 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000979 else:
980 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000981
Georg Brandl479a7e72008-02-05 18:13:15 +0000982 class A(object): pass
983 class B(A): pass
984 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000985
Georg Brandl479a7e72008-02-05 18:13:15 +0000986 # Test some very simple errors
987 raises(TypeError, "duplicate base class A",
988 type, "X", (A, A), {})
989 raises(TypeError, mro_err_msg,
990 type, "X", (A, B), {})
991 raises(TypeError, mro_err_msg,
992 type, "X", (A, C, B), {})
993 # Test a slightly more complex error
994 class GridLayout(object): pass
995 class HorizontalGrid(GridLayout): pass
996 class VerticalGrid(GridLayout): pass
997 class HVGrid(HorizontalGrid, VerticalGrid): pass
998 class VHGrid(VerticalGrid, HorizontalGrid): pass
999 raises(TypeError, mro_err_msg,
1000 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +00001001
Georg Brandl479a7e72008-02-05 18:13:15 +00001002 def test_object_class(self):
1003 # Testing object class...
1004 a = object()
1005 self.assertEqual(a.__class__, object)
1006 self.assertEqual(type(a), object)
1007 b = object()
1008 self.assertNotEqual(a, b)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001009 self.assertNotHasAttr(a, "foo")
Tim Peters808b94e2001-09-13 19:33:07 +00001010 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001011 a.foo = 12
1012 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001013 pass
1014 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001015 self.fail("object() should not allow setting a foo attribute")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001016 self.assertNotHasAttr(object(), "__dict__")
Tim Peters561f8992001-09-13 19:36:36 +00001017
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001019 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001020 x = Cdict()
1021 self.assertEqual(x.__dict__, {})
1022 x.foo = 1
1023 self.assertEqual(x.foo, 1)
1024 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025
Georg Brandl479a7e72008-02-05 18:13:15 +00001026 def test_slots(self):
1027 # Testing __slots__...
1028 class C0(object):
1029 __slots__ = []
1030 x = C0()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001031 self.assertNotHasAttr(x, "__dict__")
1032 self.assertNotHasAttr(x, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00001033
1034 class C1(object):
1035 __slots__ = ['a']
1036 x = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001037 self.assertNotHasAttr(x, "__dict__")
1038 self.assertNotHasAttr(x, "a")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001039 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001040 self.assertEqual(x.a, 1)
1041 x.a = None
1042 self.assertEqual(x.a, None)
1043 del x.a
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001044 self.assertNotHasAttr(x, "a")
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001045
Georg Brandl479a7e72008-02-05 18:13:15 +00001046 class C3(object):
1047 __slots__ = ['a', 'b', 'c']
1048 x = C3()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001049 self.assertNotHasAttr(x, "__dict__")
1050 self.assertNotHasAttr(x, 'a')
1051 self.assertNotHasAttr(x, 'b')
1052 self.assertNotHasAttr(x, 'c')
Georg Brandl479a7e72008-02-05 18:13:15 +00001053 x.a = 1
1054 x.b = 2
1055 x.c = 3
1056 self.assertEqual(x.a, 1)
1057 self.assertEqual(x.b, 2)
1058 self.assertEqual(x.c, 3)
1059
1060 class C4(object):
1061 """Validate name mangling"""
1062 __slots__ = ['__a']
1063 def __init__(self, value):
1064 self.__a = value
1065 def get(self):
1066 return self.__a
1067 x = C4(5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001068 self.assertNotHasAttr(x, '__dict__')
1069 self.assertNotHasAttr(x, '__a')
Georg Brandl479a7e72008-02-05 18:13:15 +00001070 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001071 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001072 x.__a = 6
1073 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001074 pass
1075 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001076 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001077
Georg Brandl479a7e72008-02-05 18:13:15 +00001078 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001079 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001080 class C(object):
1081 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001082 except TypeError:
1083 pass
1084 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001085 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001086 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001087 class C(object):
1088 __slots__ = ["foo bar"]
1089 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001090 pass
1091 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001092 self.fail("['foo bar'] slots not caught")
1093 try:
1094 class C(object):
1095 __slots__ = ["foo\0bar"]
1096 except TypeError:
1097 pass
1098 else:
1099 self.fail("['foo\\0bar'] slots not caught")
1100 try:
1101 class C(object):
1102 __slots__ = ["1"]
1103 except TypeError:
1104 pass
1105 else:
1106 self.fail("['1'] slots not caught")
1107 try:
1108 class C(object):
1109 __slots__ = [""]
1110 except TypeError:
1111 pass
1112 else:
1113 self.fail("[''] slots not caught")
1114 class C(object):
1115 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1116 # XXX(nnorwitz): was there supposed to be something tested
1117 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001118
Georg Brandl479a7e72008-02-05 18:13:15 +00001119 # Test a single string is not expanded as a sequence.
1120 class C(object):
1121 __slots__ = "abc"
1122 c = C()
1123 c.abc = 5
1124 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001125
Georg Brandl479a7e72008-02-05 18:13:15 +00001126 # Test unicode slot names
1127 # Test a single unicode string is not expanded as a sequence.
1128 class C(object):
1129 __slots__ = "abc"
1130 c = C()
1131 c.abc = 5
1132 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001133
Georg Brandl479a7e72008-02-05 18:13:15 +00001134 # _unicode_to_string used to modify slots in certain circumstances
1135 slots = ("foo", "bar")
1136 class C(object):
1137 __slots__ = slots
1138 x = C()
1139 x.foo = 5
1140 self.assertEqual(x.foo, 5)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001141 self.assertIs(type(slots[0]), str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001142 # this used to leak references
1143 try:
1144 class C(object):
1145 __slots__ = [chr(128)]
1146 except (TypeError, UnicodeEncodeError):
1147 pass
1148 else:
1149 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001150
Georg Brandl479a7e72008-02-05 18:13:15 +00001151 # Test leaks
1152 class Counted(object):
1153 counter = 0 # counts the number of instances alive
1154 def __init__(self):
1155 Counted.counter += 1
1156 def __del__(self):
1157 Counted.counter -= 1
1158 class C(object):
1159 __slots__ = ['a', 'b', 'c']
1160 x = C()
1161 x.a = Counted()
1162 x.b = Counted()
1163 x.c = Counted()
1164 self.assertEqual(Counted.counter, 3)
1165 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001166 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001167 self.assertEqual(Counted.counter, 0)
1168 class D(C):
1169 pass
1170 x = D()
1171 x.a = Counted()
1172 x.z = Counted()
1173 self.assertEqual(Counted.counter, 2)
1174 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001175 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001176 self.assertEqual(Counted.counter, 0)
1177 class E(D):
1178 __slots__ = ['e']
1179 x = E()
1180 x.a = Counted()
1181 x.z = Counted()
1182 x.e = Counted()
1183 self.assertEqual(Counted.counter, 3)
1184 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001185 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001186 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001187
Georg Brandl479a7e72008-02-05 18:13:15 +00001188 # Test cyclical leaks [SF bug 519621]
1189 class F(object):
1190 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001191 s = F()
1192 s.a = [Counted(), s]
1193 self.assertEqual(Counted.counter, 1)
1194 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001195 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001196 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001197
Georg Brandl479a7e72008-02-05 18:13:15 +00001198 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001199 if hasattr(gc, 'get_objects'):
1200 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001201 def __eq__(self, other):
1202 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001203 g = G()
1204 orig_objects = len(gc.get_objects())
1205 for i in range(10):
1206 g==g
1207 new_objects = len(gc.get_objects())
1208 self.assertEqual(orig_objects, new_objects)
1209
Georg Brandl479a7e72008-02-05 18:13:15 +00001210 class H(object):
1211 __slots__ = ['a', 'b']
1212 def __init__(self):
1213 self.a = 1
1214 self.b = 2
1215 def __del__(self_):
1216 self.assertEqual(self_.a, 1)
1217 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001218 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001219 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001220 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001221 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001222
Benjamin Petersond12362a2009-12-30 19:44:54 +00001223 class X(object):
1224 __slots__ = "a"
1225 with self.assertRaises(AttributeError):
1226 del X().a
1227
Georg Brandl479a7e72008-02-05 18:13:15 +00001228 def test_slots_special(self):
1229 # Testing __dict__ and __weakref__ in __slots__...
1230 class D(object):
1231 __slots__ = ["__dict__"]
1232 a = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001233 self.assertHasAttr(a, "__dict__")
1234 self.assertNotHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001235 a.foo = 42
1236 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001237
Georg Brandl479a7e72008-02-05 18:13:15 +00001238 class W(object):
1239 __slots__ = ["__weakref__"]
1240 a = W()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001241 self.assertHasAttr(a, "__weakref__")
1242 self.assertNotHasAttr(a, "__dict__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001243 try:
1244 a.foo = 42
1245 except AttributeError:
1246 pass
1247 else:
1248 self.fail("shouldn't be allowed to set a.foo")
1249
1250 class C1(W, D):
1251 __slots__ = []
1252 a = C1()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001253 self.assertHasAttr(a, "__dict__")
1254 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001255 a.foo = 42
1256 self.assertEqual(a.__dict__, {"foo": 42})
1257
1258 class C2(D, W):
1259 __slots__ = []
1260 a = C2()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001261 self.assertHasAttr(a, "__dict__")
1262 self.assertHasAttr(a, "__weakref__")
Georg Brandl479a7e72008-02-05 18:13:15 +00001263 a.foo = 42
1264 self.assertEqual(a.__dict__, {"foo": 42})
1265
Christian Heimesa156e092008-02-16 07:38:31 +00001266 def test_slots_descriptor(self):
1267 # Issue2115: slot descriptors did not correctly check
1268 # the type of the given object
1269 import abc
1270 class MyABC(metaclass=abc.ABCMeta):
1271 __slots__ = "a"
1272
1273 class Unrelated(object):
1274 pass
1275 MyABC.register(Unrelated)
1276
1277 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001278 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001279
1280 # This used to crash
1281 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1282
Georg Brandl479a7e72008-02-05 18:13:15 +00001283 def test_dynamics(self):
1284 # Testing class attribute propagation...
1285 class D(object):
1286 pass
1287 class E(D):
1288 pass
1289 class F(D):
1290 pass
1291 D.foo = 1
1292 self.assertEqual(D.foo, 1)
1293 # Test that dynamic attributes are inherited
1294 self.assertEqual(E.foo, 1)
1295 self.assertEqual(F.foo, 1)
1296 # Test dynamic instances
1297 class C(object):
1298 pass
1299 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001300 self.assertNotHasAttr(a, "foobar")
Georg Brandl479a7e72008-02-05 18:13:15 +00001301 C.foobar = 2
1302 self.assertEqual(a.foobar, 2)
1303 C.method = lambda self: 42
1304 self.assertEqual(a.method(), 42)
1305 C.__repr__ = lambda self: "C()"
1306 self.assertEqual(repr(a), "C()")
1307 C.__int__ = lambda self: 100
1308 self.assertEqual(int(a), 100)
1309 self.assertEqual(a.foobar, 2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001310 self.assertNotHasAttr(a, "spam")
Georg Brandl479a7e72008-02-05 18:13:15 +00001311 def mygetattr(self, name):
1312 if name == "spam":
1313 return "spam"
1314 raise AttributeError
1315 C.__getattr__ = mygetattr
1316 self.assertEqual(a.spam, "spam")
1317 a.new = 12
1318 self.assertEqual(a.new, 12)
1319 def mysetattr(self, name, value):
1320 if name == "spam":
1321 raise AttributeError
1322 return object.__setattr__(self, name, value)
1323 C.__setattr__ = mysetattr
1324 try:
1325 a.spam = "not spam"
1326 except AttributeError:
1327 pass
1328 else:
1329 self.fail("expected AttributeError")
1330 self.assertEqual(a.spam, "spam")
1331 class D(C):
1332 pass
1333 d = D()
1334 d.foo = 1
1335 self.assertEqual(d.foo, 1)
1336
1337 # Test handling of int*seq and seq*int
1338 class I(int):
1339 pass
1340 self.assertEqual("a"*I(2), "aa")
1341 self.assertEqual(I(2)*"a", "aa")
1342 self.assertEqual(2*I(3), 6)
1343 self.assertEqual(I(3)*2, 6)
1344 self.assertEqual(I(3)*I(2), 6)
1345
Georg Brandl479a7e72008-02-05 18:13:15 +00001346 # Test comparison of classes with dynamic metaclasses
1347 class dynamicmetaclass(type):
1348 pass
1349 class someclass(metaclass=dynamicmetaclass):
1350 pass
1351 self.assertNotEqual(someclass, object)
1352
1353 def test_errors(self):
1354 # Testing errors...
1355 try:
1356 class C(list, dict):
1357 pass
1358 except TypeError:
1359 pass
1360 else:
1361 self.fail("inheritance from both list and dict should be illegal")
1362
1363 try:
1364 class C(object, None):
1365 pass
1366 except TypeError:
1367 pass
1368 else:
1369 self.fail("inheritance from non-type should be illegal")
1370 class Classic:
1371 pass
1372
1373 try:
1374 class C(type(len)):
1375 pass
1376 except TypeError:
1377 pass
1378 else:
1379 self.fail("inheritance from CFunction should be illegal")
1380
1381 try:
1382 class C(object):
1383 __slots__ = 1
1384 except TypeError:
1385 pass
1386 else:
1387 self.fail("__slots__ = 1 should be illegal")
1388
1389 try:
1390 class C(object):
1391 __slots__ = [1]
1392 except TypeError:
1393 pass
1394 else:
1395 self.fail("__slots__ = [1] should be illegal")
1396
1397 class M1(type):
1398 pass
1399 class M2(type):
1400 pass
1401 class A1(object, metaclass=M1):
1402 pass
1403 class A2(object, metaclass=M2):
1404 pass
1405 try:
1406 class B(A1, A2):
1407 pass
1408 except TypeError:
1409 pass
1410 else:
1411 self.fail("finding the most derived metaclass should have failed")
1412
1413 def test_classmethods(self):
1414 # Testing class methods...
1415 class C(object):
1416 def foo(*a): return a
1417 goo = classmethod(foo)
1418 c = C()
1419 self.assertEqual(C.goo(1), (C, 1))
1420 self.assertEqual(c.goo(1), (C, 1))
1421 self.assertEqual(c.foo(1), (c, 1))
1422 class D(C):
1423 pass
1424 d = D()
1425 self.assertEqual(D.goo(1), (D, 1))
1426 self.assertEqual(d.goo(1), (D, 1))
1427 self.assertEqual(d.foo(1), (d, 1))
1428 self.assertEqual(D.foo(d, 1), (d, 1))
1429 # Test for a specific crash (SF bug 528132)
1430 def f(cls, arg): return (cls, arg)
1431 ff = classmethod(f)
1432 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1433 self.assertEqual(ff.__get__(0)(42), (int, 42))
1434
1435 # Test super() with classmethods (SF bug 535444)
1436 self.assertEqual(C.goo.__self__, C)
1437 self.assertEqual(D.goo.__self__, D)
1438 self.assertEqual(super(D,D).goo.__self__, D)
1439 self.assertEqual(super(D,d).goo.__self__, D)
1440 self.assertEqual(super(D,D).goo(), (D,))
1441 self.assertEqual(super(D,d).goo(), (D,))
1442
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001443 # Verify that a non-callable will raise
1444 meth = classmethod(1).__get__(1)
1445 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001446
1447 # Verify that classmethod() doesn't allow keyword args
1448 try:
1449 classmethod(f, kw=1)
1450 except TypeError:
1451 pass
1452 else:
1453 self.fail("classmethod shouldn't accept keyword args")
1454
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001455 cm = classmethod(f)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001456 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001457 cm.x = 42
1458 self.assertEqual(cm.x, 42)
1459 self.assertEqual(cm.__dict__, {"x" : 42})
1460 del cm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001461 self.assertNotHasAttr(cm, "x")
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001462
Benjamin Petersone549ead2009-03-28 21:42:05 +00001463 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001464 def test_classmethods_in_c(self):
1465 # Testing C-based class methods...
1466 import xxsubtype as spam
1467 a = (1, 2, 3)
1468 d = {'abc': 123}
1469 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1470 self.assertEqual(x, spam.spamlist)
1471 self.assertEqual(a, a1)
1472 self.assertEqual(d, d1)
1473 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1474 self.assertEqual(x, spam.spamlist)
1475 self.assertEqual(a, a1)
1476 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001477 spam_cm = spam.spamlist.__dict__['classmeth']
1478 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1479 self.assertEqual(x2, spam.spamlist)
1480 self.assertEqual(a2, a1)
1481 self.assertEqual(d2, d1)
1482 class SubSpam(spam.spamlist): pass
1483 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1484 self.assertEqual(x2, SubSpam)
1485 self.assertEqual(a2, a1)
1486 self.assertEqual(d2, d1)
1487 with self.assertRaises(TypeError):
1488 spam_cm()
1489 with self.assertRaises(TypeError):
1490 spam_cm(spam.spamlist())
1491 with self.assertRaises(TypeError):
1492 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001493
1494 def test_staticmethods(self):
1495 # Testing static methods...
1496 class C(object):
1497 def foo(*a): return a
1498 goo = staticmethod(foo)
1499 c = C()
1500 self.assertEqual(C.goo(1), (1,))
1501 self.assertEqual(c.goo(1), (1,))
1502 self.assertEqual(c.foo(1), (c, 1,))
1503 class D(C):
1504 pass
1505 d = D()
1506 self.assertEqual(D.goo(1), (1,))
1507 self.assertEqual(d.goo(1), (1,))
1508 self.assertEqual(d.foo(1), (d, 1))
1509 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001510 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001511 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001512 sm.x = 42
1513 self.assertEqual(sm.x, 42)
1514 self.assertEqual(sm.__dict__, {"x" : 42})
1515 del sm.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001516 self.assertNotHasAttr(sm, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001517
Benjamin Petersone549ead2009-03-28 21:42:05 +00001518 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001519 def test_staticmethods_in_c(self):
1520 # Testing C-based static methods...
1521 import xxsubtype as spam
1522 a = (1, 2, 3)
1523 d = {"abc": 123}
1524 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1525 self.assertEqual(x, None)
1526 self.assertEqual(a, a1)
1527 self.assertEqual(d, d1)
1528 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1529 self.assertEqual(x, None)
1530 self.assertEqual(a, a1)
1531 self.assertEqual(d, d1)
1532
1533 def test_classic(self):
1534 # Testing classic classes...
1535 class C:
1536 def foo(*a): return a
1537 goo = classmethod(foo)
1538 c = C()
1539 self.assertEqual(C.goo(1), (C, 1))
1540 self.assertEqual(c.goo(1), (C, 1))
1541 self.assertEqual(c.foo(1), (c, 1))
1542 class D(C):
1543 pass
1544 d = D()
1545 self.assertEqual(D.goo(1), (D, 1))
1546 self.assertEqual(d.goo(1), (D, 1))
1547 self.assertEqual(d.foo(1), (d, 1))
1548 self.assertEqual(D.foo(d, 1), (d, 1))
1549 class E: # *not* subclassing from C
1550 foo = C.foo
1551 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001552 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001553
1554 def test_compattr(self):
1555 # Testing computed attributes...
1556 class C(object):
1557 class computed_attribute(object):
1558 def __init__(self, get, set=None, delete=None):
1559 self.__get = get
1560 self.__set = set
1561 self.__delete = delete
1562 def __get__(self, obj, type=None):
1563 return self.__get(obj)
1564 def __set__(self, obj, value):
1565 return self.__set(obj, value)
1566 def __delete__(self, obj):
1567 return self.__delete(obj)
1568 def __init__(self):
1569 self.__x = 0
1570 def __get_x(self):
1571 x = self.__x
1572 self.__x = x+1
1573 return x
1574 def __set_x(self, x):
1575 self.__x = x
1576 def __delete_x(self):
1577 del self.__x
1578 x = computed_attribute(__get_x, __set_x, __delete_x)
1579 a = C()
1580 self.assertEqual(a.x, 0)
1581 self.assertEqual(a.x, 1)
1582 a.x = 10
1583 self.assertEqual(a.x, 10)
1584 self.assertEqual(a.x, 11)
1585 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001586 self.assertNotHasAttr(a, 'x')
Georg Brandl479a7e72008-02-05 18:13:15 +00001587
1588 def test_newslots(self):
1589 # Testing __new__ slot override...
1590 class C(list):
1591 def __new__(cls):
1592 self = list.__new__(cls)
1593 self.foo = 1
1594 return self
1595 def __init__(self):
1596 self.foo = self.foo + 2
1597 a = C()
1598 self.assertEqual(a.foo, 3)
1599 self.assertEqual(a.__class__, C)
1600 class D(C):
1601 pass
1602 b = D()
1603 self.assertEqual(b.foo, 3)
1604 self.assertEqual(b.__class__, D)
1605
1606 def test_altmro(self):
1607 # Testing mro() and overriding it...
1608 class A(object):
1609 def f(self): return "A"
1610 class B(A):
1611 pass
1612 class C(A):
1613 def f(self): return "C"
1614 class D(B, C):
1615 pass
1616 self.assertEqual(D.mro(), [D, B, C, A, object])
1617 self.assertEqual(D.__mro__, (D, B, C, A, object))
1618 self.assertEqual(D().f(), "C")
1619
1620 class PerverseMetaType(type):
1621 def mro(cls):
1622 L = type.mro(cls)
1623 L.reverse()
1624 return L
1625 class X(D,B,C,A, metaclass=PerverseMetaType):
1626 pass
1627 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1628 self.assertEqual(X().f(), "A")
1629
1630 try:
1631 class _metaclass(type):
1632 def mro(self):
1633 return [self, dict, object]
1634 class X(object, metaclass=_metaclass):
1635 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001636 # In CPython, the class creation above already raises
1637 # TypeError, as a protection against the fact that
1638 # instances of X would segfault it. In other Python
1639 # implementations it would be ok to let the class X
1640 # be created, but instead get a clean TypeError on the
1641 # __setitem__ below.
1642 x = object.__new__(X)
1643 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001644 except TypeError:
1645 pass
1646 else:
1647 self.fail("devious mro() return not caught")
1648
1649 try:
1650 class _metaclass(type):
1651 def mro(self):
1652 return [1]
1653 class X(object, metaclass=_metaclass):
1654 pass
1655 except TypeError:
1656 pass
1657 else:
1658 self.fail("non-class mro() return not caught")
1659
1660 try:
1661 class _metaclass(type):
1662 def mro(self):
1663 return 1
1664 class X(object, metaclass=_metaclass):
1665 pass
1666 except TypeError:
1667 pass
1668 else:
1669 self.fail("non-sequence mro() return not caught")
1670
1671 def test_overloading(self):
1672 # Testing operator overloading...
1673
1674 class B(object):
1675 "Intermediate class because object doesn't have a __setattr__"
1676
1677 class C(B):
1678 def __getattr__(self, name):
1679 if name == "foo":
1680 return ("getattr", name)
1681 else:
1682 raise AttributeError
1683 def __setattr__(self, name, value):
1684 if name == "foo":
1685 self.setattr = (name, value)
1686 else:
1687 return B.__setattr__(self, name, value)
1688 def __delattr__(self, name):
1689 if name == "foo":
1690 self.delattr = name
1691 else:
1692 return B.__delattr__(self, name)
1693
1694 def __getitem__(self, key):
1695 return ("getitem", key)
1696 def __setitem__(self, key, value):
1697 self.setitem = (key, value)
1698 def __delitem__(self, key):
1699 self.delitem = key
1700
1701 a = C()
1702 self.assertEqual(a.foo, ("getattr", "foo"))
1703 a.foo = 12
1704 self.assertEqual(a.setattr, ("foo", 12))
1705 del a.foo
1706 self.assertEqual(a.delattr, "foo")
1707
1708 self.assertEqual(a[12], ("getitem", 12))
1709 a[12] = 21
1710 self.assertEqual(a.setitem, (12, 21))
1711 del a[12]
1712 self.assertEqual(a.delitem, 12)
1713
1714 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1715 a[0:10] = "foo"
1716 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1717 del a[0:10]
1718 self.assertEqual(a.delitem, (slice(0, 10)))
1719
1720 def test_methods(self):
1721 # Testing methods...
1722 class C(object):
1723 def __init__(self, x):
1724 self.x = x
1725 def foo(self):
1726 return self.x
1727 c1 = C(1)
1728 self.assertEqual(c1.foo(), 1)
1729 class D(C):
1730 boo = C.foo
1731 goo = c1.foo
1732 d2 = D(2)
1733 self.assertEqual(d2.foo(), 2)
1734 self.assertEqual(d2.boo(), 2)
1735 self.assertEqual(d2.goo(), 1)
1736 class E(object):
1737 foo = C.foo
1738 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001739 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001740
Benjamin Peterson224205f2009-05-08 03:25:19 +00001741 def test_special_method_lookup(self):
1742 # The lookup of special methods bypasses __getattr__ and
1743 # __getattribute__, but they still can be descriptors.
1744
1745 def run_context(manager):
1746 with manager:
1747 pass
1748 def iden(self):
1749 return self
1750 def hello(self):
1751 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001752 def empty_seq(self):
1753 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001754 def zero(self):
1755 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001756 def complex_num(self):
1757 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001758 def stop(self):
1759 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001760 def return_true(self, thing=None):
1761 return True
1762 def do_isinstance(obj):
1763 return isinstance(int, obj)
1764 def do_issubclass(obj):
1765 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001766 def do_dict_missing(checker):
1767 class DictSub(checker.__class__, dict):
1768 pass
1769 self.assertEqual(DictSub()["hi"], 4)
1770 def some_number(self_, key):
1771 self.assertEqual(key, "hi")
1772 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001773 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001774 def format_impl(self, spec):
1775 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001776
1777 # It would be nice to have every special method tested here, but I'm
1778 # only listing the ones I can remember outside of typeobject.c, since it
1779 # does it right.
1780 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001781 ("__bytes__", bytes, hello, set(), {}),
1782 ("__reversed__", reversed, empty_seq, set(), {}),
1783 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001784 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001785 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1786 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001787 ("__missing__", do_dict_missing, some_number,
1788 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001789 ("__subclasscheck__", do_issubclass, return_true,
1790 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001791 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1792 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001793 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001794 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001795 ("__floor__", math.floor, zero, set(), {}),
1796 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001797 ("__trunc__", int, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001798 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001799 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001800 ]
1801
1802 class Checker(object):
1803 def __getattr__(self, attr, test=self):
1804 test.fail("__getattr__ called with {0}".format(attr))
1805 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001806 if attr not in ok:
1807 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001808 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001809 class SpecialDescr(object):
1810 def __init__(self, impl):
1811 self.impl = impl
1812 def __get__(self, obj, owner):
1813 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001814 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001815 class MyException(Exception):
1816 pass
1817 class ErrDescr(object):
1818 def __get__(self, obj, owner):
1819 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001820
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001821 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001822 class X(Checker):
1823 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001824 for attr, obj in env.items():
1825 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001826 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001827 runner(X())
1828
1829 record = []
1830 class X(Checker):
1831 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001832 for attr, obj in env.items():
1833 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001834 setattr(X, name, SpecialDescr(meth_impl))
1835 runner(X())
1836 self.assertEqual(record, [1], name)
1837
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001838 class X(Checker):
1839 pass
1840 for attr, obj in env.items():
1841 setattr(X, attr, obj)
1842 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001843 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001844
Georg Brandl479a7e72008-02-05 18:13:15 +00001845 def test_specials(self):
1846 # Testing special operators...
1847 # Test operators like __hash__ for which a built-in default exists
1848
1849 # Test the default behavior for static classes
1850 class C(object):
1851 def __getitem__(self, i):
1852 if 0 <= i < 10: return i
1853 raise IndexError
1854 c1 = C()
1855 c2 = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001856 self.assertFalse(not c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001857 self.assertNotEqual(id(c1), id(c2))
1858 hash(c1)
1859 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001860 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001861 self.assertTrue(c1 != c2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001862 self.assertFalse(c1 != c1)
1863 self.assertFalse(c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001864 # Note that the module name appears in str/repr, and that varies
1865 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001866 self.assertGreaterEqual(str(c1).find('C object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001867 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001868 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001869 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001870 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001871 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001872 # Test the default behavior for dynamic classes
1873 class D(object):
1874 def __getitem__(self, i):
1875 if 0 <= i < 10: return i
1876 raise IndexError
1877 d1 = D()
1878 d2 = D()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001879 self.assertFalse(not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001880 self.assertNotEqual(id(d1), id(d2))
1881 hash(d1)
1882 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001883 self.assertEqual(d1, d1)
1884 self.assertNotEqual(d1, d2)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001885 self.assertFalse(d1 != d1)
1886 self.assertFalse(d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001887 # Note that the module name appears in str/repr, and that varies
1888 # depending on whether this test is run standalone or from a framework.
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001889 self.assertGreaterEqual(str(d1).find('D object at '), 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001890 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001891 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001892 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001893 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001894 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001895 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001896 class Proxy(object):
1897 def __init__(self, x):
1898 self.x = x
1899 def __bool__(self):
1900 return not not self.x
1901 def __hash__(self):
1902 return hash(self.x)
1903 def __eq__(self, other):
1904 return self.x == other
1905 def __ne__(self, other):
1906 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001907 def __ge__(self, other):
1908 return self.x >= other
1909 def __gt__(self, other):
1910 return self.x > other
1911 def __le__(self, other):
1912 return self.x <= other
1913 def __lt__(self, other):
1914 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001915 def __str__(self):
1916 return "Proxy:%s" % self.x
1917 def __repr__(self):
1918 return "Proxy(%r)" % self.x
1919 def __contains__(self, value):
1920 return value in self.x
1921 p0 = Proxy(0)
1922 p1 = Proxy(1)
1923 p_1 = Proxy(-1)
1924 self.assertFalse(p0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001925 self.assertFalse(not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001926 self.assertEqual(hash(p0), hash(0))
1927 self.assertEqual(p0, p0)
1928 self.assertNotEqual(p0, p1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001929 self.assertFalse(p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001930 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001931 self.assertTrue(p0 < p1)
1932 self.assertTrue(p0 <= p1)
1933 self.assertTrue(p1 > p0)
1934 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001935 self.assertEqual(str(p0), "Proxy:0")
1936 self.assertEqual(repr(p0), "Proxy(0)")
1937 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001938 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001939 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001940 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001941 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001942
Georg Brandl479a7e72008-02-05 18:13:15 +00001943 def test_weakrefs(self):
1944 # Testing weak references...
1945 import weakref
1946 class C(object):
1947 pass
1948 c = C()
1949 r = weakref.ref(c)
1950 self.assertEqual(r(), c)
1951 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001952 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001953 self.assertEqual(r(), None)
1954 del r
1955 class NoWeak(object):
1956 __slots__ = ['foo']
1957 no = NoWeak()
1958 try:
1959 weakref.ref(no)
1960 except TypeError as msg:
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001961 self.assertIn("weak reference", str(msg))
Georg Brandl479a7e72008-02-05 18:13:15 +00001962 else:
1963 self.fail("weakref.ref(no) should be illegal")
1964 class Weak(object):
1965 __slots__ = ['foo', '__weakref__']
1966 yes = Weak()
1967 r = weakref.ref(yes)
1968 self.assertEqual(r(), yes)
1969 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001970 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001971 self.assertEqual(r(), None)
1972 del r
1973
1974 def test_properties(self):
1975 # Testing property...
1976 class C(object):
1977 def getx(self):
1978 return self.__x
1979 def setx(self, value):
1980 self.__x = value
1981 def delx(self):
1982 del self.__x
1983 x = property(getx, setx, delx, doc="I'm the x property.")
1984 a = C()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001985 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001986 a.x = 42
1987 self.assertEqual(a._C__x, 42)
1988 self.assertEqual(a.x, 42)
1989 del a.x
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001990 self.assertNotHasAttr(a, "x")
1991 self.assertNotHasAttr(a, "_C__x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001992 C.x.__set__(a, 100)
1993 self.assertEqual(C.x.__get__(a), 100)
1994 C.x.__delete__(a)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02001995 self.assertNotHasAttr(a, "x")
Georg Brandl479a7e72008-02-05 18:13:15 +00001996
1997 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001998 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001999
2000 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002001 self.assertIn("__doc__", attrs)
2002 self.assertIn("fget", attrs)
2003 self.assertIn("fset", attrs)
2004 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00002005
2006 self.assertEqual(raw.__doc__, "I'm the x property.")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002007 self.assertIs(raw.fget, C.__dict__['getx'])
2008 self.assertIs(raw.fset, C.__dict__['setx'])
2009 self.assertIs(raw.fdel, C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00002010
2011 for attr in "__doc__", "fget", "fset", "fdel":
2012 try:
2013 setattr(raw, attr, 42)
2014 except AttributeError as msg:
2015 if str(msg).find('readonly') < 0:
2016 self.fail("when setting readonly attr %r on a property, "
2017 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2018 else:
2019 self.fail("expected AttributeError from trying to set readonly %r "
2020 "attr on a property" % attr)
2021
2022 class D(object):
2023 __getitem__ = property(lambda s: 1/0)
2024
2025 d = D()
2026 try:
2027 for i in d:
2028 str(i)
2029 except ZeroDivisionError:
2030 pass
2031 else:
2032 self.fail("expected ZeroDivisionError from bad property")
2033
R. David Murray378c0cf2010-02-24 01:46:21 +00002034 @unittest.skipIf(sys.flags.optimize >= 2,
2035 "Docstrings are omitted with -O2 and above")
2036 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002037 class E(object):
2038 def getter(self):
2039 "getter method"
2040 return 0
2041 def setter(self_, value):
2042 "setter method"
2043 pass
2044 prop = property(getter)
2045 self.assertEqual(prop.__doc__, "getter method")
2046 prop2 = property(fset=setter)
2047 self.assertEqual(prop2.__doc__, None)
2048
R. David Murray378c0cf2010-02-24 01:46:21 +00002049 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002050 # this segfaulted in 2.5b2
2051 try:
2052 import _testcapi
2053 except ImportError:
2054 pass
2055 else:
2056 class X(object):
2057 p = property(_testcapi.test_with_docstring)
2058
2059 def test_properties_plus(self):
2060 class C(object):
2061 foo = property(doc="hello")
2062 @foo.getter
2063 def foo(self):
2064 return self._foo
2065 @foo.setter
2066 def foo(self, value):
2067 self._foo = abs(value)
2068 @foo.deleter
2069 def foo(self):
2070 del self._foo
2071 c = C()
2072 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002073 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002074 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002075 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002076 self.assertEqual(c._foo, 42)
2077 self.assertEqual(c.foo, 42)
2078 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002079 self.assertNotHasAttr(c, '_foo')
2080 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002081
2082 class D(C):
2083 @C.foo.deleter
2084 def foo(self):
2085 try:
2086 del self._foo
2087 except AttributeError:
2088 pass
2089 d = D()
2090 d.foo = 24
2091 self.assertEqual(d.foo, 24)
2092 del d.foo
2093 del d.foo
2094
2095 class E(object):
2096 @property
2097 def foo(self):
2098 return self._foo
2099 @foo.setter
2100 def foo(self, value):
2101 raise RuntimeError
2102 @foo.setter
2103 def foo(self, value):
2104 self._foo = abs(value)
2105 @foo.deleter
2106 def foo(self, value=None):
2107 del self._foo
2108
2109 e = E()
2110 e.foo = -42
2111 self.assertEqual(e.foo, 42)
2112 del e.foo
2113
2114 class F(E):
2115 @E.foo.deleter
2116 def foo(self):
2117 del self._foo
2118 @foo.setter
2119 def foo(self, value):
2120 self._foo = max(0, value)
2121 f = F()
2122 f.foo = -10
2123 self.assertEqual(f.foo, 0)
2124 del f.foo
2125
2126 def test_dict_constructors(self):
2127 # Testing dict constructor ...
2128 d = dict()
2129 self.assertEqual(d, {})
2130 d = dict({})
2131 self.assertEqual(d, {})
2132 d = dict({1: 2, 'a': 'b'})
2133 self.assertEqual(d, {1: 2, 'a': 'b'})
2134 self.assertEqual(d, dict(list(d.items())))
2135 self.assertEqual(d, dict(iter(d.items())))
2136 d = dict({'one':1, 'two':2})
2137 self.assertEqual(d, dict(one=1, two=2))
2138 self.assertEqual(d, dict(**d))
2139 self.assertEqual(d, dict({"one": 1}, two=2))
2140 self.assertEqual(d, dict([("two", 2)], one=1))
2141 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2142 self.assertEqual(d, dict(**d))
2143
2144 for badarg in 0, 0, 0j, "0", [0], (0,):
2145 try:
2146 dict(badarg)
2147 except TypeError:
2148 pass
2149 except ValueError:
2150 if badarg == "0":
2151 # It's a sequence, and its elements are also sequences (gotta
2152 # love strings <wink>), but they aren't of length 2, so this
2153 # one seemed better as a ValueError than a TypeError.
2154 pass
2155 else:
2156 self.fail("no TypeError from dict(%r)" % badarg)
2157 else:
2158 self.fail("no TypeError from dict(%r)" % badarg)
2159
2160 try:
2161 dict({}, {})
2162 except TypeError:
2163 pass
2164 else:
2165 self.fail("no TypeError from dict({}, {})")
2166
2167 class Mapping:
2168 # Lacks a .keys() method; will be added later.
2169 dict = {1:2, 3:4, 'a':1j}
2170
2171 try:
2172 dict(Mapping())
2173 except TypeError:
2174 pass
2175 else:
2176 self.fail("no TypeError from dict(incomplete mapping)")
2177
2178 Mapping.keys = lambda self: list(self.dict.keys())
2179 Mapping.__getitem__ = lambda self, i: self.dict[i]
2180 d = dict(Mapping())
2181 self.assertEqual(d, Mapping.dict)
2182
2183 # Init from sequence of iterable objects, each producing a 2-sequence.
2184 class AddressBookEntry:
2185 def __init__(self, first, last):
2186 self.first = first
2187 self.last = last
2188 def __iter__(self):
2189 return iter([self.first, self.last])
2190
2191 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2192 AddressBookEntry('Barry', 'Peters'),
2193 AddressBookEntry('Tim', 'Peters'),
2194 AddressBookEntry('Barry', 'Warsaw')])
2195 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2196
2197 d = dict(zip(range(4), range(1, 5)))
2198 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2199
2200 # Bad sequence lengths.
2201 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2202 try:
2203 dict(bad)
2204 except ValueError:
2205 pass
2206 else:
2207 self.fail("no ValueError from dict(%r)" % bad)
2208
2209 def test_dir(self):
2210 # Testing dir() ...
2211 junk = 12
2212 self.assertEqual(dir(), ['junk', 'self'])
2213 del junk
2214
2215 # Just make sure these don't blow up!
2216 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2217 dir(arg)
2218
2219 # Test dir on new-style classes. Since these have object as a
2220 # base class, a lot more gets sucked in.
2221 def interesting(strings):
2222 return [s for s in strings if not s.startswith('_')]
2223
2224 class C(object):
2225 Cdata = 1
2226 def Cmethod(self): pass
2227
2228 cstuff = ['Cdata', 'Cmethod']
2229 self.assertEqual(interesting(dir(C)), cstuff)
2230
2231 c = C()
2232 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002233 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002234
2235 c.cdata = 2
2236 c.cmethod = lambda self: 0
2237 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002238 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002239
2240 class A(C):
2241 Adata = 1
2242 def Amethod(self): pass
2243
2244 astuff = ['Adata', 'Amethod'] + cstuff
2245 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002246 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002247 a = A()
2248 self.assertEqual(interesting(dir(a)), astuff)
2249 a.adata = 42
2250 a.amethod = lambda self: 3
2251 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002252 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002253
2254 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002255 class M(type(sys)):
2256 pass
2257 minstance = M("m")
2258 minstance.b = 2
2259 minstance.a = 1
2260 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2261 self.assertEqual(names, ['a', 'b'])
2262
2263 class M2(M):
2264 def getdict(self):
2265 return "Not a dict!"
2266 __dict__ = property(getdict)
2267
2268 m2instance = M2("m2")
2269 m2instance.b = 2
2270 m2instance.a = 1
2271 self.assertEqual(m2instance.__dict__, "Not a dict!")
2272 try:
2273 dir(m2instance)
2274 except TypeError:
2275 pass
2276
2277 # Two essentially featureless objects, just inheriting stuff from
2278 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002279 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002280
2281 # Nasty test case for proxied objects
2282 class Wrapper(object):
2283 def __init__(self, obj):
2284 self.__obj = obj
2285 def __repr__(self):
2286 return "Wrapper(%s)" % repr(self.__obj)
2287 def __getitem__(self, key):
2288 return Wrapper(self.__obj[key])
2289 def __len__(self):
2290 return len(self.__obj)
2291 def __getattr__(self, name):
2292 return Wrapper(getattr(self.__obj, name))
2293
2294 class C(object):
2295 def __getclass(self):
2296 return Wrapper(type(self))
2297 __class__ = property(__getclass)
2298
2299 dir(C()) # This used to segfault
2300
2301 def test_supers(self):
2302 # Testing super...
2303
2304 class A(object):
2305 def meth(self, a):
2306 return "A(%r)" % a
2307
2308 self.assertEqual(A().meth(1), "A(1)")
2309
2310 class B(A):
2311 def __init__(self):
2312 self.__super = super(B, self)
2313 def meth(self, a):
2314 return "B(%r)" % a + self.__super.meth(a)
2315
2316 self.assertEqual(B().meth(2), "B(2)A(2)")
2317
2318 class C(A):
2319 def meth(self, a):
2320 return "C(%r)" % a + self.__super.meth(a)
2321 C._C__super = super(C)
2322
2323 self.assertEqual(C().meth(3), "C(3)A(3)")
2324
2325 class D(C, B):
2326 def meth(self, a):
2327 return "D(%r)" % a + super(D, self).meth(a)
2328
2329 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2330
2331 # Test for subclassing super
2332
2333 class mysuper(super):
2334 def __init__(self, *args):
2335 return super(mysuper, self).__init__(*args)
2336
2337 class E(D):
2338 def meth(self, a):
2339 return "E(%r)" % a + mysuper(E, self).meth(a)
2340
2341 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2342
2343 class F(E):
2344 def meth(self, a):
2345 s = self.__super # == mysuper(F, self)
2346 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2347 F._F__super = mysuper(F)
2348
2349 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2350
2351 # Make sure certain errors are raised
2352
2353 try:
2354 super(D, 42)
2355 except TypeError:
2356 pass
2357 else:
2358 self.fail("shouldn't allow super(D, 42)")
2359
2360 try:
2361 super(D, C())
2362 except TypeError:
2363 pass
2364 else:
2365 self.fail("shouldn't allow super(D, C())")
2366
2367 try:
2368 super(D).__get__(12)
2369 except TypeError:
2370 pass
2371 else:
2372 self.fail("shouldn't allow super(D).__get__(12)")
2373
2374 try:
2375 super(D).__get__(C())
2376 except TypeError:
2377 pass
2378 else:
2379 self.fail("shouldn't allow super(D).__get__(C())")
2380
2381 # Make sure data descriptors can be overridden and accessed via super
2382 # (new feature in Python 2.3)
2383
2384 class DDbase(object):
2385 def getx(self): return 42
2386 x = property(getx)
2387
2388 class DDsub(DDbase):
2389 def getx(self): return "hello"
2390 x = property(getx)
2391
2392 dd = DDsub()
2393 self.assertEqual(dd.x, "hello")
2394 self.assertEqual(super(DDsub, dd).x, 42)
2395
2396 # Ensure that super() lookup of descriptor from classmethod
2397 # works (SF ID# 743627)
2398
2399 class Base(object):
2400 aProp = property(lambda self: "foo")
2401
2402 class Sub(Base):
2403 @classmethod
2404 def test(klass):
2405 return super(Sub,klass).aProp
2406
2407 self.assertEqual(Sub.test(), Base.aProp)
2408
2409 # Verify that super() doesn't allow keyword args
2410 try:
2411 super(Base, kw=1)
2412 except TypeError:
2413 pass
2414 else:
2415 self.assertEqual("super shouldn't accept keyword args")
2416
2417 def test_basic_inheritance(self):
2418 # Testing inheritance from basic types...
2419
2420 class hexint(int):
2421 def __repr__(self):
2422 return hex(self)
2423 def __add__(self, other):
2424 return hexint(int.__add__(self, other))
2425 # (Note that overriding __radd__ doesn't work,
2426 # because the int type gets first dibs.)
2427 self.assertEqual(repr(hexint(7) + 9), "0x10")
2428 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2429 a = hexint(12345)
2430 self.assertEqual(a, 12345)
2431 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002432 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002433 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002434 self.assertIs((+a).__class__, int)
2435 self.assertIs((a >> 0).__class__, int)
2436 self.assertIs((a << 0).__class__, int)
2437 self.assertIs((hexint(0) << 12).__class__, int)
2438 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439
2440 class octlong(int):
2441 __slots__ = []
2442 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002443 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002444 def __add__(self, other):
2445 return self.__class__(super(octlong, self).__add__(other))
2446 __radd__ = __add__
2447 self.assertEqual(str(octlong(3) + 5), "0o10")
2448 # (Note that overriding __radd__ here only seems to work
2449 # because the example uses a short int left argument.)
2450 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2451 a = octlong(12345)
2452 self.assertEqual(a, 12345)
2453 self.assertEqual(int(a), 12345)
2454 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002455 self.assertIs(int(a).__class__, int)
2456 self.assertIs((+a).__class__, int)
2457 self.assertIs((-a).__class__, int)
2458 self.assertIs((-octlong(0)).__class__, int)
2459 self.assertIs((a >> 0).__class__, int)
2460 self.assertIs((a << 0).__class__, int)
2461 self.assertIs((a - 0).__class__, int)
2462 self.assertIs((a * 1).__class__, int)
2463 self.assertIs((a ** 1).__class__, int)
2464 self.assertIs((a // 1).__class__, int)
2465 self.assertIs((1 * a).__class__, int)
2466 self.assertIs((a | 0).__class__, int)
2467 self.assertIs((a ^ 0).__class__, int)
2468 self.assertIs((a & -1).__class__, int)
2469 self.assertIs((octlong(0) << 12).__class__, int)
2470 self.assertIs((octlong(0) >> 12).__class__, int)
2471 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002472
2473 # Because octlong overrides __add__, we can't check the absence of +0
2474 # optimizations using octlong.
2475 class longclone(int):
2476 pass
2477 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002478 self.assertIs((a + 0).__class__, int)
2479 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002480
2481 # Check that negative clones don't segfault
2482 a = longclone(-1)
2483 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002484 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002485
2486 class precfloat(float):
2487 __slots__ = ['prec']
2488 def __init__(self, value=0.0, prec=12):
2489 self.prec = int(prec)
2490 def __repr__(self):
2491 return "%.*g" % (self.prec, self)
2492 self.assertEqual(repr(precfloat(1.1)), "1.1")
2493 a = precfloat(12345)
2494 self.assertEqual(a, 12345.0)
2495 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002496 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002497 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002498 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002499
2500 class madcomplex(complex):
2501 def __repr__(self):
2502 return "%.17gj%+.17g" % (self.imag, self.real)
2503 a = madcomplex(-3, 4)
2504 self.assertEqual(repr(a), "4j-3")
2505 base = complex(-3, 4)
2506 self.assertEqual(base.__class__, complex)
2507 self.assertEqual(a, base)
2508 self.assertEqual(complex(a), base)
2509 self.assertEqual(complex(a).__class__, complex)
2510 a = madcomplex(a) # just trying another form of the constructor
2511 self.assertEqual(repr(a), "4j-3")
2512 self.assertEqual(a, base)
2513 self.assertEqual(complex(a), base)
2514 self.assertEqual(complex(a).__class__, complex)
2515 self.assertEqual(hash(a), hash(base))
2516 self.assertEqual((+a).__class__, complex)
2517 self.assertEqual((a + 0).__class__, complex)
2518 self.assertEqual(a + 0, base)
2519 self.assertEqual((a - 0).__class__, complex)
2520 self.assertEqual(a - 0, base)
2521 self.assertEqual((a * 1).__class__, complex)
2522 self.assertEqual(a * 1, base)
2523 self.assertEqual((a / 1).__class__, complex)
2524 self.assertEqual(a / 1, base)
2525
2526 class madtuple(tuple):
2527 _rev = None
2528 def rev(self):
2529 if self._rev is not None:
2530 return self._rev
2531 L = list(self)
2532 L.reverse()
2533 self._rev = self.__class__(L)
2534 return self._rev
2535 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2536 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2537 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2538 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2539 for i in range(512):
2540 t = madtuple(range(i))
2541 u = t.rev()
2542 v = u.rev()
2543 self.assertEqual(v, t)
2544 a = madtuple((1,2,3,4,5))
2545 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002546 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002547 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002548 self.assertIs(a[:].__class__, tuple)
2549 self.assertIs((a * 1).__class__, tuple)
2550 self.assertIs((a * 0).__class__, tuple)
2551 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002552 a = madtuple(())
2553 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002554 self.assertIs(tuple(a).__class__, tuple)
2555 self.assertIs((a + a).__class__, tuple)
2556 self.assertIs((a * 0).__class__, tuple)
2557 self.assertIs((a * 1).__class__, tuple)
2558 self.assertIs((a * 2).__class__, tuple)
2559 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002560
2561 class madstring(str):
2562 _rev = None
2563 def rev(self):
2564 if self._rev is not None:
2565 return self._rev
2566 L = list(self)
2567 L.reverse()
2568 self._rev = self.__class__("".join(L))
2569 return self._rev
2570 s = madstring("abcdefghijklmnopqrstuvwxyz")
2571 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2572 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2573 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2574 for i in range(256):
2575 s = madstring("".join(map(chr, range(i))))
2576 t = s.rev()
2577 u = t.rev()
2578 self.assertEqual(u, s)
2579 s = madstring("12345")
2580 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002581 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582
2583 base = "\x00" * 5
2584 s = madstring(base)
2585 self.assertEqual(s, base)
2586 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002587 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002588 self.assertEqual(hash(s), hash(base))
2589 self.assertEqual({s: 1}[base], 1)
2590 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002591 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002592 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002593 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002594 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002595 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002596 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002597 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002598 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002599 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002600 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002601 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002602 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002603 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002604 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002605 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002606 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002607 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002608 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002609 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002610 self.assertEqual(s.rstrip(), base)
2611 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002612 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002613 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002614 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002615 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002616 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002618 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002619 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002620 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002622 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002623 self.assertEqual(s.lower(), base)
2624
2625 class madunicode(str):
2626 _rev = None
2627 def rev(self):
2628 if self._rev is not None:
2629 return self._rev
2630 L = list(self)
2631 L.reverse()
2632 self._rev = self.__class__("".join(L))
2633 return self._rev
2634 u = madunicode("ABCDEF")
2635 self.assertEqual(u, "ABCDEF")
2636 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2637 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2638 base = "12345"
2639 u = madunicode(base)
2640 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002641 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002642 self.assertEqual(hash(u), hash(base))
2643 self.assertEqual({u: 1}[base], 1)
2644 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002645 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002646 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002647 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002649 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002651 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002652 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002653 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002654 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002655 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002656 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002657 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002658 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002659 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002660 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002661 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002662 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002663 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002664 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002665 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002666 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002667 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002668 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002669 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002670 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002671 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002672 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002673 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002674 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002675 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002676 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002677 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002678 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002679 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002680 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002681 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002682 self.assertEqual(u[0:0], "")
2683
2684 class sublist(list):
2685 pass
2686 a = sublist(range(5))
2687 self.assertEqual(a, list(range(5)))
2688 a.append("hello")
2689 self.assertEqual(a, list(range(5)) + ["hello"])
2690 a[5] = 5
2691 self.assertEqual(a, list(range(6)))
2692 a.extend(range(6, 20))
2693 self.assertEqual(a, list(range(20)))
2694 a[-5:] = []
2695 self.assertEqual(a, list(range(15)))
2696 del a[10:15]
2697 self.assertEqual(len(a), 10)
2698 self.assertEqual(a, list(range(10)))
2699 self.assertEqual(list(a), list(range(10)))
2700 self.assertEqual(a[0], 0)
2701 self.assertEqual(a[9], 9)
2702 self.assertEqual(a[-10], 0)
2703 self.assertEqual(a[-1], 9)
2704 self.assertEqual(a[:5], list(range(5)))
2705
2706 ## class CountedInput(file):
2707 ## """Counts lines read by self.readline().
2708 ##
2709 ## self.lineno is the 0-based ordinal of the last line read, up to
2710 ## a maximum of one greater than the number of lines in the file.
2711 ##
2712 ## self.ateof is true if and only if the final "" line has been read,
2713 ## at which point self.lineno stops incrementing, and further calls
2714 ## to readline() continue to return "".
2715 ## """
2716 ##
2717 ## lineno = 0
2718 ## ateof = 0
2719 ## def readline(self):
2720 ## if self.ateof:
2721 ## return ""
2722 ## s = file.readline(self)
2723 ## # Next line works too.
2724 ## # s = super(CountedInput, self).readline()
2725 ## self.lineno += 1
2726 ## if s == "":
2727 ## self.ateof = 1
2728 ## return s
2729 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002730 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002731 ## lines = ['a\n', 'b\n', 'c\n']
2732 ## try:
2733 ## f.writelines(lines)
2734 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002735 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002736 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2737 ## got = f.readline()
2738 ## self.assertEqual(expected, got)
2739 ## self.assertEqual(f.lineno, i)
2740 ## self.assertEqual(f.ateof, (i > len(lines)))
2741 ## f.close()
2742 ## finally:
2743 ## try:
2744 ## f.close()
2745 ## except:
2746 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002747 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002748
2749 def test_keywords(self):
2750 # Testing keyword args to basic type constructors ...
2751 self.assertEqual(int(x=1), 1)
2752 self.assertEqual(float(x=2), 2.0)
2753 self.assertEqual(int(x=3), 3)
2754 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2755 self.assertEqual(str(object=500), '500')
2756 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2757 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2758 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2759 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2760
2761 for constructor in (int, float, int, complex, str, str,
2762 tuple, list):
2763 try:
2764 constructor(bogus_keyword_arg=1)
2765 except TypeError:
2766 pass
2767 else:
2768 self.fail("expected TypeError from bogus keyword argument to %r"
2769 % constructor)
2770
2771 def test_str_subclass_as_dict_key(self):
2772 # Testing a str subclass used as dict key ..
2773
2774 class cistr(str):
2775 """Sublcass of str that computes __eq__ case-insensitively.
2776
2777 Also computes a hash code of the string in canonical form.
2778 """
2779
2780 def __init__(self, value):
2781 self.canonical = value.lower()
2782 self.hashcode = hash(self.canonical)
2783
2784 def __eq__(self, other):
2785 if not isinstance(other, cistr):
2786 other = cistr(other)
2787 return self.canonical == other.canonical
2788
2789 def __hash__(self):
2790 return self.hashcode
2791
2792 self.assertEqual(cistr('ABC'), 'abc')
2793 self.assertEqual('aBc', cistr('ABC'))
2794 self.assertEqual(str(cistr('ABC')), 'ABC')
2795
2796 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2797 self.assertEqual(d[cistr('one')], 1)
2798 self.assertEqual(d[cistr('tWo')], 2)
2799 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002800 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002801 self.assertEqual(d.get(cistr('thrEE')), 3)
2802
2803 def test_classic_comparisons(self):
2804 # Testing classic comparisons...
2805 class classic:
2806 pass
2807
2808 for base in (classic, int, object):
2809 class C(base):
2810 def __init__(self, value):
2811 self.value = int(value)
2812 def __eq__(self, other):
2813 if isinstance(other, C):
2814 return self.value == other.value
2815 if isinstance(other, int) or isinstance(other, int):
2816 return self.value == other
2817 return NotImplemented
2818 def __ne__(self, other):
2819 if isinstance(other, C):
2820 return self.value != other.value
2821 if isinstance(other, int) or isinstance(other, int):
2822 return self.value != other
2823 return NotImplemented
2824 def __lt__(self, other):
2825 if isinstance(other, C):
2826 return self.value < other.value
2827 if isinstance(other, int) or isinstance(other, int):
2828 return self.value < other
2829 return NotImplemented
2830 def __le__(self, other):
2831 if isinstance(other, C):
2832 return self.value <= other.value
2833 if isinstance(other, int) or isinstance(other, int):
2834 return self.value <= other
2835 return NotImplemented
2836 def __gt__(self, other):
2837 if isinstance(other, C):
2838 return self.value > other.value
2839 if isinstance(other, int) or isinstance(other, int):
2840 return self.value > other
2841 return NotImplemented
2842 def __ge__(self, other):
2843 if isinstance(other, C):
2844 return self.value >= other.value
2845 if isinstance(other, int) or isinstance(other, int):
2846 return self.value >= other
2847 return NotImplemented
2848
2849 c1 = C(1)
2850 c2 = C(2)
2851 c3 = C(3)
2852 self.assertEqual(c1, 1)
2853 c = {1: c1, 2: c2, 3: c3}
2854 for x in 1, 2, 3:
2855 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002856 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002857 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002858 eval("x %s y" % op),
2859 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002860 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002861 eval("x %s y" % op),
2862 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002863 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002864 eval("x %s y" % op),
2865 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002866
2867 def test_rich_comparisons(self):
2868 # Testing rich comparisons...
2869 class Z(complex):
2870 pass
2871 z = Z(1)
2872 self.assertEqual(z, 1+0j)
2873 self.assertEqual(1+0j, z)
2874 class ZZ(complex):
2875 def __eq__(self, other):
2876 try:
2877 return abs(self - other) <= 1e-6
2878 except:
2879 return NotImplemented
2880 zz = ZZ(1.0000003)
2881 self.assertEqual(zz, 1+0j)
2882 self.assertEqual(1+0j, zz)
2883
2884 class classic:
2885 pass
2886 for base in (classic, int, object, list):
2887 class C(base):
2888 def __init__(self, value):
2889 self.value = int(value)
2890 def __cmp__(self_, other):
2891 self.fail("shouldn't call __cmp__")
2892 def __eq__(self, other):
2893 if isinstance(other, C):
2894 return self.value == other.value
2895 if isinstance(other, int) or isinstance(other, int):
2896 return self.value == other
2897 return NotImplemented
2898 def __ne__(self, other):
2899 if isinstance(other, C):
2900 return self.value != other.value
2901 if isinstance(other, int) or isinstance(other, int):
2902 return self.value != other
2903 return NotImplemented
2904 def __lt__(self, other):
2905 if isinstance(other, C):
2906 return self.value < other.value
2907 if isinstance(other, int) or isinstance(other, int):
2908 return self.value < other
2909 return NotImplemented
2910 def __le__(self, other):
2911 if isinstance(other, C):
2912 return self.value <= other.value
2913 if isinstance(other, int) or isinstance(other, int):
2914 return self.value <= other
2915 return NotImplemented
2916 def __gt__(self, other):
2917 if isinstance(other, C):
2918 return self.value > other.value
2919 if isinstance(other, int) or isinstance(other, int):
2920 return self.value > other
2921 return NotImplemented
2922 def __ge__(self, other):
2923 if isinstance(other, C):
2924 return self.value >= other.value
2925 if isinstance(other, int) or isinstance(other, int):
2926 return self.value >= other
2927 return NotImplemented
2928 c1 = C(1)
2929 c2 = C(2)
2930 c3 = C(3)
2931 self.assertEqual(c1, 1)
2932 c = {1: c1, 2: c2, 3: c3}
2933 for x in 1, 2, 3:
2934 for y in 1, 2, 3:
2935 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002936 self.assertEqual(eval("c[x] %s c[y]" % op),
2937 eval("x %s y" % op),
2938 "x=%d, y=%d" % (x, y))
2939 self.assertEqual(eval("c[x] %s y" % op),
2940 eval("x %s y" % op),
2941 "x=%d, y=%d" % (x, y))
2942 self.assertEqual(eval("x %s c[y]" % op),
2943 eval("x %s y" % op),
2944 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002945
2946 def test_descrdoc(self):
2947 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002948 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002949 def check(descr, what):
2950 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002951 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002952 check(complex.real, "the real part of a complex number") # member descriptor
2953
2954 def test_doc_descriptor(self):
2955 # Testing __doc__ descriptor...
2956 # SF bug 542984
2957 class DocDescr(object):
2958 def __get__(self, object, otype):
2959 if object:
2960 object = object.__class__.__name__ + ' instance'
2961 if otype:
2962 otype = otype.__name__
2963 return 'object=%s; type=%s' % (object, otype)
2964 class OldClass:
2965 __doc__ = DocDescr()
2966 class NewClass(object):
2967 __doc__ = DocDescr()
2968 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2969 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2970 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2971 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2972
2973 def test_set_class(self):
2974 # Testing __class__ assignment...
2975 class C(object): pass
2976 class D(object): pass
2977 class E(object): pass
2978 class F(D, E): pass
2979 for cls in C, D, E, F:
2980 for cls2 in C, D, E, F:
2981 x = cls()
2982 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002983 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002984 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002985 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002986 def cant(x, C):
2987 try:
2988 x.__class__ = C
2989 except TypeError:
2990 pass
2991 else:
2992 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2993 try:
2994 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002995 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002996 pass
2997 else:
2998 self.fail("shouldn't allow del %r.__class__" % x)
2999 cant(C(), list)
3000 cant(list(), C)
3001 cant(C(), 1)
3002 cant(C(), object)
3003 cant(object(), list)
3004 cant(list(), object)
3005 class Int(int): __slots__ = []
3006 cant(2, Int)
3007 cant(Int(), int)
3008 cant(True, int)
3009 cant(2, bool)
3010 o = object()
3011 cant(o, type(1))
3012 cant(o, type(None))
3013 del o
3014 class G(object):
3015 __slots__ = ["a", "b"]
3016 class H(object):
3017 __slots__ = ["b", "a"]
3018 class I(object):
3019 __slots__ = ["a", "b"]
3020 class J(object):
3021 __slots__ = ["c", "b"]
3022 class K(object):
3023 __slots__ = ["a", "b", "d"]
3024 class L(H):
3025 __slots__ = ["e"]
3026 class M(I):
3027 __slots__ = ["e"]
3028 class N(J):
3029 __slots__ = ["__weakref__"]
3030 class P(J):
3031 __slots__ = ["__dict__"]
3032 class Q(J):
3033 pass
3034 class R(J):
3035 __slots__ = ["__dict__", "__weakref__"]
3036
3037 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3038 x = cls()
3039 x.a = 1
3040 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003041 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003042 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3043 self.assertEqual(x.a, 1)
3044 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003045 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003046 "assigning %r as __class__ for %r silently failed" % (cls, x))
3047 self.assertEqual(x.a, 1)
3048 for cls in G, J, K, L, M, N, P, R, list, Int:
3049 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3050 if cls is cls2:
3051 continue
3052 cant(cls(), cls2)
3053
Benjamin Peterson193152c2009-04-25 01:08:45 +00003054 # Issue5283: when __class__ changes in __del__, the wrong
3055 # type gets DECREF'd.
3056 class O(object):
3057 pass
3058 class A(object):
3059 def __del__(self):
3060 self.__class__ = O
3061 l = [A() for x in range(100)]
3062 del l
3063
Georg Brandl479a7e72008-02-05 18:13:15 +00003064 def test_set_dict(self):
3065 # Testing __dict__ assignment...
3066 class C(object): pass
3067 a = C()
3068 a.__dict__ = {'b': 1}
3069 self.assertEqual(a.b, 1)
3070 def cant(x, dict):
3071 try:
3072 x.__dict__ = dict
3073 except (AttributeError, TypeError):
3074 pass
3075 else:
3076 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3077 cant(a, None)
3078 cant(a, [])
3079 cant(a, 1)
3080 del a.__dict__ # Deleting __dict__ is allowed
3081
3082 class Base(object):
3083 pass
3084 def verify_dict_readonly(x):
3085 """
3086 x has to be an instance of a class inheriting from Base.
3087 """
3088 cant(x, {})
3089 try:
3090 del x.__dict__
3091 except (AttributeError, TypeError):
3092 pass
3093 else:
3094 self.fail("shouldn't allow del %r.__dict__" % x)
3095 dict_descr = Base.__dict__["__dict__"]
3096 try:
3097 dict_descr.__set__(x, {})
3098 except (AttributeError, TypeError):
3099 pass
3100 else:
3101 self.fail("dict_descr allowed access to %r's dict" % x)
3102
3103 # Classes don't allow __dict__ assignment and have readonly dicts
3104 class Meta1(type, Base):
3105 pass
3106 class Meta2(Base, type):
3107 pass
3108 class D(object, metaclass=Meta1):
3109 pass
3110 class E(object, metaclass=Meta2):
3111 pass
3112 for cls in C, D, E:
3113 verify_dict_readonly(cls)
3114 class_dict = cls.__dict__
3115 try:
3116 class_dict["spam"] = "eggs"
3117 except TypeError:
3118 pass
3119 else:
3120 self.fail("%r's __dict__ can be modified" % cls)
3121
3122 # Modules also disallow __dict__ assignment
3123 class Module1(types.ModuleType, Base):
3124 pass
3125 class Module2(Base, types.ModuleType):
3126 pass
3127 for ModuleType in Module1, Module2:
3128 mod = ModuleType("spam")
3129 verify_dict_readonly(mod)
3130 mod.__dict__["spam"] = "eggs"
3131
3132 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003133 # (at least not any more than regular exception's __dict__ can
3134 # be deleted; on CPython it is not the case, whereas on PyPy they
3135 # can, just like any other new-style instance's __dict__.)
3136 def can_delete_dict(e):
3137 try:
3138 del e.__dict__
3139 except (TypeError, AttributeError):
3140 return False
3141 else:
3142 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003143 class Exception1(Exception, Base):
3144 pass
3145 class Exception2(Base, Exception):
3146 pass
3147 for ExceptionType in Exception, Exception1, Exception2:
3148 e = ExceptionType()
3149 e.__dict__ = {"a": 1}
3150 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003151 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003152
3153 def test_pickles(self):
3154 # Testing pickling and copying new-style classes and objects...
3155 import pickle
3156
3157 def sorteditems(d):
3158 L = list(d.items())
3159 L.sort()
3160 return L
3161
3162 global C
3163 class C(object):
3164 def __init__(self, a, b):
3165 super(C, self).__init__()
3166 self.a = a
3167 self.b = b
3168 def __repr__(self):
3169 return "C(%r, %r)" % (self.a, self.b)
3170
3171 global C1
3172 class C1(list):
3173 def __new__(cls, a, b):
3174 return super(C1, cls).__new__(cls)
3175 def __getnewargs__(self):
3176 return (self.a, self.b)
3177 def __init__(self, a, b):
3178 self.a = a
3179 self.b = b
3180 def __repr__(self):
3181 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3182
3183 global C2
3184 class C2(int):
3185 def __new__(cls, a, b, val=0):
3186 return super(C2, cls).__new__(cls, val)
3187 def __getnewargs__(self):
3188 return (self.a, self.b, int(self))
3189 def __init__(self, a, b, val=0):
3190 self.a = a
3191 self.b = b
3192 def __repr__(self):
3193 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3194
3195 global C3
3196 class C3(object):
3197 def __init__(self, foo):
3198 self.foo = foo
3199 def __getstate__(self):
3200 return self.foo
3201 def __setstate__(self, foo):
3202 self.foo = foo
3203
3204 global C4classic, C4
3205 class C4classic: # classic
3206 pass
3207 class C4(C4classic, object): # mixed inheritance
3208 pass
3209
Guido van Rossum3926a632001-09-25 16:25:58 +00003210 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003211 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003212 s = pickle.dumps(cls, bin)
3213 cls2 = pickle.loads(s)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003214 self.assertIs(cls2, cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003215
3216 a = C1(1, 2); a.append(42); a.append(24)
3217 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003218 s = pickle.dumps((a, b), bin)
3219 x, y = pickle.loads(s)
3220 self.assertEqual(x.__class__, a.__class__)
3221 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3222 self.assertEqual(y.__class__, b.__class__)
3223 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3224 self.assertEqual(repr(x), repr(a))
3225 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003226 # Test for __getstate__ and __setstate__ on new style class
3227 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 s = pickle.dumps(u, bin)
3229 v = pickle.loads(s)
3230 self.assertEqual(u.__class__, v.__class__)
3231 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003232 # Test for picklability of hybrid class
3233 u = C4()
3234 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003235 s = pickle.dumps(u, bin)
3236 v = pickle.loads(s)
3237 self.assertEqual(u.__class__, v.__class__)
3238 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003239
Georg Brandl479a7e72008-02-05 18:13:15 +00003240 # Testing copy.deepcopy()
3241 import copy
3242 for cls in C, C1, C2:
3243 cls2 = copy.deepcopy(cls)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003244 self.assertIs(cls2, cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003245
Georg Brandl479a7e72008-02-05 18:13:15 +00003246 a = C1(1, 2); a.append(42); a.append(24)
3247 b = C2("hello", "world", 42)
3248 x, y = copy.deepcopy((a, b))
3249 self.assertEqual(x.__class__, a.__class__)
3250 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3251 self.assertEqual(y.__class__, b.__class__)
3252 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3253 self.assertEqual(repr(x), repr(a))
3254 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003255
Georg Brandl479a7e72008-02-05 18:13:15 +00003256 def test_pickle_slots(self):
3257 # Testing pickling of classes with __slots__ ...
3258 import pickle
3259 # Pickling of classes with __slots__ but without __getstate__ should fail
3260 # (if using protocol 0 or 1)
3261 global B, C, D, E
3262 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003263 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003264 for base in [object, B]:
3265 class C(base):
3266 __slots__ = ['a']
3267 class D(C):
3268 pass
3269 try:
3270 pickle.dumps(C(), 0)
3271 except TypeError:
3272 pass
3273 else:
3274 self.fail("should fail: pickle C instance - %s" % base)
3275 try:
3276 pickle.dumps(C(), 0)
3277 except TypeError:
3278 pass
3279 else:
3280 self.fail("should fail: pickle D instance - %s" % base)
3281 # Give C a nice generic __getstate__ and __setstate__
3282 class C(base):
3283 __slots__ = ['a']
3284 def __getstate__(self):
3285 try:
3286 d = self.__dict__.copy()
3287 except AttributeError:
3288 d = {}
3289 for cls in self.__class__.__mro__:
3290 for sn in cls.__dict__.get('__slots__', ()):
3291 try:
3292 d[sn] = getattr(self, sn)
3293 except AttributeError:
3294 pass
3295 return d
3296 def __setstate__(self, d):
3297 for k, v in list(d.items()):
3298 setattr(self, k, v)
3299 class D(C):
3300 pass
3301 # Now it should work
3302 x = C()
3303 y = pickle.loads(pickle.dumps(x))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003304 self.assertNotHasAttr(y, 'a')
Georg Brandl479a7e72008-02-05 18:13:15 +00003305 x.a = 42
3306 y = pickle.loads(pickle.dumps(x))
3307 self.assertEqual(y.a, 42)
3308 x = D()
3309 x.a = 42
3310 x.b = 100
3311 y = pickle.loads(pickle.dumps(x))
3312 self.assertEqual(y.a + y.b, 142)
3313 # A subclass that adds a slot should also work
3314 class E(C):
3315 __slots__ = ['b']
3316 x = E()
3317 x.a = 42
3318 x.b = "foo"
3319 y = pickle.loads(pickle.dumps(x))
3320 self.assertEqual(y.a, x.a)
3321 self.assertEqual(y.b, x.b)
3322
3323 def test_binary_operator_override(self):
3324 # Testing overrides of binary operations...
3325 class I(int):
3326 def __repr__(self):
3327 return "I(%r)" % int(self)
3328 def __add__(self, other):
3329 return I(int(self) + int(other))
3330 __radd__ = __add__
3331 def __pow__(self, other, mod=None):
3332 if mod is None:
3333 return I(pow(int(self), int(other)))
3334 else:
3335 return I(pow(int(self), int(other), int(mod)))
3336 def __rpow__(self, other, mod=None):
3337 if mod is None:
3338 return I(pow(int(other), int(self), mod))
3339 else:
3340 return I(pow(int(other), int(self), int(mod)))
3341
3342 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3343 self.assertEqual(repr(I(1) + 2), "I(3)")
3344 self.assertEqual(repr(1 + I(2)), "I(3)")
3345 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3346 self.assertEqual(repr(2 ** I(3)), "I(8)")
3347 self.assertEqual(repr(I(2) ** 3), "I(8)")
3348 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3349 class S(str):
3350 def __eq__(self, other):
3351 return self.lower() == other.lower()
3352
3353 def test_subclass_propagation(self):
3354 # Testing propagation of slot functions to subclasses...
3355 class A(object):
3356 pass
3357 class B(A):
3358 pass
3359 class C(A):
3360 pass
3361 class D(B, C):
3362 pass
3363 d = D()
3364 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3365 A.__hash__ = lambda self: 42
3366 self.assertEqual(hash(d), 42)
3367 C.__hash__ = lambda self: 314
3368 self.assertEqual(hash(d), 314)
3369 B.__hash__ = lambda self: 144
3370 self.assertEqual(hash(d), 144)
3371 D.__hash__ = lambda self: 100
3372 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003373 D.__hash__ = None
3374 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003375 del D.__hash__
3376 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003377 B.__hash__ = None
3378 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003379 del B.__hash__
3380 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003381 C.__hash__ = None
3382 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003383 del C.__hash__
3384 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003385 A.__hash__ = None
3386 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003387 del A.__hash__
3388 self.assertEqual(hash(d), orig_hash)
3389 d.foo = 42
3390 d.bar = 42
3391 self.assertEqual(d.foo, 42)
3392 self.assertEqual(d.bar, 42)
3393 def __getattribute__(self, name):
3394 if name == "foo":
3395 return 24
3396 return object.__getattribute__(self, name)
3397 A.__getattribute__ = __getattribute__
3398 self.assertEqual(d.foo, 24)
3399 self.assertEqual(d.bar, 42)
3400 def __getattr__(self, name):
3401 if name in ("spam", "foo", "bar"):
3402 return "hello"
3403 raise AttributeError(name)
3404 B.__getattr__ = __getattr__
3405 self.assertEqual(d.spam, "hello")
3406 self.assertEqual(d.foo, 24)
3407 self.assertEqual(d.bar, 42)
3408 del A.__getattribute__
3409 self.assertEqual(d.foo, 42)
3410 del d.foo
3411 self.assertEqual(d.foo, "hello")
3412 self.assertEqual(d.bar, 42)
3413 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003414 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003415 d.foo
3416 except AttributeError:
3417 pass
3418 else:
3419 self.fail("d.foo should be undefined now")
3420
3421 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003422 class A(object):
3423 pass
3424 class B(A):
3425 pass
3426 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003427 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003428 A.__setitem__ = lambda *a: None # crash
3429
3430 def test_buffer_inheritance(self):
3431 # Testing that buffer interface is inherited ...
3432
3433 import binascii
3434 # SF bug [#470040] ParseTuple t# vs subclasses.
3435
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003436 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003437 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003438 base = b'abc'
3439 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003440 # b2a_hex uses the buffer interface to get its argument's value, via
3441 # PyArg_ParseTuple 't#' code.
3442 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3443
Georg Brandl479a7e72008-02-05 18:13:15 +00003444 class MyInt(int):
3445 pass
3446 m = MyInt(42)
3447 try:
3448 binascii.b2a_hex(m)
3449 self.fail('subclass of int should not have a buffer interface')
3450 except TypeError:
3451 pass
3452
3453 def test_str_of_str_subclass(self):
3454 # Testing __str__ defined in subclass of str ...
3455 import binascii
3456 import io
3457
3458 class octetstring(str):
3459 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003460 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003461 def __repr__(self):
3462 return self + " repr"
3463
3464 o = octetstring('A')
3465 self.assertEqual(type(o), octetstring)
3466 self.assertEqual(type(str(o)), str)
3467 self.assertEqual(type(repr(o)), str)
3468 self.assertEqual(ord(o), 0x41)
3469 self.assertEqual(str(o), '41')
3470 self.assertEqual(repr(o), 'A repr')
3471 self.assertEqual(o.__str__(), '41')
3472 self.assertEqual(o.__repr__(), 'A repr')
3473
3474 capture = io.StringIO()
3475 # Calling str() or not exercises different internal paths.
3476 print(o, file=capture)
3477 print(str(o), file=capture)
3478 self.assertEqual(capture.getvalue(), '41\n41\n')
3479 capture.close()
3480
3481 def test_keyword_arguments(self):
3482 # Testing keyword arguments to __init__, __call__...
3483 def f(a): return a
3484 self.assertEqual(f.__call__(a=42), 42)
3485 a = []
3486 list.__init__(a, sequence=[0, 1, 2])
3487 self.assertEqual(a, [0, 1, 2])
3488
3489 def test_recursive_call(self):
3490 # Testing recursive __call__() by setting to instance of class...
3491 class A(object):
3492 pass
3493
3494 A.__call__ = A()
3495 try:
3496 A()()
3497 except RuntimeError:
3498 pass
3499 else:
3500 self.fail("Recursion limit should have been reached for __call__()")
3501
3502 def test_delete_hook(self):
3503 # Testing __del__ hook...
3504 log = []
3505 class C(object):
3506 def __del__(self):
3507 log.append(1)
3508 c = C()
3509 self.assertEqual(log, [])
3510 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003511 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003512 self.assertEqual(log, [1])
3513
3514 class D(object): pass
3515 d = D()
3516 try: del d[0]
3517 except TypeError: pass
3518 else: self.fail("invalid del() didn't raise TypeError")
3519
3520 def test_hash_inheritance(self):
3521 # Testing hash of mutable subclasses...
3522
3523 class mydict(dict):
3524 pass
3525 d = mydict()
3526 try:
3527 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003528 except TypeError:
3529 pass
3530 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003531 self.fail("hash() of dict subclass should fail")
3532
3533 class mylist(list):
3534 pass
3535 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003536 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003537 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003538 except TypeError:
3539 pass
3540 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003541 self.fail("hash() of list subclass should fail")
3542
3543 def test_str_operations(self):
3544 try: 'a' + 5
3545 except TypeError: pass
3546 else: self.fail("'' + 5 doesn't raise TypeError")
3547
3548 try: ''.split('')
3549 except ValueError: pass
3550 else: self.fail("''.split('') doesn't raise ValueError")
3551
3552 try: ''.join([0])
3553 except TypeError: pass
3554 else: self.fail("''.join([0]) doesn't raise TypeError")
3555
3556 try: ''.rindex('5')
3557 except ValueError: pass
3558 else: self.fail("''.rindex('5') doesn't raise ValueError")
3559
3560 try: '%(n)s' % None
3561 except TypeError: pass
3562 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3563
3564 try: '%(n' % {}
3565 except ValueError: pass
3566 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3567
3568 try: '%*s' % ('abc')
3569 except TypeError: pass
3570 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3571
3572 try: '%*.*s' % ('abc', 5)
3573 except TypeError: pass
3574 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3575
3576 try: '%s' % (1, 2)
3577 except TypeError: pass
3578 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3579
3580 try: '%' % None
3581 except ValueError: pass
3582 else: self.fail("'%' % None doesn't raise ValueError")
3583
3584 self.assertEqual('534253'.isdigit(), 1)
3585 self.assertEqual('534253x'.isdigit(), 0)
3586 self.assertEqual('%c' % 5, '\x05')
3587 self.assertEqual('%c' % '5', '5')
3588
3589 def test_deepcopy_recursive(self):
3590 # Testing deepcopy of recursive objects...
3591 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003592 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003593 a = Node()
3594 b = Node()
3595 a.b = b
3596 b.a = a
3597 z = deepcopy(a) # This blew up before
3598
3599 def test_unintialized_modules(self):
3600 # Testing uninitialized module objects...
3601 from types import ModuleType as M
3602 m = M.__new__(M)
3603 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003604 self.assertNotHasAttr(m, "__name__")
3605 self.assertNotHasAttr(m, "__file__")
3606 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003607 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003608 m.foo = 1
3609 self.assertEqual(m.__dict__, {"foo": 1})
3610
3611 def test_funny_new(self):
3612 # Testing __new__ returning something unexpected...
3613 class C(object):
3614 def __new__(cls, arg):
3615 if isinstance(arg, str): return [1, 2, 3]
3616 elif isinstance(arg, int): return object.__new__(D)
3617 else: return object.__new__(cls)
3618 class D(C):
3619 def __init__(self, arg):
3620 self.foo = arg
3621 self.assertEqual(C("1"), [1, 2, 3])
3622 self.assertEqual(D("1"), [1, 2, 3])
3623 d = D(None)
3624 self.assertEqual(d.foo, None)
3625 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003626 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003627 self.assertEqual(d.foo, 1)
3628 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003629 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003630 self.assertEqual(d.foo, 1)
3631
3632 def test_imul_bug(self):
3633 # Testing for __imul__ problems...
3634 # SF bug 544647
3635 class C(object):
3636 def __imul__(self, other):
3637 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003638 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003639 y = x
3640 y *= 1.0
3641 self.assertEqual(y, (x, 1.0))
3642 y = x
3643 y *= 2
3644 self.assertEqual(y, (x, 2))
3645 y = x
3646 y *= 3
3647 self.assertEqual(y, (x, 3))
3648 y = x
3649 y *= 1<<100
3650 self.assertEqual(y, (x, 1<<100))
3651 y = x
3652 y *= None
3653 self.assertEqual(y, (x, None))
3654 y = x
3655 y *= "foo"
3656 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003657
Georg Brandl479a7e72008-02-05 18:13:15 +00003658 def test_copy_setstate(self):
3659 # Testing that copy.*copy() correctly uses __setstate__...
3660 import copy
3661 class C(object):
3662 def __init__(self, foo=None):
3663 self.foo = foo
3664 self.__foo = foo
3665 def setfoo(self, foo=None):
3666 self.foo = foo
3667 def getfoo(self):
3668 return self.__foo
3669 def __getstate__(self):
3670 return [self.foo]
3671 def __setstate__(self_, lst):
3672 self.assertEqual(len(lst), 1)
3673 self_.__foo = self_.foo = lst[0]
3674 a = C(42)
3675 a.setfoo(24)
3676 self.assertEqual(a.foo, 24)
3677 self.assertEqual(a.getfoo(), 42)
3678 b = copy.copy(a)
3679 self.assertEqual(b.foo, 24)
3680 self.assertEqual(b.getfoo(), 24)
3681 b = copy.deepcopy(a)
3682 self.assertEqual(b.foo, 24)
3683 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003684
Georg Brandl479a7e72008-02-05 18:13:15 +00003685 def test_slices(self):
3686 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003687
Georg Brandl479a7e72008-02-05 18:13:15 +00003688 # Strings
3689 self.assertEqual("hello"[:4], "hell")
3690 self.assertEqual("hello"[slice(4)], "hell")
3691 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3692 class S(str):
3693 def __getitem__(self, x):
3694 return str.__getitem__(self, x)
3695 self.assertEqual(S("hello")[:4], "hell")
3696 self.assertEqual(S("hello")[slice(4)], "hell")
3697 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3698 # Tuples
3699 self.assertEqual((1,2,3)[:2], (1,2))
3700 self.assertEqual((1,2,3)[slice(2)], (1,2))
3701 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3702 class T(tuple):
3703 def __getitem__(self, x):
3704 return tuple.__getitem__(self, x)
3705 self.assertEqual(T((1,2,3))[:2], (1,2))
3706 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3707 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3708 # Lists
3709 self.assertEqual([1,2,3][:2], [1,2])
3710 self.assertEqual([1,2,3][slice(2)], [1,2])
3711 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3712 class L(list):
3713 def __getitem__(self, x):
3714 return list.__getitem__(self, x)
3715 self.assertEqual(L([1,2,3])[:2], [1,2])
3716 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3717 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3718 # Now do lists and __setitem__
3719 a = L([1,2,3])
3720 a[slice(1, 3)] = [3,2]
3721 self.assertEqual(a, [1,3,2])
3722 a[slice(0, 2, 1)] = [3,1]
3723 self.assertEqual(a, [3,1,2])
3724 a.__setitem__(slice(1, 3), [2,1])
3725 self.assertEqual(a, [3,2,1])
3726 a.__setitem__(slice(0, 2, 1), [2,3])
3727 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003728
Georg Brandl479a7e72008-02-05 18:13:15 +00003729 def test_subtype_resurrection(self):
3730 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003731
Georg Brandl479a7e72008-02-05 18:13:15 +00003732 class C(object):
3733 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003734
Georg Brandl479a7e72008-02-05 18:13:15 +00003735 def __del__(self):
3736 # resurrect the instance
3737 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003738
Georg Brandl479a7e72008-02-05 18:13:15 +00003739 c = C()
3740 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003741
Benjamin Petersone549ead2009-03-28 21:42:05 +00003742 # The most interesting thing here is whether this blows up, due to
3743 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3744 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003745 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003746
Georg Brandl479a7e72008-02-05 18:13:15 +00003747 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003748 # the last container slot works: that will attempt to delete c again,
3749 # which will cause c to get appended back to the container again
3750 # "during" the del. (On non-CPython implementations, however, __del__
3751 # is typically not called again.)
3752 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003753 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003754 del C.container[-1]
3755 if support.check_impl_detail():
3756 support.gc_collect()
3757 self.assertEqual(len(C.container), 1)
3758 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003759
Georg Brandl479a7e72008-02-05 18:13:15 +00003760 # Make c mortal again, so that the test framework with -l doesn't report
3761 # it as a leak.
3762 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003763
Georg Brandl479a7e72008-02-05 18:13:15 +00003764 def test_slots_trash(self):
3765 # Testing slot trash...
3766 # Deallocating deeply nested slotted trash caused stack overflows
3767 class trash(object):
3768 __slots__ = ['x']
3769 def __init__(self, x):
3770 self.x = x
3771 o = None
3772 for i in range(50000):
3773 o = trash(o)
3774 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003775
Georg Brandl479a7e72008-02-05 18:13:15 +00003776 def test_slots_multiple_inheritance(self):
3777 # SF bug 575229, multiple inheritance w/ slots dumps core
3778 class A(object):
3779 __slots__=()
3780 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003781 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003782 class C(A,B) :
3783 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003784 if support.check_impl_detail():
3785 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003786 self.assertHasAttr(C, '__dict__')
3787 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003788 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003789
Georg Brandl479a7e72008-02-05 18:13:15 +00003790 def test_rmul(self):
3791 # Testing correct invocation of __rmul__...
3792 # SF patch 592646
3793 class C(object):
3794 def __mul__(self, other):
3795 return "mul"
3796 def __rmul__(self, other):
3797 return "rmul"
3798 a = C()
3799 self.assertEqual(a*2, "mul")
3800 self.assertEqual(a*2.2, "mul")
3801 self.assertEqual(2*a, "rmul")
3802 self.assertEqual(2.2*a, "rmul")
3803
3804 def test_ipow(self):
3805 # Testing correct invocation of __ipow__...
3806 # [SF bug 620179]
3807 class C(object):
3808 def __ipow__(self, other):
3809 pass
3810 a = C()
3811 a **= 2
3812
3813 def test_mutable_bases(self):
3814 # Testing mutable bases...
3815
3816 # stuff that should work:
3817 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003818 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003819 class C2(object):
3820 def __getattribute__(self, attr):
3821 if attr == 'a':
3822 return 2
3823 else:
3824 return super(C2, self).__getattribute__(attr)
3825 def meth(self):
3826 return 1
3827 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003828 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003829 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003830 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003831 d = D()
3832 e = E()
3833 D.__bases__ = (C,)
3834 D.__bases__ = (C2,)
3835 self.assertEqual(d.meth(), 1)
3836 self.assertEqual(e.meth(), 1)
3837 self.assertEqual(d.a, 2)
3838 self.assertEqual(e.a, 2)
3839 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003840
Georg Brandl479a7e72008-02-05 18:13:15 +00003841 try:
3842 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003843 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003844 pass
3845 else:
3846 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003847
Georg Brandl479a7e72008-02-05 18:13:15 +00003848 try:
3849 D.__bases__ = ()
3850 except TypeError as msg:
3851 if str(msg) == "a new-style class can't have only classic bases":
3852 self.fail("wrong error message for .__bases__ = ()")
3853 else:
3854 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003855
Georg Brandl479a7e72008-02-05 18:13:15 +00003856 try:
3857 D.__bases__ = (D,)
3858 except TypeError:
3859 pass
3860 else:
3861 # actually, we'll have crashed by here...
3862 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003863
Georg Brandl479a7e72008-02-05 18:13:15 +00003864 try:
3865 D.__bases__ = (C, C)
3866 except TypeError:
3867 pass
3868 else:
3869 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003870
Georg Brandl479a7e72008-02-05 18:13:15 +00003871 try:
3872 D.__bases__ = (E,)
3873 except TypeError:
3874 pass
3875 else:
3876 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003877
Benjamin Petersonae937c02009-04-18 20:54:08 +00003878 def test_builtin_bases(self):
3879 # Make sure all the builtin types can have their base queried without
3880 # segfaulting. See issue #5787.
3881 builtin_types = [tp for tp in builtins.__dict__.values()
3882 if isinstance(tp, type)]
3883 for tp in builtin_types:
3884 object.__getattribute__(tp, "__bases__")
3885 if tp is not object:
3886 self.assertEqual(len(tp.__bases__), 1, tp)
3887
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003888 class L(list):
3889 pass
3890
3891 class C(object):
3892 pass
3893
3894 class D(C):
3895 pass
3896
3897 try:
3898 L.__bases__ = (dict,)
3899 except TypeError:
3900 pass
3901 else:
3902 self.fail("shouldn't turn list subclass into dict subclass")
3903
3904 try:
3905 list.__bases__ = (dict,)
3906 except TypeError:
3907 pass
3908 else:
3909 self.fail("shouldn't be able to assign to list.__bases__")
3910
3911 try:
3912 D.__bases__ = (C, list)
3913 except TypeError:
3914 pass
3915 else:
3916 assert 0, "best_base calculation found wanting"
3917
Benjamin Petersonae937c02009-04-18 20:54:08 +00003918
Georg Brandl479a7e72008-02-05 18:13:15 +00003919 def test_mutable_bases_with_failing_mro(self):
3920 # Testing mutable bases with failing mro...
3921 class WorkOnce(type):
3922 def __new__(self, name, bases, ns):
3923 self.flag = 0
3924 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3925 def mro(self):
3926 if self.flag > 0:
3927 raise RuntimeError("bozo")
3928 else:
3929 self.flag += 1
3930 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003931
Georg Brandl479a7e72008-02-05 18:13:15 +00003932 class WorkAlways(type):
3933 def mro(self):
3934 # this is here to make sure that .mro()s aren't called
3935 # with an exception set (which was possible at one point).
3936 # An error message will be printed in a debug build.
3937 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003938 return type.mro(self)
3939
Georg Brandl479a7e72008-02-05 18:13:15 +00003940 class C(object):
3941 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003942
Georg Brandl479a7e72008-02-05 18:13:15 +00003943 class C2(object):
3944 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003945
Georg Brandl479a7e72008-02-05 18:13:15 +00003946 class D(C):
3947 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003948
Georg Brandl479a7e72008-02-05 18:13:15 +00003949 class E(D):
3950 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003951
Georg Brandl479a7e72008-02-05 18:13:15 +00003952 class F(D, metaclass=WorkOnce):
3953 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003954
Georg Brandl479a7e72008-02-05 18:13:15 +00003955 class G(D, metaclass=WorkAlways):
3956 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003957
Georg Brandl479a7e72008-02-05 18:13:15 +00003958 # Immediate subclasses have their mro's adjusted in alphabetical
3959 # order, so E's will get adjusted before adjusting F's fails. We
3960 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003961
Georg Brandl479a7e72008-02-05 18:13:15 +00003962 E_mro_before = E.__mro__
3963 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003964
Armin Rigofd163f92005-12-29 15:59:19 +00003965 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003966 D.__bases__ = (C2,)
3967 except RuntimeError:
3968 self.assertEqual(E.__mro__, E_mro_before)
3969 self.assertEqual(D.__mro__, D_mro_before)
3970 else:
3971 self.fail("exception not propagated")
3972
3973 def test_mutable_bases_catch_mro_conflict(self):
3974 # Testing mutable bases catch mro conflict...
3975 class A(object):
3976 pass
3977
3978 class B(object):
3979 pass
3980
3981 class C(A, B):
3982 pass
3983
3984 class D(A, B):
3985 pass
3986
3987 class E(C, D):
3988 pass
3989
3990 try:
3991 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003992 except TypeError:
3993 pass
3994 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003995 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003996
Georg Brandl479a7e72008-02-05 18:13:15 +00003997 def test_mutable_names(self):
3998 # Testing mutable names...
3999 class C(object):
4000 pass
4001
4002 # C.__module__ could be 'test_descr' or '__main__'
4003 mod = C.__module__
4004
4005 C.__name__ = 'D'
4006 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4007
4008 C.__name__ = 'D.E'
4009 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4010
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004011 def test_evil_type_name(self):
4012 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4013 # execution while the type structure was not in a sane state, and a
4014 # possible segmentation fault as a result. See bug #16447.
4015 class Nasty(str):
4016 def __del__(self):
4017 C.__name__ = "other"
4018
4019 class C:
4020 pass
4021
4022 C.__name__ = Nasty("abc")
4023 C.__name__ = "normal"
4024
Georg Brandl479a7e72008-02-05 18:13:15 +00004025 def test_subclass_right_op(self):
4026 # Testing correct dispatch of subclass overloading __r<op>__...
4027
4028 # This code tests various cases where right-dispatch of a subclass
4029 # should be preferred over left-dispatch of a base class.
4030
4031 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4032
4033 class B(int):
4034 def __floordiv__(self, other):
4035 return "B.__floordiv__"
4036 def __rfloordiv__(self, other):
4037 return "B.__rfloordiv__"
4038
4039 self.assertEqual(B(1) // 1, "B.__floordiv__")
4040 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4041
4042 # Case 2: subclass of object; this is just the baseline for case 3
4043
4044 class C(object):
4045 def __floordiv__(self, other):
4046 return "C.__floordiv__"
4047 def __rfloordiv__(self, other):
4048 return "C.__rfloordiv__"
4049
4050 self.assertEqual(C() // 1, "C.__floordiv__")
4051 self.assertEqual(1 // C(), "C.__rfloordiv__")
4052
4053 # Case 3: subclass of new-style class; here it gets interesting
4054
4055 class D(C):
4056 def __floordiv__(self, other):
4057 return "D.__floordiv__"
4058 def __rfloordiv__(self, other):
4059 return "D.__rfloordiv__"
4060
4061 self.assertEqual(D() // C(), "D.__floordiv__")
4062 self.assertEqual(C() // D(), "D.__rfloordiv__")
4063
4064 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4065
4066 class E(C):
4067 pass
4068
4069 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4070
4071 self.assertEqual(E() // 1, "C.__floordiv__")
4072 self.assertEqual(1 // E(), "C.__rfloordiv__")
4073 self.assertEqual(E() // C(), "C.__floordiv__")
4074 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4075
Benjamin Petersone549ead2009-03-28 21:42:05 +00004076 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004077 def test_meth_class_get(self):
4078 # Testing __get__ method of METH_CLASS C methods...
4079 # Full coverage of descrobject.c::classmethod_get()
4080
4081 # Baseline
4082 arg = [1, 2, 3]
4083 res = {1: None, 2: None, 3: None}
4084 self.assertEqual(dict.fromkeys(arg), res)
4085 self.assertEqual({}.fromkeys(arg), res)
4086
4087 # Now get the descriptor
4088 descr = dict.__dict__["fromkeys"]
4089
4090 # More baseline using the descriptor directly
4091 self.assertEqual(descr.__get__(None, dict)(arg), res)
4092 self.assertEqual(descr.__get__({})(arg), res)
4093
4094 # Now check various error cases
4095 try:
4096 descr.__get__(None, None)
4097 except TypeError:
4098 pass
4099 else:
4100 self.fail("shouldn't have allowed descr.__get__(None, None)")
4101 try:
4102 descr.__get__(42)
4103 except TypeError:
4104 pass
4105 else:
4106 self.fail("shouldn't have allowed descr.__get__(42)")
4107 try:
4108 descr.__get__(None, 42)
4109 except TypeError:
4110 pass
4111 else:
4112 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4113 try:
4114 descr.__get__(None, int)
4115 except TypeError:
4116 pass
4117 else:
4118 self.fail("shouldn't have allowed descr.__get__(None, int)")
4119
4120 def test_isinst_isclass(self):
4121 # Testing proxy isinstance() and isclass()...
4122 class Proxy(object):
4123 def __init__(self, obj):
4124 self.__obj = obj
4125 def __getattribute__(self, name):
4126 if name.startswith("_Proxy__"):
4127 return object.__getattribute__(self, name)
4128 else:
4129 return getattr(self.__obj, name)
4130 # Test with a classic class
4131 class C:
4132 pass
4133 a = C()
4134 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004135 self.assertIsInstance(a, C) # Baseline
4136 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004137 # Test with a classic subclass
4138 class D(C):
4139 pass
4140 a = D()
4141 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004142 self.assertIsInstance(a, C) # Baseline
4143 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004144 # Test with a new-style class
4145 class C(object):
4146 pass
4147 a = C()
4148 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004149 self.assertIsInstance(a, C) # Baseline
4150 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004151 # Test with a new-style subclass
4152 class D(C):
4153 pass
4154 a = D()
4155 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004156 self.assertIsInstance(a, C) # Baseline
4157 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004158
4159 def test_proxy_super(self):
4160 # Testing super() for a proxy object...
4161 class Proxy(object):
4162 def __init__(self, obj):
4163 self.__obj = obj
4164 def __getattribute__(self, name):
4165 if name.startswith("_Proxy__"):
4166 return object.__getattribute__(self, name)
4167 else:
4168 return getattr(self.__obj, name)
4169
4170 class B(object):
4171 def f(self):
4172 return "B.f"
4173
4174 class C(B):
4175 def f(self):
4176 return super(C, self).f() + "->C.f"
4177
4178 obj = C()
4179 p = Proxy(obj)
4180 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4181
4182 def test_carloverre(self):
4183 # Testing prohibition of Carlo Verre's hack...
4184 try:
4185 object.__setattr__(str, "foo", 42)
4186 except TypeError:
4187 pass
4188 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004189 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004190 try:
4191 object.__delattr__(str, "lower")
4192 except TypeError:
4193 pass
4194 else:
4195 self.fail("Carlo Verre __delattr__ succeeded!")
4196
4197 def test_weakref_segfault(self):
4198 # Testing weakref segfault...
4199 # SF 742911
4200 import weakref
4201
4202 class Provoker:
4203 def __init__(self, referrent):
4204 self.ref = weakref.ref(referrent)
4205
4206 def __del__(self):
4207 x = self.ref()
4208
4209 class Oops(object):
4210 pass
4211
4212 o = Oops()
4213 o.whatever = Provoker(o)
4214 del o
4215
4216 def test_wrapper_segfault(self):
4217 # SF 927248: deeply nested wrappers could cause stack overflow
4218 f = lambda:None
4219 for i in range(1000000):
4220 f = f.__call__
4221 f = None
4222
4223 def test_file_fault(self):
4224 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004225 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004226 class StdoutGuard:
4227 def __getattr__(self, attr):
4228 sys.stdout = sys.__stdout__
4229 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4230 sys.stdout = StdoutGuard()
4231 try:
4232 print("Oops!")
4233 except RuntimeError:
4234 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004235 finally:
4236 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004237
4238 def test_vicious_descriptor_nonsense(self):
4239 # Testing vicious_descriptor_nonsense...
4240
4241 # A potential segfault spotted by Thomas Wouters in mail to
4242 # python-dev 2003-04-17, turned into an example & fixed by Michael
4243 # Hudson just less than four months later...
4244
4245 class Evil(object):
4246 def __hash__(self):
4247 return hash('attr')
4248 def __eq__(self, other):
4249 del C.attr
4250 return 0
4251
4252 class Descr(object):
4253 def __get__(self, ob, type=None):
4254 return 1
4255
4256 class C(object):
4257 attr = Descr()
4258
4259 c = C()
4260 c.__dict__[Evil()] = 0
4261
4262 self.assertEqual(c.attr, 1)
4263 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004264 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004265 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004266
4267 def test_init(self):
4268 # SF 1155938
4269 class Foo(object):
4270 def __init__(self):
4271 return 10
4272 try:
4273 Foo()
4274 except TypeError:
4275 pass
4276 else:
4277 self.fail("did not test __init__() for None return")
4278
4279 def test_method_wrapper(self):
4280 # Testing method-wrapper objects...
4281 # <type 'method-wrapper'> did not support any reflection before 2.5
4282
Mark Dickinson211c6252009-02-01 10:28:51 +00004283 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004284
4285 l = []
4286 self.assertEqual(l.__add__, l.__add__)
4287 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004288 self.assertNotEqual(l.__add__, [5].__add__)
4289 self.assertNotEqual(l.__add__, l.__mul__)
4290 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004291 if hasattr(l.__add__, '__self__'):
4292 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004293 self.assertIs(l.__add__.__self__, l)
4294 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004295 else:
4296 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004297 self.assertIs(l.__add__.im_self, l)
4298 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004299 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4300 try:
4301 hash(l.__add__)
4302 except TypeError:
4303 pass
4304 else:
4305 self.fail("no TypeError from hash([].__add__)")
4306
4307 t = ()
4308 t += (7,)
4309 self.assertEqual(t.__add__, (7,).__add__)
4310 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4311
4312 def test_not_implemented(self):
4313 # Testing NotImplemented...
4314 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 import operator
4316
4317 def specialmethod(self, other):
4318 return NotImplemented
4319
4320 def check(expr, x, y):
4321 try:
4322 exec(expr, {'x': x, 'y': y, 'operator': operator})
4323 except TypeError:
4324 pass
4325 else:
4326 self.fail("no TypeError from %r" % (expr,))
4327
4328 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4329 # TypeErrors
4330 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4331 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004332 for name, expr, iexpr in [
4333 ('__add__', 'x + y', 'x += y'),
4334 ('__sub__', 'x - y', 'x -= y'),
4335 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004336 ('__truediv__', 'operator.truediv(x, y)', None),
4337 ('__floordiv__', 'operator.floordiv(x, y)', None),
4338 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004339 ('__mod__', 'x % y', 'x %= y'),
4340 ('__divmod__', 'divmod(x, y)', None),
4341 ('__pow__', 'x ** y', 'x **= y'),
4342 ('__lshift__', 'x << y', 'x <<= y'),
4343 ('__rshift__', 'x >> y', 'x >>= y'),
4344 ('__and__', 'x & y', 'x &= y'),
4345 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004346 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004347 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004348 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004349 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004350 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004351 check(expr, a, N1)
4352 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004353 if iexpr:
4354 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004355 check(iexpr, a, N1)
4356 check(iexpr, a, N2)
4357 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004358 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004359 c = C()
4360 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004361 check(iexpr, c, N1)
4362 check(iexpr, c, N2)
4363
Georg Brandl479a7e72008-02-05 18:13:15 +00004364 def test_assign_slice(self):
4365 # ceval.c's assign_slice used to check for
4366 # tp->tp_as_sequence->sq_slice instead of
4367 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004368
Georg Brandl479a7e72008-02-05 18:13:15 +00004369 class C(object):
4370 def __setitem__(self, idx, value):
4371 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004372
Georg Brandl479a7e72008-02-05 18:13:15 +00004373 c = C()
4374 c[1:2] = 3
4375 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004376
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004377 def test_set_and_no_get(self):
4378 # See
4379 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4380 class Descr(object):
4381
4382 def __init__(self, name):
4383 self.name = name
4384
4385 def __set__(self, obj, value):
4386 obj.__dict__[self.name] = value
4387 descr = Descr("a")
4388
4389 class X(object):
4390 a = descr
4391
4392 x = X()
4393 self.assertIs(x.a, descr)
4394 x.a = 42
4395 self.assertEqual(x.a, 42)
4396
Benjamin Peterson21896a32010-03-21 22:03:03 +00004397 # Also check type_getattro for correctness.
4398 class Meta(type):
4399 pass
4400 class X(object):
4401 __metaclass__ = Meta
4402 X.a = 42
4403 Meta.a = Descr("a")
4404 self.assertEqual(X.a, 42)
4405
Benjamin Peterson9262b842008-11-17 22:45:50 +00004406 def test_getattr_hooks(self):
4407 # issue 4230
4408
4409 class Descriptor(object):
4410 counter = 0
4411 def __get__(self, obj, objtype=None):
4412 def getter(name):
4413 self.counter += 1
4414 raise AttributeError(name)
4415 return getter
4416
4417 descr = Descriptor()
4418 class A(object):
4419 __getattribute__ = descr
4420 class B(object):
4421 __getattr__ = descr
4422 class C(object):
4423 __getattribute__ = descr
4424 __getattr__ = descr
4425
4426 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004427 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004428 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004429 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004430 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004431 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004432
Benjamin Peterson9262b842008-11-17 22:45:50 +00004433 class EvilGetattribute(object):
4434 # This used to segfault
4435 def __getattr__(self, name):
4436 raise AttributeError(name)
4437 def __getattribute__(self, name):
4438 del EvilGetattribute.__getattr__
4439 for i in range(5):
4440 gc.collect()
4441 raise AttributeError(name)
4442
4443 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4444
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004445 def test_type___getattribute__(self):
4446 self.assertRaises(TypeError, type.__getattribute__, list, type)
4447
Benjamin Peterson477ba912011-01-12 15:34:01 +00004448 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004449 # type pretends not to have __abstractmethods__.
4450 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4451 class meta(type):
4452 pass
4453 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004454 class X(object):
4455 pass
4456 with self.assertRaises(AttributeError):
4457 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004458
Victor Stinner3249dec2011-05-01 23:19:15 +02004459 def test_proxy_call(self):
4460 class FakeStr:
4461 __class__ = str
4462
4463 fake_str = FakeStr()
4464 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004465 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004466
4467 # call a method descriptor
4468 with self.assertRaises(TypeError):
4469 str.split(fake_str)
4470
4471 # call a slot wrapper descriptor
4472 with self.assertRaises(TypeError):
4473 str.__add__(fake_str, "abc")
4474
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004475 def test_repr_as_str(self):
4476 # Issue #11603: crash or infinite loop when rebinding __str__ as
4477 # __repr__.
4478 class Foo:
4479 pass
4480 Foo.__repr__ = Foo.__str__
4481 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004482 self.assertRaises(RuntimeError, str, foo)
4483 self.assertRaises(RuntimeError, repr, foo)
4484
4485 def test_mixing_slot_wrappers(self):
4486 class X(dict):
4487 __setattr__ = dict.__setitem__
4488 x = X()
4489 x.y = 42
4490 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004491
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004492 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004493 with self.assertRaises(ValueError) as cm:
4494 class X:
4495 __slots__ = ["foo"]
4496 foo = None
4497 m = str(cm.exception)
4498 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4499
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004500 def test_set_doc(self):
4501 class X:
4502 "elephant"
4503 X.__doc__ = "banana"
4504 self.assertEqual(X.__doc__, "banana")
4505 with self.assertRaises(TypeError) as cm:
4506 type(list).__dict__["__doc__"].__set__(list, "blah")
4507 self.assertIn("can't set list.__doc__", str(cm.exception))
4508 with self.assertRaises(TypeError) as cm:
4509 type(X).__dict__["__doc__"].__delete__(X)
4510 self.assertIn("can't delete X.__doc__", str(cm.exception))
4511 self.assertEqual(X.__doc__, "banana")
4512
Antoine Pitrou9d574812011-12-12 13:47:25 +01004513 def test_qualname(self):
4514 descriptors = [str.lower, complex.real, float.real, int.__add__]
4515 types = ['method', 'member', 'getset', 'wrapper']
4516
4517 # make sure we have an example of each type of descriptor
4518 for d, n in zip(descriptors, types):
4519 self.assertEqual(type(d).__name__, n + '_descriptor')
4520
4521 for d in descriptors:
4522 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4523 self.assertEqual(d.__qualname__, qualname)
4524
4525 self.assertEqual(str.lower.__qualname__, 'str.lower')
4526 self.assertEqual(complex.real.__qualname__, 'complex.real')
4527 self.assertEqual(float.real.__qualname__, 'float.real')
4528 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4529
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004530 class X:
4531 pass
4532 with self.assertRaises(TypeError):
4533 del X.__qualname__
4534
4535 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4536 str, 'Oink')
4537
Victor Stinner6f738742012-02-25 01:22:36 +01004538 def test_qualname_dict(self):
4539 ns = {'__qualname__': 'some.name'}
4540 tp = type('Foo', (), ns)
4541 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004542 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004543 self.assertEqual(ns, {'__qualname__': 'some.name'})
4544
4545 ns = {'__qualname__': 1}
4546 self.assertRaises(TypeError, type, 'Foo', (), ns)
4547
Benjamin Peterson52c42432012-03-07 18:41:11 -06004548 def test_cycle_through_dict(self):
4549 # See bug #1469629
4550 class X(dict):
4551 def __init__(self):
4552 dict.__init__(self)
4553 self.__dict__ = self
4554 x = X()
4555 x.attr = 42
4556 wr = weakref.ref(x)
4557 del x
4558 support.gc_collect()
4559 self.assertIsNone(wr())
4560 for o in gc.get_objects():
4561 self.assertIsNot(type(o), X)
4562
Benjamin Peterson96384b92012-03-17 00:05:44 -05004563 def test_object_new_and_init_with_parameters(self):
4564 # See issue #1683368
4565 class OverrideNeither:
4566 pass
4567 self.assertRaises(TypeError, OverrideNeither, 1)
4568 self.assertRaises(TypeError, OverrideNeither, kw=1)
4569 class OverrideNew:
4570 def __new__(cls, foo, kw=0, *args, **kwds):
4571 return object.__new__(cls, *args, **kwds)
4572 class OverrideInit:
4573 def __init__(self, foo, kw=0, *args, **kwargs):
4574 return object.__init__(self, *args, **kwargs)
4575 class OverrideBoth(OverrideNew, OverrideInit):
4576 pass
4577 for case in OverrideNew, OverrideInit, OverrideBoth:
4578 case(1)
4579 case(1, kw=2)
4580 self.assertRaises(TypeError, case, 1, 2, 3)
4581 self.assertRaises(TypeError, case, 1, 2, foo=3)
4582
Antoine Pitrou9d574812011-12-12 13:47:25 +01004583
Georg Brandl479a7e72008-02-05 18:13:15 +00004584class DictProxyTests(unittest.TestCase):
4585 def setUp(self):
4586 class C(object):
4587 def meth(self):
4588 pass
4589 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004590
Brett Cannon7a540732011-02-22 03:04:06 +00004591 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4592 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004593 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004594 # Testing dict-proxy keys...
4595 it = self.C.__dict__.keys()
4596 self.assertNotIsInstance(it, list)
4597 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004598 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004599 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004600 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004601
Brett Cannon7a540732011-02-22 03:04:06 +00004602 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4603 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004604 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004605 # Testing dict-proxy values...
4606 it = self.C.__dict__.values()
4607 self.assertNotIsInstance(it, list)
4608 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004609 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004610
Brett Cannon7a540732011-02-22 03:04:06 +00004611 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4612 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004613 def test_iter_items(self):
4614 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004615 it = self.C.__dict__.items()
4616 self.assertNotIsInstance(it, list)
4617 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004618 keys.sort()
4619 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004620 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004621
Georg Brandl479a7e72008-02-05 18:13:15 +00004622 def test_dict_type_with_metaclass(self):
4623 # Testing type of __dict__ when metaclass set...
4624 class B(object):
4625 pass
4626 class M(type):
4627 pass
4628 class C(metaclass=M):
4629 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4630 pass
4631 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004632
Ezio Melottiac53ab62010-12-18 14:59:43 +00004633 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004634 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004635 # We can't blindly compare with the repr of another dict as ordering
4636 # of keys and values is arbitrary and may differ.
4637 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004638 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004639 self.assertTrue(r.endswith(')'), r)
4640 for k, v in self.C.__dict__.items():
4641 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004642
Christian Heimesbbffeb62008-01-24 09:42:52 +00004643
Georg Brandl479a7e72008-02-05 18:13:15 +00004644class PTypesLongInitTest(unittest.TestCase):
4645 # This is in its own TestCase so that it can be run before any other tests.
4646 def test_pytype_long_ready(self):
4647 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004648
Georg Brandl479a7e72008-02-05 18:13:15 +00004649 # This dumps core when SF bug 551412 isn't fixed --
4650 # but only when test_descr.py is run separately.
4651 # (That can't be helped -- as soon as PyType_Ready()
4652 # is called for PyLong_Type, the bug is gone.)
4653 class UserLong(object):
4654 def __pow__(self, *args):
4655 pass
4656 try:
4657 pow(0, UserLong(), 0)
4658 except:
4659 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004660
Georg Brandl479a7e72008-02-05 18:13:15 +00004661 # Another segfault only when run early
4662 # (before PyType_Ready(tuple) is called)
4663 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004664
4665
Victor Stinnerd74782b2012-03-09 00:39:08 +01004666class MiscTests(unittest.TestCase):
4667 def test_type_lookup_mro_reference(self):
4668 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4669 # the type MRO because it may be modified during the lookup, if
4670 # __bases__ is set during the lookup for example.
4671 class MyKey(object):
4672 def __hash__(self):
4673 return hash('mykey')
4674
4675 def __eq__(self, other):
4676 X.__bases__ = (Base2,)
4677
4678 class Base(object):
4679 mykey = 'from Base'
4680 mykey2 = 'from Base'
4681
4682 class Base2(object):
4683 mykey = 'from Base2'
4684 mykey2 = 'from Base2'
4685
4686 X = type('X', (Base,), {MyKey(): 5})
4687 # mykey is read from Base
4688 self.assertEqual(X.mykey, 'from Base')
4689 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4690 self.assertEqual(X.mykey2, 'from Base2')
4691
4692
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004693def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004694 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004695 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01004696 ClassPropertiesAndMethods, DictProxyTests,
4697 MiscTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004698
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004699if __name__ == "__main__":
4700 test_main()