blob: 1a891a8063c9fe3b7c6b0e9c041d5706ea15e307 [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
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002049 @support.cpython_only
R. David Murray378c0cf2010-02-24 01:46:21 +00002050 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002051 # this segfaulted in 2.5b2
2052 try:
2053 import _testcapi
2054 except ImportError:
2055 pass
2056 else:
2057 class X(object):
2058 p = property(_testcapi.test_with_docstring)
2059
2060 def test_properties_plus(self):
2061 class C(object):
2062 foo = property(doc="hello")
2063 @foo.getter
2064 def foo(self):
2065 return self._foo
2066 @foo.setter
2067 def foo(self, value):
2068 self._foo = abs(value)
2069 @foo.deleter
2070 def foo(self):
2071 del self._foo
2072 c = C()
2073 self.assertEqual(C.foo.__doc__, "hello")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002074 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002075 c.foo = -42
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002076 self.assertHasAttr(c, '_foo')
Georg Brandl479a7e72008-02-05 18:13:15 +00002077 self.assertEqual(c._foo, 42)
2078 self.assertEqual(c.foo, 42)
2079 del c.foo
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002080 self.assertNotHasAttr(c, '_foo')
2081 self.assertNotHasAttr(c, "foo")
Georg Brandl479a7e72008-02-05 18:13:15 +00002082
2083 class D(C):
2084 @C.foo.deleter
2085 def foo(self):
2086 try:
2087 del self._foo
2088 except AttributeError:
2089 pass
2090 d = D()
2091 d.foo = 24
2092 self.assertEqual(d.foo, 24)
2093 del d.foo
2094 del d.foo
2095
2096 class E(object):
2097 @property
2098 def foo(self):
2099 return self._foo
2100 @foo.setter
2101 def foo(self, value):
2102 raise RuntimeError
2103 @foo.setter
2104 def foo(self, value):
2105 self._foo = abs(value)
2106 @foo.deleter
2107 def foo(self, value=None):
2108 del self._foo
2109
2110 e = E()
2111 e.foo = -42
2112 self.assertEqual(e.foo, 42)
2113 del e.foo
2114
2115 class F(E):
2116 @E.foo.deleter
2117 def foo(self):
2118 del self._foo
2119 @foo.setter
2120 def foo(self, value):
2121 self._foo = max(0, value)
2122 f = F()
2123 f.foo = -10
2124 self.assertEqual(f.foo, 0)
2125 del f.foo
2126
2127 def test_dict_constructors(self):
2128 # Testing dict constructor ...
2129 d = dict()
2130 self.assertEqual(d, {})
2131 d = dict({})
2132 self.assertEqual(d, {})
2133 d = dict({1: 2, 'a': 'b'})
2134 self.assertEqual(d, {1: 2, 'a': 'b'})
2135 self.assertEqual(d, dict(list(d.items())))
2136 self.assertEqual(d, dict(iter(d.items())))
2137 d = dict({'one':1, 'two':2})
2138 self.assertEqual(d, dict(one=1, two=2))
2139 self.assertEqual(d, dict(**d))
2140 self.assertEqual(d, dict({"one": 1}, two=2))
2141 self.assertEqual(d, dict([("two", 2)], one=1))
2142 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2143 self.assertEqual(d, dict(**d))
2144
2145 for badarg in 0, 0, 0j, "0", [0], (0,):
2146 try:
2147 dict(badarg)
2148 except TypeError:
2149 pass
2150 except ValueError:
2151 if badarg == "0":
2152 # It's a sequence, and its elements are also sequences (gotta
2153 # love strings <wink>), but they aren't of length 2, so this
2154 # one seemed better as a ValueError than a TypeError.
2155 pass
2156 else:
2157 self.fail("no TypeError from dict(%r)" % badarg)
2158 else:
2159 self.fail("no TypeError from dict(%r)" % badarg)
2160
2161 try:
2162 dict({}, {})
2163 except TypeError:
2164 pass
2165 else:
2166 self.fail("no TypeError from dict({}, {})")
2167
2168 class Mapping:
2169 # Lacks a .keys() method; will be added later.
2170 dict = {1:2, 3:4, 'a':1j}
2171
2172 try:
2173 dict(Mapping())
2174 except TypeError:
2175 pass
2176 else:
2177 self.fail("no TypeError from dict(incomplete mapping)")
2178
2179 Mapping.keys = lambda self: list(self.dict.keys())
2180 Mapping.__getitem__ = lambda self, i: self.dict[i]
2181 d = dict(Mapping())
2182 self.assertEqual(d, Mapping.dict)
2183
2184 # Init from sequence of iterable objects, each producing a 2-sequence.
2185 class AddressBookEntry:
2186 def __init__(self, first, last):
2187 self.first = first
2188 self.last = last
2189 def __iter__(self):
2190 return iter([self.first, self.last])
2191
2192 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2193 AddressBookEntry('Barry', 'Peters'),
2194 AddressBookEntry('Tim', 'Peters'),
2195 AddressBookEntry('Barry', 'Warsaw')])
2196 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2197
2198 d = dict(zip(range(4), range(1, 5)))
2199 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2200
2201 # Bad sequence lengths.
2202 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2203 try:
2204 dict(bad)
2205 except ValueError:
2206 pass
2207 else:
2208 self.fail("no ValueError from dict(%r)" % bad)
2209
2210 def test_dir(self):
2211 # Testing dir() ...
2212 junk = 12
2213 self.assertEqual(dir(), ['junk', 'self'])
2214 del junk
2215
2216 # Just make sure these don't blow up!
2217 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2218 dir(arg)
2219
2220 # Test dir on new-style classes. Since these have object as a
2221 # base class, a lot more gets sucked in.
2222 def interesting(strings):
2223 return [s for s in strings if not s.startswith('_')]
2224
2225 class C(object):
2226 Cdata = 1
2227 def Cmethod(self): pass
2228
2229 cstuff = ['Cdata', 'Cmethod']
2230 self.assertEqual(interesting(dir(C)), cstuff)
2231
2232 c = C()
2233 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002234 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002235
2236 c.cdata = 2
2237 c.cmethod = lambda self: 0
2238 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002239 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002240
2241 class A(C):
2242 Adata = 1
2243 def Amethod(self): pass
2244
2245 astuff = ['Adata', 'Amethod'] + cstuff
2246 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002247 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002248 a = A()
2249 self.assertEqual(interesting(dir(a)), astuff)
2250 a.adata = 42
2251 a.amethod = lambda self: 3
2252 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002253 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002254
2255 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002256 class M(type(sys)):
2257 pass
2258 minstance = M("m")
2259 minstance.b = 2
2260 minstance.a = 1
2261 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2262 self.assertEqual(names, ['a', 'b'])
2263
2264 class M2(M):
2265 def getdict(self):
2266 return "Not a dict!"
2267 __dict__ = property(getdict)
2268
2269 m2instance = M2("m2")
2270 m2instance.b = 2
2271 m2instance.a = 1
2272 self.assertEqual(m2instance.__dict__, "Not a dict!")
2273 try:
2274 dir(m2instance)
2275 except TypeError:
2276 pass
2277
2278 # Two essentially featureless objects, just inheriting stuff from
2279 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002280 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002281
2282 # Nasty test case for proxied objects
2283 class Wrapper(object):
2284 def __init__(self, obj):
2285 self.__obj = obj
2286 def __repr__(self):
2287 return "Wrapper(%s)" % repr(self.__obj)
2288 def __getitem__(self, key):
2289 return Wrapper(self.__obj[key])
2290 def __len__(self):
2291 return len(self.__obj)
2292 def __getattr__(self, name):
2293 return Wrapper(getattr(self.__obj, name))
2294
2295 class C(object):
2296 def __getclass(self):
2297 return Wrapper(type(self))
2298 __class__ = property(__getclass)
2299
2300 dir(C()) # This used to segfault
2301
2302 def test_supers(self):
2303 # Testing super...
2304
2305 class A(object):
2306 def meth(self, a):
2307 return "A(%r)" % a
2308
2309 self.assertEqual(A().meth(1), "A(1)")
2310
2311 class B(A):
2312 def __init__(self):
2313 self.__super = super(B, self)
2314 def meth(self, a):
2315 return "B(%r)" % a + self.__super.meth(a)
2316
2317 self.assertEqual(B().meth(2), "B(2)A(2)")
2318
2319 class C(A):
2320 def meth(self, a):
2321 return "C(%r)" % a + self.__super.meth(a)
2322 C._C__super = super(C)
2323
2324 self.assertEqual(C().meth(3), "C(3)A(3)")
2325
2326 class D(C, B):
2327 def meth(self, a):
2328 return "D(%r)" % a + super(D, self).meth(a)
2329
2330 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2331
2332 # Test for subclassing super
2333
2334 class mysuper(super):
2335 def __init__(self, *args):
2336 return super(mysuper, self).__init__(*args)
2337
2338 class E(D):
2339 def meth(self, a):
2340 return "E(%r)" % a + mysuper(E, self).meth(a)
2341
2342 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2343
2344 class F(E):
2345 def meth(self, a):
2346 s = self.__super # == mysuper(F, self)
2347 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2348 F._F__super = mysuper(F)
2349
2350 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2351
2352 # Make sure certain errors are raised
2353
2354 try:
2355 super(D, 42)
2356 except TypeError:
2357 pass
2358 else:
2359 self.fail("shouldn't allow super(D, 42)")
2360
2361 try:
2362 super(D, C())
2363 except TypeError:
2364 pass
2365 else:
2366 self.fail("shouldn't allow super(D, C())")
2367
2368 try:
2369 super(D).__get__(12)
2370 except TypeError:
2371 pass
2372 else:
2373 self.fail("shouldn't allow super(D).__get__(12)")
2374
2375 try:
2376 super(D).__get__(C())
2377 except TypeError:
2378 pass
2379 else:
2380 self.fail("shouldn't allow super(D).__get__(C())")
2381
2382 # Make sure data descriptors can be overridden and accessed via super
2383 # (new feature in Python 2.3)
2384
2385 class DDbase(object):
2386 def getx(self): return 42
2387 x = property(getx)
2388
2389 class DDsub(DDbase):
2390 def getx(self): return "hello"
2391 x = property(getx)
2392
2393 dd = DDsub()
2394 self.assertEqual(dd.x, "hello")
2395 self.assertEqual(super(DDsub, dd).x, 42)
2396
2397 # Ensure that super() lookup of descriptor from classmethod
2398 # works (SF ID# 743627)
2399
2400 class Base(object):
2401 aProp = property(lambda self: "foo")
2402
2403 class Sub(Base):
2404 @classmethod
2405 def test(klass):
2406 return super(Sub,klass).aProp
2407
2408 self.assertEqual(Sub.test(), Base.aProp)
2409
2410 # Verify that super() doesn't allow keyword args
2411 try:
2412 super(Base, kw=1)
2413 except TypeError:
2414 pass
2415 else:
2416 self.assertEqual("super shouldn't accept keyword args")
2417
2418 def test_basic_inheritance(self):
2419 # Testing inheritance from basic types...
2420
2421 class hexint(int):
2422 def __repr__(self):
2423 return hex(self)
2424 def __add__(self, other):
2425 return hexint(int.__add__(self, other))
2426 # (Note that overriding __radd__ doesn't work,
2427 # because the int type gets first dibs.)
2428 self.assertEqual(repr(hexint(7) + 9), "0x10")
2429 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2430 a = hexint(12345)
2431 self.assertEqual(a, 12345)
2432 self.assertEqual(int(a), 12345)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002433 self.assertIs(int(a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002434 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002435 self.assertIs((+a).__class__, int)
2436 self.assertIs((a >> 0).__class__, int)
2437 self.assertIs((a << 0).__class__, int)
2438 self.assertIs((hexint(0) << 12).__class__, int)
2439 self.assertIs((hexint(0) >> 12).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002440
2441 class octlong(int):
2442 __slots__ = []
2443 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002444 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002445 def __add__(self, other):
2446 return self.__class__(super(octlong, self).__add__(other))
2447 __radd__ = __add__
2448 self.assertEqual(str(octlong(3) + 5), "0o10")
2449 # (Note that overriding __radd__ here only seems to work
2450 # because the example uses a short int left argument.)
2451 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2452 a = octlong(12345)
2453 self.assertEqual(a, 12345)
2454 self.assertEqual(int(a), 12345)
2455 self.assertEqual(hash(a), hash(12345))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002456 self.assertIs(int(a).__class__, int)
2457 self.assertIs((+a).__class__, int)
2458 self.assertIs((-a).__class__, int)
2459 self.assertIs((-octlong(0)).__class__, int)
2460 self.assertIs((a >> 0).__class__, int)
2461 self.assertIs((a << 0).__class__, int)
2462 self.assertIs((a - 0).__class__, int)
2463 self.assertIs((a * 1).__class__, int)
2464 self.assertIs((a ** 1).__class__, int)
2465 self.assertIs((a // 1).__class__, int)
2466 self.assertIs((1 * a).__class__, int)
2467 self.assertIs((a | 0).__class__, int)
2468 self.assertIs((a ^ 0).__class__, int)
2469 self.assertIs((a & -1).__class__, int)
2470 self.assertIs((octlong(0) << 12).__class__, int)
2471 self.assertIs((octlong(0) >> 12).__class__, int)
2472 self.assertIs(abs(octlong(0)).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002473
2474 # Because octlong overrides __add__, we can't check the absence of +0
2475 # optimizations using octlong.
2476 class longclone(int):
2477 pass
2478 a = longclone(1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002479 self.assertIs((a + 0).__class__, int)
2480 self.assertIs((0 + a).__class__, int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002481
2482 # Check that negative clones don't segfault
2483 a = longclone(-1)
2484 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002485 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002486
2487 class precfloat(float):
2488 __slots__ = ['prec']
2489 def __init__(self, value=0.0, prec=12):
2490 self.prec = int(prec)
2491 def __repr__(self):
2492 return "%.*g" % (self.prec, self)
2493 self.assertEqual(repr(precfloat(1.1)), "1.1")
2494 a = precfloat(12345)
2495 self.assertEqual(a, 12345.0)
2496 self.assertEqual(float(a), 12345.0)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002497 self.assertIs(float(a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002498 self.assertEqual(hash(a), hash(12345.0))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002499 self.assertIs((+a).__class__, float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002500
2501 class madcomplex(complex):
2502 def __repr__(self):
2503 return "%.17gj%+.17g" % (self.imag, self.real)
2504 a = madcomplex(-3, 4)
2505 self.assertEqual(repr(a), "4j-3")
2506 base = complex(-3, 4)
2507 self.assertEqual(base.__class__, complex)
2508 self.assertEqual(a, base)
2509 self.assertEqual(complex(a), base)
2510 self.assertEqual(complex(a).__class__, complex)
2511 a = madcomplex(a) # just trying another form of the constructor
2512 self.assertEqual(repr(a), "4j-3")
2513 self.assertEqual(a, base)
2514 self.assertEqual(complex(a), base)
2515 self.assertEqual(complex(a).__class__, complex)
2516 self.assertEqual(hash(a), hash(base))
2517 self.assertEqual((+a).__class__, complex)
2518 self.assertEqual((a + 0).__class__, complex)
2519 self.assertEqual(a + 0, base)
2520 self.assertEqual((a - 0).__class__, complex)
2521 self.assertEqual(a - 0, base)
2522 self.assertEqual((a * 1).__class__, complex)
2523 self.assertEqual(a * 1, base)
2524 self.assertEqual((a / 1).__class__, complex)
2525 self.assertEqual(a / 1, base)
2526
2527 class madtuple(tuple):
2528 _rev = None
2529 def rev(self):
2530 if self._rev is not None:
2531 return self._rev
2532 L = list(self)
2533 L.reverse()
2534 self._rev = self.__class__(L)
2535 return self._rev
2536 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2537 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2538 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2539 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2540 for i in range(512):
2541 t = madtuple(range(i))
2542 u = t.rev()
2543 v = u.rev()
2544 self.assertEqual(v, t)
2545 a = madtuple((1,2,3,4,5))
2546 self.assertEqual(tuple(a), (1,2,3,4,5))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002547 self.assertIs(tuple(a).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002548 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002549 self.assertIs(a[:].__class__, tuple)
2550 self.assertIs((a * 1).__class__, tuple)
2551 self.assertIs((a * 0).__class__, tuple)
2552 self.assertIs((a + ()).__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002553 a = madtuple(())
2554 self.assertEqual(tuple(a), ())
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002555 self.assertIs(tuple(a).__class__, tuple)
2556 self.assertIs((a + a).__class__, tuple)
2557 self.assertIs((a * 0).__class__, tuple)
2558 self.assertIs((a * 1).__class__, tuple)
2559 self.assertIs((a * 2).__class__, tuple)
2560 self.assertIs(a[:].__class__, tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002561
2562 class madstring(str):
2563 _rev = None
2564 def rev(self):
2565 if self._rev is not None:
2566 return self._rev
2567 L = list(self)
2568 L.reverse()
2569 self._rev = self.__class__("".join(L))
2570 return self._rev
2571 s = madstring("abcdefghijklmnopqrstuvwxyz")
2572 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2573 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2574 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2575 for i in range(256):
2576 s = madstring("".join(map(chr, range(i))))
2577 t = s.rev()
2578 u = t.rev()
2579 self.assertEqual(u, s)
2580 s = madstring("12345")
2581 self.assertEqual(str(s), "12345")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002582 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002583
2584 base = "\x00" * 5
2585 s = madstring(base)
2586 self.assertEqual(s, base)
2587 self.assertEqual(str(s), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002588 self.assertIs(str(s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002589 self.assertEqual(hash(s), hash(base))
2590 self.assertEqual({s: 1}[base], 1)
2591 self.assertEqual({base: 1}[s], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002592 self.assertIs((s + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002593 self.assertEqual(s + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002594 self.assertIs(("" + s).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002595 self.assertEqual("" + s, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002596 self.assertIs((s * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002597 self.assertEqual(s * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002598 self.assertIs((s * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002599 self.assertEqual(s * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002600 self.assertIs((s * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002601 self.assertEqual(s * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002602 self.assertIs(s[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002603 self.assertEqual(s[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002604 self.assertIs(s[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002605 self.assertEqual(s[0:0], "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002606 self.assertIs(s.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002607 self.assertEqual(s.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002608 self.assertIs(s.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002609 self.assertEqual(s.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002610 self.assertIs(s.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002611 self.assertEqual(s.rstrip(), base)
2612 identitytab = {}
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002613 self.assertIs(s.translate(identitytab).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002614 self.assertEqual(s.translate(identitytab), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002615 self.assertIs(s.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002616 self.assertEqual(s.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002617 self.assertIs(s.ljust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002618 self.assertEqual(s.ljust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002619 self.assertIs(s.rjust(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002620 self.assertEqual(s.rjust(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002621 self.assertIs(s.center(len(s)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002622 self.assertEqual(s.center(len(s)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002623 self.assertIs(s.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002624 self.assertEqual(s.lower(), base)
2625
2626 class madunicode(str):
2627 _rev = None
2628 def rev(self):
2629 if self._rev is not None:
2630 return self._rev
2631 L = list(self)
2632 L.reverse()
2633 self._rev = self.__class__("".join(L))
2634 return self._rev
2635 u = madunicode("ABCDEF")
2636 self.assertEqual(u, "ABCDEF")
2637 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2638 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2639 base = "12345"
2640 u = madunicode(base)
2641 self.assertEqual(str(u), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002642 self.assertIs(str(u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002643 self.assertEqual(hash(u), hash(base))
2644 self.assertEqual({u: 1}[base], 1)
2645 self.assertEqual({base: 1}[u], 1)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002646 self.assertIs(u.strip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002647 self.assertEqual(u.strip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002648 self.assertIs(u.lstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002649 self.assertEqual(u.lstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002650 self.assertIs(u.rstrip().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002651 self.assertEqual(u.rstrip(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002652 self.assertIs(u.replace("x", "x").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002653 self.assertEqual(u.replace("x", "x"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002654 self.assertIs(u.replace("xy", "xy").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002655 self.assertEqual(u.replace("xy", "xy"), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002656 self.assertIs(u.center(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002657 self.assertEqual(u.center(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002658 self.assertIs(u.ljust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002659 self.assertEqual(u.ljust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002660 self.assertIs(u.rjust(len(u)).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002661 self.assertEqual(u.rjust(len(u)), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002662 self.assertIs(u.lower().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002663 self.assertEqual(u.lower(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002664 self.assertIs(u.upper().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002665 self.assertEqual(u.upper(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002666 self.assertIs(u.capitalize().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002667 self.assertEqual(u.capitalize(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002668 self.assertIs(u.title().__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002669 self.assertEqual(u.title(), base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002670 self.assertIs((u + "").__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002671 self.assertEqual(u + "", base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002672 self.assertIs(("" + u).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002673 self.assertEqual("" + u, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002674 self.assertIs((u * 0).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002675 self.assertEqual(u * 0, "")
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002676 self.assertIs((u * 1).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002677 self.assertEqual(u * 1, base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002678 self.assertIs((u * 2).__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002679 self.assertEqual(u * 2, base + base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002680 self.assertIs(u[:].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002681 self.assertEqual(u[:], base)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002682 self.assertIs(u[0:0].__class__, str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002683 self.assertEqual(u[0:0], "")
2684
2685 class sublist(list):
2686 pass
2687 a = sublist(range(5))
2688 self.assertEqual(a, list(range(5)))
2689 a.append("hello")
2690 self.assertEqual(a, list(range(5)) + ["hello"])
2691 a[5] = 5
2692 self.assertEqual(a, list(range(6)))
2693 a.extend(range(6, 20))
2694 self.assertEqual(a, list(range(20)))
2695 a[-5:] = []
2696 self.assertEqual(a, list(range(15)))
2697 del a[10:15]
2698 self.assertEqual(len(a), 10)
2699 self.assertEqual(a, list(range(10)))
2700 self.assertEqual(list(a), list(range(10)))
2701 self.assertEqual(a[0], 0)
2702 self.assertEqual(a[9], 9)
2703 self.assertEqual(a[-10], 0)
2704 self.assertEqual(a[-1], 9)
2705 self.assertEqual(a[:5], list(range(5)))
2706
2707 ## class CountedInput(file):
2708 ## """Counts lines read by self.readline().
2709 ##
2710 ## self.lineno is the 0-based ordinal of the last line read, up to
2711 ## a maximum of one greater than the number of lines in the file.
2712 ##
2713 ## self.ateof is true if and only if the final "" line has been read,
2714 ## at which point self.lineno stops incrementing, and further calls
2715 ## to readline() continue to return "".
2716 ## """
2717 ##
2718 ## lineno = 0
2719 ## ateof = 0
2720 ## def readline(self):
2721 ## if self.ateof:
2722 ## return ""
2723 ## s = file.readline(self)
2724 ## # Next line works too.
2725 ## # s = super(CountedInput, self).readline()
2726 ## self.lineno += 1
2727 ## if s == "":
2728 ## self.ateof = 1
2729 ## return s
2730 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002731 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002732 ## lines = ['a\n', 'b\n', 'c\n']
2733 ## try:
2734 ## f.writelines(lines)
2735 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002736 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002737 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2738 ## got = f.readline()
2739 ## self.assertEqual(expected, got)
2740 ## self.assertEqual(f.lineno, i)
2741 ## self.assertEqual(f.ateof, (i > len(lines)))
2742 ## f.close()
2743 ## finally:
2744 ## try:
2745 ## f.close()
2746 ## except:
2747 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002748 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002749
2750 def test_keywords(self):
2751 # Testing keyword args to basic type constructors ...
2752 self.assertEqual(int(x=1), 1)
2753 self.assertEqual(float(x=2), 2.0)
2754 self.assertEqual(int(x=3), 3)
2755 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2756 self.assertEqual(str(object=500), '500')
2757 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2758 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2759 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2760 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2761
2762 for constructor in (int, float, int, complex, str, str,
2763 tuple, list):
2764 try:
2765 constructor(bogus_keyword_arg=1)
2766 except TypeError:
2767 pass
2768 else:
2769 self.fail("expected TypeError from bogus keyword argument to %r"
2770 % constructor)
2771
2772 def test_str_subclass_as_dict_key(self):
2773 # Testing a str subclass used as dict key ..
2774
2775 class cistr(str):
2776 """Sublcass of str that computes __eq__ case-insensitively.
2777
2778 Also computes a hash code of the string in canonical form.
2779 """
2780
2781 def __init__(self, value):
2782 self.canonical = value.lower()
2783 self.hashcode = hash(self.canonical)
2784
2785 def __eq__(self, other):
2786 if not isinstance(other, cistr):
2787 other = cistr(other)
2788 return self.canonical == other.canonical
2789
2790 def __hash__(self):
2791 return self.hashcode
2792
2793 self.assertEqual(cistr('ABC'), 'abc')
2794 self.assertEqual('aBc', cistr('ABC'))
2795 self.assertEqual(str(cistr('ABC')), 'ABC')
2796
2797 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2798 self.assertEqual(d[cistr('one')], 1)
2799 self.assertEqual(d[cistr('tWo')], 2)
2800 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002801 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002802 self.assertEqual(d.get(cistr('thrEE')), 3)
2803
2804 def test_classic_comparisons(self):
2805 # Testing classic comparisons...
2806 class classic:
2807 pass
2808
2809 for base in (classic, int, object):
2810 class C(base):
2811 def __init__(self, value):
2812 self.value = int(value)
2813 def __eq__(self, other):
2814 if isinstance(other, C):
2815 return self.value == other.value
2816 if isinstance(other, int) or isinstance(other, int):
2817 return self.value == other
2818 return NotImplemented
2819 def __ne__(self, other):
2820 if isinstance(other, C):
2821 return self.value != other.value
2822 if isinstance(other, int) or isinstance(other, int):
2823 return self.value != other
2824 return NotImplemented
2825 def __lt__(self, other):
2826 if isinstance(other, C):
2827 return self.value < other.value
2828 if isinstance(other, int) or isinstance(other, int):
2829 return self.value < other
2830 return NotImplemented
2831 def __le__(self, other):
2832 if isinstance(other, C):
2833 return self.value <= other.value
2834 if isinstance(other, int) or isinstance(other, int):
2835 return self.value <= other
2836 return NotImplemented
2837 def __gt__(self, other):
2838 if isinstance(other, C):
2839 return self.value > other.value
2840 if isinstance(other, int) or isinstance(other, int):
2841 return self.value > other
2842 return NotImplemented
2843 def __ge__(self, other):
2844 if isinstance(other, C):
2845 return self.value >= other.value
2846 if isinstance(other, int) or isinstance(other, int):
2847 return self.value >= other
2848 return NotImplemented
2849
2850 c1 = C(1)
2851 c2 = C(2)
2852 c3 = C(3)
2853 self.assertEqual(c1, 1)
2854 c = {1: c1, 2: c2, 3: c3}
2855 for x in 1, 2, 3:
2856 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002857 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002858 self.assertEqual(eval("c[x] %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002859 eval("x %s y" % op),
2860 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002861 self.assertEqual(eval("c[x] %s y" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002862 eval("x %s y" % op),
2863 "x=%d, y=%d" % (x, y))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002864 self.assertEqual(eval("x %s c[y]" % op),
Mark Dickinsona56c4672009-01-27 18:17:45 +00002865 eval("x %s y" % op),
2866 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002867
2868 def test_rich_comparisons(self):
2869 # Testing rich comparisons...
2870 class Z(complex):
2871 pass
2872 z = Z(1)
2873 self.assertEqual(z, 1+0j)
2874 self.assertEqual(1+0j, z)
2875 class ZZ(complex):
2876 def __eq__(self, other):
2877 try:
2878 return abs(self - other) <= 1e-6
2879 except:
2880 return NotImplemented
2881 zz = ZZ(1.0000003)
2882 self.assertEqual(zz, 1+0j)
2883 self.assertEqual(1+0j, zz)
2884
2885 class classic:
2886 pass
2887 for base in (classic, int, object, list):
2888 class C(base):
2889 def __init__(self, value):
2890 self.value = int(value)
2891 def __cmp__(self_, other):
2892 self.fail("shouldn't call __cmp__")
2893 def __eq__(self, other):
2894 if isinstance(other, C):
2895 return self.value == other.value
2896 if isinstance(other, int) or isinstance(other, int):
2897 return self.value == other
2898 return NotImplemented
2899 def __ne__(self, other):
2900 if isinstance(other, C):
2901 return self.value != other.value
2902 if isinstance(other, int) or isinstance(other, int):
2903 return self.value != other
2904 return NotImplemented
2905 def __lt__(self, other):
2906 if isinstance(other, C):
2907 return self.value < other.value
2908 if isinstance(other, int) or isinstance(other, int):
2909 return self.value < other
2910 return NotImplemented
2911 def __le__(self, other):
2912 if isinstance(other, C):
2913 return self.value <= other.value
2914 if isinstance(other, int) or isinstance(other, int):
2915 return self.value <= other
2916 return NotImplemented
2917 def __gt__(self, other):
2918 if isinstance(other, C):
2919 return self.value > other.value
2920 if isinstance(other, int) or isinstance(other, int):
2921 return self.value > other
2922 return NotImplemented
2923 def __ge__(self, other):
2924 if isinstance(other, C):
2925 return self.value >= other.value
2926 if isinstance(other, int) or isinstance(other, int):
2927 return self.value >= other
2928 return NotImplemented
2929 c1 = C(1)
2930 c2 = C(2)
2931 c3 = C(3)
2932 self.assertEqual(c1, 1)
2933 c = {1: c1, 2: c2, 3: c3}
2934 for x in 1, 2, 3:
2935 for y in 1, 2, 3:
2936 for op in "<", "<=", "==", "!=", ">", ">=":
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002937 self.assertEqual(eval("c[x] %s c[y]" % op),
2938 eval("x %s y" % op),
2939 "x=%d, y=%d" % (x, y))
2940 self.assertEqual(eval("c[x] %s y" % op),
2941 eval("x %s y" % op),
2942 "x=%d, y=%d" % (x, y))
2943 self.assertEqual(eval("x %s c[y]" % op),
2944 eval("x %s y" % op),
2945 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002946
2947 def test_descrdoc(self):
2948 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002949 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002950 def check(descr, what):
2951 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002952 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002953 check(complex.real, "the real part of a complex number") # member descriptor
2954
2955 def test_doc_descriptor(self):
2956 # Testing __doc__ descriptor...
2957 # SF bug 542984
2958 class DocDescr(object):
2959 def __get__(self, object, otype):
2960 if object:
2961 object = object.__class__.__name__ + ' instance'
2962 if otype:
2963 otype = otype.__name__
2964 return 'object=%s; type=%s' % (object, otype)
2965 class OldClass:
2966 __doc__ = DocDescr()
2967 class NewClass(object):
2968 __doc__ = DocDescr()
2969 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2970 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2971 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2972 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2973
2974 def test_set_class(self):
2975 # Testing __class__ assignment...
2976 class C(object): pass
2977 class D(object): pass
2978 class E(object): pass
2979 class F(D, E): pass
2980 for cls in C, D, E, F:
2981 for cls2 in C, D, E, F:
2982 x = cls()
2983 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002984 self.assertIs(x.__class__, cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002985 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02002986 self.assertIs(x.__class__, cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002987 def cant(x, C):
2988 try:
2989 x.__class__ = C
2990 except TypeError:
2991 pass
2992 else:
2993 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2994 try:
2995 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002996 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002997 pass
2998 else:
2999 self.fail("shouldn't allow del %r.__class__" % x)
3000 cant(C(), list)
3001 cant(list(), C)
3002 cant(C(), 1)
3003 cant(C(), object)
3004 cant(object(), list)
3005 cant(list(), object)
3006 class Int(int): __slots__ = []
3007 cant(2, Int)
3008 cant(Int(), int)
3009 cant(True, int)
3010 cant(2, bool)
3011 o = object()
3012 cant(o, type(1))
3013 cant(o, type(None))
3014 del o
3015 class G(object):
3016 __slots__ = ["a", "b"]
3017 class H(object):
3018 __slots__ = ["b", "a"]
3019 class I(object):
3020 __slots__ = ["a", "b"]
3021 class J(object):
3022 __slots__ = ["c", "b"]
3023 class K(object):
3024 __slots__ = ["a", "b", "d"]
3025 class L(H):
3026 __slots__ = ["e"]
3027 class M(I):
3028 __slots__ = ["e"]
3029 class N(J):
3030 __slots__ = ["__weakref__"]
3031 class P(J):
3032 __slots__ = ["__dict__"]
3033 class Q(J):
3034 pass
3035 class R(J):
3036 __slots__ = ["__dict__", "__weakref__"]
3037
3038 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3039 x = cls()
3040 x.a = 1
3041 x.__class__ = cls2
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003042 self.assertIs(x.__class__, cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003043 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3044 self.assertEqual(x.a, 1)
3045 x.__class__ = cls
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003046 self.assertIs(x.__class__, cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003047 "assigning %r as __class__ for %r silently failed" % (cls, x))
3048 self.assertEqual(x.a, 1)
3049 for cls in G, J, K, L, M, N, P, R, list, Int:
3050 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3051 if cls is cls2:
3052 continue
3053 cant(cls(), cls2)
3054
Benjamin Peterson193152c2009-04-25 01:08:45 +00003055 # Issue5283: when __class__ changes in __del__, the wrong
3056 # type gets DECREF'd.
3057 class O(object):
3058 pass
3059 class A(object):
3060 def __del__(self):
3061 self.__class__ = O
3062 l = [A() for x in range(100)]
3063 del l
3064
Georg Brandl479a7e72008-02-05 18:13:15 +00003065 def test_set_dict(self):
3066 # Testing __dict__ assignment...
3067 class C(object): pass
3068 a = C()
3069 a.__dict__ = {'b': 1}
3070 self.assertEqual(a.b, 1)
3071 def cant(x, dict):
3072 try:
3073 x.__dict__ = dict
3074 except (AttributeError, TypeError):
3075 pass
3076 else:
3077 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3078 cant(a, None)
3079 cant(a, [])
3080 cant(a, 1)
3081 del a.__dict__ # Deleting __dict__ is allowed
3082
3083 class Base(object):
3084 pass
3085 def verify_dict_readonly(x):
3086 """
3087 x has to be an instance of a class inheriting from Base.
3088 """
3089 cant(x, {})
3090 try:
3091 del x.__dict__
3092 except (AttributeError, TypeError):
3093 pass
3094 else:
3095 self.fail("shouldn't allow del %r.__dict__" % x)
3096 dict_descr = Base.__dict__["__dict__"]
3097 try:
3098 dict_descr.__set__(x, {})
3099 except (AttributeError, TypeError):
3100 pass
3101 else:
3102 self.fail("dict_descr allowed access to %r's dict" % x)
3103
3104 # Classes don't allow __dict__ assignment and have readonly dicts
3105 class Meta1(type, Base):
3106 pass
3107 class Meta2(Base, type):
3108 pass
3109 class D(object, metaclass=Meta1):
3110 pass
3111 class E(object, metaclass=Meta2):
3112 pass
3113 for cls in C, D, E:
3114 verify_dict_readonly(cls)
3115 class_dict = cls.__dict__
3116 try:
3117 class_dict["spam"] = "eggs"
3118 except TypeError:
3119 pass
3120 else:
3121 self.fail("%r's __dict__ can be modified" % cls)
3122
3123 # Modules also disallow __dict__ assignment
3124 class Module1(types.ModuleType, Base):
3125 pass
3126 class Module2(Base, types.ModuleType):
3127 pass
3128 for ModuleType in Module1, Module2:
3129 mod = ModuleType("spam")
3130 verify_dict_readonly(mod)
3131 mod.__dict__["spam"] = "eggs"
3132
3133 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003134 # (at least not any more than regular exception's __dict__ can
3135 # be deleted; on CPython it is not the case, whereas on PyPy they
3136 # can, just like any other new-style instance's __dict__.)
3137 def can_delete_dict(e):
3138 try:
3139 del e.__dict__
3140 except (TypeError, AttributeError):
3141 return False
3142 else:
3143 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003144 class Exception1(Exception, Base):
3145 pass
3146 class Exception2(Base, Exception):
3147 pass
3148 for ExceptionType in Exception, Exception1, Exception2:
3149 e = ExceptionType()
3150 e.__dict__ = {"a": 1}
3151 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003152 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003153
3154 def test_pickles(self):
3155 # Testing pickling and copying new-style classes and objects...
3156 import pickle
3157
3158 def sorteditems(d):
3159 L = list(d.items())
3160 L.sort()
3161 return L
3162
3163 global C
3164 class C(object):
3165 def __init__(self, a, b):
3166 super(C, self).__init__()
3167 self.a = a
3168 self.b = b
3169 def __repr__(self):
3170 return "C(%r, %r)" % (self.a, self.b)
3171
3172 global C1
3173 class C1(list):
3174 def __new__(cls, a, b):
3175 return super(C1, cls).__new__(cls)
3176 def __getnewargs__(self):
3177 return (self.a, self.b)
3178 def __init__(self, a, b):
3179 self.a = a
3180 self.b = b
3181 def __repr__(self):
3182 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3183
3184 global C2
3185 class C2(int):
3186 def __new__(cls, a, b, val=0):
3187 return super(C2, cls).__new__(cls, val)
3188 def __getnewargs__(self):
3189 return (self.a, self.b, int(self))
3190 def __init__(self, a, b, val=0):
3191 self.a = a
3192 self.b = b
3193 def __repr__(self):
3194 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3195
3196 global C3
3197 class C3(object):
3198 def __init__(self, foo):
3199 self.foo = foo
3200 def __getstate__(self):
3201 return self.foo
3202 def __setstate__(self, foo):
3203 self.foo = foo
3204
3205 global C4classic, C4
3206 class C4classic: # classic
3207 pass
3208 class C4(C4classic, object): # mixed inheritance
3209 pass
3210
Guido van Rossum3926a632001-09-25 16:25:58 +00003211 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003212 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003213 s = pickle.dumps(cls, bin)
3214 cls2 = pickle.loads(s)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003215 self.assertIs(cls2, cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003216
3217 a = C1(1, 2); a.append(42); a.append(24)
3218 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003219 s = pickle.dumps((a, b), bin)
3220 x, y = pickle.loads(s)
3221 self.assertEqual(x.__class__, a.__class__)
3222 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3223 self.assertEqual(y.__class__, b.__class__)
3224 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3225 self.assertEqual(repr(x), repr(a))
3226 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003227 # Test for __getstate__ and __setstate__ on new style class
3228 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003229 s = pickle.dumps(u, bin)
3230 v = pickle.loads(s)
3231 self.assertEqual(u.__class__, v.__class__)
3232 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003233 # Test for picklability of hybrid class
3234 u = C4()
3235 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003236 s = pickle.dumps(u, bin)
3237 v = pickle.loads(s)
3238 self.assertEqual(u.__class__, v.__class__)
3239 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003240
Georg Brandl479a7e72008-02-05 18:13:15 +00003241 # Testing copy.deepcopy()
3242 import copy
3243 for cls in C, C1, C2:
3244 cls2 = copy.deepcopy(cls)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003245 self.assertIs(cls2, cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003246
Georg Brandl479a7e72008-02-05 18:13:15 +00003247 a = C1(1, 2); a.append(42); a.append(24)
3248 b = C2("hello", "world", 42)
3249 x, y = copy.deepcopy((a, b))
3250 self.assertEqual(x.__class__, a.__class__)
3251 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3252 self.assertEqual(y.__class__, b.__class__)
3253 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3254 self.assertEqual(repr(x), repr(a))
3255 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003256
Georg Brandl479a7e72008-02-05 18:13:15 +00003257 def test_pickle_slots(self):
3258 # Testing pickling of classes with __slots__ ...
3259 import pickle
3260 # Pickling of classes with __slots__ but without __getstate__ should fail
3261 # (if using protocol 0 or 1)
3262 global B, C, D, E
3263 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003264 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003265 for base in [object, B]:
3266 class C(base):
3267 __slots__ = ['a']
3268 class D(C):
3269 pass
3270 try:
3271 pickle.dumps(C(), 0)
3272 except TypeError:
3273 pass
3274 else:
3275 self.fail("should fail: pickle C instance - %s" % base)
3276 try:
3277 pickle.dumps(C(), 0)
3278 except TypeError:
3279 pass
3280 else:
3281 self.fail("should fail: pickle D instance - %s" % base)
3282 # Give C a nice generic __getstate__ and __setstate__
3283 class C(base):
3284 __slots__ = ['a']
3285 def __getstate__(self):
3286 try:
3287 d = self.__dict__.copy()
3288 except AttributeError:
3289 d = {}
3290 for cls in self.__class__.__mro__:
3291 for sn in cls.__dict__.get('__slots__', ()):
3292 try:
3293 d[sn] = getattr(self, sn)
3294 except AttributeError:
3295 pass
3296 return d
3297 def __setstate__(self, d):
3298 for k, v in list(d.items()):
3299 setattr(self, k, v)
3300 class D(C):
3301 pass
3302 # Now it should work
3303 x = C()
3304 y = pickle.loads(pickle.dumps(x))
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003305 self.assertNotHasAttr(y, 'a')
Georg Brandl479a7e72008-02-05 18:13:15 +00003306 x.a = 42
3307 y = pickle.loads(pickle.dumps(x))
3308 self.assertEqual(y.a, 42)
3309 x = D()
3310 x.a = 42
3311 x.b = 100
3312 y = pickle.loads(pickle.dumps(x))
3313 self.assertEqual(y.a + y.b, 142)
3314 # A subclass that adds a slot should also work
3315 class E(C):
3316 __slots__ = ['b']
3317 x = E()
3318 x.a = 42
3319 x.b = "foo"
3320 y = pickle.loads(pickle.dumps(x))
3321 self.assertEqual(y.a, x.a)
3322 self.assertEqual(y.b, x.b)
3323
3324 def test_binary_operator_override(self):
3325 # Testing overrides of binary operations...
3326 class I(int):
3327 def __repr__(self):
3328 return "I(%r)" % int(self)
3329 def __add__(self, other):
3330 return I(int(self) + int(other))
3331 __radd__ = __add__
3332 def __pow__(self, other, mod=None):
3333 if mod is None:
3334 return I(pow(int(self), int(other)))
3335 else:
3336 return I(pow(int(self), int(other), int(mod)))
3337 def __rpow__(self, other, mod=None):
3338 if mod is None:
3339 return I(pow(int(other), int(self), mod))
3340 else:
3341 return I(pow(int(other), int(self), int(mod)))
3342
3343 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3344 self.assertEqual(repr(I(1) + 2), "I(3)")
3345 self.assertEqual(repr(1 + I(2)), "I(3)")
3346 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3347 self.assertEqual(repr(2 ** I(3)), "I(8)")
3348 self.assertEqual(repr(I(2) ** 3), "I(8)")
3349 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3350 class S(str):
3351 def __eq__(self, other):
3352 return self.lower() == other.lower()
3353
3354 def test_subclass_propagation(self):
3355 # Testing propagation of slot functions to subclasses...
3356 class A(object):
3357 pass
3358 class B(A):
3359 pass
3360 class C(A):
3361 pass
3362 class D(B, C):
3363 pass
3364 d = D()
3365 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3366 A.__hash__ = lambda self: 42
3367 self.assertEqual(hash(d), 42)
3368 C.__hash__ = lambda self: 314
3369 self.assertEqual(hash(d), 314)
3370 B.__hash__ = lambda self: 144
3371 self.assertEqual(hash(d), 144)
3372 D.__hash__ = lambda self: 100
3373 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003374 D.__hash__ = None
3375 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003376 del D.__hash__
3377 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003378 B.__hash__ = None
3379 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003380 del B.__hash__
3381 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003382 C.__hash__ = None
3383 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003384 del C.__hash__
3385 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003386 A.__hash__ = None
3387 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003388 del A.__hash__
3389 self.assertEqual(hash(d), orig_hash)
3390 d.foo = 42
3391 d.bar = 42
3392 self.assertEqual(d.foo, 42)
3393 self.assertEqual(d.bar, 42)
3394 def __getattribute__(self, name):
3395 if name == "foo":
3396 return 24
3397 return object.__getattribute__(self, name)
3398 A.__getattribute__ = __getattribute__
3399 self.assertEqual(d.foo, 24)
3400 self.assertEqual(d.bar, 42)
3401 def __getattr__(self, name):
3402 if name in ("spam", "foo", "bar"):
3403 return "hello"
3404 raise AttributeError(name)
3405 B.__getattr__ = __getattr__
3406 self.assertEqual(d.spam, "hello")
3407 self.assertEqual(d.foo, 24)
3408 self.assertEqual(d.bar, 42)
3409 del A.__getattribute__
3410 self.assertEqual(d.foo, 42)
3411 del d.foo
3412 self.assertEqual(d.foo, "hello")
3413 self.assertEqual(d.bar, 42)
3414 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003415 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003416 d.foo
3417 except AttributeError:
3418 pass
3419 else:
3420 self.fail("d.foo should be undefined now")
3421
3422 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003423 class A(object):
3424 pass
3425 class B(A):
3426 pass
3427 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003428 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003429 A.__setitem__ = lambda *a: None # crash
3430
3431 def test_buffer_inheritance(self):
3432 # Testing that buffer interface is inherited ...
3433
3434 import binascii
3435 # SF bug [#470040] ParseTuple t# vs subclasses.
3436
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003437 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003438 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003439 base = b'abc'
3440 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003441 # b2a_hex uses the buffer interface to get its argument's value, via
3442 # PyArg_ParseTuple 't#' code.
3443 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3444
Georg Brandl479a7e72008-02-05 18:13:15 +00003445 class MyInt(int):
3446 pass
3447 m = MyInt(42)
3448 try:
3449 binascii.b2a_hex(m)
3450 self.fail('subclass of int should not have a buffer interface')
3451 except TypeError:
3452 pass
3453
3454 def test_str_of_str_subclass(self):
3455 # Testing __str__ defined in subclass of str ...
3456 import binascii
3457 import io
3458
3459 class octetstring(str):
3460 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003461 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003462 def __repr__(self):
3463 return self + " repr"
3464
3465 o = octetstring('A')
3466 self.assertEqual(type(o), octetstring)
3467 self.assertEqual(type(str(o)), str)
3468 self.assertEqual(type(repr(o)), str)
3469 self.assertEqual(ord(o), 0x41)
3470 self.assertEqual(str(o), '41')
3471 self.assertEqual(repr(o), 'A repr')
3472 self.assertEqual(o.__str__(), '41')
3473 self.assertEqual(o.__repr__(), 'A repr')
3474
3475 capture = io.StringIO()
3476 # Calling str() or not exercises different internal paths.
3477 print(o, file=capture)
3478 print(str(o), file=capture)
3479 self.assertEqual(capture.getvalue(), '41\n41\n')
3480 capture.close()
3481
3482 def test_keyword_arguments(self):
3483 # Testing keyword arguments to __init__, __call__...
3484 def f(a): return a
3485 self.assertEqual(f.__call__(a=42), 42)
3486 a = []
3487 list.__init__(a, sequence=[0, 1, 2])
3488 self.assertEqual(a, [0, 1, 2])
3489
3490 def test_recursive_call(self):
3491 # Testing recursive __call__() by setting to instance of class...
3492 class A(object):
3493 pass
3494
3495 A.__call__ = A()
3496 try:
3497 A()()
3498 except RuntimeError:
3499 pass
3500 else:
3501 self.fail("Recursion limit should have been reached for __call__()")
3502
3503 def test_delete_hook(self):
3504 # Testing __del__ hook...
3505 log = []
3506 class C(object):
3507 def __del__(self):
3508 log.append(1)
3509 c = C()
3510 self.assertEqual(log, [])
3511 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003512 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003513 self.assertEqual(log, [1])
3514
3515 class D(object): pass
3516 d = D()
3517 try: del d[0]
3518 except TypeError: pass
3519 else: self.fail("invalid del() didn't raise TypeError")
3520
3521 def test_hash_inheritance(self):
3522 # Testing hash of mutable subclasses...
3523
3524 class mydict(dict):
3525 pass
3526 d = mydict()
3527 try:
3528 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003529 except TypeError:
3530 pass
3531 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003532 self.fail("hash() of dict subclass should fail")
3533
3534 class mylist(list):
3535 pass
3536 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003537 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003538 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003539 except TypeError:
3540 pass
3541 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003542 self.fail("hash() of list subclass should fail")
3543
3544 def test_str_operations(self):
3545 try: 'a' + 5
3546 except TypeError: pass
3547 else: self.fail("'' + 5 doesn't raise TypeError")
3548
3549 try: ''.split('')
3550 except ValueError: pass
3551 else: self.fail("''.split('') doesn't raise ValueError")
3552
3553 try: ''.join([0])
3554 except TypeError: pass
3555 else: self.fail("''.join([0]) doesn't raise TypeError")
3556
3557 try: ''.rindex('5')
3558 except ValueError: pass
3559 else: self.fail("''.rindex('5') doesn't raise ValueError")
3560
3561 try: '%(n)s' % None
3562 except TypeError: pass
3563 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3564
3565 try: '%(n' % {}
3566 except ValueError: pass
3567 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3568
3569 try: '%*s' % ('abc')
3570 except TypeError: pass
3571 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3572
3573 try: '%*.*s' % ('abc', 5)
3574 except TypeError: pass
3575 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3576
3577 try: '%s' % (1, 2)
3578 except TypeError: pass
3579 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3580
3581 try: '%' % None
3582 except ValueError: pass
3583 else: self.fail("'%' % None doesn't raise ValueError")
3584
3585 self.assertEqual('534253'.isdigit(), 1)
3586 self.assertEqual('534253x'.isdigit(), 0)
3587 self.assertEqual('%c' % 5, '\x05')
3588 self.assertEqual('%c' % '5', '5')
3589
3590 def test_deepcopy_recursive(self):
3591 # Testing deepcopy of recursive objects...
3592 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003593 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003594 a = Node()
3595 b = Node()
3596 a.b = b
3597 b.a = a
3598 z = deepcopy(a) # This blew up before
3599
3600 def test_unintialized_modules(self):
3601 # Testing uninitialized module objects...
3602 from types import ModuleType as M
3603 m = M.__new__(M)
3604 str(m)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003605 self.assertNotHasAttr(m, "__name__")
3606 self.assertNotHasAttr(m, "__file__")
3607 self.assertNotHasAttr(m, "foo")
Benjamin Petersone549ead2009-03-28 21:42:05 +00003608 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003609 m.foo = 1
3610 self.assertEqual(m.__dict__, {"foo": 1})
3611
3612 def test_funny_new(self):
3613 # Testing __new__ returning something unexpected...
3614 class C(object):
3615 def __new__(cls, arg):
3616 if isinstance(arg, str): return [1, 2, 3]
3617 elif isinstance(arg, int): return object.__new__(D)
3618 else: return object.__new__(cls)
3619 class D(C):
3620 def __init__(self, arg):
3621 self.foo = arg
3622 self.assertEqual(C("1"), [1, 2, 3])
3623 self.assertEqual(D("1"), [1, 2, 3])
3624 d = D(None)
3625 self.assertEqual(d.foo, None)
3626 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003627 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003628 self.assertEqual(d.foo, 1)
3629 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003630 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003631 self.assertEqual(d.foo, 1)
3632
3633 def test_imul_bug(self):
3634 # Testing for __imul__ problems...
3635 # SF bug 544647
3636 class C(object):
3637 def __imul__(self, other):
3638 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003639 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003640 y = x
3641 y *= 1.0
3642 self.assertEqual(y, (x, 1.0))
3643 y = x
3644 y *= 2
3645 self.assertEqual(y, (x, 2))
3646 y = x
3647 y *= 3
3648 self.assertEqual(y, (x, 3))
3649 y = x
3650 y *= 1<<100
3651 self.assertEqual(y, (x, 1<<100))
3652 y = x
3653 y *= None
3654 self.assertEqual(y, (x, None))
3655 y = x
3656 y *= "foo"
3657 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003658
Georg Brandl479a7e72008-02-05 18:13:15 +00003659 def test_copy_setstate(self):
3660 # Testing that copy.*copy() correctly uses __setstate__...
3661 import copy
3662 class C(object):
3663 def __init__(self, foo=None):
3664 self.foo = foo
3665 self.__foo = foo
3666 def setfoo(self, foo=None):
3667 self.foo = foo
3668 def getfoo(self):
3669 return self.__foo
3670 def __getstate__(self):
3671 return [self.foo]
3672 def __setstate__(self_, lst):
3673 self.assertEqual(len(lst), 1)
3674 self_.__foo = self_.foo = lst[0]
3675 a = C(42)
3676 a.setfoo(24)
3677 self.assertEqual(a.foo, 24)
3678 self.assertEqual(a.getfoo(), 42)
3679 b = copy.copy(a)
3680 self.assertEqual(b.foo, 24)
3681 self.assertEqual(b.getfoo(), 24)
3682 b = copy.deepcopy(a)
3683 self.assertEqual(b.foo, 24)
3684 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003685
Georg Brandl479a7e72008-02-05 18:13:15 +00003686 def test_slices(self):
3687 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003688
Georg Brandl479a7e72008-02-05 18:13:15 +00003689 # Strings
3690 self.assertEqual("hello"[:4], "hell")
3691 self.assertEqual("hello"[slice(4)], "hell")
3692 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3693 class S(str):
3694 def __getitem__(self, x):
3695 return str.__getitem__(self, x)
3696 self.assertEqual(S("hello")[:4], "hell")
3697 self.assertEqual(S("hello")[slice(4)], "hell")
3698 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3699 # Tuples
3700 self.assertEqual((1,2,3)[:2], (1,2))
3701 self.assertEqual((1,2,3)[slice(2)], (1,2))
3702 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3703 class T(tuple):
3704 def __getitem__(self, x):
3705 return tuple.__getitem__(self, x)
3706 self.assertEqual(T((1,2,3))[:2], (1,2))
3707 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3708 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3709 # Lists
3710 self.assertEqual([1,2,3][:2], [1,2])
3711 self.assertEqual([1,2,3][slice(2)], [1,2])
3712 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3713 class L(list):
3714 def __getitem__(self, x):
3715 return list.__getitem__(self, x)
3716 self.assertEqual(L([1,2,3])[:2], [1,2])
3717 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3718 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3719 # Now do lists and __setitem__
3720 a = L([1,2,3])
3721 a[slice(1, 3)] = [3,2]
3722 self.assertEqual(a, [1,3,2])
3723 a[slice(0, 2, 1)] = [3,1]
3724 self.assertEqual(a, [3,1,2])
3725 a.__setitem__(slice(1, 3), [2,1])
3726 self.assertEqual(a, [3,2,1])
3727 a.__setitem__(slice(0, 2, 1), [2,3])
3728 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003729
Georg Brandl479a7e72008-02-05 18:13:15 +00003730 def test_subtype_resurrection(self):
3731 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003732
Georg Brandl479a7e72008-02-05 18:13:15 +00003733 class C(object):
3734 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003735
Georg Brandl479a7e72008-02-05 18:13:15 +00003736 def __del__(self):
3737 # resurrect the instance
3738 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003739
Georg Brandl479a7e72008-02-05 18:13:15 +00003740 c = C()
3741 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003742
Benjamin Petersone549ead2009-03-28 21:42:05 +00003743 # The most interesting thing here is whether this blows up, due to
3744 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3745 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003746 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003747
Georg Brandl479a7e72008-02-05 18:13:15 +00003748 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003749 # the last container slot works: that will attempt to delete c again,
3750 # which will cause c to get appended back to the container again
3751 # "during" the del. (On non-CPython implementations, however, __del__
3752 # is typically not called again.)
3753 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003754 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003755 del C.container[-1]
3756 if support.check_impl_detail():
3757 support.gc_collect()
3758 self.assertEqual(len(C.container), 1)
3759 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003760
Georg Brandl479a7e72008-02-05 18:13:15 +00003761 # Make c mortal again, so that the test framework with -l doesn't report
3762 # it as a leak.
3763 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003764
Georg Brandl479a7e72008-02-05 18:13:15 +00003765 def test_slots_trash(self):
3766 # Testing slot trash...
3767 # Deallocating deeply nested slotted trash caused stack overflows
3768 class trash(object):
3769 __slots__ = ['x']
3770 def __init__(self, x):
3771 self.x = x
3772 o = None
3773 for i in range(50000):
3774 o = trash(o)
3775 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003776
Georg Brandl479a7e72008-02-05 18:13:15 +00003777 def test_slots_multiple_inheritance(self):
3778 # SF bug 575229, multiple inheritance w/ slots dumps core
3779 class A(object):
3780 __slots__=()
3781 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003782 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 class C(A,B) :
3784 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003785 if support.check_impl_detail():
3786 self.assertEqual(C.__basicsize__, B.__basicsize__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02003787 self.assertHasAttr(C, '__dict__')
3788 self.assertHasAttr(C, '__weakref__')
Georg Brandl479a7e72008-02-05 18:13:15 +00003789 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003790
Georg Brandl479a7e72008-02-05 18:13:15 +00003791 def test_rmul(self):
3792 # Testing correct invocation of __rmul__...
3793 # SF patch 592646
3794 class C(object):
3795 def __mul__(self, other):
3796 return "mul"
3797 def __rmul__(self, other):
3798 return "rmul"
3799 a = C()
3800 self.assertEqual(a*2, "mul")
3801 self.assertEqual(a*2.2, "mul")
3802 self.assertEqual(2*a, "rmul")
3803 self.assertEqual(2.2*a, "rmul")
3804
3805 def test_ipow(self):
3806 # Testing correct invocation of __ipow__...
3807 # [SF bug 620179]
3808 class C(object):
3809 def __ipow__(self, other):
3810 pass
3811 a = C()
3812 a **= 2
3813
3814 def test_mutable_bases(self):
3815 # Testing mutable bases...
3816
3817 # stuff that should work:
3818 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003819 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003820 class C2(object):
3821 def __getattribute__(self, attr):
3822 if attr == 'a':
3823 return 2
3824 else:
3825 return super(C2, self).__getattribute__(attr)
3826 def meth(self):
3827 return 1
3828 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003829 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003830 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003831 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003832 d = D()
3833 e = E()
3834 D.__bases__ = (C,)
3835 D.__bases__ = (C2,)
3836 self.assertEqual(d.meth(), 1)
3837 self.assertEqual(e.meth(), 1)
3838 self.assertEqual(d.a, 2)
3839 self.assertEqual(e.a, 2)
3840 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003841
Georg Brandl479a7e72008-02-05 18:13:15 +00003842 try:
3843 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003844 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003845 pass
3846 else:
3847 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003848
Georg Brandl479a7e72008-02-05 18:13:15 +00003849 try:
3850 D.__bases__ = ()
3851 except TypeError as msg:
3852 if str(msg) == "a new-style class can't have only classic bases":
3853 self.fail("wrong error message for .__bases__ = ()")
3854 else:
3855 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003856
Georg Brandl479a7e72008-02-05 18:13:15 +00003857 try:
3858 D.__bases__ = (D,)
3859 except TypeError:
3860 pass
3861 else:
3862 # actually, we'll have crashed by here...
3863 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003864
Georg Brandl479a7e72008-02-05 18:13:15 +00003865 try:
3866 D.__bases__ = (C, C)
3867 except TypeError:
3868 pass
3869 else:
3870 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003871
Georg Brandl479a7e72008-02-05 18:13:15 +00003872 try:
3873 D.__bases__ = (E,)
3874 except TypeError:
3875 pass
3876 else:
3877 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003878
Benjamin Petersonae937c02009-04-18 20:54:08 +00003879 def test_builtin_bases(self):
3880 # Make sure all the builtin types can have their base queried without
3881 # segfaulting. See issue #5787.
3882 builtin_types = [tp for tp in builtins.__dict__.values()
3883 if isinstance(tp, type)]
3884 for tp in builtin_types:
3885 object.__getattribute__(tp, "__bases__")
3886 if tp is not object:
3887 self.assertEqual(len(tp.__bases__), 1, tp)
3888
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003889 class L(list):
3890 pass
3891
3892 class C(object):
3893 pass
3894
3895 class D(C):
3896 pass
3897
3898 try:
3899 L.__bases__ = (dict,)
3900 except TypeError:
3901 pass
3902 else:
3903 self.fail("shouldn't turn list subclass into dict subclass")
3904
3905 try:
3906 list.__bases__ = (dict,)
3907 except TypeError:
3908 pass
3909 else:
3910 self.fail("shouldn't be able to assign to list.__bases__")
3911
3912 try:
3913 D.__bases__ = (C, list)
3914 except TypeError:
3915 pass
3916 else:
3917 assert 0, "best_base calculation found wanting"
3918
Benjamin Petersonae937c02009-04-18 20:54:08 +00003919
Georg Brandl479a7e72008-02-05 18:13:15 +00003920 def test_mutable_bases_with_failing_mro(self):
3921 # Testing mutable bases with failing mro...
3922 class WorkOnce(type):
3923 def __new__(self, name, bases, ns):
3924 self.flag = 0
3925 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3926 def mro(self):
3927 if self.flag > 0:
3928 raise RuntimeError("bozo")
3929 else:
3930 self.flag += 1
3931 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003932
Georg Brandl479a7e72008-02-05 18:13:15 +00003933 class WorkAlways(type):
3934 def mro(self):
3935 # this is here to make sure that .mro()s aren't called
3936 # with an exception set (which was possible at one point).
3937 # An error message will be printed in a debug build.
3938 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003939 return type.mro(self)
3940
Georg Brandl479a7e72008-02-05 18:13:15 +00003941 class C(object):
3942 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003943
Georg Brandl479a7e72008-02-05 18:13:15 +00003944 class C2(object):
3945 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003946
Georg Brandl479a7e72008-02-05 18:13:15 +00003947 class D(C):
3948 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003949
Georg Brandl479a7e72008-02-05 18:13:15 +00003950 class E(D):
3951 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003952
Georg Brandl479a7e72008-02-05 18:13:15 +00003953 class F(D, metaclass=WorkOnce):
3954 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003955
Georg Brandl479a7e72008-02-05 18:13:15 +00003956 class G(D, metaclass=WorkAlways):
3957 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003958
Georg Brandl479a7e72008-02-05 18:13:15 +00003959 # Immediate subclasses have their mro's adjusted in alphabetical
3960 # order, so E's will get adjusted before adjusting F's fails. We
3961 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003962
Georg Brandl479a7e72008-02-05 18:13:15 +00003963 E_mro_before = E.__mro__
3964 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003965
Armin Rigofd163f92005-12-29 15:59:19 +00003966 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003967 D.__bases__ = (C2,)
3968 except RuntimeError:
3969 self.assertEqual(E.__mro__, E_mro_before)
3970 self.assertEqual(D.__mro__, D_mro_before)
3971 else:
3972 self.fail("exception not propagated")
3973
3974 def test_mutable_bases_catch_mro_conflict(self):
3975 # Testing mutable bases catch mro conflict...
3976 class A(object):
3977 pass
3978
3979 class B(object):
3980 pass
3981
3982 class C(A, B):
3983 pass
3984
3985 class D(A, B):
3986 pass
3987
3988 class E(C, D):
3989 pass
3990
3991 try:
3992 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003993 except TypeError:
3994 pass
3995 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003996 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003997
Georg Brandl479a7e72008-02-05 18:13:15 +00003998 def test_mutable_names(self):
3999 # Testing mutable names...
4000 class C(object):
4001 pass
4002
4003 # C.__module__ could be 'test_descr' or '__main__'
4004 mod = C.__module__
4005
4006 C.__name__ = 'D'
4007 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4008
4009 C.__name__ = 'D.E'
4010 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4011
Mark Dickinson64aafeb2013-04-13 15:26:58 +01004012 def test_evil_type_name(self):
4013 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4014 # execution while the type structure was not in a sane state, and a
4015 # possible segmentation fault as a result. See bug #16447.
4016 class Nasty(str):
4017 def __del__(self):
4018 C.__name__ = "other"
4019
4020 class C:
4021 pass
4022
4023 C.__name__ = Nasty("abc")
4024 C.__name__ = "normal"
4025
Georg Brandl479a7e72008-02-05 18:13:15 +00004026 def test_subclass_right_op(self):
4027 # Testing correct dispatch of subclass overloading __r<op>__...
4028
4029 # This code tests various cases where right-dispatch of a subclass
4030 # should be preferred over left-dispatch of a base class.
4031
4032 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4033
4034 class B(int):
4035 def __floordiv__(self, other):
4036 return "B.__floordiv__"
4037 def __rfloordiv__(self, other):
4038 return "B.__rfloordiv__"
4039
4040 self.assertEqual(B(1) // 1, "B.__floordiv__")
4041 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4042
4043 # Case 2: subclass of object; this is just the baseline for case 3
4044
4045 class C(object):
4046 def __floordiv__(self, other):
4047 return "C.__floordiv__"
4048 def __rfloordiv__(self, other):
4049 return "C.__rfloordiv__"
4050
4051 self.assertEqual(C() // 1, "C.__floordiv__")
4052 self.assertEqual(1 // C(), "C.__rfloordiv__")
4053
4054 # Case 3: subclass of new-style class; here it gets interesting
4055
4056 class D(C):
4057 def __floordiv__(self, other):
4058 return "D.__floordiv__"
4059 def __rfloordiv__(self, other):
4060 return "D.__rfloordiv__"
4061
4062 self.assertEqual(D() // C(), "D.__floordiv__")
4063 self.assertEqual(C() // D(), "D.__rfloordiv__")
4064
4065 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4066
4067 class E(C):
4068 pass
4069
4070 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4071
4072 self.assertEqual(E() // 1, "C.__floordiv__")
4073 self.assertEqual(1 // E(), "C.__rfloordiv__")
4074 self.assertEqual(E() // C(), "C.__floordiv__")
4075 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4076
Benjamin Petersone549ead2009-03-28 21:42:05 +00004077 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004078 def test_meth_class_get(self):
4079 # Testing __get__ method of METH_CLASS C methods...
4080 # Full coverage of descrobject.c::classmethod_get()
4081
4082 # Baseline
4083 arg = [1, 2, 3]
4084 res = {1: None, 2: None, 3: None}
4085 self.assertEqual(dict.fromkeys(arg), res)
4086 self.assertEqual({}.fromkeys(arg), res)
4087
4088 # Now get the descriptor
4089 descr = dict.__dict__["fromkeys"]
4090
4091 # More baseline using the descriptor directly
4092 self.assertEqual(descr.__get__(None, dict)(arg), res)
4093 self.assertEqual(descr.__get__({})(arg), res)
4094
4095 # Now check various error cases
4096 try:
4097 descr.__get__(None, None)
4098 except TypeError:
4099 pass
4100 else:
4101 self.fail("shouldn't have allowed descr.__get__(None, None)")
4102 try:
4103 descr.__get__(42)
4104 except TypeError:
4105 pass
4106 else:
4107 self.fail("shouldn't have allowed descr.__get__(42)")
4108 try:
4109 descr.__get__(None, 42)
4110 except TypeError:
4111 pass
4112 else:
4113 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4114 try:
4115 descr.__get__(None, int)
4116 except TypeError:
4117 pass
4118 else:
4119 self.fail("shouldn't have allowed descr.__get__(None, int)")
4120
4121 def test_isinst_isclass(self):
4122 # Testing proxy isinstance() and isclass()...
4123 class Proxy(object):
4124 def __init__(self, obj):
4125 self.__obj = obj
4126 def __getattribute__(self, name):
4127 if name.startswith("_Proxy__"):
4128 return object.__getattribute__(self, name)
4129 else:
4130 return getattr(self.__obj, name)
4131 # Test with a classic class
4132 class C:
4133 pass
4134 a = C()
4135 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004136 self.assertIsInstance(a, C) # Baseline
4137 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004138 # Test with a classic subclass
4139 class D(C):
4140 pass
4141 a = D()
4142 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004143 self.assertIsInstance(a, C) # Baseline
4144 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004145 # Test with a new-style class
4146 class C(object):
4147 pass
4148 a = C()
4149 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004150 self.assertIsInstance(a, C) # Baseline
4151 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004152 # Test with a new-style subclass
4153 class D(C):
4154 pass
4155 a = D()
4156 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004157 self.assertIsInstance(a, C) # Baseline
4158 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004159
4160 def test_proxy_super(self):
4161 # Testing super() for a proxy object...
4162 class Proxy(object):
4163 def __init__(self, obj):
4164 self.__obj = obj
4165 def __getattribute__(self, name):
4166 if name.startswith("_Proxy__"):
4167 return object.__getattribute__(self, name)
4168 else:
4169 return getattr(self.__obj, name)
4170
4171 class B(object):
4172 def f(self):
4173 return "B.f"
4174
4175 class C(B):
4176 def f(self):
4177 return super(C, self).f() + "->C.f"
4178
4179 obj = C()
4180 p = Proxy(obj)
4181 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4182
4183 def test_carloverre(self):
4184 # Testing prohibition of Carlo Verre's hack...
4185 try:
4186 object.__setattr__(str, "foo", 42)
4187 except TypeError:
4188 pass
4189 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004190 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004191 try:
4192 object.__delattr__(str, "lower")
4193 except TypeError:
4194 pass
4195 else:
4196 self.fail("Carlo Verre __delattr__ succeeded!")
4197
4198 def test_weakref_segfault(self):
4199 # Testing weakref segfault...
4200 # SF 742911
4201 import weakref
4202
4203 class Provoker:
4204 def __init__(self, referrent):
4205 self.ref = weakref.ref(referrent)
4206
4207 def __del__(self):
4208 x = self.ref()
4209
4210 class Oops(object):
4211 pass
4212
4213 o = Oops()
4214 o.whatever = Provoker(o)
4215 del o
4216
4217 def test_wrapper_segfault(self):
4218 # SF 927248: deeply nested wrappers could cause stack overflow
4219 f = lambda:None
4220 for i in range(1000000):
4221 f = f.__call__
4222 f = None
4223
4224 def test_file_fault(self):
4225 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004226 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004227 class StdoutGuard:
4228 def __getattr__(self, attr):
4229 sys.stdout = sys.__stdout__
4230 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4231 sys.stdout = StdoutGuard()
4232 try:
4233 print("Oops!")
4234 except RuntimeError:
4235 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004236 finally:
4237 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004238
4239 def test_vicious_descriptor_nonsense(self):
4240 # Testing vicious_descriptor_nonsense...
4241
4242 # A potential segfault spotted by Thomas Wouters in mail to
4243 # python-dev 2003-04-17, turned into an example & fixed by Michael
4244 # Hudson just less than four months later...
4245
4246 class Evil(object):
4247 def __hash__(self):
4248 return hash('attr')
4249 def __eq__(self, other):
4250 del C.attr
4251 return 0
4252
4253 class Descr(object):
4254 def __get__(self, ob, type=None):
4255 return 1
4256
4257 class C(object):
4258 attr = Descr()
4259
4260 c = C()
4261 c.__dict__[Evil()] = 0
4262
4263 self.assertEqual(c.attr, 1)
4264 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004265 support.gc_collect()
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004266 self.assertNotHasAttr(c, 'attr')
Georg Brandl479a7e72008-02-05 18:13:15 +00004267
4268 def test_init(self):
4269 # SF 1155938
4270 class Foo(object):
4271 def __init__(self):
4272 return 10
4273 try:
4274 Foo()
4275 except TypeError:
4276 pass
4277 else:
4278 self.fail("did not test __init__() for None return")
4279
4280 def test_method_wrapper(self):
4281 # Testing method-wrapper objects...
4282 # <type 'method-wrapper'> did not support any reflection before 2.5
4283
Mark Dickinson211c6252009-02-01 10:28:51 +00004284 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004285
4286 l = []
4287 self.assertEqual(l.__add__, l.__add__)
4288 self.assertEqual(l.__add__, [].__add__)
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004289 self.assertNotEqual(l.__add__, [5].__add__)
4290 self.assertNotEqual(l.__add__, l.__mul__)
4291 self.assertEqual(l.__add__.__name__, '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004292 if hasattr(l.__add__, '__self__'):
4293 # CPython
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004294 self.assertIs(l.__add__.__self__, l)
4295 self.assertIs(l.__add__.__objclass__, list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004296 else:
4297 # Python implementations where [].__add__ is a normal bound method
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004298 self.assertIs(l.__add__.im_self, l)
4299 self.assertIs(l.__add__.im_class, list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004300 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4301 try:
4302 hash(l.__add__)
4303 except TypeError:
4304 pass
4305 else:
4306 self.fail("no TypeError from hash([].__add__)")
4307
4308 t = ()
4309 t += (7,)
4310 self.assertEqual(t.__add__, (7,).__add__)
4311 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4312
4313 def test_not_implemented(self):
4314 # Testing NotImplemented...
4315 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004316 import operator
4317
4318 def specialmethod(self, other):
4319 return NotImplemented
4320
4321 def check(expr, x, y):
4322 try:
4323 exec(expr, {'x': x, 'y': y, 'operator': operator})
4324 except TypeError:
4325 pass
4326 else:
4327 self.fail("no TypeError from %r" % (expr,))
4328
4329 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4330 # TypeErrors
4331 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4332 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004333 for name, expr, iexpr in [
4334 ('__add__', 'x + y', 'x += y'),
4335 ('__sub__', 'x - y', 'x -= y'),
4336 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004337 ('__truediv__', 'operator.truediv(x, y)', None),
4338 ('__floordiv__', 'operator.floordiv(x, y)', None),
4339 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004340 ('__mod__', 'x % y', 'x %= y'),
4341 ('__divmod__', 'divmod(x, y)', None),
4342 ('__pow__', 'x ** y', 'x **= y'),
4343 ('__lshift__', 'x << y', 'x <<= y'),
4344 ('__rshift__', 'x >> y', 'x >>= y'),
4345 ('__and__', 'x & y', 'x &= y'),
4346 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004347 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004348 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004349 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004350 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004351 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004352 check(expr, a, N1)
4353 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004354 if iexpr:
4355 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004356 check(iexpr, a, N1)
4357 check(iexpr, a, N2)
4358 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004359 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004360 c = C()
4361 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004362 check(iexpr, c, N1)
4363 check(iexpr, c, N2)
4364
Georg Brandl479a7e72008-02-05 18:13:15 +00004365 def test_assign_slice(self):
4366 # ceval.c's assign_slice used to check for
4367 # tp->tp_as_sequence->sq_slice instead of
4368 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004369
Georg Brandl479a7e72008-02-05 18:13:15 +00004370 class C(object):
4371 def __setitem__(self, idx, value):
4372 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004373
Georg Brandl479a7e72008-02-05 18:13:15 +00004374 c = C()
4375 c[1:2] = 3
4376 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004377
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004378 def test_set_and_no_get(self):
4379 # See
4380 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4381 class Descr(object):
4382
4383 def __init__(self, name):
4384 self.name = name
4385
4386 def __set__(self, obj, value):
4387 obj.__dict__[self.name] = value
4388 descr = Descr("a")
4389
4390 class X(object):
4391 a = descr
4392
4393 x = X()
4394 self.assertIs(x.a, descr)
4395 x.a = 42
4396 self.assertEqual(x.a, 42)
4397
Benjamin Peterson21896a32010-03-21 22:03:03 +00004398 # Also check type_getattro for correctness.
4399 class Meta(type):
4400 pass
4401 class X(object):
4402 __metaclass__ = Meta
4403 X.a = 42
4404 Meta.a = Descr("a")
4405 self.assertEqual(X.a, 42)
4406
Benjamin Peterson9262b842008-11-17 22:45:50 +00004407 def test_getattr_hooks(self):
4408 # issue 4230
4409
4410 class Descriptor(object):
4411 counter = 0
4412 def __get__(self, obj, objtype=None):
4413 def getter(name):
4414 self.counter += 1
4415 raise AttributeError(name)
4416 return getter
4417
4418 descr = Descriptor()
4419 class A(object):
4420 __getattribute__ = descr
4421 class B(object):
4422 __getattr__ = descr
4423 class C(object):
4424 __getattribute__ = descr
4425 __getattr__ = descr
4426
4427 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004428 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004429 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004430 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004431 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004432 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004433
Benjamin Peterson9262b842008-11-17 22:45:50 +00004434 class EvilGetattribute(object):
4435 # This used to segfault
4436 def __getattr__(self, name):
4437 raise AttributeError(name)
4438 def __getattribute__(self, name):
4439 del EvilGetattribute.__getattr__
4440 for i in range(5):
4441 gc.collect()
4442 raise AttributeError(name)
4443
4444 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4445
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004446 def test_type___getattribute__(self):
4447 self.assertRaises(TypeError, type.__getattribute__, list, type)
4448
Benjamin Peterson477ba912011-01-12 15:34:01 +00004449 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004450 # type pretends not to have __abstractmethods__.
4451 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4452 class meta(type):
4453 pass
4454 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004455 class X(object):
4456 pass
4457 with self.assertRaises(AttributeError):
4458 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004459
Victor Stinner3249dec2011-05-01 23:19:15 +02004460 def test_proxy_call(self):
4461 class FakeStr:
4462 __class__ = str
4463
4464 fake_str = FakeStr()
4465 # isinstance() reads __class__
Serhiy Storchaka76edd212013-11-17 23:38:50 +02004466 self.assertIsInstance(fake_str, str)
Victor Stinner3249dec2011-05-01 23:19:15 +02004467
4468 # call a method descriptor
4469 with self.assertRaises(TypeError):
4470 str.split(fake_str)
4471
4472 # call a slot wrapper descriptor
4473 with self.assertRaises(TypeError):
4474 str.__add__(fake_str, "abc")
4475
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004476 def test_repr_as_str(self):
4477 # Issue #11603: crash or infinite loop when rebinding __str__ as
4478 # __repr__.
4479 class Foo:
4480 pass
4481 Foo.__repr__ = Foo.__str__
4482 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004483 self.assertRaises(RuntimeError, str, foo)
4484 self.assertRaises(RuntimeError, repr, foo)
4485
4486 def test_mixing_slot_wrappers(self):
4487 class X(dict):
4488 __setattr__ = dict.__setitem__
4489 x = X()
4490 x.y = 42
4491 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004492
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004493 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004494 with self.assertRaises(ValueError) as cm:
4495 class X:
4496 __slots__ = ["foo"]
4497 foo = None
4498 m = str(cm.exception)
4499 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4500
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004501 def test_set_doc(self):
4502 class X:
4503 "elephant"
4504 X.__doc__ = "banana"
4505 self.assertEqual(X.__doc__, "banana")
4506 with self.assertRaises(TypeError) as cm:
4507 type(list).__dict__["__doc__"].__set__(list, "blah")
4508 self.assertIn("can't set list.__doc__", str(cm.exception))
4509 with self.assertRaises(TypeError) as cm:
4510 type(X).__dict__["__doc__"].__delete__(X)
4511 self.assertIn("can't delete X.__doc__", str(cm.exception))
4512 self.assertEqual(X.__doc__, "banana")
4513
Antoine Pitrou9d574812011-12-12 13:47:25 +01004514 def test_qualname(self):
4515 descriptors = [str.lower, complex.real, float.real, int.__add__]
4516 types = ['method', 'member', 'getset', 'wrapper']
4517
4518 # make sure we have an example of each type of descriptor
4519 for d, n in zip(descriptors, types):
4520 self.assertEqual(type(d).__name__, n + '_descriptor')
4521
4522 for d in descriptors:
4523 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4524 self.assertEqual(d.__qualname__, qualname)
4525
4526 self.assertEqual(str.lower.__qualname__, 'str.lower')
4527 self.assertEqual(complex.real.__qualname__, 'complex.real')
4528 self.assertEqual(float.real.__qualname__, 'float.real')
4529 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4530
Benjamin Peterson2c05a2e2012-10-31 00:01:15 -04004531 class X:
4532 pass
4533 with self.assertRaises(TypeError):
4534 del X.__qualname__
4535
4536 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4537 str, 'Oink')
4538
Victor Stinner6f738742012-02-25 01:22:36 +01004539 def test_qualname_dict(self):
4540 ns = {'__qualname__': 'some.name'}
4541 tp = type('Foo', (), ns)
4542 self.assertEqual(tp.__qualname__, 'some.name')
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004543 self.assertNotIn('__qualname__', tp.__dict__)
Victor Stinner6f738742012-02-25 01:22:36 +01004544 self.assertEqual(ns, {'__qualname__': 'some.name'})
4545
4546 ns = {'__qualname__': 1}
4547 self.assertRaises(TypeError, type, 'Foo', (), ns)
4548
Benjamin Peterson52c42432012-03-07 18:41:11 -06004549 def test_cycle_through_dict(self):
4550 # See bug #1469629
4551 class X(dict):
4552 def __init__(self):
4553 dict.__init__(self)
4554 self.__dict__ = self
4555 x = X()
4556 x.attr = 42
4557 wr = weakref.ref(x)
4558 del x
4559 support.gc_collect()
4560 self.assertIsNone(wr())
4561 for o in gc.get_objects():
4562 self.assertIsNot(type(o), X)
4563
Benjamin Peterson96384b92012-03-17 00:05:44 -05004564 def test_object_new_and_init_with_parameters(self):
4565 # See issue #1683368
4566 class OverrideNeither:
4567 pass
4568 self.assertRaises(TypeError, OverrideNeither, 1)
4569 self.assertRaises(TypeError, OverrideNeither, kw=1)
4570 class OverrideNew:
4571 def __new__(cls, foo, kw=0, *args, **kwds):
4572 return object.__new__(cls, *args, **kwds)
4573 class OverrideInit:
4574 def __init__(self, foo, kw=0, *args, **kwargs):
4575 return object.__init__(self, *args, **kwargs)
4576 class OverrideBoth(OverrideNew, OverrideInit):
4577 pass
4578 for case in OverrideNew, OverrideInit, OverrideBoth:
4579 case(1)
4580 case(1, kw=2)
4581 self.assertRaises(TypeError, case, 1, 2, 3)
4582 self.assertRaises(TypeError, case, 1, 2, foo=3)
4583
Antoine Pitrou9d574812011-12-12 13:47:25 +01004584
Georg Brandl479a7e72008-02-05 18:13:15 +00004585class DictProxyTests(unittest.TestCase):
4586 def setUp(self):
4587 class C(object):
4588 def meth(self):
4589 pass
4590 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004591
Brett Cannon7a540732011-02-22 03:04:06 +00004592 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4593 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004594 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004595 # Testing dict-proxy keys...
4596 it = self.C.__dict__.keys()
4597 self.assertNotIsInstance(it, list)
4598 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004599 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004600 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004601 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004602
Brett Cannon7a540732011-02-22 03:04:06 +00004603 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4604 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004605 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004606 # Testing dict-proxy values...
4607 it = self.C.__dict__.values()
4608 self.assertNotIsInstance(it, list)
4609 values = list(it)
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004610 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004611
Brett Cannon7a540732011-02-22 03:04:06 +00004612 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4613 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004614 def test_iter_items(self):
4615 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004616 it = self.C.__dict__.items()
4617 self.assertNotIsInstance(it, list)
4618 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004619 keys.sort()
4620 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Benjamin Peterson8afa7fa2012-10-30 23:51:03 -04004621 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004622
Georg Brandl479a7e72008-02-05 18:13:15 +00004623 def test_dict_type_with_metaclass(self):
4624 # Testing type of __dict__ when metaclass set...
4625 class B(object):
4626 pass
4627 class M(type):
4628 pass
4629 class C(metaclass=M):
4630 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4631 pass
4632 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004633
Ezio Melottiac53ab62010-12-18 14:59:43 +00004634 def test_repr(self):
Victor Stinner0db176f2012-04-16 00:16:30 +02004635 # Testing mappingproxy.__repr__.
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004636 # We can't blindly compare with the repr of another dict as ordering
4637 # of keys and values is arbitrary and may differ.
4638 r = repr(self.C.__dict__)
Victor Stinner0db176f2012-04-16 00:16:30 +02004639 self.assertTrue(r.startswith('mappingproxy('), r)
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004640 self.assertTrue(r.endswith(')'), r)
4641 for k, v in self.C.__dict__.items():
4642 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004643
Christian Heimesbbffeb62008-01-24 09:42:52 +00004644
Georg Brandl479a7e72008-02-05 18:13:15 +00004645class PTypesLongInitTest(unittest.TestCase):
4646 # This is in its own TestCase so that it can be run before any other tests.
4647 def test_pytype_long_ready(self):
4648 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004649
Georg Brandl479a7e72008-02-05 18:13:15 +00004650 # This dumps core when SF bug 551412 isn't fixed --
4651 # but only when test_descr.py is run separately.
4652 # (That can't be helped -- as soon as PyType_Ready()
4653 # is called for PyLong_Type, the bug is gone.)
4654 class UserLong(object):
4655 def __pow__(self, *args):
4656 pass
4657 try:
4658 pow(0, UserLong(), 0)
4659 except:
4660 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004661
Georg Brandl479a7e72008-02-05 18:13:15 +00004662 # Another segfault only when run early
4663 # (before PyType_Ready(tuple) is called)
4664 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004665
4666
Victor Stinnerd74782b2012-03-09 00:39:08 +01004667class MiscTests(unittest.TestCase):
4668 def test_type_lookup_mro_reference(self):
4669 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4670 # the type MRO because it may be modified during the lookup, if
4671 # __bases__ is set during the lookup for example.
4672 class MyKey(object):
4673 def __hash__(self):
4674 return hash('mykey')
4675
4676 def __eq__(self, other):
4677 X.__bases__ = (Base2,)
4678
4679 class Base(object):
4680 mykey = 'from Base'
4681 mykey2 = 'from Base'
4682
4683 class Base2(object):
4684 mykey = 'from Base2'
4685 mykey2 = 'from Base2'
4686
4687 X = type('X', (Base,), {MyKey(): 5})
4688 # mykey is read from Base
4689 self.assertEqual(X.mykey, 'from Base')
4690 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4691 self.assertEqual(X.mykey2, 'from Base2')
4692
4693
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004694def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004695 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004696 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Victor Stinnerd74782b2012-03-09 00:39:08 +01004697 ClassPropertiesAndMethods, DictProxyTests,
4698 MiscTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004700if __name__ == "__main__":
4701 test_main()