blob: cdaf7d2aca01100feb455f162700b3832d7ca2ba [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
391 def test_python_dicts(self):
392 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000393 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000394 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000395 d = dict()
396 self.assertEqual(d, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000397 self.assertTrue(d.__class__ is dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000398 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000399 class C(dict):
400 state = -1
401 def __init__(self_local, *a, **kw):
402 if a:
403 self.assertEqual(len(a), 1)
404 self_local.state = a[0]
405 if kw:
406 for k, v in list(kw.items()):
407 self_local[v] = k
408 def __getitem__(self, key):
409 return self.get(key, 0)
410 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000411 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000412 dict.__setitem__(self_local, key, value)
413 def setstate(self, state):
414 self.state = state
415 def getstate(self):
416 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000417 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000418 a1 = C(12)
419 self.assertEqual(a1.state, 12)
420 a2 = C(foo=1, bar=2)
421 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
422 a = C()
423 self.assertEqual(a.state, -1)
424 self.assertEqual(a.getstate(), -1)
425 a.setstate(0)
426 self.assertEqual(a.state, 0)
427 self.assertEqual(a.getstate(), 0)
428 a.setstate(10)
429 self.assertEqual(a.state, 10)
430 self.assertEqual(a.getstate(), 10)
431 self.assertEqual(a[42], 0)
432 a[42] = 24
433 self.assertEqual(a[42], 24)
434 N = 50
435 for i in range(N):
436 a[i] = C()
437 for j in range(N):
438 a[i][j] = i*j
439 for i in range(N):
440 for j in range(N):
441 self.assertEqual(a[i][j], i*j)
442
443 def test_python_lists(self):
444 # Testing Python subclass of list...
445 class C(list):
446 def __getitem__(self, i):
447 if isinstance(i, slice):
448 return i.start, i.stop
449 return list.__getitem__(self, i) + 100
450 a = C()
451 a.extend([0,1,2])
452 self.assertEqual(a[0], 100)
453 self.assertEqual(a[1], 101)
454 self.assertEqual(a[2], 102)
455 self.assertEqual(a[100:200], (100,200))
456
457 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000458 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000459 class C(metaclass=type):
460 def __init__(self):
461 self.__state = 0
462 def getstate(self):
463 return self.__state
464 def setstate(self, state):
465 self.__state = state
466 a = C()
467 self.assertEqual(a.getstate(), 0)
468 a.setstate(10)
469 self.assertEqual(a.getstate(), 10)
470 class _metaclass(type):
471 def myself(cls): return cls
472 class D(metaclass=_metaclass):
473 pass
474 self.assertEqual(D.myself(), D)
475 d = D()
476 self.assertEqual(d.__class__, D)
477 class M1(type):
478 def __new__(cls, name, bases, dict):
479 dict['__spam__'] = 1
480 return type.__new__(cls, name, bases, dict)
481 class C(metaclass=M1):
482 pass
483 self.assertEqual(C.__spam__, 1)
484 c = C()
485 self.assertEqual(c.__spam__, 1)
486
487 class _instance(object):
488 pass
489 class M2(object):
490 @staticmethod
491 def __new__(cls, name, bases, dict):
492 self = object.__new__(cls)
493 self.name = name
494 self.bases = bases
495 self.dict = dict
496 return self
497 def __call__(self):
498 it = _instance()
499 # Early binding of methods
500 for key in self.dict:
501 if key.startswith("__"):
502 continue
503 setattr(it, key, self.dict[key].__get__(it, self))
504 return it
505 class C(metaclass=M2):
506 def spam(self):
507 return 42
508 self.assertEqual(C.name, 'C')
509 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000510 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000511 c = C()
512 self.assertEqual(c.spam(), 42)
513
514 # More metaclass examples
515
516 class autosuper(type):
517 # Automatically add __super to the class
518 # This trick only works for dynamic classes
519 def __new__(metaclass, name, bases, dict):
520 cls = super(autosuper, metaclass).__new__(metaclass,
521 name, bases, dict)
522 # Name mangling for __super removes leading underscores
523 while name[:1] == "_":
524 name = name[1:]
525 if name:
526 name = "_%s__super" % name
527 else:
528 name = "__super"
529 setattr(cls, name, super(cls))
530 return cls
531 class A(metaclass=autosuper):
532 def meth(self):
533 return "A"
534 class B(A):
535 def meth(self):
536 return "B" + self.__super.meth()
537 class C(A):
538 def meth(self):
539 return "C" + self.__super.meth()
540 class D(C, B):
541 def meth(self):
542 return "D" + self.__super.meth()
543 self.assertEqual(D().meth(), "DCBA")
544 class E(B, C):
545 def meth(self):
546 return "E" + self.__super.meth()
547 self.assertEqual(E().meth(), "EBCA")
548
549 class autoproperty(type):
550 # Automatically create property attributes when methods
551 # named _get_x and/or _set_x are found
552 def __new__(metaclass, name, bases, dict):
553 hits = {}
554 for key, val in dict.items():
555 if key.startswith("_get_"):
556 key = key[5:]
557 get, set = hits.get(key, (None, None))
558 get = val
559 hits[key] = get, set
560 elif key.startswith("_set_"):
561 key = key[5:]
562 get, set = hits.get(key, (None, None))
563 set = val
564 hits[key] = get, set
565 for key, (get, set) in hits.items():
566 dict[key] = property(get, set)
567 return super(autoproperty, metaclass).__new__(metaclass,
568 name, bases, dict)
569 class A(metaclass=autoproperty):
570 def _get_x(self):
571 return -self.__x
572 def _set_x(self, x):
573 self.__x = -x
574 a = A()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000575 self.assertTrue(not hasattr(a, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +0000576 a.x = 12
577 self.assertEqual(a.x, 12)
578 self.assertEqual(a._A__x, -12)
579
580 class multimetaclass(autoproperty, autosuper):
581 # Merge of multiple cooperating metaclasses
582 pass
583 class A(metaclass=multimetaclass):
584 def _get_x(self):
585 return "A"
586 class B(A):
587 def _get_x(self):
588 return "B" + self.__super._get_x()
589 class C(A):
590 def _get_x(self):
591 return "C" + self.__super._get_x()
592 class D(C, B):
593 def _get_x(self):
594 return "D" + self.__super._get_x()
595 self.assertEqual(D().x, "DCBA")
596
597 # Make sure type(x) doesn't call x.__class__.__init__
598 class T(type):
599 counter = 0
600 def __init__(self, *args):
601 T.counter += 1
602 class C(metaclass=T):
603 pass
604 self.assertEqual(T.counter, 1)
605 a = C()
606 self.assertEqual(type(a), C)
607 self.assertEqual(T.counter, 1)
608
609 class C(object): pass
610 c = C()
611 try: c()
612 except TypeError: pass
613 else: self.fail("calling object w/o call method should raise "
614 "TypeError")
615
616 # Testing code to find most derived baseclass
617 class A(type):
618 def __new__(*args, **kwargs):
619 return type.__new__(*args, **kwargs)
620
621 class B(object):
622 pass
623
624 class C(object, metaclass=A):
625 pass
626
627 # The most derived metaclass of D is A rather than type.
628 class D(B, C):
629 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000630 self.assertIs(A, type(D))
631
632 # issue1294232: correct metaclass calculation
633 new_calls = [] # to check the order of __new__ calls
634 class AMeta(type):
635 @staticmethod
636 def __new__(mcls, name, bases, ns):
637 new_calls.append('AMeta')
638 return super().__new__(mcls, name, bases, ns)
639 @classmethod
640 def __prepare__(mcls, name, bases):
641 return {}
642
643 class BMeta(AMeta):
644 @staticmethod
645 def __new__(mcls, name, bases, ns):
646 new_calls.append('BMeta')
647 return super().__new__(mcls, name, bases, ns)
648 @classmethod
649 def __prepare__(mcls, name, bases):
650 ns = super().__prepare__(name, bases)
651 ns['BMeta_was_here'] = True
652 return ns
653
654 class A(metaclass=AMeta):
655 pass
656 self.assertEqual(['AMeta'], new_calls)
657 new_calls[:] = []
658
659 class B(metaclass=BMeta):
660 pass
661 # BMeta.__new__ calls AMeta.__new__ with super:
662 self.assertEqual(['BMeta', 'AMeta'], new_calls)
663 new_calls[:] = []
664
665 class C(A, B):
666 pass
667 # The most derived metaclass is BMeta:
668 self.assertEqual(['BMeta', 'AMeta'], new_calls)
669 new_calls[:] = []
670 # BMeta.__prepare__ should've been called:
671 self.assertIn('BMeta_was_here', C.__dict__)
672
673 # The order of the bases shouldn't matter:
674 class C2(B, A):
675 pass
676 self.assertEqual(['BMeta', 'AMeta'], new_calls)
677 new_calls[:] = []
678 self.assertIn('BMeta_was_here', C2.__dict__)
679
680 # Check correct metaclass calculation when a metaclass is declared:
681 class D(C, metaclass=type):
682 pass
683 self.assertEqual(['BMeta', 'AMeta'], new_calls)
684 new_calls[:] = []
685 self.assertIn('BMeta_was_here', D.__dict__)
686
687 class E(C, metaclass=AMeta):
688 pass
689 self.assertEqual(['BMeta', 'AMeta'], new_calls)
690 new_calls[:] = []
691 self.assertIn('BMeta_was_here', E.__dict__)
692
693 # Special case: the given metaclass isn't a class,
694 # so there is no metaclass calculation.
695 marker = object()
696 def func(*args, **kwargs):
697 return marker
698 class X(metaclass=func):
699 pass
700 class Y(object, metaclass=func):
701 pass
702 class Z(D, metaclass=func):
703 pass
704 self.assertIs(marker, X)
705 self.assertIs(marker, Y)
706 self.assertIs(marker, Z)
707
708 # The given metaclass is a class,
709 # but not a descendant of type.
710 prepare_calls = [] # to track __prepare__ calls
711 class ANotMeta:
712 def __new__(mcls, *args, **kwargs):
713 new_calls.append('ANotMeta')
714 return super().__new__(mcls)
715 @classmethod
716 def __prepare__(mcls, name, bases):
717 prepare_calls.append('ANotMeta')
718 return {}
719 class BNotMeta(ANotMeta):
720 def __new__(mcls, *args, **kwargs):
721 new_calls.append('BNotMeta')
722 return super().__new__(mcls)
723 @classmethod
724 def __prepare__(mcls, name, bases):
725 prepare_calls.append('BNotMeta')
726 return super().__prepare__(name, bases)
727
728 class A(metaclass=ANotMeta):
729 pass
730 self.assertIs(ANotMeta, type(A))
731 self.assertEqual(['ANotMeta'], prepare_calls)
732 prepare_calls[:] = []
733 self.assertEqual(['ANotMeta'], new_calls)
734 new_calls[:] = []
735
736 class B(metaclass=BNotMeta):
737 pass
738 self.assertIs(BNotMeta, type(B))
739 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
740 prepare_calls[:] = []
741 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
742 new_calls[:] = []
743
744 class C(A, B):
745 pass
746 self.assertIs(BNotMeta, type(C))
747 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
748 new_calls[:] = []
749 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
750 prepare_calls[:] = []
751
752 class C2(B, A):
753 pass
754 self.assertIs(BNotMeta, type(C2))
755 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
756 new_calls[:] = []
757 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
758 prepare_calls[:] = []
759
760 # This is a TypeError, because of a metaclass conflict:
761 # BNotMeta is neither a subclass, nor a superclass of type
762 with self.assertRaises(TypeError):
763 class D(C, metaclass=type):
764 pass
765
766 class E(C, metaclass=ANotMeta):
767 pass
768 self.assertIs(BNotMeta, type(E))
769 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
770 new_calls[:] = []
771 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
772 prepare_calls[:] = []
773
774 class F(object(), C):
775 pass
776 self.assertIs(BNotMeta, type(F))
777 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
778 new_calls[:] = []
779 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
780 prepare_calls[:] = []
781
782 class F2(C, object()):
783 pass
784 self.assertIs(BNotMeta, type(F2))
785 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
786 new_calls[:] = []
787 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
788 prepare_calls[:] = []
789
790 # TypeError: BNotMeta is neither a
791 # subclass, nor a superclass of int
792 with self.assertRaises(TypeError):
793 class X(C, int()):
794 pass
795 with self.assertRaises(TypeError):
796 class X(int(), C):
797 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000798
799 def test_module_subclasses(self):
800 # Testing Python subclass of module...
801 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000802 MT = type(sys)
803 class MM(MT):
804 def __init__(self, name):
805 MT.__init__(self, name)
806 def __getattribute__(self, name):
807 log.append(("getattr", name))
808 return MT.__getattribute__(self, name)
809 def __setattr__(self, name, value):
810 log.append(("setattr", name, value))
811 MT.__setattr__(self, name, value)
812 def __delattr__(self, name):
813 log.append(("delattr", name))
814 MT.__delattr__(self, name)
815 a = MM("a")
816 a.foo = 12
817 x = a.foo
818 del a.foo
819 self.assertEqual(log, [("setattr", "foo", 12),
820 ("getattr", "foo"),
821 ("delattr", "foo")])
822
823 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000824 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000825 class Module(types.ModuleType, str):
826 pass
827 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000828 pass
829 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000830 self.fail("inheriting from ModuleType and str at the same time "
831 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000832
Georg Brandl479a7e72008-02-05 18:13:15 +0000833 def test_multiple_inheritance(self):
834 # Testing multiple inheritance...
835 class C(object):
836 def __init__(self):
837 self.__state = 0
838 def getstate(self):
839 return self.__state
840 def setstate(self, state):
841 self.__state = state
842 a = C()
843 self.assertEqual(a.getstate(), 0)
844 a.setstate(10)
845 self.assertEqual(a.getstate(), 10)
846 class D(dict, C):
847 def __init__(self):
848 type({}).__init__(self)
849 C.__init__(self)
850 d = D()
851 self.assertEqual(list(d.keys()), [])
852 d["hello"] = "world"
853 self.assertEqual(list(d.items()), [("hello", "world")])
854 self.assertEqual(d["hello"], "world")
855 self.assertEqual(d.getstate(), 0)
856 d.setstate(10)
857 self.assertEqual(d.getstate(), 10)
858 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000859
Georg Brandl479a7e72008-02-05 18:13:15 +0000860 # SF bug #442833
861 class Node(object):
862 def __int__(self):
863 return int(self.foo())
864 def foo(self):
865 return "23"
866 class Frag(Node, list):
867 def foo(self):
868 return "42"
869 self.assertEqual(Node().__int__(), 23)
870 self.assertEqual(int(Node()), 23)
871 self.assertEqual(Frag().__int__(), 42)
872 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000873
Georg Brandl479a7e72008-02-05 18:13:15 +0000874 def test_diamond_inheritence(self):
875 # Testing multiple inheritance special cases...
876 class A(object):
877 def spam(self): return "A"
878 self.assertEqual(A().spam(), "A")
879 class B(A):
880 def boo(self): return "B"
881 def spam(self): return "B"
882 self.assertEqual(B().spam(), "B")
883 self.assertEqual(B().boo(), "B")
884 class C(A):
885 def boo(self): return "C"
886 self.assertEqual(C().spam(), "A")
887 self.assertEqual(C().boo(), "C")
888 class D(B, C): pass
889 self.assertEqual(D().spam(), "B")
890 self.assertEqual(D().boo(), "B")
891 self.assertEqual(D.__mro__, (D, B, C, A, object))
892 class E(C, B): pass
893 self.assertEqual(E().spam(), "B")
894 self.assertEqual(E().boo(), "C")
895 self.assertEqual(E.__mro__, (E, C, B, A, object))
896 # MRO order disagreement
897 try:
898 class F(D, E): pass
899 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000900 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000901 else:
902 self.fail("expected MRO order disagreement (F)")
903 try:
904 class G(E, D): pass
905 except TypeError:
906 pass
907 else:
908 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000909
Georg Brandl479a7e72008-02-05 18:13:15 +0000910 # see thread python-dev/2002-October/029035.html
911 def test_ex5_from_c3_switch(self):
912 # Testing ex5 from C3 switch discussion...
913 class A(object): pass
914 class B(object): pass
915 class C(object): pass
916 class X(A): pass
917 class Y(A): pass
918 class Z(X,B,Y,C): pass
919 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000920
Georg Brandl479a7e72008-02-05 18:13:15 +0000921 # see "A Monotonic Superclass Linearization for Dylan",
922 # by Kim Barrett et al. (OOPSLA 1996)
923 def test_monotonicity(self):
924 # Testing MRO monotonicity...
925 class Boat(object): pass
926 class DayBoat(Boat): pass
927 class WheelBoat(Boat): pass
928 class EngineLess(DayBoat): pass
929 class SmallMultihull(DayBoat): pass
930 class PedalWheelBoat(EngineLess,WheelBoat): pass
931 class SmallCatamaran(SmallMultihull): pass
932 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000933
Georg Brandl479a7e72008-02-05 18:13:15 +0000934 self.assertEqual(PedalWheelBoat.__mro__,
935 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
936 self.assertEqual(SmallCatamaran.__mro__,
937 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
938 self.assertEqual(Pedalo.__mro__,
939 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
940 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000941
Georg Brandl479a7e72008-02-05 18:13:15 +0000942 # see "A Monotonic Superclass Linearization for Dylan",
943 # by Kim Barrett et al. (OOPSLA 1996)
944 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200945 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000946 class Pane(object): pass
947 class ScrollingMixin(object): pass
948 class EditingMixin(object): pass
949 class ScrollablePane(Pane,ScrollingMixin): pass
950 class EditablePane(Pane,EditingMixin): pass
951 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000952
Georg Brandl479a7e72008-02-05 18:13:15 +0000953 self.assertEqual(EditableScrollablePane.__mro__,
954 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
955 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000956
Georg Brandl479a7e72008-02-05 18:13:15 +0000957 def test_mro_disagreement(self):
958 # Testing error messages for MRO disagreement...
959 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000960order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000961
Georg Brandl479a7e72008-02-05 18:13:15 +0000962 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000963 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000964 callable(*args)
965 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000966 # the exact msg is generally considered an impl detail
967 if support.check_impl_detail():
968 if not str(msg).startswith(expected):
969 self.fail("Message %r, expected %r" %
970 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000971 else:
972 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000973
Georg Brandl479a7e72008-02-05 18:13:15 +0000974 class A(object): pass
975 class B(A): pass
976 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000977
Georg Brandl479a7e72008-02-05 18:13:15 +0000978 # Test some very simple errors
979 raises(TypeError, "duplicate base class A",
980 type, "X", (A, A), {})
981 raises(TypeError, mro_err_msg,
982 type, "X", (A, B), {})
983 raises(TypeError, mro_err_msg,
984 type, "X", (A, C, B), {})
985 # Test a slightly more complex error
986 class GridLayout(object): pass
987 class HorizontalGrid(GridLayout): pass
988 class VerticalGrid(GridLayout): pass
989 class HVGrid(HorizontalGrid, VerticalGrid): pass
990 class VHGrid(VerticalGrid, HorizontalGrid): pass
991 raises(TypeError, mro_err_msg,
992 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000993
Georg Brandl479a7e72008-02-05 18:13:15 +0000994 def test_object_class(self):
995 # Testing object class...
996 a = object()
997 self.assertEqual(a.__class__, object)
998 self.assertEqual(type(a), object)
999 b = object()
1000 self.assertNotEqual(a, b)
1001 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +00001002 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001003 a.foo = 12
1004 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001005 pass
1006 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001007 self.fail("object() should not allow setting a foo attribute")
1008 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +00001009
Georg Brandl479a7e72008-02-05 18:13:15 +00001010 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001011 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001012 x = Cdict()
1013 self.assertEqual(x.__dict__, {})
1014 x.foo = 1
1015 self.assertEqual(x.foo, 1)
1016 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001017
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 def test_slots(self):
1019 # Testing __slots__...
1020 class C0(object):
1021 __slots__ = []
1022 x = C0()
1023 self.assertFalse(hasattr(x, "__dict__"))
1024 self.assertFalse(hasattr(x, "foo"))
1025
1026 class C1(object):
1027 __slots__ = ['a']
1028 x = C1()
1029 self.assertFalse(hasattr(x, "__dict__"))
1030 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001032 self.assertEqual(x.a, 1)
1033 x.a = None
1034 self.assertEqual(x.a, None)
1035 del x.a
1036 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001037
Georg Brandl479a7e72008-02-05 18:13:15 +00001038 class C3(object):
1039 __slots__ = ['a', 'b', 'c']
1040 x = C3()
1041 self.assertFalse(hasattr(x, "__dict__"))
1042 self.assertFalse(hasattr(x, 'a'))
1043 self.assertFalse(hasattr(x, 'b'))
1044 self.assertFalse(hasattr(x, 'c'))
1045 x.a = 1
1046 x.b = 2
1047 x.c = 3
1048 self.assertEqual(x.a, 1)
1049 self.assertEqual(x.b, 2)
1050 self.assertEqual(x.c, 3)
1051
1052 class C4(object):
1053 """Validate name mangling"""
1054 __slots__ = ['__a']
1055 def __init__(self, value):
1056 self.__a = value
1057 def get(self):
1058 return self.__a
1059 x = C4(5)
1060 self.assertFalse(hasattr(x, '__dict__'))
1061 self.assertFalse(hasattr(x, '__a'))
1062 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001063 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001064 x.__a = 6
1065 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001066 pass
1067 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001068 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001069
Georg Brandl479a7e72008-02-05 18:13:15 +00001070 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001071 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001072 class C(object):
1073 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001074 except TypeError:
1075 pass
1076 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001077 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001078 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001079 class C(object):
1080 __slots__ = ["foo bar"]
1081 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001082 pass
1083 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001084 self.fail("['foo bar'] slots not caught")
1085 try:
1086 class C(object):
1087 __slots__ = ["foo\0bar"]
1088 except TypeError:
1089 pass
1090 else:
1091 self.fail("['foo\\0bar'] slots not caught")
1092 try:
1093 class C(object):
1094 __slots__ = ["1"]
1095 except TypeError:
1096 pass
1097 else:
1098 self.fail("['1'] slots not caught")
1099 try:
1100 class C(object):
1101 __slots__ = [""]
1102 except TypeError:
1103 pass
1104 else:
1105 self.fail("[''] slots not caught")
1106 class C(object):
1107 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1108 # XXX(nnorwitz): was there supposed to be something tested
1109 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001110
Georg Brandl479a7e72008-02-05 18:13:15 +00001111 # Test a single string is not expanded as a sequence.
1112 class C(object):
1113 __slots__ = "abc"
1114 c = C()
1115 c.abc = 5
1116 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001117
Georg Brandl479a7e72008-02-05 18:13:15 +00001118 # Test unicode slot names
1119 # Test a single unicode 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 Rossum3926a632001-09-25 16:25:58 +00001125
Georg Brandl479a7e72008-02-05 18:13:15 +00001126 # _unicode_to_string used to modify slots in certain circumstances
1127 slots = ("foo", "bar")
1128 class C(object):
1129 __slots__ = slots
1130 x = C()
1131 x.foo = 5
1132 self.assertEqual(x.foo, 5)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001133 self.assertTrue(type(slots[0]) is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001134 # this used to leak references
1135 try:
1136 class C(object):
1137 __slots__ = [chr(128)]
1138 except (TypeError, UnicodeEncodeError):
1139 pass
1140 else:
1141 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001142
Georg Brandl479a7e72008-02-05 18:13:15 +00001143 # Test leaks
1144 class Counted(object):
1145 counter = 0 # counts the number of instances alive
1146 def __init__(self):
1147 Counted.counter += 1
1148 def __del__(self):
1149 Counted.counter -= 1
1150 class C(object):
1151 __slots__ = ['a', 'b', 'c']
1152 x = C()
1153 x.a = Counted()
1154 x.b = Counted()
1155 x.c = Counted()
1156 self.assertEqual(Counted.counter, 3)
1157 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001158 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001159 self.assertEqual(Counted.counter, 0)
1160 class D(C):
1161 pass
1162 x = D()
1163 x.a = Counted()
1164 x.z = Counted()
1165 self.assertEqual(Counted.counter, 2)
1166 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001167 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001168 self.assertEqual(Counted.counter, 0)
1169 class E(D):
1170 __slots__ = ['e']
1171 x = E()
1172 x.a = Counted()
1173 x.z = Counted()
1174 x.e = Counted()
1175 self.assertEqual(Counted.counter, 3)
1176 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001177 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001178 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001179
Georg Brandl479a7e72008-02-05 18:13:15 +00001180 # Test cyclical leaks [SF bug 519621]
1181 class F(object):
1182 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001183 s = F()
1184 s.a = [Counted(), s]
1185 self.assertEqual(Counted.counter, 1)
1186 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001187 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001188 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001189
Georg Brandl479a7e72008-02-05 18:13:15 +00001190 # Test lookup leaks [SF bug 572567]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001191 if hasattr(gc, 'get_objects'):
1192 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001193 def __eq__(self, other):
1194 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001195 g = G()
1196 orig_objects = len(gc.get_objects())
1197 for i in range(10):
1198 g==g
1199 new_objects = len(gc.get_objects())
1200 self.assertEqual(orig_objects, new_objects)
1201
Georg Brandl479a7e72008-02-05 18:13:15 +00001202 class H(object):
1203 __slots__ = ['a', 'b']
1204 def __init__(self):
1205 self.a = 1
1206 self.b = 2
1207 def __del__(self_):
1208 self.assertEqual(self_.a, 1)
1209 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001210 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001211 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001212 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001213 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001214
Benjamin Petersond12362a2009-12-30 19:44:54 +00001215 class X(object):
1216 __slots__ = "a"
1217 with self.assertRaises(AttributeError):
1218 del X().a
1219
Georg Brandl479a7e72008-02-05 18:13:15 +00001220 def test_slots_special(self):
1221 # Testing __dict__ and __weakref__ in __slots__...
1222 class D(object):
1223 __slots__ = ["__dict__"]
1224 a = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001225 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001226 self.assertFalse(hasattr(a, "__weakref__"))
1227 a.foo = 42
1228 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001229
Georg Brandl479a7e72008-02-05 18:13:15 +00001230 class W(object):
1231 __slots__ = ["__weakref__"]
1232 a = W()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001233 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001234 self.assertFalse(hasattr(a, "__dict__"))
1235 try:
1236 a.foo = 42
1237 except AttributeError:
1238 pass
1239 else:
1240 self.fail("shouldn't be allowed to set a.foo")
1241
1242 class C1(W, D):
1243 __slots__ = []
1244 a = C1()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001245 self.assertTrue(hasattr(a, "__dict__"))
1246 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001247 a.foo = 42
1248 self.assertEqual(a.__dict__, {"foo": 42})
1249
1250 class C2(D, W):
1251 __slots__ = []
1252 a = C2()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001253 self.assertTrue(hasattr(a, "__dict__"))
1254 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001255 a.foo = 42
1256 self.assertEqual(a.__dict__, {"foo": 42})
1257
Christian Heimesa156e092008-02-16 07:38:31 +00001258 def test_slots_descriptor(self):
1259 # Issue2115: slot descriptors did not correctly check
1260 # the type of the given object
1261 import abc
1262 class MyABC(metaclass=abc.ABCMeta):
1263 __slots__ = "a"
1264
1265 class Unrelated(object):
1266 pass
1267 MyABC.register(Unrelated)
1268
1269 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001270 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001271
1272 # This used to crash
1273 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1274
Georg Brandl479a7e72008-02-05 18:13:15 +00001275 def test_dynamics(self):
1276 # Testing class attribute propagation...
1277 class D(object):
1278 pass
1279 class E(D):
1280 pass
1281 class F(D):
1282 pass
1283 D.foo = 1
1284 self.assertEqual(D.foo, 1)
1285 # Test that dynamic attributes are inherited
1286 self.assertEqual(E.foo, 1)
1287 self.assertEqual(F.foo, 1)
1288 # Test dynamic instances
1289 class C(object):
1290 pass
1291 a = C()
1292 self.assertFalse(hasattr(a, "foobar"))
1293 C.foobar = 2
1294 self.assertEqual(a.foobar, 2)
1295 C.method = lambda self: 42
1296 self.assertEqual(a.method(), 42)
1297 C.__repr__ = lambda self: "C()"
1298 self.assertEqual(repr(a), "C()")
1299 C.__int__ = lambda self: 100
1300 self.assertEqual(int(a), 100)
1301 self.assertEqual(a.foobar, 2)
1302 self.assertFalse(hasattr(a, "spam"))
1303 def mygetattr(self, name):
1304 if name == "spam":
1305 return "spam"
1306 raise AttributeError
1307 C.__getattr__ = mygetattr
1308 self.assertEqual(a.spam, "spam")
1309 a.new = 12
1310 self.assertEqual(a.new, 12)
1311 def mysetattr(self, name, value):
1312 if name == "spam":
1313 raise AttributeError
1314 return object.__setattr__(self, name, value)
1315 C.__setattr__ = mysetattr
1316 try:
1317 a.spam = "not spam"
1318 except AttributeError:
1319 pass
1320 else:
1321 self.fail("expected AttributeError")
1322 self.assertEqual(a.spam, "spam")
1323 class D(C):
1324 pass
1325 d = D()
1326 d.foo = 1
1327 self.assertEqual(d.foo, 1)
1328
1329 # Test handling of int*seq and seq*int
1330 class I(int):
1331 pass
1332 self.assertEqual("a"*I(2), "aa")
1333 self.assertEqual(I(2)*"a", "aa")
1334 self.assertEqual(2*I(3), 6)
1335 self.assertEqual(I(3)*2, 6)
1336 self.assertEqual(I(3)*I(2), 6)
1337
Georg Brandl479a7e72008-02-05 18:13:15 +00001338 # Test comparison of classes with dynamic metaclasses
1339 class dynamicmetaclass(type):
1340 pass
1341 class someclass(metaclass=dynamicmetaclass):
1342 pass
1343 self.assertNotEqual(someclass, object)
1344
1345 def test_errors(self):
1346 # Testing errors...
1347 try:
1348 class C(list, dict):
1349 pass
1350 except TypeError:
1351 pass
1352 else:
1353 self.fail("inheritance from both list and dict should be illegal")
1354
1355 try:
1356 class C(object, None):
1357 pass
1358 except TypeError:
1359 pass
1360 else:
1361 self.fail("inheritance from non-type should be illegal")
1362 class Classic:
1363 pass
1364
1365 try:
1366 class C(type(len)):
1367 pass
1368 except TypeError:
1369 pass
1370 else:
1371 self.fail("inheritance from CFunction should be illegal")
1372
1373 try:
1374 class C(object):
1375 __slots__ = 1
1376 except TypeError:
1377 pass
1378 else:
1379 self.fail("__slots__ = 1 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 class M1(type):
1390 pass
1391 class M2(type):
1392 pass
1393 class A1(object, metaclass=M1):
1394 pass
1395 class A2(object, metaclass=M2):
1396 pass
1397 try:
1398 class B(A1, A2):
1399 pass
1400 except TypeError:
1401 pass
1402 else:
1403 self.fail("finding the most derived metaclass should have failed")
1404
1405 def test_classmethods(self):
1406 # Testing class methods...
1407 class C(object):
1408 def foo(*a): return a
1409 goo = classmethod(foo)
1410 c = C()
1411 self.assertEqual(C.goo(1), (C, 1))
1412 self.assertEqual(c.goo(1), (C, 1))
1413 self.assertEqual(c.foo(1), (c, 1))
1414 class D(C):
1415 pass
1416 d = D()
1417 self.assertEqual(D.goo(1), (D, 1))
1418 self.assertEqual(d.goo(1), (D, 1))
1419 self.assertEqual(d.foo(1), (d, 1))
1420 self.assertEqual(D.foo(d, 1), (d, 1))
1421 # Test for a specific crash (SF bug 528132)
1422 def f(cls, arg): return (cls, arg)
1423 ff = classmethod(f)
1424 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1425 self.assertEqual(ff.__get__(0)(42), (int, 42))
1426
1427 # Test super() with classmethods (SF bug 535444)
1428 self.assertEqual(C.goo.__self__, C)
1429 self.assertEqual(D.goo.__self__, D)
1430 self.assertEqual(super(D,D).goo.__self__, D)
1431 self.assertEqual(super(D,d).goo.__self__, D)
1432 self.assertEqual(super(D,D).goo(), (D,))
1433 self.assertEqual(super(D,d).goo(), (D,))
1434
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001435 # Verify that a non-callable will raise
1436 meth = classmethod(1).__get__(1)
1437 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001438
1439 # Verify that classmethod() doesn't allow keyword args
1440 try:
1441 classmethod(f, kw=1)
1442 except TypeError:
1443 pass
1444 else:
1445 self.fail("classmethod shouldn't accept keyword args")
1446
Benjamin Petersone549ead2009-03-28 21:42:05 +00001447 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001448 def test_classmethods_in_c(self):
1449 # Testing C-based class methods...
1450 import xxsubtype as spam
1451 a = (1, 2, 3)
1452 d = {'abc': 123}
1453 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1454 self.assertEqual(x, spam.spamlist)
1455 self.assertEqual(a, a1)
1456 self.assertEqual(d, d1)
1457 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1458 self.assertEqual(x, spam.spamlist)
1459 self.assertEqual(a, a1)
1460 self.assertEqual(d, d1)
Benjamin Peterson7295c6a2012-05-01 09:51:09 -04001461 spam_cm = spam.spamlist.__dict__['classmeth']
1462 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1463 self.assertEqual(x2, spam.spamlist)
1464 self.assertEqual(a2, a1)
1465 self.assertEqual(d2, d1)
1466 class SubSpam(spam.spamlist): pass
1467 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1468 self.assertEqual(x2, SubSpam)
1469 self.assertEqual(a2, a1)
1470 self.assertEqual(d2, d1)
1471 with self.assertRaises(TypeError):
1472 spam_cm()
1473 with self.assertRaises(TypeError):
1474 spam_cm(spam.spamlist())
1475 with self.assertRaises(TypeError):
1476 spam_cm(list)
Georg Brandl479a7e72008-02-05 18:13:15 +00001477
1478 def test_staticmethods(self):
1479 # Testing static methods...
1480 class C(object):
1481 def foo(*a): return a
1482 goo = staticmethod(foo)
1483 c = C()
1484 self.assertEqual(C.goo(1), (1,))
1485 self.assertEqual(c.goo(1), (1,))
1486 self.assertEqual(c.foo(1), (c, 1,))
1487 class D(C):
1488 pass
1489 d = D()
1490 self.assertEqual(D.goo(1), (1,))
1491 self.assertEqual(d.goo(1), (1,))
1492 self.assertEqual(d.foo(1), (d, 1))
1493 self.assertEqual(D.foo(d, 1), (d, 1))
1494
Benjamin Petersone549ead2009-03-28 21:42:05 +00001495 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001496 def test_staticmethods_in_c(self):
1497 # Testing C-based static methods...
1498 import xxsubtype as spam
1499 a = (1, 2, 3)
1500 d = {"abc": 123}
1501 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1502 self.assertEqual(x, None)
1503 self.assertEqual(a, a1)
1504 self.assertEqual(d, d1)
1505 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1506 self.assertEqual(x, None)
1507 self.assertEqual(a, a1)
1508 self.assertEqual(d, d1)
1509
1510 def test_classic(self):
1511 # Testing classic classes...
1512 class C:
1513 def foo(*a): return a
1514 goo = classmethod(foo)
1515 c = C()
1516 self.assertEqual(C.goo(1), (C, 1))
1517 self.assertEqual(c.goo(1), (C, 1))
1518 self.assertEqual(c.foo(1), (c, 1))
1519 class D(C):
1520 pass
1521 d = D()
1522 self.assertEqual(D.goo(1), (D, 1))
1523 self.assertEqual(d.goo(1), (D, 1))
1524 self.assertEqual(d.foo(1), (d, 1))
1525 self.assertEqual(D.foo(d, 1), (d, 1))
1526 class E: # *not* subclassing from C
1527 foo = C.foo
1528 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001529 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001530
1531 def test_compattr(self):
1532 # Testing computed attributes...
1533 class C(object):
1534 class computed_attribute(object):
1535 def __init__(self, get, set=None, delete=None):
1536 self.__get = get
1537 self.__set = set
1538 self.__delete = delete
1539 def __get__(self, obj, type=None):
1540 return self.__get(obj)
1541 def __set__(self, obj, value):
1542 return self.__set(obj, value)
1543 def __delete__(self, obj):
1544 return self.__delete(obj)
1545 def __init__(self):
1546 self.__x = 0
1547 def __get_x(self):
1548 x = self.__x
1549 self.__x = x+1
1550 return x
1551 def __set_x(self, x):
1552 self.__x = x
1553 def __delete_x(self):
1554 del self.__x
1555 x = computed_attribute(__get_x, __set_x, __delete_x)
1556 a = C()
1557 self.assertEqual(a.x, 0)
1558 self.assertEqual(a.x, 1)
1559 a.x = 10
1560 self.assertEqual(a.x, 10)
1561 self.assertEqual(a.x, 11)
1562 del a.x
1563 self.assertEqual(hasattr(a, 'x'), 0)
1564
1565 def test_newslots(self):
1566 # Testing __new__ slot override...
1567 class C(list):
1568 def __new__(cls):
1569 self = list.__new__(cls)
1570 self.foo = 1
1571 return self
1572 def __init__(self):
1573 self.foo = self.foo + 2
1574 a = C()
1575 self.assertEqual(a.foo, 3)
1576 self.assertEqual(a.__class__, C)
1577 class D(C):
1578 pass
1579 b = D()
1580 self.assertEqual(b.foo, 3)
1581 self.assertEqual(b.__class__, D)
1582
1583 def test_altmro(self):
1584 # Testing mro() and overriding it...
1585 class A(object):
1586 def f(self): return "A"
1587 class B(A):
1588 pass
1589 class C(A):
1590 def f(self): return "C"
1591 class D(B, C):
1592 pass
1593 self.assertEqual(D.mro(), [D, B, C, A, object])
1594 self.assertEqual(D.__mro__, (D, B, C, A, object))
1595 self.assertEqual(D().f(), "C")
1596
1597 class PerverseMetaType(type):
1598 def mro(cls):
1599 L = type.mro(cls)
1600 L.reverse()
1601 return L
1602 class X(D,B,C,A, metaclass=PerverseMetaType):
1603 pass
1604 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1605 self.assertEqual(X().f(), "A")
1606
1607 try:
1608 class _metaclass(type):
1609 def mro(self):
1610 return [self, dict, object]
1611 class X(object, metaclass=_metaclass):
1612 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001613 # In CPython, the class creation above already raises
1614 # TypeError, as a protection against the fact that
1615 # instances of X would segfault it. In other Python
1616 # implementations it would be ok to let the class X
1617 # be created, but instead get a clean TypeError on the
1618 # __setitem__ below.
1619 x = object.__new__(X)
1620 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001621 except TypeError:
1622 pass
1623 else:
1624 self.fail("devious mro() return not caught")
1625
1626 try:
1627 class _metaclass(type):
1628 def mro(self):
1629 return [1]
1630 class X(object, metaclass=_metaclass):
1631 pass
1632 except TypeError:
1633 pass
1634 else:
1635 self.fail("non-class mro() return not caught")
1636
1637 try:
1638 class _metaclass(type):
1639 def mro(self):
1640 return 1
1641 class X(object, metaclass=_metaclass):
1642 pass
1643 except TypeError:
1644 pass
1645 else:
1646 self.fail("non-sequence mro() return not caught")
1647
1648 def test_overloading(self):
1649 # Testing operator overloading...
1650
1651 class B(object):
1652 "Intermediate class because object doesn't have a __setattr__"
1653
1654 class C(B):
1655 def __getattr__(self, name):
1656 if name == "foo":
1657 return ("getattr", name)
1658 else:
1659 raise AttributeError
1660 def __setattr__(self, name, value):
1661 if name == "foo":
1662 self.setattr = (name, value)
1663 else:
1664 return B.__setattr__(self, name, value)
1665 def __delattr__(self, name):
1666 if name == "foo":
1667 self.delattr = name
1668 else:
1669 return B.__delattr__(self, name)
1670
1671 def __getitem__(self, key):
1672 return ("getitem", key)
1673 def __setitem__(self, key, value):
1674 self.setitem = (key, value)
1675 def __delitem__(self, key):
1676 self.delitem = key
1677
1678 a = C()
1679 self.assertEqual(a.foo, ("getattr", "foo"))
1680 a.foo = 12
1681 self.assertEqual(a.setattr, ("foo", 12))
1682 del a.foo
1683 self.assertEqual(a.delattr, "foo")
1684
1685 self.assertEqual(a[12], ("getitem", 12))
1686 a[12] = 21
1687 self.assertEqual(a.setitem, (12, 21))
1688 del a[12]
1689 self.assertEqual(a.delitem, 12)
1690
1691 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1692 a[0:10] = "foo"
1693 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1694 del a[0:10]
1695 self.assertEqual(a.delitem, (slice(0, 10)))
1696
1697 def test_methods(self):
1698 # Testing methods...
1699 class C(object):
1700 def __init__(self, x):
1701 self.x = x
1702 def foo(self):
1703 return self.x
1704 c1 = C(1)
1705 self.assertEqual(c1.foo(), 1)
1706 class D(C):
1707 boo = C.foo
1708 goo = c1.foo
1709 d2 = D(2)
1710 self.assertEqual(d2.foo(), 2)
1711 self.assertEqual(d2.boo(), 2)
1712 self.assertEqual(d2.goo(), 1)
1713 class E(object):
1714 foo = C.foo
1715 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001716 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001717
Benjamin Peterson224205f2009-05-08 03:25:19 +00001718 def test_special_method_lookup(self):
1719 # The lookup of special methods bypasses __getattr__ and
1720 # __getattribute__, but they still can be descriptors.
1721
1722 def run_context(manager):
1723 with manager:
1724 pass
1725 def iden(self):
1726 return self
1727 def hello(self):
1728 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001729 def empty_seq(self):
1730 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001731 def zero(self):
1732 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001733 def complex_num(self):
1734 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001735 def stop(self):
1736 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001737 def return_true(self, thing=None):
1738 return True
1739 def do_isinstance(obj):
1740 return isinstance(int, obj)
1741 def do_issubclass(obj):
1742 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001743 def do_dict_missing(checker):
1744 class DictSub(checker.__class__, dict):
1745 pass
1746 self.assertEqual(DictSub()["hi"], 4)
1747 def some_number(self_, key):
1748 self.assertEqual(key, "hi")
1749 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001750 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001751 def format_impl(self, spec):
1752 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001753
1754 # It would be nice to have every special method tested here, but I'm
1755 # only listing the ones I can remember outside of typeobject.c, since it
1756 # does it right.
1757 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001758 ("__bytes__", bytes, hello, set(), {}),
1759 ("__reversed__", reversed, empty_seq, set(), {}),
1760 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001761 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001762 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1763 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001764 ("__missing__", do_dict_missing, some_number,
1765 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001766 ("__subclasscheck__", do_issubclass, return_true,
1767 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001768 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1769 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001770 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001771 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001772 ("__floor__", math.floor, zero, set(), {}),
1773 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001774 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001775 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001776 ]
1777
1778 class Checker(object):
1779 def __getattr__(self, attr, test=self):
1780 test.fail("__getattr__ called with {0}".format(attr))
1781 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001782 if attr not in ok:
1783 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001784 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001785 class SpecialDescr(object):
1786 def __init__(self, impl):
1787 self.impl = impl
1788 def __get__(self, obj, owner):
1789 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001790 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001791 class MyException(Exception):
1792 pass
1793 class ErrDescr(object):
1794 def __get__(self, obj, owner):
1795 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001796
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001797 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001798 class X(Checker):
1799 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001800 for attr, obj in env.items():
1801 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001802 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001803 runner(X())
1804
1805 record = []
1806 class X(Checker):
1807 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001808 for attr, obj in env.items():
1809 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001810 setattr(X, name, SpecialDescr(meth_impl))
1811 runner(X())
1812 self.assertEqual(record, [1], name)
1813
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001814 class X(Checker):
1815 pass
1816 for attr, obj in env.items():
1817 setattr(X, attr, obj)
1818 setattr(X, name, ErrDescr())
1819 try:
1820 runner(X())
1821 except MyException:
1822 pass
1823 else:
1824 self.fail("{0!r} didn't raise".format(name))
1825
Georg Brandl479a7e72008-02-05 18:13:15 +00001826 def test_specials(self):
1827 # Testing special operators...
1828 # Test operators like __hash__ for which a built-in default exists
1829
1830 # Test the default behavior for static classes
1831 class C(object):
1832 def __getitem__(self, i):
1833 if 0 <= i < 10: return i
1834 raise IndexError
1835 c1 = C()
1836 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001837 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001838 self.assertNotEqual(id(c1), id(c2))
1839 hash(c1)
1840 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001841 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001842 self.assertTrue(c1 != c2)
1843 self.assertTrue(not c1 != c1)
1844 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001845 # Note that the module name appears in str/repr, and that varies
1846 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001847 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001848 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001849 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001850 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001851 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001852 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001853 # Test the default behavior for dynamic classes
1854 class D(object):
1855 def __getitem__(self, i):
1856 if 0 <= i < 10: return i
1857 raise IndexError
1858 d1 = D()
1859 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001860 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001861 self.assertNotEqual(id(d1), id(d2))
1862 hash(d1)
1863 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001864 self.assertEqual(d1, d1)
1865 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001866 self.assertTrue(not d1 != d1)
1867 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001868 # Note that the module name appears in str/repr, and that varies
1869 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001870 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001871 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001872 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001873 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001874 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001875 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001876 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001877 class Proxy(object):
1878 def __init__(self, x):
1879 self.x = x
1880 def __bool__(self):
1881 return not not self.x
1882 def __hash__(self):
1883 return hash(self.x)
1884 def __eq__(self, other):
1885 return self.x == other
1886 def __ne__(self, other):
1887 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001888 def __ge__(self, other):
1889 return self.x >= other
1890 def __gt__(self, other):
1891 return self.x > other
1892 def __le__(self, other):
1893 return self.x <= other
1894 def __lt__(self, other):
1895 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001896 def __str__(self):
1897 return "Proxy:%s" % self.x
1898 def __repr__(self):
1899 return "Proxy(%r)" % self.x
1900 def __contains__(self, value):
1901 return value in self.x
1902 p0 = Proxy(0)
1903 p1 = Proxy(1)
1904 p_1 = Proxy(-1)
1905 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001906 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001907 self.assertEqual(hash(p0), hash(0))
1908 self.assertEqual(p0, p0)
1909 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001910 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001911 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001912 self.assertTrue(p0 < p1)
1913 self.assertTrue(p0 <= p1)
1914 self.assertTrue(p1 > p0)
1915 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001916 self.assertEqual(str(p0), "Proxy:0")
1917 self.assertEqual(repr(p0), "Proxy(0)")
1918 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001919 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001920 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001921 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001922 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001923
Georg Brandl479a7e72008-02-05 18:13:15 +00001924 def test_weakrefs(self):
1925 # Testing weak references...
1926 import weakref
1927 class C(object):
1928 pass
1929 c = C()
1930 r = weakref.ref(c)
1931 self.assertEqual(r(), c)
1932 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001933 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001934 self.assertEqual(r(), None)
1935 del r
1936 class NoWeak(object):
1937 __slots__ = ['foo']
1938 no = NoWeak()
1939 try:
1940 weakref.ref(no)
1941 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001942 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001943 else:
1944 self.fail("weakref.ref(no) should be illegal")
1945 class Weak(object):
1946 __slots__ = ['foo', '__weakref__']
1947 yes = Weak()
1948 r = weakref.ref(yes)
1949 self.assertEqual(r(), yes)
1950 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001951 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001952 self.assertEqual(r(), None)
1953 del r
1954
1955 def test_properties(self):
1956 # Testing property...
1957 class C(object):
1958 def getx(self):
1959 return self.__x
1960 def setx(self, value):
1961 self.__x = value
1962 def delx(self):
1963 del self.__x
1964 x = property(getx, setx, delx, doc="I'm the x property.")
1965 a = C()
1966 self.assertFalse(hasattr(a, "x"))
1967 a.x = 42
1968 self.assertEqual(a._C__x, 42)
1969 self.assertEqual(a.x, 42)
1970 del a.x
1971 self.assertFalse(hasattr(a, "x"))
1972 self.assertFalse(hasattr(a, "_C__x"))
1973 C.x.__set__(a, 100)
1974 self.assertEqual(C.x.__get__(a), 100)
1975 C.x.__delete__(a)
1976 self.assertFalse(hasattr(a, "x"))
1977
1978 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001979 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001980
1981 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001982 self.assertIn("__doc__", attrs)
1983 self.assertIn("fget", attrs)
1984 self.assertIn("fset", attrs)
1985 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001986
1987 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001988 self.assertTrue(raw.fget is C.__dict__['getx'])
1989 self.assertTrue(raw.fset is C.__dict__['setx'])
1990 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001991
1992 for attr in "__doc__", "fget", "fset", "fdel":
1993 try:
1994 setattr(raw, attr, 42)
1995 except AttributeError as msg:
1996 if str(msg).find('readonly') < 0:
1997 self.fail("when setting readonly attr %r on a property, "
1998 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1999 else:
2000 self.fail("expected AttributeError from trying to set readonly %r "
2001 "attr on a property" % attr)
2002
2003 class D(object):
2004 __getitem__ = property(lambda s: 1/0)
2005
2006 d = D()
2007 try:
2008 for i in d:
2009 str(i)
2010 except ZeroDivisionError:
2011 pass
2012 else:
2013 self.fail("expected ZeroDivisionError from bad property")
2014
R. David Murray378c0cf2010-02-24 01:46:21 +00002015 @unittest.skipIf(sys.flags.optimize >= 2,
2016 "Docstrings are omitted with -O2 and above")
2017 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002018 class E(object):
2019 def getter(self):
2020 "getter method"
2021 return 0
2022 def setter(self_, value):
2023 "setter method"
2024 pass
2025 prop = property(getter)
2026 self.assertEqual(prop.__doc__, "getter method")
2027 prop2 = property(fset=setter)
2028 self.assertEqual(prop2.__doc__, None)
2029
R. David Murray378c0cf2010-02-24 01:46:21 +00002030 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002031 # this segfaulted in 2.5b2
2032 try:
2033 import _testcapi
2034 except ImportError:
2035 pass
2036 else:
2037 class X(object):
2038 p = property(_testcapi.test_with_docstring)
2039
2040 def test_properties_plus(self):
2041 class C(object):
2042 foo = property(doc="hello")
2043 @foo.getter
2044 def foo(self):
2045 return self._foo
2046 @foo.setter
2047 def foo(self, value):
2048 self._foo = abs(value)
2049 @foo.deleter
2050 def foo(self):
2051 del self._foo
2052 c = C()
2053 self.assertEqual(C.foo.__doc__, "hello")
2054 self.assertFalse(hasattr(c, "foo"))
2055 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002056 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00002057 self.assertEqual(c._foo, 42)
2058 self.assertEqual(c.foo, 42)
2059 del c.foo
2060 self.assertFalse(hasattr(c, '_foo'))
2061 self.assertFalse(hasattr(c, "foo"))
2062
2063 class D(C):
2064 @C.foo.deleter
2065 def foo(self):
2066 try:
2067 del self._foo
2068 except AttributeError:
2069 pass
2070 d = D()
2071 d.foo = 24
2072 self.assertEqual(d.foo, 24)
2073 del d.foo
2074 del d.foo
2075
2076 class E(object):
2077 @property
2078 def foo(self):
2079 return self._foo
2080 @foo.setter
2081 def foo(self, value):
2082 raise RuntimeError
2083 @foo.setter
2084 def foo(self, value):
2085 self._foo = abs(value)
2086 @foo.deleter
2087 def foo(self, value=None):
2088 del self._foo
2089
2090 e = E()
2091 e.foo = -42
2092 self.assertEqual(e.foo, 42)
2093 del e.foo
2094
2095 class F(E):
2096 @E.foo.deleter
2097 def foo(self):
2098 del self._foo
2099 @foo.setter
2100 def foo(self, value):
2101 self._foo = max(0, value)
2102 f = F()
2103 f.foo = -10
2104 self.assertEqual(f.foo, 0)
2105 del f.foo
2106
2107 def test_dict_constructors(self):
2108 # Testing dict constructor ...
2109 d = dict()
2110 self.assertEqual(d, {})
2111 d = dict({})
2112 self.assertEqual(d, {})
2113 d = dict({1: 2, 'a': 'b'})
2114 self.assertEqual(d, {1: 2, 'a': 'b'})
2115 self.assertEqual(d, dict(list(d.items())))
2116 self.assertEqual(d, dict(iter(d.items())))
2117 d = dict({'one':1, 'two':2})
2118 self.assertEqual(d, dict(one=1, two=2))
2119 self.assertEqual(d, dict(**d))
2120 self.assertEqual(d, dict({"one": 1}, two=2))
2121 self.assertEqual(d, dict([("two", 2)], one=1))
2122 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2123 self.assertEqual(d, dict(**d))
2124
2125 for badarg in 0, 0, 0j, "0", [0], (0,):
2126 try:
2127 dict(badarg)
2128 except TypeError:
2129 pass
2130 except ValueError:
2131 if badarg == "0":
2132 # It's a sequence, and its elements are also sequences (gotta
2133 # love strings <wink>), but they aren't of length 2, so this
2134 # one seemed better as a ValueError than a TypeError.
2135 pass
2136 else:
2137 self.fail("no TypeError from dict(%r)" % badarg)
2138 else:
2139 self.fail("no TypeError from dict(%r)" % badarg)
2140
2141 try:
2142 dict({}, {})
2143 except TypeError:
2144 pass
2145 else:
2146 self.fail("no TypeError from dict({}, {})")
2147
2148 class Mapping:
2149 # Lacks a .keys() method; will be added later.
2150 dict = {1:2, 3:4, 'a':1j}
2151
2152 try:
2153 dict(Mapping())
2154 except TypeError:
2155 pass
2156 else:
2157 self.fail("no TypeError from dict(incomplete mapping)")
2158
2159 Mapping.keys = lambda self: list(self.dict.keys())
2160 Mapping.__getitem__ = lambda self, i: self.dict[i]
2161 d = dict(Mapping())
2162 self.assertEqual(d, Mapping.dict)
2163
2164 # Init from sequence of iterable objects, each producing a 2-sequence.
2165 class AddressBookEntry:
2166 def __init__(self, first, last):
2167 self.first = first
2168 self.last = last
2169 def __iter__(self):
2170 return iter([self.first, self.last])
2171
2172 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2173 AddressBookEntry('Barry', 'Peters'),
2174 AddressBookEntry('Tim', 'Peters'),
2175 AddressBookEntry('Barry', 'Warsaw')])
2176 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2177
2178 d = dict(zip(range(4), range(1, 5)))
2179 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2180
2181 # Bad sequence lengths.
2182 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2183 try:
2184 dict(bad)
2185 except ValueError:
2186 pass
2187 else:
2188 self.fail("no ValueError from dict(%r)" % bad)
2189
2190 def test_dir(self):
2191 # Testing dir() ...
2192 junk = 12
2193 self.assertEqual(dir(), ['junk', 'self'])
2194 del junk
2195
2196 # Just make sure these don't blow up!
2197 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2198 dir(arg)
2199
2200 # Test dir on new-style classes. Since these have object as a
2201 # base class, a lot more gets sucked in.
2202 def interesting(strings):
2203 return [s for s in strings if not s.startswith('_')]
2204
2205 class C(object):
2206 Cdata = 1
2207 def Cmethod(self): pass
2208
2209 cstuff = ['Cdata', 'Cmethod']
2210 self.assertEqual(interesting(dir(C)), cstuff)
2211
2212 c = C()
2213 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002214 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002215
2216 c.cdata = 2
2217 c.cmethod = lambda self: 0
2218 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002219 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002220
2221 class A(C):
2222 Adata = 1
2223 def Amethod(self): pass
2224
2225 astuff = ['Adata', 'Amethod'] + cstuff
2226 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002227 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002228 a = A()
2229 self.assertEqual(interesting(dir(a)), astuff)
2230 a.adata = 42
2231 a.amethod = lambda self: 3
2232 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002233 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002234
2235 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002236 class M(type(sys)):
2237 pass
2238 minstance = M("m")
2239 minstance.b = 2
2240 minstance.a = 1
2241 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2242 self.assertEqual(names, ['a', 'b'])
2243
2244 class M2(M):
2245 def getdict(self):
2246 return "Not a dict!"
2247 __dict__ = property(getdict)
2248
2249 m2instance = M2("m2")
2250 m2instance.b = 2
2251 m2instance.a = 1
2252 self.assertEqual(m2instance.__dict__, "Not a dict!")
2253 try:
2254 dir(m2instance)
2255 except TypeError:
2256 pass
2257
2258 # Two essentially featureless objects, just inheriting stuff from
2259 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002260 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2261 if support.check_impl_detail():
2262 # None differs in PyPy: it has a __nonzero__
2263 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002264
2265 # Nasty test case for proxied objects
2266 class Wrapper(object):
2267 def __init__(self, obj):
2268 self.__obj = obj
2269 def __repr__(self):
2270 return "Wrapper(%s)" % repr(self.__obj)
2271 def __getitem__(self, key):
2272 return Wrapper(self.__obj[key])
2273 def __len__(self):
2274 return len(self.__obj)
2275 def __getattr__(self, name):
2276 return Wrapper(getattr(self.__obj, name))
2277
2278 class C(object):
2279 def __getclass(self):
2280 return Wrapper(type(self))
2281 __class__ = property(__getclass)
2282
2283 dir(C()) # This used to segfault
2284
2285 def test_supers(self):
2286 # Testing super...
2287
2288 class A(object):
2289 def meth(self, a):
2290 return "A(%r)" % a
2291
2292 self.assertEqual(A().meth(1), "A(1)")
2293
2294 class B(A):
2295 def __init__(self):
2296 self.__super = super(B, self)
2297 def meth(self, a):
2298 return "B(%r)" % a + self.__super.meth(a)
2299
2300 self.assertEqual(B().meth(2), "B(2)A(2)")
2301
2302 class C(A):
2303 def meth(self, a):
2304 return "C(%r)" % a + self.__super.meth(a)
2305 C._C__super = super(C)
2306
2307 self.assertEqual(C().meth(3), "C(3)A(3)")
2308
2309 class D(C, B):
2310 def meth(self, a):
2311 return "D(%r)" % a + super(D, self).meth(a)
2312
2313 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2314
2315 # Test for subclassing super
2316
2317 class mysuper(super):
2318 def __init__(self, *args):
2319 return super(mysuper, self).__init__(*args)
2320
2321 class E(D):
2322 def meth(self, a):
2323 return "E(%r)" % a + mysuper(E, self).meth(a)
2324
2325 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2326
2327 class F(E):
2328 def meth(self, a):
2329 s = self.__super # == mysuper(F, self)
2330 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2331 F._F__super = mysuper(F)
2332
2333 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2334
2335 # Make sure certain errors are raised
2336
2337 try:
2338 super(D, 42)
2339 except TypeError:
2340 pass
2341 else:
2342 self.fail("shouldn't allow super(D, 42)")
2343
2344 try:
2345 super(D, C())
2346 except TypeError:
2347 pass
2348 else:
2349 self.fail("shouldn't allow super(D, C())")
2350
2351 try:
2352 super(D).__get__(12)
2353 except TypeError:
2354 pass
2355 else:
2356 self.fail("shouldn't allow super(D).__get__(12)")
2357
2358 try:
2359 super(D).__get__(C())
2360 except TypeError:
2361 pass
2362 else:
2363 self.fail("shouldn't allow super(D).__get__(C())")
2364
2365 # Make sure data descriptors can be overridden and accessed via super
2366 # (new feature in Python 2.3)
2367
2368 class DDbase(object):
2369 def getx(self): return 42
2370 x = property(getx)
2371
2372 class DDsub(DDbase):
2373 def getx(self): return "hello"
2374 x = property(getx)
2375
2376 dd = DDsub()
2377 self.assertEqual(dd.x, "hello")
2378 self.assertEqual(super(DDsub, dd).x, 42)
2379
2380 # Ensure that super() lookup of descriptor from classmethod
2381 # works (SF ID# 743627)
2382
2383 class Base(object):
2384 aProp = property(lambda self: "foo")
2385
2386 class Sub(Base):
2387 @classmethod
2388 def test(klass):
2389 return super(Sub,klass).aProp
2390
2391 self.assertEqual(Sub.test(), Base.aProp)
2392
2393 # Verify that super() doesn't allow keyword args
2394 try:
2395 super(Base, kw=1)
2396 except TypeError:
2397 pass
2398 else:
2399 self.assertEqual("super shouldn't accept keyword args")
2400
2401 def test_basic_inheritance(self):
2402 # Testing inheritance from basic types...
2403
2404 class hexint(int):
2405 def __repr__(self):
2406 return hex(self)
2407 def __add__(self, other):
2408 return hexint(int.__add__(self, other))
2409 # (Note that overriding __radd__ doesn't work,
2410 # because the int type gets first dibs.)
2411 self.assertEqual(repr(hexint(7) + 9), "0x10")
2412 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2413 a = hexint(12345)
2414 self.assertEqual(a, 12345)
2415 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002416 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002417 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002418 self.assertTrue((+a).__class__ is int)
2419 self.assertTrue((a >> 0).__class__ is int)
2420 self.assertTrue((a << 0).__class__ is int)
2421 self.assertTrue((hexint(0) << 12).__class__ is int)
2422 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002423
2424 class octlong(int):
2425 __slots__ = []
2426 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002427 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002428 def __add__(self, other):
2429 return self.__class__(super(octlong, self).__add__(other))
2430 __radd__ = __add__
2431 self.assertEqual(str(octlong(3) + 5), "0o10")
2432 # (Note that overriding __radd__ here only seems to work
2433 # because the example uses a short int left argument.)
2434 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2435 a = octlong(12345)
2436 self.assertEqual(a, 12345)
2437 self.assertEqual(int(a), 12345)
2438 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002439 self.assertTrue(int(a).__class__ is int)
2440 self.assertTrue((+a).__class__ is int)
2441 self.assertTrue((-a).__class__ is int)
2442 self.assertTrue((-octlong(0)).__class__ is int)
2443 self.assertTrue((a >> 0).__class__ is int)
2444 self.assertTrue((a << 0).__class__ is int)
2445 self.assertTrue((a - 0).__class__ is int)
2446 self.assertTrue((a * 1).__class__ is int)
2447 self.assertTrue((a ** 1).__class__ is int)
2448 self.assertTrue((a // 1).__class__ is int)
2449 self.assertTrue((1 * a).__class__ is int)
2450 self.assertTrue((a | 0).__class__ is int)
2451 self.assertTrue((a ^ 0).__class__ is int)
2452 self.assertTrue((a & -1).__class__ is int)
2453 self.assertTrue((octlong(0) << 12).__class__ is int)
2454 self.assertTrue((octlong(0) >> 12).__class__ is int)
2455 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002456
2457 # Because octlong overrides __add__, we can't check the absence of +0
2458 # optimizations using octlong.
2459 class longclone(int):
2460 pass
2461 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002462 self.assertTrue((a + 0).__class__ is int)
2463 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002464
2465 # Check that negative clones don't segfault
2466 a = longclone(-1)
2467 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002468 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002469
2470 class precfloat(float):
2471 __slots__ = ['prec']
2472 def __init__(self, value=0.0, prec=12):
2473 self.prec = int(prec)
2474 def __repr__(self):
2475 return "%.*g" % (self.prec, self)
2476 self.assertEqual(repr(precfloat(1.1)), "1.1")
2477 a = precfloat(12345)
2478 self.assertEqual(a, 12345.0)
2479 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002480 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002481 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002482 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002483
2484 class madcomplex(complex):
2485 def __repr__(self):
2486 return "%.17gj%+.17g" % (self.imag, self.real)
2487 a = madcomplex(-3, 4)
2488 self.assertEqual(repr(a), "4j-3")
2489 base = complex(-3, 4)
2490 self.assertEqual(base.__class__, complex)
2491 self.assertEqual(a, base)
2492 self.assertEqual(complex(a), base)
2493 self.assertEqual(complex(a).__class__, complex)
2494 a = madcomplex(a) # just trying another form of the constructor
2495 self.assertEqual(repr(a), "4j-3")
2496 self.assertEqual(a, base)
2497 self.assertEqual(complex(a), base)
2498 self.assertEqual(complex(a).__class__, complex)
2499 self.assertEqual(hash(a), hash(base))
2500 self.assertEqual((+a).__class__, complex)
2501 self.assertEqual((a + 0).__class__, complex)
2502 self.assertEqual(a + 0, base)
2503 self.assertEqual((a - 0).__class__, complex)
2504 self.assertEqual(a - 0, base)
2505 self.assertEqual((a * 1).__class__, complex)
2506 self.assertEqual(a * 1, base)
2507 self.assertEqual((a / 1).__class__, complex)
2508 self.assertEqual(a / 1, base)
2509
2510 class madtuple(tuple):
2511 _rev = None
2512 def rev(self):
2513 if self._rev is not None:
2514 return self._rev
2515 L = list(self)
2516 L.reverse()
2517 self._rev = self.__class__(L)
2518 return self._rev
2519 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2520 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2521 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2522 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2523 for i in range(512):
2524 t = madtuple(range(i))
2525 u = t.rev()
2526 v = u.rev()
2527 self.assertEqual(v, t)
2528 a = madtuple((1,2,3,4,5))
2529 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002530 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002531 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002532 self.assertTrue(a[:].__class__ is tuple)
2533 self.assertTrue((a * 1).__class__ is tuple)
2534 self.assertTrue((a * 0).__class__ is tuple)
2535 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002536 a = madtuple(())
2537 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002538 self.assertTrue(tuple(a).__class__ is tuple)
2539 self.assertTrue((a + a).__class__ is tuple)
2540 self.assertTrue((a * 0).__class__ is tuple)
2541 self.assertTrue((a * 1).__class__ is tuple)
2542 self.assertTrue((a * 2).__class__ is tuple)
2543 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002544
2545 class madstring(str):
2546 _rev = None
2547 def rev(self):
2548 if self._rev is not None:
2549 return self._rev
2550 L = list(self)
2551 L.reverse()
2552 self._rev = self.__class__("".join(L))
2553 return self._rev
2554 s = madstring("abcdefghijklmnopqrstuvwxyz")
2555 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2556 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2557 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2558 for i in range(256):
2559 s = madstring("".join(map(chr, range(i))))
2560 t = s.rev()
2561 u = t.rev()
2562 self.assertEqual(u, s)
2563 s = madstring("12345")
2564 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002565 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002566
2567 base = "\x00" * 5
2568 s = madstring(base)
2569 self.assertEqual(s, base)
2570 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002571 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002572 self.assertEqual(hash(s), hash(base))
2573 self.assertEqual({s: 1}[base], 1)
2574 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002575 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002576 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002577 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002578 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002579 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002580 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002581 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002583 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002584 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002585 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002586 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002587 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002588 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002589 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002590 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002591 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002592 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002593 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002594 self.assertEqual(s.rstrip(), base)
2595 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002596 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002597 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002598 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002599 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002600 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002601 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002602 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002603 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002604 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002605 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002606 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002607 self.assertEqual(s.lower(), base)
2608
2609 class madunicode(str):
2610 _rev = None
2611 def rev(self):
2612 if self._rev is not None:
2613 return self._rev
2614 L = list(self)
2615 L.reverse()
2616 self._rev = self.__class__("".join(L))
2617 return self._rev
2618 u = madunicode("ABCDEF")
2619 self.assertEqual(u, "ABCDEF")
2620 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2621 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2622 base = "12345"
2623 u = madunicode(base)
2624 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002625 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002626 self.assertEqual(hash(u), hash(base))
2627 self.assertEqual({u: 1}[base], 1)
2628 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002629 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002630 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002631 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002632 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002633 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002634 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002635 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002636 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002637 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002638 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002639 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002640 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002641 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002642 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002643 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002644 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002645 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002646 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002647 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002649 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002651 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002652 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002653 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002654 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002655 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002656 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002657 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002658 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002659 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002660 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002661 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002662 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002663 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002664 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002665 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002666 self.assertEqual(u[0:0], "")
2667
2668 class sublist(list):
2669 pass
2670 a = sublist(range(5))
2671 self.assertEqual(a, list(range(5)))
2672 a.append("hello")
2673 self.assertEqual(a, list(range(5)) + ["hello"])
2674 a[5] = 5
2675 self.assertEqual(a, list(range(6)))
2676 a.extend(range(6, 20))
2677 self.assertEqual(a, list(range(20)))
2678 a[-5:] = []
2679 self.assertEqual(a, list(range(15)))
2680 del a[10:15]
2681 self.assertEqual(len(a), 10)
2682 self.assertEqual(a, list(range(10)))
2683 self.assertEqual(list(a), list(range(10)))
2684 self.assertEqual(a[0], 0)
2685 self.assertEqual(a[9], 9)
2686 self.assertEqual(a[-10], 0)
2687 self.assertEqual(a[-1], 9)
2688 self.assertEqual(a[:5], list(range(5)))
2689
2690 ## class CountedInput(file):
2691 ## """Counts lines read by self.readline().
2692 ##
2693 ## self.lineno is the 0-based ordinal of the last line read, up to
2694 ## a maximum of one greater than the number of lines in the file.
2695 ##
2696 ## self.ateof is true if and only if the final "" line has been read,
2697 ## at which point self.lineno stops incrementing, and further calls
2698 ## to readline() continue to return "".
2699 ## """
2700 ##
2701 ## lineno = 0
2702 ## ateof = 0
2703 ## def readline(self):
2704 ## if self.ateof:
2705 ## return ""
2706 ## s = file.readline(self)
2707 ## # Next line works too.
2708 ## # s = super(CountedInput, self).readline()
2709 ## self.lineno += 1
2710 ## if s == "":
2711 ## self.ateof = 1
2712 ## return s
2713 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002714 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002715 ## lines = ['a\n', 'b\n', 'c\n']
2716 ## try:
2717 ## f.writelines(lines)
2718 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002719 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002720 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2721 ## got = f.readline()
2722 ## self.assertEqual(expected, got)
2723 ## self.assertEqual(f.lineno, i)
2724 ## self.assertEqual(f.ateof, (i > len(lines)))
2725 ## f.close()
2726 ## finally:
2727 ## try:
2728 ## f.close()
2729 ## except:
2730 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002731 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002732
2733 def test_keywords(self):
2734 # Testing keyword args to basic type constructors ...
2735 self.assertEqual(int(x=1), 1)
2736 self.assertEqual(float(x=2), 2.0)
2737 self.assertEqual(int(x=3), 3)
2738 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2739 self.assertEqual(str(object=500), '500')
2740 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2741 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2742 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2743 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2744
2745 for constructor in (int, float, int, complex, str, str,
2746 tuple, list):
2747 try:
2748 constructor(bogus_keyword_arg=1)
2749 except TypeError:
2750 pass
2751 else:
2752 self.fail("expected TypeError from bogus keyword argument to %r"
2753 % constructor)
2754
2755 def test_str_subclass_as_dict_key(self):
2756 # Testing a str subclass used as dict key ..
2757
2758 class cistr(str):
2759 """Sublcass of str that computes __eq__ case-insensitively.
2760
2761 Also computes a hash code of the string in canonical form.
2762 """
2763
2764 def __init__(self, value):
2765 self.canonical = value.lower()
2766 self.hashcode = hash(self.canonical)
2767
2768 def __eq__(self, other):
2769 if not isinstance(other, cistr):
2770 other = cistr(other)
2771 return self.canonical == other.canonical
2772
2773 def __hash__(self):
2774 return self.hashcode
2775
2776 self.assertEqual(cistr('ABC'), 'abc')
2777 self.assertEqual('aBc', cistr('ABC'))
2778 self.assertEqual(str(cistr('ABC')), 'ABC')
2779
2780 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2781 self.assertEqual(d[cistr('one')], 1)
2782 self.assertEqual(d[cistr('tWo')], 2)
2783 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002784 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002785 self.assertEqual(d.get(cistr('thrEE')), 3)
2786
2787 def test_classic_comparisons(self):
2788 # Testing classic comparisons...
2789 class classic:
2790 pass
2791
2792 for base in (classic, int, object):
2793 class C(base):
2794 def __init__(self, value):
2795 self.value = int(value)
2796 def __eq__(self, other):
2797 if isinstance(other, C):
2798 return self.value == other.value
2799 if isinstance(other, int) or isinstance(other, int):
2800 return self.value == other
2801 return NotImplemented
2802 def __ne__(self, other):
2803 if isinstance(other, C):
2804 return self.value != other.value
2805 if isinstance(other, int) or isinstance(other, int):
2806 return self.value != other
2807 return NotImplemented
2808 def __lt__(self, other):
2809 if isinstance(other, C):
2810 return self.value < other.value
2811 if isinstance(other, int) or isinstance(other, int):
2812 return self.value < other
2813 return NotImplemented
2814 def __le__(self, other):
2815 if isinstance(other, C):
2816 return self.value <= other.value
2817 if isinstance(other, int) or isinstance(other, int):
2818 return self.value <= other
2819 return NotImplemented
2820 def __gt__(self, other):
2821 if isinstance(other, C):
2822 return self.value > other.value
2823 if isinstance(other, int) or isinstance(other, int):
2824 return self.value > other
2825 return NotImplemented
2826 def __ge__(self, other):
2827 if isinstance(other, C):
2828 return self.value >= other.value
2829 if isinstance(other, int) or isinstance(other, int):
2830 return self.value >= other
2831 return NotImplemented
2832
2833 c1 = C(1)
2834 c2 = C(2)
2835 c3 = C(3)
2836 self.assertEqual(c1, 1)
2837 c = {1: c1, 2: c2, 3: c3}
2838 for x in 1, 2, 3:
2839 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002840 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002841 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002842 eval("x %s y" % op),
2843 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002844 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002845 eval("x %s y" % op),
2846 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002847 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002848 eval("x %s y" % op),
2849 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002850
2851 def test_rich_comparisons(self):
2852 # Testing rich comparisons...
2853 class Z(complex):
2854 pass
2855 z = Z(1)
2856 self.assertEqual(z, 1+0j)
2857 self.assertEqual(1+0j, z)
2858 class ZZ(complex):
2859 def __eq__(self, other):
2860 try:
2861 return abs(self - other) <= 1e-6
2862 except:
2863 return NotImplemented
2864 zz = ZZ(1.0000003)
2865 self.assertEqual(zz, 1+0j)
2866 self.assertEqual(1+0j, zz)
2867
2868 class classic:
2869 pass
2870 for base in (classic, int, object, list):
2871 class C(base):
2872 def __init__(self, value):
2873 self.value = int(value)
2874 def __cmp__(self_, other):
2875 self.fail("shouldn't call __cmp__")
2876 def __eq__(self, other):
2877 if isinstance(other, C):
2878 return self.value == other.value
2879 if isinstance(other, int) or isinstance(other, int):
2880 return self.value == other
2881 return NotImplemented
2882 def __ne__(self, other):
2883 if isinstance(other, C):
2884 return self.value != other.value
2885 if isinstance(other, int) or isinstance(other, int):
2886 return self.value != other
2887 return NotImplemented
2888 def __lt__(self, other):
2889 if isinstance(other, C):
2890 return self.value < other.value
2891 if isinstance(other, int) or isinstance(other, int):
2892 return self.value < other
2893 return NotImplemented
2894 def __le__(self, other):
2895 if isinstance(other, C):
2896 return self.value <= other.value
2897 if isinstance(other, int) or isinstance(other, int):
2898 return self.value <= other
2899 return NotImplemented
2900 def __gt__(self, other):
2901 if isinstance(other, C):
2902 return self.value > other.value
2903 if isinstance(other, int) or isinstance(other, int):
2904 return self.value > other
2905 return NotImplemented
2906 def __ge__(self, other):
2907 if isinstance(other, C):
2908 return self.value >= other.value
2909 if isinstance(other, int) or isinstance(other, int):
2910 return self.value >= other
2911 return NotImplemented
2912 c1 = C(1)
2913 c2 = C(2)
2914 c3 = C(3)
2915 self.assertEqual(c1, 1)
2916 c = {1: c1, 2: c2, 3: c3}
2917 for x in 1, 2, 3:
2918 for y in 1, 2, 3:
2919 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002920 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002921 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002922 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002923 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002924 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002925 "x=%d, y=%d" % (x, y))
2926
2927 def test_descrdoc(self):
2928 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002929 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002930 def check(descr, what):
2931 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002932 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002933 check(complex.real, "the real part of a complex number") # member descriptor
2934
2935 def test_doc_descriptor(self):
2936 # Testing __doc__ descriptor...
2937 # SF bug 542984
2938 class DocDescr(object):
2939 def __get__(self, object, otype):
2940 if object:
2941 object = object.__class__.__name__ + ' instance'
2942 if otype:
2943 otype = otype.__name__
2944 return 'object=%s; type=%s' % (object, otype)
2945 class OldClass:
2946 __doc__ = DocDescr()
2947 class NewClass(object):
2948 __doc__ = DocDescr()
2949 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2950 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2951 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2952 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2953
2954 def test_set_class(self):
2955 # Testing __class__ assignment...
2956 class C(object): pass
2957 class D(object): pass
2958 class E(object): pass
2959 class F(D, E): pass
2960 for cls in C, D, E, F:
2961 for cls2 in C, D, E, F:
2962 x = cls()
2963 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002964 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002965 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002966 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002967 def cant(x, C):
2968 try:
2969 x.__class__ = C
2970 except TypeError:
2971 pass
2972 else:
2973 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2974 try:
2975 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002976 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002977 pass
2978 else:
2979 self.fail("shouldn't allow del %r.__class__" % x)
2980 cant(C(), list)
2981 cant(list(), C)
2982 cant(C(), 1)
2983 cant(C(), object)
2984 cant(object(), list)
2985 cant(list(), object)
2986 class Int(int): __slots__ = []
2987 cant(2, Int)
2988 cant(Int(), int)
2989 cant(True, int)
2990 cant(2, bool)
2991 o = object()
2992 cant(o, type(1))
2993 cant(o, type(None))
2994 del o
2995 class G(object):
2996 __slots__ = ["a", "b"]
2997 class H(object):
2998 __slots__ = ["b", "a"]
2999 class I(object):
3000 __slots__ = ["a", "b"]
3001 class J(object):
3002 __slots__ = ["c", "b"]
3003 class K(object):
3004 __slots__ = ["a", "b", "d"]
3005 class L(H):
3006 __slots__ = ["e"]
3007 class M(I):
3008 __slots__ = ["e"]
3009 class N(J):
3010 __slots__ = ["__weakref__"]
3011 class P(J):
3012 __slots__ = ["__dict__"]
3013 class Q(J):
3014 pass
3015 class R(J):
3016 __slots__ = ["__dict__", "__weakref__"]
3017
3018 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3019 x = cls()
3020 x.a = 1
3021 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003022 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003023 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3024 self.assertEqual(x.a, 1)
3025 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003026 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003027 "assigning %r as __class__ for %r silently failed" % (cls, x))
3028 self.assertEqual(x.a, 1)
3029 for cls in G, J, K, L, M, N, P, R, list, Int:
3030 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3031 if cls is cls2:
3032 continue
3033 cant(cls(), cls2)
3034
Benjamin Peterson193152c2009-04-25 01:08:45 +00003035 # Issue5283: when __class__ changes in __del__, the wrong
3036 # type gets DECREF'd.
3037 class O(object):
3038 pass
3039 class A(object):
3040 def __del__(self):
3041 self.__class__ = O
3042 l = [A() for x in range(100)]
3043 del l
3044
Georg Brandl479a7e72008-02-05 18:13:15 +00003045 def test_set_dict(self):
3046 # Testing __dict__ assignment...
3047 class C(object): pass
3048 a = C()
3049 a.__dict__ = {'b': 1}
3050 self.assertEqual(a.b, 1)
3051 def cant(x, dict):
3052 try:
3053 x.__dict__ = dict
3054 except (AttributeError, TypeError):
3055 pass
3056 else:
3057 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3058 cant(a, None)
3059 cant(a, [])
3060 cant(a, 1)
3061 del a.__dict__ # Deleting __dict__ is allowed
3062
3063 class Base(object):
3064 pass
3065 def verify_dict_readonly(x):
3066 """
3067 x has to be an instance of a class inheriting from Base.
3068 """
3069 cant(x, {})
3070 try:
3071 del x.__dict__
3072 except (AttributeError, TypeError):
3073 pass
3074 else:
3075 self.fail("shouldn't allow del %r.__dict__" % x)
3076 dict_descr = Base.__dict__["__dict__"]
3077 try:
3078 dict_descr.__set__(x, {})
3079 except (AttributeError, TypeError):
3080 pass
3081 else:
3082 self.fail("dict_descr allowed access to %r's dict" % x)
3083
3084 # Classes don't allow __dict__ assignment and have readonly dicts
3085 class Meta1(type, Base):
3086 pass
3087 class Meta2(Base, type):
3088 pass
3089 class D(object, metaclass=Meta1):
3090 pass
3091 class E(object, metaclass=Meta2):
3092 pass
3093 for cls in C, D, E:
3094 verify_dict_readonly(cls)
3095 class_dict = cls.__dict__
3096 try:
3097 class_dict["spam"] = "eggs"
3098 except TypeError:
3099 pass
3100 else:
3101 self.fail("%r's __dict__ can be modified" % cls)
3102
3103 # Modules also disallow __dict__ assignment
3104 class Module1(types.ModuleType, Base):
3105 pass
3106 class Module2(Base, types.ModuleType):
3107 pass
3108 for ModuleType in Module1, Module2:
3109 mod = ModuleType("spam")
3110 verify_dict_readonly(mod)
3111 mod.__dict__["spam"] = "eggs"
3112
3113 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003114 # (at least not any more than regular exception's __dict__ can
3115 # be deleted; on CPython it is not the case, whereas on PyPy they
3116 # can, just like any other new-style instance's __dict__.)
3117 def can_delete_dict(e):
3118 try:
3119 del e.__dict__
3120 except (TypeError, AttributeError):
3121 return False
3122 else:
3123 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003124 class Exception1(Exception, Base):
3125 pass
3126 class Exception2(Base, Exception):
3127 pass
3128 for ExceptionType in Exception, Exception1, Exception2:
3129 e = ExceptionType()
3130 e.__dict__ = {"a": 1}
3131 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003132 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003133
3134 def test_pickles(self):
3135 # Testing pickling and copying new-style classes and objects...
3136 import pickle
3137
3138 def sorteditems(d):
3139 L = list(d.items())
3140 L.sort()
3141 return L
3142
3143 global C
3144 class C(object):
3145 def __init__(self, a, b):
3146 super(C, self).__init__()
3147 self.a = a
3148 self.b = b
3149 def __repr__(self):
3150 return "C(%r, %r)" % (self.a, self.b)
3151
3152 global C1
3153 class C1(list):
3154 def __new__(cls, a, b):
3155 return super(C1, cls).__new__(cls)
3156 def __getnewargs__(self):
3157 return (self.a, self.b)
3158 def __init__(self, a, b):
3159 self.a = a
3160 self.b = b
3161 def __repr__(self):
3162 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3163
3164 global C2
3165 class C2(int):
3166 def __new__(cls, a, b, val=0):
3167 return super(C2, cls).__new__(cls, val)
3168 def __getnewargs__(self):
3169 return (self.a, self.b, int(self))
3170 def __init__(self, a, b, val=0):
3171 self.a = a
3172 self.b = b
3173 def __repr__(self):
3174 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3175
3176 global C3
3177 class C3(object):
3178 def __init__(self, foo):
3179 self.foo = foo
3180 def __getstate__(self):
3181 return self.foo
3182 def __setstate__(self, foo):
3183 self.foo = foo
3184
3185 global C4classic, C4
3186 class C4classic: # classic
3187 pass
3188 class C4(C4classic, object): # mixed inheritance
3189 pass
3190
Guido van Rossum3926a632001-09-25 16:25:58 +00003191 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003192 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003193 s = pickle.dumps(cls, bin)
3194 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003195 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003196
3197 a = C1(1, 2); a.append(42); a.append(24)
3198 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003199 s = pickle.dumps((a, b), bin)
3200 x, y = pickle.loads(s)
3201 self.assertEqual(x.__class__, a.__class__)
3202 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3203 self.assertEqual(y.__class__, b.__class__)
3204 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3205 self.assertEqual(repr(x), repr(a))
3206 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003207 # Test for __getstate__ and __setstate__ on new style class
3208 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003209 s = pickle.dumps(u, bin)
3210 v = pickle.loads(s)
3211 self.assertEqual(u.__class__, v.__class__)
3212 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003213 # Test for picklability of hybrid class
3214 u = C4()
3215 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003216 s = pickle.dumps(u, bin)
3217 v = pickle.loads(s)
3218 self.assertEqual(u.__class__, v.__class__)
3219 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003220
Georg Brandl479a7e72008-02-05 18:13:15 +00003221 # Testing copy.deepcopy()
3222 import copy
3223 for cls in C, C1, C2:
3224 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003225 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003226
Georg Brandl479a7e72008-02-05 18:13:15 +00003227 a = C1(1, 2); a.append(42); a.append(24)
3228 b = C2("hello", "world", 42)
3229 x, y = copy.deepcopy((a, b))
3230 self.assertEqual(x.__class__, a.__class__)
3231 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3232 self.assertEqual(y.__class__, b.__class__)
3233 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3234 self.assertEqual(repr(x), repr(a))
3235 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003236
Georg Brandl479a7e72008-02-05 18:13:15 +00003237 def test_pickle_slots(self):
3238 # Testing pickling of classes with __slots__ ...
3239 import pickle
3240 # Pickling of classes with __slots__ but without __getstate__ should fail
3241 # (if using protocol 0 or 1)
3242 global B, C, D, E
3243 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003244 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003245 for base in [object, B]:
3246 class C(base):
3247 __slots__ = ['a']
3248 class D(C):
3249 pass
3250 try:
3251 pickle.dumps(C(), 0)
3252 except TypeError:
3253 pass
3254 else:
3255 self.fail("should fail: pickle C instance - %s" % base)
3256 try:
3257 pickle.dumps(C(), 0)
3258 except TypeError:
3259 pass
3260 else:
3261 self.fail("should fail: pickle D instance - %s" % base)
3262 # Give C a nice generic __getstate__ and __setstate__
3263 class C(base):
3264 __slots__ = ['a']
3265 def __getstate__(self):
3266 try:
3267 d = self.__dict__.copy()
3268 except AttributeError:
3269 d = {}
3270 for cls in self.__class__.__mro__:
3271 for sn in cls.__dict__.get('__slots__', ()):
3272 try:
3273 d[sn] = getattr(self, sn)
3274 except AttributeError:
3275 pass
3276 return d
3277 def __setstate__(self, d):
3278 for k, v in list(d.items()):
3279 setattr(self, k, v)
3280 class D(C):
3281 pass
3282 # Now it should work
3283 x = C()
3284 y = pickle.loads(pickle.dumps(x))
3285 self.assertEqual(hasattr(y, 'a'), 0)
3286 x.a = 42
3287 y = pickle.loads(pickle.dumps(x))
3288 self.assertEqual(y.a, 42)
3289 x = D()
3290 x.a = 42
3291 x.b = 100
3292 y = pickle.loads(pickle.dumps(x))
3293 self.assertEqual(y.a + y.b, 142)
3294 # A subclass that adds a slot should also work
3295 class E(C):
3296 __slots__ = ['b']
3297 x = E()
3298 x.a = 42
3299 x.b = "foo"
3300 y = pickle.loads(pickle.dumps(x))
3301 self.assertEqual(y.a, x.a)
3302 self.assertEqual(y.b, x.b)
3303
3304 def test_binary_operator_override(self):
3305 # Testing overrides of binary operations...
3306 class I(int):
3307 def __repr__(self):
3308 return "I(%r)" % int(self)
3309 def __add__(self, other):
3310 return I(int(self) + int(other))
3311 __radd__ = __add__
3312 def __pow__(self, other, mod=None):
3313 if mod is None:
3314 return I(pow(int(self), int(other)))
3315 else:
3316 return I(pow(int(self), int(other), int(mod)))
3317 def __rpow__(self, other, mod=None):
3318 if mod is None:
3319 return I(pow(int(other), int(self), mod))
3320 else:
3321 return I(pow(int(other), int(self), int(mod)))
3322
3323 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3324 self.assertEqual(repr(I(1) + 2), "I(3)")
3325 self.assertEqual(repr(1 + I(2)), "I(3)")
3326 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3327 self.assertEqual(repr(2 ** I(3)), "I(8)")
3328 self.assertEqual(repr(I(2) ** 3), "I(8)")
3329 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3330 class S(str):
3331 def __eq__(self, other):
3332 return self.lower() == other.lower()
3333
3334 def test_subclass_propagation(self):
3335 # Testing propagation of slot functions to subclasses...
3336 class A(object):
3337 pass
3338 class B(A):
3339 pass
3340 class C(A):
3341 pass
3342 class D(B, C):
3343 pass
3344 d = D()
3345 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3346 A.__hash__ = lambda self: 42
3347 self.assertEqual(hash(d), 42)
3348 C.__hash__ = lambda self: 314
3349 self.assertEqual(hash(d), 314)
3350 B.__hash__ = lambda self: 144
3351 self.assertEqual(hash(d), 144)
3352 D.__hash__ = lambda self: 100
3353 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003354 D.__hash__ = None
3355 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003356 del D.__hash__
3357 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003358 B.__hash__ = None
3359 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003360 del B.__hash__
3361 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003362 C.__hash__ = None
3363 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003364 del C.__hash__
3365 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003366 A.__hash__ = None
3367 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003368 del A.__hash__
3369 self.assertEqual(hash(d), orig_hash)
3370 d.foo = 42
3371 d.bar = 42
3372 self.assertEqual(d.foo, 42)
3373 self.assertEqual(d.bar, 42)
3374 def __getattribute__(self, name):
3375 if name == "foo":
3376 return 24
3377 return object.__getattribute__(self, name)
3378 A.__getattribute__ = __getattribute__
3379 self.assertEqual(d.foo, 24)
3380 self.assertEqual(d.bar, 42)
3381 def __getattr__(self, name):
3382 if name in ("spam", "foo", "bar"):
3383 return "hello"
3384 raise AttributeError(name)
3385 B.__getattr__ = __getattr__
3386 self.assertEqual(d.spam, "hello")
3387 self.assertEqual(d.foo, 24)
3388 self.assertEqual(d.bar, 42)
3389 del A.__getattribute__
3390 self.assertEqual(d.foo, 42)
3391 del d.foo
3392 self.assertEqual(d.foo, "hello")
3393 self.assertEqual(d.bar, 42)
3394 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003395 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003396 d.foo
3397 except AttributeError:
3398 pass
3399 else:
3400 self.fail("d.foo should be undefined now")
3401
3402 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003403 class A(object):
3404 pass
3405 class B(A):
3406 pass
3407 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003408 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003409 A.__setitem__ = lambda *a: None # crash
3410
3411 def test_buffer_inheritance(self):
3412 # Testing that buffer interface is inherited ...
3413
3414 import binascii
3415 # SF bug [#470040] ParseTuple t# vs subclasses.
3416
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003417 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003418 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003419 base = b'abc'
3420 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003421 # b2a_hex uses the buffer interface to get its argument's value, via
3422 # PyArg_ParseTuple 't#' code.
3423 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3424
Georg Brandl479a7e72008-02-05 18:13:15 +00003425 class MyInt(int):
3426 pass
3427 m = MyInt(42)
3428 try:
3429 binascii.b2a_hex(m)
3430 self.fail('subclass of int should not have a buffer interface')
3431 except TypeError:
3432 pass
3433
3434 def test_str_of_str_subclass(self):
3435 # Testing __str__ defined in subclass of str ...
3436 import binascii
3437 import io
3438
3439 class octetstring(str):
3440 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003441 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003442 def __repr__(self):
3443 return self + " repr"
3444
3445 o = octetstring('A')
3446 self.assertEqual(type(o), octetstring)
3447 self.assertEqual(type(str(o)), str)
3448 self.assertEqual(type(repr(o)), str)
3449 self.assertEqual(ord(o), 0x41)
3450 self.assertEqual(str(o), '41')
3451 self.assertEqual(repr(o), 'A repr')
3452 self.assertEqual(o.__str__(), '41')
3453 self.assertEqual(o.__repr__(), 'A repr')
3454
3455 capture = io.StringIO()
3456 # Calling str() or not exercises different internal paths.
3457 print(o, file=capture)
3458 print(str(o), file=capture)
3459 self.assertEqual(capture.getvalue(), '41\n41\n')
3460 capture.close()
3461
3462 def test_keyword_arguments(self):
3463 # Testing keyword arguments to __init__, __call__...
3464 def f(a): return a
3465 self.assertEqual(f.__call__(a=42), 42)
3466 a = []
3467 list.__init__(a, sequence=[0, 1, 2])
3468 self.assertEqual(a, [0, 1, 2])
3469
3470 def test_recursive_call(self):
3471 # Testing recursive __call__() by setting to instance of class...
3472 class A(object):
3473 pass
3474
3475 A.__call__ = A()
3476 try:
3477 A()()
3478 except RuntimeError:
3479 pass
3480 else:
3481 self.fail("Recursion limit should have been reached for __call__()")
3482
3483 def test_delete_hook(self):
3484 # Testing __del__ hook...
3485 log = []
3486 class C(object):
3487 def __del__(self):
3488 log.append(1)
3489 c = C()
3490 self.assertEqual(log, [])
3491 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003492 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003493 self.assertEqual(log, [1])
3494
3495 class D(object): pass
3496 d = D()
3497 try: del d[0]
3498 except TypeError: pass
3499 else: self.fail("invalid del() didn't raise TypeError")
3500
3501 def test_hash_inheritance(self):
3502 # Testing hash of mutable subclasses...
3503
3504 class mydict(dict):
3505 pass
3506 d = mydict()
3507 try:
3508 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003509 except TypeError:
3510 pass
3511 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003512 self.fail("hash() of dict subclass should fail")
3513
3514 class mylist(list):
3515 pass
3516 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003517 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003518 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003519 except TypeError:
3520 pass
3521 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003522 self.fail("hash() of list subclass should fail")
3523
3524 def test_str_operations(self):
3525 try: 'a' + 5
3526 except TypeError: pass
3527 else: self.fail("'' + 5 doesn't raise TypeError")
3528
3529 try: ''.split('')
3530 except ValueError: pass
3531 else: self.fail("''.split('') doesn't raise ValueError")
3532
3533 try: ''.join([0])
3534 except TypeError: pass
3535 else: self.fail("''.join([0]) doesn't raise TypeError")
3536
3537 try: ''.rindex('5')
3538 except ValueError: pass
3539 else: self.fail("''.rindex('5') doesn't raise ValueError")
3540
3541 try: '%(n)s' % None
3542 except TypeError: pass
3543 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3544
3545 try: '%(n' % {}
3546 except ValueError: pass
3547 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3548
3549 try: '%*s' % ('abc')
3550 except TypeError: pass
3551 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3552
3553 try: '%*.*s' % ('abc', 5)
3554 except TypeError: pass
3555 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3556
3557 try: '%s' % (1, 2)
3558 except TypeError: pass
3559 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3560
3561 try: '%' % None
3562 except ValueError: pass
3563 else: self.fail("'%' % None doesn't raise ValueError")
3564
3565 self.assertEqual('534253'.isdigit(), 1)
3566 self.assertEqual('534253x'.isdigit(), 0)
3567 self.assertEqual('%c' % 5, '\x05')
3568 self.assertEqual('%c' % '5', '5')
3569
3570 def test_deepcopy_recursive(self):
3571 # Testing deepcopy of recursive objects...
3572 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003573 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003574 a = Node()
3575 b = Node()
3576 a.b = b
3577 b.a = a
3578 z = deepcopy(a) # This blew up before
3579
3580 def test_unintialized_modules(self):
3581 # Testing uninitialized module objects...
3582 from types import ModuleType as M
3583 m = M.__new__(M)
3584 str(m)
3585 self.assertEqual(hasattr(m, "__name__"), 0)
3586 self.assertEqual(hasattr(m, "__file__"), 0)
3587 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003588 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003589 m.foo = 1
3590 self.assertEqual(m.__dict__, {"foo": 1})
3591
3592 def test_funny_new(self):
3593 # Testing __new__ returning something unexpected...
3594 class C(object):
3595 def __new__(cls, arg):
3596 if isinstance(arg, str): return [1, 2, 3]
3597 elif isinstance(arg, int): return object.__new__(D)
3598 else: return object.__new__(cls)
3599 class D(C):
3600 def __init__(self, arg):
3601 self.foo = arg
3602 self.assertEqual(C("1"), [1, 2, 3])
3603 self.assertEqual(D("1"), [1, 2, 3])
3604 d = D(None)
3605 self.assertEqual(d.foo, None)
3606 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003607 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003608 self.assertEqual(d.foo, 1)
3609 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003610 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003611 self.assertEqual(d.foo, 1)
3612
3613 def test_imul_bug(self):
3614 # Testing for __imul__ problems...
3615 # SF bug 544647
3616 class C(object):
3617 def __imul__(self, other):
3618 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003619 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003620 y = x
3621 y *= 1.0
3622 self.assertEqual(y, (x, 1.0))
3623 y = x
3624 y *= 2
3625 self.assertEqual(y, (x, 2))
3626 y = x
3627 y *= 3
3628 self.assertEqual(y, (x, 3))
3629 y = x
3630 y *= 1<<100
3631 self.assertEqual(y, (x, 1<<100))
3632 y = x
3633 y *= None
3634 self.assertEqual(y, (x, None))
3635 y = x
3636 y *= "foo"
3637 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003638
Georg Brandl479a7e72008-02-05 18:13:15 +00003639 def test_copy_setstate(self):
3640 # Testing that copy.*copy() correctly uses __setstate__...
3641 import copy
3642 class C(object):
3643 def __init__(self, foo=None):
3644 self.foo = foo
3645 self.__foo = foo
3646 def setfoo(self, foo=None):
3647 self.foo = foo
3648 def getfoo(self):
3649 return self.__foo
3650 def __getstate__(self):
3651 return [self.foo]
3652 def __setstate__(self_, lst):
3653 self.assertEqual(len(lst), 1)
3654 self_.__foo = self_.foo = lst[0]
3655 a = C(42)
3656 a.setfoo(24)
3657 self.assertEqual(a.foo, 24)
3658 self.assertEqual(a.getfoo(), 42)
3659 b = copy.copy(a)
3660 self.assertEqual(b.foo, 24)
3661 self.assertEqual(b.getfoo(), 24)
3662 b = copy.deepcopy(a)
3663 self.assertEqual(b.foo, 24)
3664 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003665
Georg Brandl479a7e72008-02-05 18:13:15 +00003666 def test_slices(self):
3667 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003668
Georg Brandl479a7e72008-02-05 18:13:15 +00003669 # Strings
3670 self.assertEqual("hello"[:4], "hell")
3671 self.assertEqual("hello"[slice(4)], "hell")
3672 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3673 class S(str):
3674 def __getitem__(self, x):
3675 return str.__getitem__(self, x)
3676 self.assertEqual(S("hello")[:4], "hell")
3677 self.assertEqual(S("hello")[slice(4)], "hell")
3678 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3679 # Tuples
3680 self.assertEqual((1,2,3)[:2], (1,2))
3681 self.assertEqual((1,2,3)[slice(2)], (1,2))
3682 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3683 class T(tuple):
3684 def __getitem__(self, x):
3685 return tuple.__getitem__(self, x)
3686 self.assertEqual(T((1,2,3))[:2], (1,2))
3687 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3688 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3689 # Lists
3690 self.assertEqual([1,2,3][:2], [1,2])
3691 self.assertEqual([1,2,3][slice(2)], [1,2])
3692 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3693 class L(list):
3694 def __getitem__(self, x):
3695 return list.__getitem__(self, x)
3696 self.assertEqual(L([1,2,3])[:2], [1,2])
3697 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3698 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3699 # Now do lists and __setitem__
3700 a = L([1,2,3])
3701 a[slice(1, 3)] = [3,2]
3702 self.assertEqual(a, [1,3,2])
3703 a[slice(0, 2, 1)] = [3,1]
3704 self.assertEqual(a, [3,1,2])
3705 a.__setitem__(slice(1, 3), [2,1])
3706 self.assertEqual(a, [3,2,1])
3707 a.__setitem__(slice(0, 2, 1), [2,3])
3708 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003709
Georg Brandl479a7e72008-02-05 18:13:15 +00003710 def test_subtype_resurrection(self):
3711 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003712
Georg Brandl479a7e72008-02-05 18:13:15 +00003713 class C(object):
3714 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003715
Georg Brandl479a7e72008-02-05 18:13:15 +00003716 def __del__(self):
3717 # resurrect the instance
3718 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003719
Georg Brandl479a7e72008-02-05 18:13:15 +00003720 c = C()
3721 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003722
Benjamin Petersone549ead2009-03-28 21:42:05 +00003723 # The most interesting thing here is whether this blows up, due to
3724 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3725 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003726 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003727
Georg Brandl479a7e72008-02-05 18:13:15 +00003728 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003729 # the last container slot works: that will attempt to delete c again,
3730 # which will cause c to get appended back to the container again
3731 # "during" the del. (On non-CPython implementations, however, __del__
3732 # is typically not called again.)
3733 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003734 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003735 del C.container[-1]
3736 if support.check_impl_detail():
3737 support.gc_collect()
3738 self.assertEqual(len(C.container), 1)
3739 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003740
Georg Brandl479a7e72008-02-05 18:13:15 +00003741 # Make c mortal again, so that the test framework with -l doesn't report
3742 # it as a leak.
3743 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003744
Georg Brandl479a7e72008-02-05 18:13:15 +00003745 def test_slots_trash(self):
3746 # Testing slot trash...
3747 # Deallocating deeply nested slotted trash caused stack overflows
3748 class trash(object):
3749 __slots__ = ['x']
3750 def __init__(self, x):
3751 self.x = x
3752 o = None
3753 for i in range(50000):
3754 o = trash(o)
3755 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003756
Georg Brandl479a7e72008-02-05 18:13:15 +00003757 def test_slots_multiple_inheritance(self):
3758 # SF bug 575229, multiple inheritance w/ slots dumps core
3759 class A(object):
3760 __slots__=()
3761 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003762 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003763 class C(A,B) :
3764 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003765 if support.check_impl_detail():
3766 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003767 self.assertTrue(hasattr(C, '__dict__'))
3768 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003769 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003770
Georg Brandl479a7e72008-02-05 18:13:15 +00003771 def test_rmul(self):
3772 # Testing correct invocation of __rmul__...
3773 # SF patch 592646
3774 class C(object):
3775 def __mul__(self, other):
3776 return "mul"
3777 def __rmul__(self, other):
3778 return "rmul"
3779 a = C()
3780 self.assertEqual(a*2, "mul")
3781 self.assertEqual(a*2.2, "mul")
3782 self.assertEqual(2*a, "rmul")
3783 self.assertEqual(2.2*a, "rmul")
3784
3785 def test_ipow(self):
3786 # Testing correct invocation of __ipow__...
3787 # [SF bug 620179]
3788 class C(object):
3789 def __ipow__(self, other):
3790 pass
3791 a = C()
3792 a **= 2
3793
3794 def test_mutable_bases(self):
3795 # Testing mutable bases...
3796
3797 # stuff that should work:
3798 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003799 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 class C2(object):
3801 def __getattribute__(self, attr):
3802 if attr == 'a':
3803 return 2
3804 else:
3805 return super(C2, self).__getattribute__(attr)
3806 def meth(self):
3807 return 1
3808 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003809 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003810 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003811 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003812 d = D()
3813 e = E()
3814 D.__bases__ = (C,)
3815 D.__bases__ = (C2,)
3816 self.assertEqual(d.meth(), 1)
3817 self.assertEqual(e.meth(), 1)
3818 self.assertEqual(d.a, 2)
3819 self.assertEqual(e.a, 2)
3820 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003821
Georg Brandl479a7e72008-02-05 18:13:15 +00003822 try:
3823 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003824 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003825 pass
3826 else:
3827 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003828
Georg Brandl479a7e72008-02-05 18:13:15 +00003829 try:
3830 D.__bases__ = ()
3831 except TypeError as msg:
3832 if str(msg) == "a new-style class can't have only classic bases":
3833 self.fail("wrong error message for .__bases__ = ()")
3834 else:
3835 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003836
Georg Brandl479a7e72008-02-05 18:13:15 +00003837 try:
3838 D.__bases__ = (D,)
3839 except TypeError:
3840 pass
3841 else:
3842 # actually, we'll have crashed by here...
3843 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003844
Georg Brandl479a7e72008-02-05 18:13:15 +00003845 try:
3846 D.__bases__ = (C, C)
3847 except TypeError:
3848 pass
3849 else:
3850 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003851
Georg Brandl479a7e72008-02-05 18:13:15 +00003852 try:
3853 D.__bases__ = (E,)
3854 except TypeError:
3855 pass
3856 else:
3857 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003858
Benjamin Petersonae937c02009-04-18 20:54:08 +00003859 def test_builtin_bases(self):
3860 # Make sure all the builtin types can have their base queried without
3861 # segfaulting. See issue #5787.
3862 builtin_types = [tp for tp in builtins.__dict__.values()
3863 if isinstance(tp, type)]
3864 for tp in builtin_types:
3865 object.__getattribute__(tp, "__bases__")
3866 if tp is not object:
3867 self.assertEqual(len(tp.__bases__), 1, tp)
3868
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003869 class L(list):
3870 pass
3871
3872 class C(object):
3873 pass
3874
3875 class D(C):
3876 pass
3877
3878 try:
3879 L.__bases__ = (dict,)
3880 except TypeError:
3881 pass
3882 else:
3883 self.fail("shouldn't turn list subclass into dict subclass")
3884
3885 try:
3886 list.__bases__ = (dict,)
3887 except TypeError:
3888 pass
3889 else:
3890 self.fail("shouldn't be able to assign to list.__bases__")
3891
3892 try:
3893 D.__bases__ = (C, list)
3894 except TypeError:
3895 pass
3896 else:
3897 assert 0, "best_base calculation found wanting"
3898
Benjamin Petersonae937c02009-04-18 20:54:08 +00003899
Georg Brandl479a7e72008-02-05 18:13:15 +00003900 def test_mutable_bases_with_failing_mro(self):
3901 # Testing mutable bases with failing mro...
3902 class WorkOnce(type):
3903 def __new__(self, name, bases, ns):
3904 self.flag = 0
3905 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3906 def mro(self):
3907 if self.flag > 0:
3908 raise RuntimeError("bozo")
3909 else:
3910 self.flag += 1
3911 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003912
Georg Brandl479a7e72008-02-05 18:13:15 +00003913 class WorkAlways(type):
3914 def mro(self):
3915 # this is here to make sure that .mro()s aren't called
3916 # with an exception set (which was possible at one point).
3917 # An error message will be printed in a debug build.
3918 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003919 return type.mro(self)
3920
Georg Brandl479a7e72008-02-05 18:13:15 +00003921 class C(object):
3922 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003923
Georg Brandl479a7e72008-02-05 18:13:15 +00003924 class C2(object):
3925 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003926
Georg Brandl479a7e72008-02-05 18:13:15 +00003927 class D(C):
3928 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003929
Georg Brandl479a7e72008-02-05 18:13:15 +00003930 class E(D):
3931 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003932
Georg Brandl479a7e72008-02-05 18:13:15 +00003933 class F(D, metaclass=WorkOnce):
3934 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003935
Georg Brandl479a7e72008-02-05 18:13:15 +00003936 class G(D, metaclass=WorkAlways):
3937 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003938
Georg Brandl479a7e72008-02-05 18:13:15 +00003939 # Immediate subclasses have their mro's adjusted in alphabetical
3940 # order, so E's will get adjusted before adjusting F's fails. We
3941 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003942
Georg Brandl479a7e72008-02-05 18:13:15 +00003943 E_mro_before = E.__mro__
3944 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003945
Armin Rigofd163f92005-12-29 15:59:19 +00003946 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003947 D.__bases__ = (C2,)
3948 except RuntimeError:
3949 self.assertEqual(E.__mro__, E_mro_before)
3950 self.assertEqual(D.__mro__, D_mro_before)
3951 else:
3952 self.fail("exception not propagated")
3953
3954 def test_mutable_bases_catch_mro_conflict(self):
3955 # Testing mutable bases catch mro conflict...
3956 class A(object):
3957 pass
3958
3959 class B(object):
3960 pass
3961
3962 class C(A, B):
3963 pass
3964
3965 class D(A, B):
3966 pass
3967
3968 class E(C, D):
3969 pass
3970
3971 try:
3972 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003973 except TypeError:
3974 pass
3975 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003976 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003977
Georg Brandl479a7e72008-02-05 18:13:15 +00003978 def test_mutable_names(self):
3979 # Testing mutable names...
3980 class C(object):
3981 pass
3982
3983 # C.__module__ could be 'test_descr' or '__main__'
3984 mod = C.__module__
3985
3986 C.__name__ = 'D'
3987 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3988
3989 C.__name__ = 'D.E'
3990 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3991
3992 def test_subclass_right_op(self):
3993 # Testing correct dispatch of subclass overloading __r<op>__...
3994
3995 # This code tests various cases where right-dispatch of a subclass
3996 # should be preferred over left-dispatch of a base class.
3997
3998 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3999
4000 class B(int):
4001 def __floordiv__(self, other):
4002 return "B.__floordiv__"
4003 def __rfloordiv__(self, other):
4004 return "B.__rfloordiv__"
4005
4006 self.assertEqual(B(1) // 1, "B.__floordiv__")
4007 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4008
4009 # Case 2: subclass of object; this is just the baseline for case 3
4010
4011 class C(object):
4012 def __floordiv__(self, other):
4013 return "C.__floordiv__"
4014 def __rfloordiv__(self, other):
4015 return "C.__rfloordiv__"
4016
4017 self.assertEqual(C() // 1, "C.__floordiv__")
4018 self.assertEqual(1 // C(), "C.__rfloordiv__")
4019
4020 # Case 3: subclass of new-style class; here it gets interesting
4021
4022 class D(C):
4023 def __floordiv__(self, other):
4024 return "D.__floordiv__"
4025 def __rfloordiv__(self, other):
4026 return "D.__rfloordiv__"
4027
4028 self.assertEqual(D() // C(), "D.__floordiv__")
4029 self.assertEqual(C() // D(), "D.__rfloordiv__")
4030
4031 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4032
4033 class E(C):
4034 pass
4035
4036 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4037
4038 self.assertEqual(E() // 1, "C.__floordiv__")
4039 self.assertEqual(1 // E(), "C.__rfloordiv__")
4040 self.assertEqual(E() // C(), "C.__floordiv__")
4041 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4042
Benjamin Petersone549ead2009-03-28 21:42:05 +00004043 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004044 def test_meth_class_get(self):
4045 # Testing __get__ method of METH_CLASS C methods...
4046 # Full coverage of descrobject.c::classmethod_get()
4047
4048 # Baseline
4049 arg = [1, 2, 3]
4050 res = {1: None, 2: None, 3: None}
4051 self.assertEqual(dict.fromkeys(arg), res)
4052 self.assertEqual({}.fromkeys(arg), res)
4053
4054 # Now get the descriptor
4055 descr = dict.__dict__["fromkeys"]
4056
4057 # More baseline using the descriptor directly
4058 self.assertEqual(descr.__get__(None, dict)(arg), res)
4059 self.assertEqual(descr.__get__({})(arg), res)
4060
4061 # Now check various error cases
4062 try:
4063 descr.__get__(None, None)
4064 except TypeError:
4065 pass
4066 else:
4067 self.fail("shouldn't have allowed descr.__get__(None, None)")
4068 try:
4069 descr.__get__(42)
4070 except TypeError:
4071 pass
4072 else:
4073 self.fail("shouldn't have allowed descr.__get__(42)")
4074 try:
4075 descr.__get__(None, 42)
4076 except TypeError:
4077 pass
4078 else:
4079 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4080 try:
4081 descr.__get__(None, int)
4082 except TypeError:
4083 pass
4084 else:
4085 self.fail("shouldn't have allowed descr.__get__(None, int)")
4086
4087 def test_isinst_isclass(self):
4088 # Testing proxy isinstance() and isclass()...
4089 class Proxy(object):
4090 def __init__(self, obj):
4091 self.__obj = obj
4092 def __getattribute__(self, name):
4093 if name.startswith("_Proxy__"):
4094 return object.__getattribute__(self, name)
4095 else:
4096 return getattr(self.__obj, name)
4097 # Test with a classic class
4098 class C:
4099 pass
4100 a = C()
4101 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004102 self.assertIsInstance(a, C) # Baseline
4103 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004104 # Test with a classic subclass
4105 class D(C):
4106 pass
4107 a = D()
4108 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004109 self.assertIsInstance(a, C) # Baseline
4110 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004111 # Test with a new-style class
4112 class C(object):
4113 pass
4114 a = C()
4115 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004116 self.assertIsInstance(a, C) # Baseline
4117 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004118 # Test with a new-style subclass
4119 class D(C):
4120 pass
4121 a = D()
4122 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004123 self.assertIsInstance(a, C) # Baseline
4124 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004125
4126 def test_proxy_super(self):
4127 # Testing super() for a proxy object...
4128 class Proxy(object):
4129 def __init__(self, obj):
4130 self.__obj = obj
4131 def __getattribute__(self, name):
4132 if name.startswith("_Proxy__"):
4133 return object.__getattribute__(self, name)
4134 else:
4135 return getattr(self.__obj, name)
4136
4137 class B(object):
4138 def f(self):
4139 return "B.f"
4140
4141 class C(B):
4142 def f(self):
4143 return super(C, self).f() + "->C.f"
4144
4145 obj = C()
4146 p = Proxy(obj)
4147 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4148
4149 def test_carloverre(self):
4150 # Testing prohibition of Carlo Verre's hack...
4151 try:
4152 object.__setattr__(str, "foo", 42)
4153 except TypeError:
4154 pass
4155 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004156 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004157 try:
4158 object.__delattr__(str, "lower")
4159 except TypeError:
4160 pass
4161 else:
4162 self.fail("Carlo Verre __delattr__ succeeded!")
4163
4164 def test_weakref_segfault(self):
4165 # Testing weakref segfault...
4166 # SF 742911
4167 import weakref
4168
4169 class Provoker:
4170 def __init__(self, referrent):
4171 self.ref = weakref.ref(referrent)
4172
4173 def __del__(self):
4174 x = self.ref()
4175
4176 class Oops(object):
4177 pass
4178
4179 o = Oops()
4180 o.whatever = Provoker(o)
4181 del o
4182
4183 def test_wrapper_segfault(self):
4184 # SF 927248: deeply nested wrappers could cause stack overflow
4185 f = lambda:None
4186 for i in range(1000000):
4187 f = f.__call__
4188 f = None
4189
4190 def test_file_fault(self):
4191 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004192 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004193 class StdoutGuard:
4194 def __getattr__(self, attr):
4195 sys.stdout = sys.__stdout__
4196 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4197 sys.stdout = StdoutGuard()
4198 try:
4199 print("Oops!")
4200 except RuntimeError:
4201 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004202 finally:
4203 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004204
4205 def test_vicious_descriptor_nonsense(self):
4206 # Testing vicious_descriptor_nonsense...
4207
4208 # A potential segfault spotted by Thomas Wouters in mail to
4209 # python-dev 2003-04-17, turned into an example & fixed by Michael
4210 # Hudson just less than four months later...
4211
4212 class Evil(object):
4213 def __hash__(self):
4214 return hash('attr')
4215 def __eq__(self, other):
4216 del C.attr
4217 return 0
4218
4219 class Descr(object):
4220 def __get__(self, ob, type=None):
4221 return 1
4222
4223 class C(object):
4224 attr = Descr()
4225
4226 c = C()
4227 c.__dict__[Evil()] = 0
4228
4229 self.assertEqual(c.attr, 1)
4230 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004231 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004232 self.assertEqual(hasattr(c, 'attr'), False)
4233
4234 def test_init(self):
4235 # SF 1155938
4236 class Foo(object):
4237 def __init__(self):
4238 return 10
4239 try:
4240 Foo()
4241 except TypeError:
4242 pass
4243 else:
4244 self.fail("did not test __init__() for None return")
4245
4246 def test_method_wrapper(self):
4247 # Testing method-wrapper objects...
4248 # <type 'method-wrapper'> did not support any reflection before 2.5
4249
Mark Dickinson211c6252009-02-01 10:28:51 +00004250 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004251
4252 l = []
4253 self.assertEqual(l.__add__, l.__add__)
4254 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004255 self.assertTrue(l.__add__ != [5].__add__)
4256 self.assertTrue(l.__add__ != l.__mul__)
4257 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004258 if hasattr(l.__add__, '__self__'):
4259 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004260 self.assertTrue(l.__add__.__self__ is l)
4261 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004262 else:
4263 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004264 self.assertTrue(l.__add__.im_self is l)
4265 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004266 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4267 try:
4268 hash(l.__add__)
4269 except TypeError:
4270 pass
4271 else:
4272 self.fail("no TypeError from hash([].__add__)")
4273
4274 t = ()
4275 t += (7,)
4276 self.assertEqual(t.__add__, (7,).__add__)
4277 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4278
4279 def test_not_implemented(self):
4280 # Testing NotImplemented...
4281 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004282 import operator
4283
4284 def specialmethod(self, other):
4285 return NotImplemented
4286
4287 def check(expr, x, y):
4288 try:
4289 exec(expr, {'x': x, 'y': y, 'operator': operator})
4290 except TypeError:
4291 pass
4292 else:
4293 self.fail("no TypeError from %r" % (expr,))
4294
4295 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4296 # TypeErrors
4297 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4298 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004299 for name, expr, iexpr in [
4300 ('__add__', 'x + y', 'x += y'),
4301 ('__sub__', 'x - y', 'x -= y'),
4302 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004303 ('__truediv__', 'operator.truediv(x, y)', None),
4304 ('__floordiv__', 'operator.floordiv(x, y)', None),
4305 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004306 ('__mod__', 'x % y', 'x %= y'),
4307 ('__divmod__', 'divmod(x, y)', None),
4308 ('__pow__', 'x ** y', 'x **= y'),
4309 ('__lshift__', 'x << y', 'x <<= y'),
4310 ('__rshift__', 'x >> y', 'x >>= y'),
4311 ('__and__', 'x & y', 'x &= y'),
4312 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004313 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004314 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004316 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004317 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004318 check(expr, a, N1)
4319 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004320 if iexpr:
4321 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004322 check(iexpr, a, N1)
4323 check(iexpr, a, N2)
4324 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004325 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004326 c = C()
4327 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004328 check(iexpr, c, N1)
4329 check(iexpr, c, N2)
4330
Georg Brandl479a7e72008-02-05 18:13:15 +00004331 def test_assign_slice(self):
4332 # ceval.c's assign_slice used to check for
4333 # tp->tp_as_sequence->sq_slice instead of
4334 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004335
Georg Brandl479a7e72008-02-05 18:13:15 +00004336 class C(object):
4337 def __setitem__(self, idx, value):
4338 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004339
Georg Brandl479a7e72008-02-05 18:13:15 +00004340 c = C()
4341 c[1:2] = 3
4342 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004343
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004344 def test_set_and_no_get(self):
4345 # See
4346 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4347 class Descr(object):
4348
4349 def __init__(self, name):
4350 self.name = name
4351
4352 def __set__(self, obj, value):
4353 obj.__dict__[self.name] = value
4354 descr = Descr("a")
4355
4356 class X(object):
4357 a = descr
4358
4359 x = X()
4360 self.assertIs(x.a, descr)
4361 x.a = 42
4362 self.assertEqual(x.a, 42)
4363
Benjamin Peterson21896a32010-03-21 22:03:03 +00004364 # Also check type_getattro for correctness.
4365 class Meta(type):
4366 pass
4367 class X(object):
4368 __metaclass__ = Meta
4369 X.a = 42
4370 Meta.a = Descr("a")
4371 self.assertEqual(X.a, 42)
4372
Benjamin Peterson9262b842008-11-17 22:45:50 +00004373 def test_getattr_hooks(self):
4374 # issue 4230
4375
4376 class Descriptor(object):
4377 counter = 0
4378 def __get__(self, obj, objtype=None):
4379 def getter(name):
4380 self.counter += 1
4381 raise AttributeError(name)
4382 return getter
4383
4384 descr = Descriptor()
4385 class A(object):
4386 __getattribute__ = descr
4387 class B(object):
4388 __getattr__ = descr
4389 class C(object):
4390 __getattribute__ = descr
4391 __getattr__ = descr
4392
4393 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004394 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004395 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004396 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004397 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004398 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004399
Benjamin Peterson9262b842008-11-17 22:45:50 +00004400 class EvilGetattribute(object):
4401 # This used to segfault
4402 def __getattr__(self, name):
4403 raise AttributeError(name)
4404 def __getattribute__(self, name):
4405 del EvilGetattribute.__getattr__
4406 for i in range(5):
4407 gc.collect()
4408 raise AttributeError(name)
4409
4410 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4411
Benjamin Peterson16d84ac2012-03-16 09:32:59 -05004412 def test_type___getattribute__(self):
4413 self.assertRaises(TypeError, type.__getattribute__, list, type)
4414
Benjamin Peterson477ba912011-01-12 15:34:01 +00004415 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004416 # type pretends not to have __abstractmethods__.
4417 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4418 class meta(type):
4419 pass
4420 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004421 class X(object):
4422 pass
4423 with self.assertRaises(AttributeError):
4424 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004425
Victor Stinner3249dec2011-05-01 23:19:15 +02004426 def test_proxy_call(self):
4427 class FakeStr:
4428 __class__ = str
4429
4430 fake_str = FakeStr()
4431 # isinstance() reads __class__
4432 self.assertTrue(isinstance(fake_str, str))
4433
4434 # call a method descriptor
4435 with self.assertRaises(TypeError):
4436 str.split(fake_str)
4437
4438 # call a slot wrapper descriptor
4439 with self.assertRaises(TypeError):
4440 str.__add__(fake_str, "abc")
4441
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004442 def test_repr_as_str(self):
4443 # Issue #11603: crash or infinite loop when rebinding __str__ as
4444 # __repr__.
4445 class Foo:
4446 pass
4447 Foo.__repr__ = Foo.__str__
4448 foo = Foo()
Benjamin Peterson7b166872012-04-24 11:06:25 -04004449 self.assertRaises(RuntimeError, str, foo)
4450 self.assertRaises(RuntimeError, repr, foo)
4451
4452 def test_mixing_slot_wrappers(self):
4453 class X(dict):
4454 __setattr__ = dict.__setitem__
4455 x = X()
4456 x.y = 42
4457 self.assertEqual(x["y"], 42)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004458
Benjamin Peterson52c42432012-03-07 18:41:11 -06004459 def test_cycle_through_dict(self):
4460 # See bug #1469629
4461 class X(dict):
4462 def __init__(self):
4463 dict.__init__(self)
4464 self.__dict__ = self
4465 x = X()
4466 x.attr = 42
4467 wr = weakref.ref(x)
4468 del x
4469 support.gc_collect()
4470 self.assertIsNone(wr())
4471 for o in gc.get_objects():
4472 self.assertIsNot(type(o), X)
4473
Georg Brandl479a7e72008-02-05 18:13:15 +00004474class DictProxyTests(unittest.TestCase):
4475 def setUp(self):
4476 class C(object):
4477 def meth(self):
4478 pass
4479 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004480
Georg Brandl479a7e72008-02-05 18:13:15 +00004481 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004482 # Testing dict-proxy keys...
4483 it = self.C.__dict__.keys()
4484 self.assertNotIsInstance(it, list)
4485 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004486 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004487 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl479a7e72008-02-05 18:13:15 +00004488 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004489
Georg Brandl479a7e72008-02-05 18:13:15 +00004490 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004491 # Testing dict-proxy values...
4492 it = self.C.__dict__.values()
4493 self.assertNotIsInstance(it, list)
4494 values = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004495 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004496
Georg Brandl479a7e72008-02-05 18:13:15 +00004497 def test_iter_items(self):
4498 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004499 it = self.C.__dict__.items()
4500 self.assertNotIsInstance(it, list)
4501 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004502 keys.sort()
4503 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4504 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004505
Georg Brandl479a7e72008-02-05 18:13:15 +00004506 def test_dict_type_with_metaclass(self):
4507 # Testing type of __dict__ when metaclass set...
4508 class B(object):
4509 pass
4510 class M(type):
4511 pass
4512 class C(metaclass=M):
4513 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4514 pass
4515 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004516
Ezio Melottiac53ab62010-12-18 14:59:43 +00004517 def test_repr(self):
4518 # Testing dict_proxy.__repr__
Georg Brandl2daf6ae2012-02-20 19:54:16 +01004519 def sorted_dict_repr(repr_):
4520 # Given the repr of a dict, sort the keys
4521 assert repr_.startswith('{')
4522 assert repr_.endswith('}')
4523 kvs = repr_[1:-1].split(', ')
4524 return '{' + ', '.join(sorted(kvs)) + '}'
Ezio Melottiac53ab62010-12-18 14:59:43 +00004525 dict_ = {k: v for k, v in self.C.__dict__.items()}
Georg Brandl2daf6ae2012-02-20 19:54:16 +01004526 repr_ = repr(self.C.__dict__)
Georg Brandlc425a942012-02-20 21:37:22 +01004527 self.assertTrue(repr_.startswith('dict_proxy('))
4528 self.assertTrue(repr_.endswith(')'))
Georg Brandl2daf6ae2012-02-20 19:54:16 +01004529 self.assertEqual(sorted_dict_repr(repr_[len('dict_proxy('):-len(')')]),
4530 sorted_dict_repr('{!r}'.format(dict_)))
Ezio Melottiac53ab62010-12-18 14:59:43 +00004531
Christian Heimesbbffeb62008-01-24 09:42:52 +00004532
Georg Brandl479a7e72008-02-05 18:13:15 +00004533class PTypesLongInitTest(unittest.TestCase):
4534 # This is in its own TestCase so that it can be run before any other tests.
4535 def test_pytype_long_ready(self):
4536 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004537
Georg Brandl479a7e72008-02-05 18:13:15 +00004538 # This dumps core when SF bug 551412 isn't fixed --
4539 # but only when test_descr.py is run separately.
4540 # (That can't be helped -- as soon as PyType_Ready()
4541 # is called for PyLong_Type, the bug is gone.)
4542 class UserLong(object):
4543 def __pow__(self, *args):
4544 pass
4545 try:
4546 pow(0, UserLong(), 0)
4547 except:
4548 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004549
Georg Brandl479a7e72008-02-05 18:13:15 +00004550 # Another segfault only when run early
4551 # (before PyType_Ready(tuple) is called)
4552 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004553
4554
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004555def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004556 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004557 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004558 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004559
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004560if __name__ == "__main__":
4561 test_main()