blob: 407959d75ba65ab49761c3f93093f9a0de1fd66b [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Guido van Rossum360e4b82007-05-14 22:51:27 +00002import types
Georg Brandl479a7e72008-02-05 18:13:15 +00003import unittest
4import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00005
Georg Brandl479a7e72008-02-05 18:13:15 +00006from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00008
Tim Peters6d6c1a32001-08-02 04:15:00 +00009
Georg Brandl479a7e72008-02-05 18:13:15 +000010class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000011
Georg Brandl479a7e72008-02-05 18:13:15 +000012 def __init__(self, *args, **kwargs):
13 unittest.TestCase.__init__(self, *args, **kwargs)
14 self.binops = {
15 'add': '+',
16 'sub': '-',
17 'mul': '*',
18 'div': '/',
19 'divmod': 'divmod',
20 'pow': '**',
21 'lshift': '<<',
22 'rshift': '>>',
23 'and': '&',
24 'xor': '^',
25 'or': '|',
26 'cmp': 'cmp',
27 'lt': '<',
28 'le': '<=',
29 'eq': '==',
30 'ne': '!=',
31 'gt': '>',
32 'ge': '>=',
33 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000034
Georg Brandl479a7e72008-02-05 18:13:15 +000035 for name, expr in list(self.binops.items()):
36 if expr.islower():
37 expr = expr + "(a, b)"
38 else:
39 expr = 'a %s b' % expr
40 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000041
Georg Brandl479a7e72008-02-05 18:13:15 +000042 self.unops = {
43 'pos': '+',
44 'neg': '-',
45 'abs': 'abs',
46 'invert': '~',
47 'int': 'int',
48 'float': 'float',
49 'oct': 'oct',
50 'hex': 'hex',
51 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000052
Georg Brandl479a7e72008-02-05 18:13:15 +000053 for name, expr in list(self.unops.items()):
54 if expr.islower():
55 expr = expr + "(a)"
56 else:
57 expr = '%s a' % expr
58 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000059
Georg Brandl479a7e72008-02-05 18:13:15 +000060 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
61 d = {'a': a}
62 self.assertEqual(eval(expr, d), res)
63 t = type(a)
64 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000065
Georg Brandl479a7e72008-02-05 18:13:15 +000066 # Find method in parent class
67 while meth not in t.__dict__:
68 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000069 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
70 # method object; the getattr() below obtains its underlying function.
71 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000072 self.assertEqual(m(a), res)
73 bm = getattr(a, meth)
74 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000075
Georg Brandl479a7e72008-02-05 18:13:15 +000076 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
77 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000078
Georg Brandl479a7e72008-02-05 18:13:15 +000079 # XXX Hack so this passes before 2.3 when -Qnew is specified.
80 if meth == "__div__" and 1/2 == 0.5:
81 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000082
Georg Brandl479a7e72008-02-05 18:13:15 +000083 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000084
Georg Brandl479a7e72008-02-05 18:13:15 +000085 self.assertEqual(eval(expr, d), res)
86 t = type(a)
87 m = getattr(t, meth)
88 while meth not in t.__dict__:
89 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000090 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
91 # method object; the getattr() below obtains its underlying function.
92 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000093 self.assertEqual(m(a, b), res)
94 bm = getattr(a, meth)
95 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000096
Georg Brandl479a7e72008-02-05 18:13:15 +000097 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
98 d = {'a': a, 'b': b, 'c': c}
99 self.assertEqual(eval(expr, d), res)
100 t = type(a)
101 m = getattr(t, meth)
102 while meth not in t.__dict__:
103 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000104 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
105 # method object; the getattr() below obtains its underlying function.
106 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000107 self.assertEqual(m(a, slice(b, c)), res)
108 bm = getattr(a, meth)
109 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110
Georg Brandl479a7e72008-02-05 18:13:15 +0000111 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
112 d = {'a': deepcopy(a), 'b': b}
113 exec(stmt, d)
114 self.assertEqual(d['a'], res)
115 t = type(a)
116 m = getattr(t, meth)
117 while meth not in t.__dict__:
118 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000119 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
120 # method object; the getattr() below obtains its underlying function.
121 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000122 d['a'] = deepcopy(a)
123 m(d['a'], b)
124 self.assertEqual(d['a'], res)
125 d['a'] = deepcopy(a)
126 bm = getattr(d['a'], meth)
127 bm(b)
128 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000129
Georg Brandl479a7e72008-02-05 18:13:15 +0000130 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
131 d = {'a': deepcopy(a), 'b': b, 'c': c}
132 exec(stmt, d)
133 self.assertEqual(d['a'], res)
134 t = type(a)
135 m = getattr(t, meth)
136 while meth not in t.__dict__:
137 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000138 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
139 # method object; the getattr() below obtains its underlying function.
140 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000141 d['a'] = deepcopy(a)
142 m(d['a'], b, c)
143 self.assertEqual(d['a'], res)
144 d['a'] = deepcopy(a)
145 bm = getattr(d['a'], meth)
146 bm(b, c)
147 self.assertEqual(d['a'], res)
148
149 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
150 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
151 exec(stmt, dictionary)
152 self.assertEqual(dictionary['a'], res)
153 t = type(a)
154 while meth not in t.__dict__:
155 t = t.__bases__[0]
156 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000157 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
158 # method object; the getattr() below obtains its underlying function.
159 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000160 dictionary['a'] = deepcopy(a)
161 m(dictionary['a'], slice(b, c), d)
162 self.assertEqual(dictionary['a'], res)
163 dictionary['a'] = deepcopy(a)
164 bm = getattr(dictionary['a'], meth)
165 bm(slice(b, c), d)
166 self.assertEqual(dictionary['a'], res)
167
168 def test_lists(self):
169 # Testing list operations...
170 # Asserts are within individual test methods
171 self.binop_test([1], [2], [1,2], "a+b", "__add__")
172 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
173 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
174 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
175 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
176 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
177 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
178 self.unop_test([1,2,3], 3, "len(a)", "__len__")
179 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
181 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
182 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
183 "__setitem__")
184
185 def test_dicts(self):
186 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000187 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
188 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
190
191 d = {1:2, 3:4}
192 l1 = []
193 for i in list(d.keys()):
194 l1.append(i)
195 l = []
196 for i in iter(d):
197 l.append(i)
198 self.assertEqual(l, l1)
199 l = []
200 for i in d.__iter__():
201 l.append(i)
202 self.assertEqual(l, l1)
203 l = []
204 for i in dict.__iter__(d):
205 l.append(i)
206 self.assertEqual(l, l1)
207 d = {1:2, 3:4}
208 self.unop_test(d, 2, "len(a)", "__len__")
209 self.assertEqual(eval(repr(d), {}), d)
210 self.assertEqual(eval(d.__repr__(), {}), d)
211 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
212 "__setitem__")
213
214 # Tests for unary and binary operators
215 def number_operators(self, a, b, skip=[]):
216 dict = {'a': a, 'b': b}
217
218 for name, expr in list(self.binops.items()):
219 if name not in skip:
220 name = "__%s__" % name
221 if hasattr(a, name):
222 res = eval(expr, dict)
223 self.binop_test(a, b, res, expr, name)
224
225 for name, expr in list(self.unops.items()):
226 if name not in skip:
227 name = "__%s__" % name
228 if hasattr(a, name):
229 res = eval(expr, dict)
230 self.unop_test(a, res, expr, name)
231
232 def test_ints(self):
233 # Testing int operations...
234 self.number_operators(100, 3)
235 # The following crashes in Python 2.2
236 self.assertEqual((1).__bool__(), 1)
237 self.assertEqual((0).__bool__(), 0)
238 # This returns 'NotImplemented' in Python 2.2
239 class C(int):
240 def __add__(self, other):
241 return NotImplemented
242 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000243 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000244 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000245 except TypeError:
246 pass
247 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000248 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000249
Georg Brandl479a7e72008-02-05 18:13:15 +0000250 def test_longs(self):
251 # Testing long operations...
252 self.number_operators(100, 3)
Tim Peters25786c02001-09-02 08:22:48 +0000253
Georg Brandl479a7e72008-02-05 18:13:15 +0000254 def test_floats(self):
255 # Testing float operations...
256 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000257
Georg Brandl479a7e72008-02-05 18:13:15 +0000258 def test_complexes(self):
259 # Testing complex operations...
260 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
261 'int', 'long', 'float',
262 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000263
Georg Brandl479a7e72008-02-05 18:13:15 +0000264 class Number(complex):
265 __slots__ = ['prec']
266 def __new__(cls, *args, **kwds):
267 result = complex.__new__(cls, *args)
268 result.prec = kwds.get('prec', 12)
269 return result
270 def __repr__(self):
271 prec = self.prec
272 if self.imag == 0.0:
273 return "%.*g" % (prec, self.real)
274 if self.real == 0.0:
275 return "%.*gj" % (prec, self.imag)
276 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
277 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000278
Georg Brandl479a7e72008-02-05 18:13:15 +0000279 a = Number(3.14, prec=6)
280 self.assertEqual(repr(a), "3.14")
281 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000282
Georg Brandl479a7e72008-02-05 18:13:15 +0000283 a = Number(a, prec=2)
284 self.assertEqual(repr(a), "3.1")
285 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000286
Georg Brandl479a7e72008-02-05 18:13:15 +0000287 a = Number(234.5)
288 self.assertEqual(repr(a), "234.5")
289 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000290
Benjamin Petersone549ead2009-03-28 21:42:05 +0000291 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000292 def test_spam_lists(self):
293 # Testing spamlist operations...
294 import copy, xxsubtype as spam
295
296 def spamlist(l, memo=None):
297 import xxsubtype as spam
298 return spam.spamlist(l)
299
300 # This is an ugly hack:
301 copy._deepcopy_dispatch[spam.spamlist] = spamlist
302
303 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
304 "__add__")
305 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
306 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
307 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
308 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
309 "__getitem__")
310 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
311 "__iadd__")
312 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
313 "__imul__")
314 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
315 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
316 "__mul__")
317 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
318 "__rmul__")
319 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
320 "__setitem__")
321 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
322 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
323 # Test subclassing
324 class C(spam.spamlist):
325 def foo(self): return 1
326 a = C()
327 self.assertEqual(a, [])
328 self.assertEqual(a.foo(), 1)
329 a.append(100)
330 self.assertEqual(a, [100])
331 self.assertEqual(a.getstate(), 0)
332 a.setstate(42)
333 self.assertEqual(a.getstate(), 42)
334
Benjamin Petersone549ead2009-03-28 21:42:05 +0000335 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000336 def test_spam_dicts(self):
337 # Testing spamdict operations...
338 import copy, xxsubtype as spam
339 def spamdict(d, memo=None):
340 import xxsubtype as spam
341 sd = spam.spamdict()
342 for k, v in list(d.items()):
343 sd[k] = v
344 return sd
345 # This is an ugly hack:
346 copy._deepcopy_dispatch[spam.spamdict] = spamdict
347
Georg Brandl479a7e72008-02-05 18:13:15 +0000348 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
349 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
350 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
351 d = spamdict({1:2,3:4})
352 l1 = []
353 for i in list(d.keys()):
354 l1.append(i)
355 l = []
356 for i in iter(d):
357 l.append(i)
358 self.assertEqual(l, l1)
359 l = []
360 for i in d.__iter__():
361 l.append(i)
362 self.assertEqual(l, l1)
363 l = []
364 for i in type(spamdict({})).__iter__(d):
365 l.append(i)
366 self.assertEqual(l, l1)
367 straightd = {1:2, 3:4}
368 spamd = spamdict(straightd)
369 self.unop_test(spamd, 2, "len(a)", "__len__")
370 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
371 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
372 "a[b]=c", "__setitem__")
373 # Test subclassing
374 class C(spam.spamdict):
375 def foo(self): return 1
376 a = C()
377 self.assertEqual(list(a.items()), [])
378 self.assertEqual(a.foo(), 1)
379 a['foo'] = 'bar'
380 self.assertEqual(list(a.items()), [('foo', 'bar')])
381 self.assertEqual(a.getstate(), 0)
382 a.setstate(100)
383 self.assertEqual(a.getstate(), 100)
384
385class ClassPropertiesAndMethods(unittest.TestCase):
386
387 def test_python_dicts(self):
388 # Testing Python subclass of dict...
389 self.assert_(issubclass(dict, dict))
390 self.assert_(isinstance({}, dict))
391 d = dict()
392 self.assertEqual(d, {})
393 self.assert_(d.__class__ is dict)
394 self.assert_(isinstance(d, dict))
395 class C(dict):
396 state = -1
397 def __init__(self_local, *a, **kw):
398 if a:
399 self.assertEqual(len(a), 1)
400 self_local.state = a[0]
401 if kw:
402 for k, v in list(kw.items()):
403 self_local[v] = k
404 def __getitem__(self, key):
405 return self.get(key, 0)
406 def __setitem__(self_local, key, value):
407 self.assert_(isinstance(key, type(0)))
408 dict.__setitem__(self_local, key, value)
409 def setstate(self, state):
410 self.state = state
411 def getstate(self):
412 return self.state
413 self.assert_(issubclass(C, dict))
414 a1 = C(12)
415 self.assertEqual(a1.state, 12)
416 a2 = C(foo=1, bar=2)
417 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
418 a = C()
419 self.assertEqual(a.state, -1)
420 self.assertEqual(a.getstate(), -1)
421 a.setstate(0)
422 self.assertEqual(a.state, 0)
423 self.assertEqual(a.getstate(), 0)
424 a.setstate(10)
425 self.assertEqual(a.state, 10)
426 self.assertEqual(a.getstate(), 10)
427 self.assertEqual(a[42], 0)
428 a[42] = 24
429 self.assertEqual(a[42], 24)
430 N = 50
431 for i in range(N):
432 a[i] = C()
433 for j in range(N):
434 a[i][j] = i*j
435 for i in range(N):
436 for j in range(N):
437 self.assertEqual(a[i][j], i*j)
438
439 def test_python_lists(self):
440 # Testing Python subclass of list...
441 class C(list):
442 def __getitem__(self, i):
443 if isinstance(i, slice):
444 return i.start, i.stop
445 return list.__getitem__(self, i) + 100
446 a = C()
447 a.extend([0,1,2])
448 self.assertEqual(a[0], 100)
449 self.assertEqual(a[1], 101)
450 self.assertEqual(a[2], 102)
451 self.assertEqual(a[100:200], (100,200))
452
453 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000454 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000455 class C(metaclass=type):
456 def __init__(self):
457 self.__state = 0
458 def getstate(self):
459 return self.__state
460 def setstate(self, state):
461 self.__state = state
462 a = C()
463 self.assertEqual(a.getstate(), 0)
464 a.setstate(10)
465 self.assertEqual(a.getstate(), 10)
466 class _metaclass(type):
467 def myself(cls): return cls
468 class D(metaclass=_metaclass):
469 pass
470 self.assertEqual(D.myself(), D)
471 d = D()
472 self.assertEqual(d.__class__, D)
473 class M1(type):
474 def __new__(cls, name, bases, dict):
475 dict['__spam__'] = 1
476 return type.__new__(cls, name, bases, dict)
477 class C(metaclass=M1):
478 pass
479 self.assertEqual(C.__spam__, 1)
480 c = C()
481 self.assertEqual(c.__spam__, 1)
482
483 class _instance(object):
484 pass
485 class M2(object):
486 @staticmethod
487 def __new__(cls, name, bases, dict):
488 self = object.__new__(cls)
489 self.name = name
490 self.bases = bases
491 self.dict = dict
492 return self
493 def __call__(self):
494 it = _instance()
495 # Early binding of methods
496 for key in self.dict:
497 if key.startswith("__"):
498 continue
499 setattr(it, key, self.dict[key].__get__(it, self))
500 return it
501 class C(metaclass=M2):
502 def spam(self):
503 return 42
504 self.assertEqual(C.name, 'C')
505 self.assertEqual(C.bases, ())
506 self.assert_('spam' in C.dict)
507 c = C()
508 self.assertEqual(c.spam(), 42)
509
510 # More metaclass examples
511
512 class autosuper(type):
513 # Automatically add __super to the class
514 # This trick only works for dynamic classes
515 def __new__(metaclass, name, bases, dict):
516 cls = super(autosuper, metaclass).__new__(metaclass,
517 name, bases, dict)
518 # Name mangling for __super removes leading underscores
519 while name[:1] == "_":
520 name = name[1:]
521 if name:
522 name = "_%s__super" % name
523 else:
524 name = "__super"
525 setattr(cls, name, super(cls))
526 return cls
527 class A(metaclass=autosuper):
528 def meth(self):
529 return "A"
530 class B(A):
531 def meth(self):
532 return "B" + self.__super.meth()
533 class C(A):
534 def meth(self):
535 return "C" + self.__super.meth()
536 class D(C, B):
537 def meth(self):
538 return "D" + self.__super.meth()
539 self.assertEqual(D().meth(), "DCBA")
540 class E(B, C):
541 def meth(self):
542 return "E" + self.__super.meth()
543 self.assertEqual(E().meth(), "EBCA")
544
545 class autoproperty(type):
546 # Automatically create property attributes when methods
547 # named _get_x and/or _set_x are found
548 def __new__(metaclass, name, bases, dict):
549 hits = {}
550 for key, val in dict.items():
551 if key.startswith("_get_"):
552 key = key[5:]
553 get, set = hits.get(key, (None, None))
554 get = val
555 hits[key] = get, set
556 elif key.startswith("_set_"):
557 key = key[5:]
558 get, set = hits.get(key, (None, None))
559 set = val
560 hits[key] = get, set
561 for key, (get, set) in hits.items():
562 dict[key] = property(get, set)
563 return super(autoproperty, metaclass).__new__(metaclass,
564 name, bases, dict)
565 class A(metaclass=autoproperty):
566 def _get_x(self):
567 return -self.__x
568 def _set_x(self, x):
569 self.__x = -x
570 a = A()
571 self.assert_(not hasattr(a, "x"))
572 a.x = 12
573 self.assertEqual(a.x, 12)
574 self.assertEqual(a._A__x, -12)
575
576 class multimetaclass(autoproperty, autosuper):
577 # Merge of multiple cooperating metaclasses
578 pass
579 class A(metaclass=multimetaclass):
580 def _get_x(self):
581 return "A"
582 class B(A):
583 def _get_x(self):
584 return "B" + self.__super._get_x()
585 class C(A):
586 def _get_x(self):
587 return "C" + self.__super._get_x()
588 class D(C, B):
589 def _get_x(self):
590 return "D" + self.__super._get_x()
591 self.assertEqual(D().x, "DCBA")
592
593 # Make sure type(x) doesn't call x.__class__.__init__
594 class T(type):
595 counter = 0
596 def __init__(self, *args):
597 T.counter += 1
598 class C(metaclass=T):
599 pass
600 self.assertEqual(T.counter, 1)
601 a = C()
602 self.assertEqual(type(a), C)
603 self.assertEqual(T.counter, 1)
604
605 class C(object): pass
606 c = C()
607 try: c()
608 except TypeError: pass
609 else: self.fail("calling object w/o call method should raise "
610 "TypeError")
611
612 # Testing code to find most derived baseclass
613 class A(type):
614 def __new__(*args, **kwargs):
615 return type.__new__(*args, **kwargs)
616
617 class B(object):
618 pass
619
620 class C(object, metaclass=A):
621 pass
622
623 # The most derived metaclass of D is A rather than type.
624 class D(B, C):
625 pass
626
627 def test_module_subclasses(self):
628 # Testing Python subclass of module...
629 log = []
630 import types, sys
631 MT = type(sys)
632 class MM(MT):
633 def __init__(self, name):
634 MT.__init__(self, name)
635 def __getattribute__(self, name):
636 log.append(("getattr", name))
637 return MT.__getattribute__(self, name)
638 def __setattr__(self, name, value):
639 log.append(("setattr", name, value))
640 MT.__setattr__(self, name, value)
641 def __delattr__(self, name):
642 log.append(("delattr", name))
643 MT.__delattr__(self, name)
644 a = MM("a")
645 a.foo = 12
646 x = a.foo
647 del a.foo
648 self.assertEqual(log, [("setattr", "foo", 12),
649 ("getattr", "foo"),
650 ("delattr", "foo")])
651
652 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000653 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000654 class Module(types.ModuleType, str):
655 pass
656 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000657 pass
658 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000659 self.fail("inheriting from ModuleType and str at the same time "
660 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000661
Georg Brandl479a7e72008-02-05 18:13:15 +0000662 def test_multiple_inheritance(self):
663 # Testing multiple inheritance...
664 class C(object):
665 def __init__(self):
666 self.__state = 0
667 def getstate(self):
668 return self.__state
669 def setstate(self, state):
670 self.__state = state
671 a = C()
672 self.assertEqual(a.getstate(), 0)
673 a.setstate(10)
674 self.assertEqual(a.getstate(), 10)
675 class D(dict, C):
676 def __init__(self):
677 type({}).__init__(self)
678 C.__init__(self)
679 d = D()
680 self.assertEqual(list(d.keys()), [])
681 d["hello"] = "world"
682 self.assertEqual(list(d.items()), [("hello", "world")])
683 self.assertEqual(d["hello"], "world")
684 self.assertEqual(d.getstate(), 0)
685 d.setstate(10)
686 self.assertEqual(d.getstate(), 10)
687 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000688
Georg Brandl479a7e72008-02-05 18:13:15 +0000689 # SF bug #442833
690 class Node(object):
691 def __int__(self):
692 return int(self.foo())
693 def foo(self):
694 return "23"
695 class Frag(Node, list):
696 def foo(self):
697 return "42"
698 self.assertEqual(Node().__int__(), 23)
699 self.assertEqual(int(Node()), 23)
700 self.assertEqual(Frag().__int__(), 42)
701 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000702
Georg Brandl479a7e72008-02-05 18:13:15 +0000703 def test_diamond_inheritence(self):
704 # Testing multiple inheritance special cases...
705 class A(object):
706 def spam(self): return "A"
707 self.assertEqual(A().spam(), "A")
708 class B(A):
709 def boo(self): return "B"
710 def spam(self): return "B"
711 self.assertEqual(B().spam(), "B")
712 self.assertEqual(B().boo(), "B")
713 class C(A):
714 def boo(self): return "C"
715 self.assertEqual(C().spam(), "A")
716 self.assertEqual(C().boo(), "C")
717 class D(B, C): pass
718 self.assertEqual(D().spam(), "B")
719 self.assertEqual(D().boo(), "B")
720 self.assertEqual(D.__mro__, (D, B, C, A, object))
721 class E(C, B): pass
722 self.assertEqual(E().spam(), "B")
723 self.assertEqual(E().boo(), "C")
724 self.assertEqual(E.__mro__, (E, C, B, A, object))
725 # MRO order disagreement
726 try:
727 class F(D, E): pass
728 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000729 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000730 else:
731 self.fail("expected MRO order disagreement (F)")
732 try:
733 class G(E, D): pass
734 except TypeError:
735 pass
736 else:
737 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000738
Georg Brandl479a7e72008-02-05 18:13:15 +0000739 # see thread python-dev/2002-October/029035.html
740 def test_ex5_from_c3_switch(self):
741 # Testing ex5 from C3 switch discussion...
742 class A(object): pass
743 class B(object): pass
744 class C(object): pass
745 class X(A): pass
746 class Y(A): pass
747 class Z(X,B,Y,C): pass
748 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749
Georg Brandl479a7e72008-02-05 18:13:15 +0000750 # see "A Monotonic Superclass Linearization for Dylan",
751 # by Kim Barrett et al. (OOPSLA 1996)
752 def test_monotonicity(self):
753 # Testing MRO monotonicity...
754 class Boat(object): pass
755 class DayBoat(Boat): pass
756 class WheelBoat(Boat): pass
757 class EngineLess(DayBoat): pass
758 class SmallMultihull(DayBoat): pass
759 class PedalWheelBoat(EngineLess,WheelBoat): pass
760 class SmallCatamaran(SmallMultihull): pass
761 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000762
Georg Brandl479a7e72008-02-05 18:13:15 +0000763 self.assertEqual(PedalWheelBoat.__mro__,
764 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
765 self.assertEqual(SmallCatamaran.__mro__,
766 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
767 self.assertEqual(Pedalo.__mro__,
768 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
769 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000770
Georg Brandl479a7e72008-02-05 18:13:15 +0000771 # see "A Monotonic Superclass Linearization for Dylan",
772 # by Kim Barrett et al. (OOPSLA 1996)
773 def test_consistency_with_epg(self):
774 # Testing consistentcy with EPG...
775 class Pane(object): pass
776 class ScrollingMixin(object): pass
777 class EditingMixin(object): pass
778 class ScrollablePane(Pane,ScrollingMixin): pass
779 class EditablePane(Pane,EditingMixin): pass
780 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000781
Georg Brandl479a7e72008-02-05 18:13:15 +0000782 self.assertEqual(EditableScrollablePane.__mro__,
783 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
784 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000785
Georg Brandl479a7e72008-02-05 18:13:15 +0000786 def test_mro_disagreement(self):
787 # Testing error messages for MRO disagreement...
788 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000789order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000790
Georg Brandl479a7e72008-02-05 18:13:15 +0000791 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000792 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000793 callable(*args)
794 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000795 # the exact msg is generally considered an impl detail
796 if support.check_impl_detail():
797 if not str(msg).startswith(expected):
798 self.fail("Message %r, expected %r" %
799 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000800 else:
801 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000802
Georg Brandl479a7e72008-02-05 18:13:15 +0000803 class A(object): pass
804 class B(A): pass
805 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000806
Georg Brandl479a7e72008-02-05 18:13:15 +0000807 # Test some very simple errors
808 raises(TypeError, "duplicate base class A",
809 type, "X", (A, A), {})
810 raises(TypeError, mro_err_msg,
811 type, "X", (A, B), {})
812 raises(TypeError, mro_err_msg,
813 type, "X", (A, C, B), {})
814 # Test a slightly more complex error
815 class GridLayout(object): pass
816 class HorizontalGrid(GridLayout): pass
817 class VerticalGrid(GridLayout): pass
818 class HVGrid(HorizontalGrid, VerticalGrid): pass
819 class VHGrid(VerticalGrid, HorizontalGrid): pass
820 raises(TypeError, mro_err_msg,
821 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000822
Georg Brandl479a7e72008-02-05 18:13:15 +0000823 def test_object_class(self):
824 # Testing object class...
825 a = object()
826 self.assertEqual(a.__class__, object)
827 self.assertEqual(type(a), object)
828 b = object()
829 self.assertNotEqual(a, b)
830 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +0000831 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000832 a.foo = 12
833 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +0000834 pass
835 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000836 self.fail("object() should not allow setting a foo attribute")
837 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +0000838
Georg Brandl479a7e72008-02-05 18:13:15 +0000839 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000840 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000841 x = Cdict()
842 self.assertEqual(x.__dict__, {})
843 x.foo = 1
844 self.assertEqual(x.foo, 1)
845 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846
Georg Brandl479a7e72008-02-05 18:13:15 +0000847 def test_slots(self):
848 # Testing __slots__...
849 class C0(object):
850 __slots__ = []
851 x = C0()
852 self.assertFalse(hasattr(x, "__dict__"))
853 self.assertFalse(hasattr(x, "foo"))
854
855 class C1(object):
856 __slots__ = ['a']
857 x = C1()
858 self.assertFalse(hasattr(x, "__dict__"))
859 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +0000861 self.assertEqual(x.a, 1)
862 x.a = None
863 self.assertEqual(x.a, None)
864 del x.a
865 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000866
Georg Brandl479a7e72008-02-05 18:13:15 +0000867 class C3(object):
868 __slots__ = ['a', 'b', 'c']
869 x = C3()
870 self.assertFalse(hasattr(x, "__dict__"))
871 self.assertFalse(hasattr(x, 'a'))
872 self.assertFalse(hasattr(x, 'b'))
873 self.assertFalse(hasattr(x, 'c'))
874 x.a = 1
875 x.b = 2
876 x.c = 3
877 self.assertEqual(x.a, 1)
878 self.assertEqual(x.b, 2)
879 self.assertEqual(x.c, 3)
880
881 class C4(object):
882 """Validate name mangling"""
883 __slots__ = ['__a']
884 def __init__(self, value):
885 self.__a = value
886 def get(self):
887 return self.__a
888 x = C4(5)
889 self.assertFalse(hasattr(x, '__dict__'))
890 self.assertFalse(hasattr(x, '__a'))
891 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000892 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000893 x.__a = 6
894 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +0000895 pass
896 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000897 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000898
Georg Brandl479a7e72008-02-05 18:13:15 +0000899 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +0000900 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000901 class C(object):
902 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +0000903 except TypeError:
904 pass
905 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000906 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000907 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000908 class C(object):
909 __slots__ = ["foo bar"]
910 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000911 pass
912 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000913 self.fail("['foo bar'] slots not caught")
914 try:
915 class C(object):
916 __slots__ = ["foo\0bar"]
917 except TypeError:
918 pass
919 else:
920 self.fail("['foo\\0bar'] slots not caught")
921 try:
922 class C(object):
923 __slots__ = ["1"]
924 except TypeError:
925 pass
926 else:
927 self.fail("['1'] slots not caught")
928 try:
929 class C(object):
930 __slots__ = [""]
931 except TypeError:
932 pass
933 else:
934 self.fail("[''] slots not caught")
935 class C(object):
936 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
937 # XXX(nnorwitz): was there supposed to be something tested
938 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +0000939
Georg Brandl479a7e72008-02-05 18:13:15 +0000940 # Test a single string is not expanded as a sequence.
941 class C(object):
942 __slots__ = "abc"
943 c = C()
944 c.abc = 5
945 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000946
Georg Brandl479a7e72008-02-05 18:13:15 +0000947 # Test unicode slot names
948 # Test a single unicode string is not expanded as a sequence.
949 class C(object):
950 __slots__ = "abc"
951 c = C()
952 c.abc = 5
953 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +0000954
Georg Brandl479a7e72008-02-05 18:13:15 +0000955 # _unicode_to_string used to modify slots in certain circumstances
956 slots = ("foo", "bar")
957 class C(object):
958 __slots__ = slots
959 x = C()
960 x.foo = 5
961 self.assertEqual(x.foo, 5)
962 self.assert_(type(slots[0]) is str)
963 # this used to leak references
964 try:
965 class C(object):
966 __slots__ = [chr(128)]
967 except (TypeError, UnicodeEncodeError):
968 pass
969 else:
970 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +0000971
Georg Brandl479a7e72008-02-05 18:13:15 +0000972 # Test leaks
973 class Counted(object):
974 counter = 0 # counts the number of instances alive
975 def __init__(self):
976 Counted.counter += 1
977 def __del__(self):
978 Counted.counter -= 1
979 class C(object):
980 __slots__ = ['a', 'b', 'c']
981 x = C()
982 x.a = Counted()
983 x.b = Counted()
984 x.c = Counted()
985 self.assertEqual(Counted.counter, 3)
986 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000987 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000988 self.assertEqual(Counted.counter, 0)
989 class D(C):
990 pass
991 x = D()
992 x.a = Counted()
993 x.z = Counted()
994 self.assertEqual(Counted.counter, 2)
995 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000996 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000997 self.assertEqual(Counted.counter, 0)
998 class E(D):
999 __slots__ = ['e']
1000 x = E()
1001 x.a = Counted()
1002 x.z = Counted()
1003 x.e = Counted()
1004 self.assertEqual(Counted.counter, 3)
1005 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001006 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001007 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001008
Georg Brandl479a7e72008-02-05 18:13:15 +00001009 # Test cyclical leaks [SF bug 519621]
1010 class F(object):
1011 __slots__ = ['a', 'b']
1012 log = []
1013 s = F()
1014 s.a = [Counted(), s]
1015 self.assertEqual(Counted.counter, 1)
1016 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001017 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001019
Georg Brandl479a7e72008-02-05 18:13:15 +00001020 # Test lookup leaks [SF bug 572567]
1021 import sys,gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001022 if hasattr(gc, 'get_objects'):
1023 class G(object):
1024 def __cmp__(self, other):
1025 return 0
1026 g = G()
1027 orig_objects = len(gc.get_objects())
1028 for i in range(10):
1029 g==g
1030 new_objects = len(gc.get_objects())
1031 self.assertEqual(orig_objects, new_objects)
1032
Georg Brandl479a7e72008-02-05 18:13:15 +00001033 class H(object):
1034 __slots__ = ['a', 'b']
1035 def __init__(self):
1036 self.a = 1
1037 self.b = 2
1038 def __del__(self_):
1039 self.assertEqual(self_.a, 1)
1040 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001041 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001042 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001043 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001044 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001045
Georg Brandl479a7e72008-02-05 18:13:15 +00001046 def test_slots_special(self):
1047 # Testing __dict__ and __weakref__ in __slots__...
1048 class D(object):
1049 __slots__ = ["__dict__"]
1050 a = D()
1051 self.assert_(hasattr(a, "__dict__"))
1052 self.assertFalse(hasattr(a, "__weakref__"))
1053 a.foo = 42
1054 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001055
Georg Brandl479a7e72008-02-05 18:13:15 +00001056 class W(object):
1057 __slots__ = ["__weakref__"]
1058 a = W()
1059 self.assert_(hasattr(a, "__weakref__"))
1060 self.assertFalse(hasattr(a, "__dict__"))
1061 try:
1062 a.foo = 42
1063 except AttributeError:
1064 pass
1065 else:
1066 self.fail("shouldn't be allowed to set a.foo")
1067
1068 class C1(W, D):
1069 __slots__ = []
1070 a = C1()
1071 self.assert_(hasattr(a, "__dict__"))
1072 self.assert_(hasattr(a, "__weakref__"))
1073 a.foo = 42
1074 self.assertEqual(a.__dict__, {"foo": 42})
1075
1076 class C2(D, W):
1077 __slots__ = []
1078 a = C2()
1079 self.assert_(hasattr(a, "__dict__"))
1080 self.assert_(hasattr(a, "__weakref__"))
1081 a.foo = 42
1082 self.assertEqual(a.__dict__, {"foo": 42})
1083
Christian Heimesa156e092008-02-16 07:38:31 +00001084 def test_slots_descriptor(self):
1085 # Issue2115: slot descriptors did not correctly check
1086 # the type of the given object
1087 import abc
1088 class MyABC(metaclass=abc.ABCMeta):
1089 __slots__ = "a"
1090
1091 class Unrelated(object):
1092 pass
1093 MyABC.register(Unrelated)
1094
1095 u = Unrelated()
1096 self.assert_(isinstance(u, MyABC))
1097
1098 # This used to crash
1099 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1100
Georg Brandl479a7e72008-02-05 18:13:15 +00001101 def test_dynamics(self):
1102 # Testing class attribute propagation...
1103 class D(object):
1104 pass
1105 class E(D):
1106 pass
1107 class F(D):
1108 pass
1109 D.foo = 1
1110 self.assertEqual(D.foo, 1)
1111 # Test that dynamic attributes are inherited
1112 self.assertEqual(E.foo, 1)
1113 self.assertEqual(F.foo, 1)
1114 # Test dynamic instances
1115 class C(object):
1116 pass
1117 a = C()
1118 self.assertFalse(hasattr(a, "foobar"))
1119 C.foobar = 2
1120 self.assertEqual(a.foobar, 2)
1121 C.method = lambda self: 42
1122 self.assertEqual(a.method(), 42)
1123 C.__repr__ = lambda self: "C()"
1124 self.assertEqual(repr(a), "C()")
1125 C.__int__ = lambda self: 100
1126 self.assertEqual(int(a), 100)
1127 self.assertEqual(a.foobar, 2)
1128 self.assertFalse(hasattr(a, "spam"))
1129 def mygetattr(self, name):
1130 if name == "spam":
1131 return "spam"
1132 raise AttributeError
1133 C.__getattr__ = mygetattr
1134 self.assertEqual(a.spam, "spam")
1135 a.new = 12
1136 self.assertEqual(a.new, 12)
1137 def mysetattr(self, name, value):
1138 if name == "spam":
1139 raise AttributeError
1140 return object.__setattr__(self, name, value)
1141 C.__setattr__ = mysetattr
1142 try:
1143 a.spam = "not spam"
1144 except AttributeError:
1145 pass
1146 else:
1147 self.fail("expected AttributeError")
1148 self.assertEqual(a.spam, "spam")
1149 class D(C):
1150 pass
1151 d = D()
1152 d.foo = 1
1153 self.assertEqual(d.foo, 1)
1154
1155 # Test handling of int*seq and seq*int
1156 class I(int):
1157 pass
1158 self.assertEqual("a"*I(2), "aa")
1159 self.assertEqual(I(2)*"a", "aa")
1160 self.assertEqual(2*I(3), 6)
1161 self.assertEqual(I(3)*2, 6)
1162 self.assertEqual(I(3)*I(2), 6)
1163
1164 # Test handling of long*seq and seq*long
1165 class L(int):
1166 pass
1167 self.assertEqual("a"*L(2), "aa")
1168 self.assertEqual(L(2)*"a", "aa")
1169 self.assertEqual(2*L(3), 6)
1170 self.assertEqual(L(3)*2, 6)
1171 self.assertEqual(L(3)*L(2), 6)
1172
1173 # Test comparison of classes with dynamic metaclasses
1174 class dynamicmetaclass(type):
1175 pass
1176 class someclass(metaclass=dynamicmetaclass):
1177 pass
1178 self.assertNotEqual(someclass, object)
1179
1180 def test_errors(self):
1181 # Testing errors...
1182 try:
1183 class C(list, dict):
1184 pass
1185 except TypeError:
1186 pass
1187 else:
1188 self.fail("inheritance from both list and dict should be illegal")
1189
1190 try:
1191 class C(object, None):
1192 pass
1193 except TypeError:
1194 pass
1195 else:
1196 self.fail("inheritance from non-type should be illegal")
1197 class Classic:
1198 pass
1199
1200 try:
1201 class C(type(len)):
1202 pass
1203 except TypeError:
1204 pass
1205 else:
1206 self.fail("inheritance from CFunction should be illegal")
1207
1208 try:
1209 class C(object):
1210 __slots__ = 1
1211 except TypeError:
1212 pass
1213 else:
1214 self.fail("__slots__ = 1 should be illegal")
1215
1216 try:
1217 class C(object):
1218 __slots__ = [1]
1219 except TypeError:
1220 pass
1221 else:
1222 self.fail("__slots__ = [1] should be illegal")
1223
1224 class M1(type):
1225 pass
1226 class M2(type):
1227 pass
1228 class A1(object, metaclass=M1):
1229 pass
1230 class A2(object, metaclass=M2):
1231 pass
1232 try:
1233 class B(A1, A2):
1234 pass
1235 except TypeError:
1236 pass
1237 else:
1238 self.fail("finding the most derived metaclass should have failed")
1239
1240 def test_classmethods(self):
1241 # Testing class methods...
1242 class C(object):
1243 def foo(*a): return a
1244 goo = classmethod(foo)
1245 c = C()
1246 self.assertEqual(C.goo(1), (C, 1))
1247 self.assertEqual(c.goo(1), (C, 1))
1248 self.assertEqual(c.foo(1), (c, 1))
1249 class D(C):
1250 pass
1251 d = D()
1252 self.assertEqual(D.goo(1), (D, 1))
1253 self.assertEqual(d.goo(1), (D, 1))
1254 self.assertEqual(d.foo(1), (d, 1))
1255 self.assertEqual(D.foo(d, 1), (d, 1))
1256 # Test for a specific crash (SF bug 528132)
1257 def f(cls, arg): return (cls, arg)
1258 ff = classmethod(f)
1259 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1260 self.assertEqual(ff.__get__(0)(42), (int, 42))
1261
1262 # Test super() with classmethods (SF bug 535444)
1263 self.assertEqual(C.goo.__self__, C)
1264 self.assertEqual(D.goo.__self__, D)
1265 self.assertEqual(super(D,D).goo.__self__, D)
1266 self.assertEqual(super(D,d).goo.__self__, D)
1267 self.assertEqual(super(D,D).goo(), (D,))
1268 self.assertEqual(super(D,d).goo(), (D,))
1269
1270 # Verify that argument is checked for callability (SF bug 753451)
1271 try:
1272 classmethod(1).__get__(1)
1273 except TypeError:
1274 pass
1275 else:
1276 self.fail("classmethod should check for callability")
1277
1278 # Verify that classmethod() doesn't allow keyword args
1279 try:
1280 classmethod(f, kw=1)
1281 except TypeError:
1282 pass
1283 else:
1284 self.fail("classmethod shouldn't accept keyword args")
1285
Benjamin Petersone549ead2009-03-28 21:42:05 +00001286 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001287 def test_classmethods_in_c(self):
1288 # Testing C-based class methods...
1289 import xxsubtype as spam
1290 a = (1, 2, 3)
1291 d = {'abc': 123}
1292 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1293 self.assertEqual(x, spam.spamlist)
1294 self.assertEqual(a, a1)
1295 self.assertEqual(d, d1)
1296 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1297 self.assertEqual(x, spam.spamlist)
1298 self.assertEqual(a, a1)
1299 self.assertEqual(d, d1)
1300
1301 def test_staticmethods(self):
1302 # Testing static methods...
1303 class C(object):
1304 def foo(*a): return a
1305 goo = staticmethod(foo)
1306 c = C()
1307 self.assertEqual(C.goo(1), (1,))
1308 self.assertEqual(c.goo(1), (1,))
1309 self.assertEqual(c.foo(1), (c, 1,))
1310 class D(C):
1311 pass
1312 d = D()
1313 self.assertEqual(D.goo(1), (1,))
1314 self.assertEqual(d.goo(1), (1,))
1315 self.assertEqual(d.foo(1), (d, 1))
1316 self.assertEqual(D.foo(d, 1), (d, 1))
1317
Benjamin Petersone549ead2009-03-28 21:42:05 +00001318 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001319 def test_staticmethods_in_c(self):
1320 # Testing C-based static methods...
1321 import xxsubtype as spam
1322 a = (1, 2, 3)
1323 d = {"abc": 123}
1324 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1325 self.assertEqual(x, None)
1326 self.assertEqual(a, a1)
1327 self.assertEqual(d, d1)
1328 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1329 self.assertEqual(x, None)
1330 self.assertEqual(a, a1)
1331 self.assertEqual(d, d1)
1332
1333 def test_classic(self):
1334 # Testing classic classes...
1335 class C:
1336 def foo(*a): return a
1337 goo = classmethod(foo)
1338 c = C()
1339 self.assertEqual(C.goo(1), (C, 1))
1340 self.assertEqual(c.goo(1), (C, 1))
1341 self.assertEqual(c.foo(1), (c, 1))
1342 class D(C):
1343 pass
1344 d = D()
1345 self.assertEqual(D.goo(1), (D, 1))
1346 self.assertEqual(d.goo(1), (D, 1))
1347 self.assertEqual(d.foo(1), (d, 1))
1348 self.assertEqual(D.foo(d, 1), (d, 1))
1349 class E: # *not* subclassing from C
1350 foo = C.foo
1351 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1352 self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
1353
1354 def test_compattr(self):
1355 # Testing computed attributes...
1356 class C(object):
1357 class computed_attribute(object):
1358 def __init__(self, get, set=None, delete=None):
1359 self.__get = get
1360 self.__set = set
1361 self.__delete = delete
1362 def __get__(self, obj, type=None):
1363 return self.__get(obj)
1364 def __set__(self, obj, value):
1365 return self.__set(obj, value)
1366 def __delete__(self, obj):
1367 return self.__delete(obj)
1368 def __init__(self):
1369 self.__x = 0
1370 def __get_x(self):
1371 x = self.__x
1372 self.__x = x+1
1373 return x
1374 def __set_x(self, x):
1375 self.__x = x
1376 def __delete_x(self):
1377 del self.__x
1378 x = computed_attribute(__get_x, __set_x, __delete_x)
1379 a = C()
1380 self.assertEqual(a.x, 0)
1381 self.assertEqual(a.x, 1)
1382 a.x = 10
1383 self.assertEqual(a.x, 10)
1384 self.assertEqual(a.x, 11)
1385 del a.x
1386 self.assertEqual(hasattr(a, 'x'), 0)
1387
1388 def test_newslots(self):
1389 # Testing __new__ slot override...
1390 class C(list):
1391 def __new__(cls):
1392 self = list.__new__(cls)
1393 self.foo = 1
1394 return self
1395 def __init__(self):
1396 self.foo = self.foo + 2
1397 a = C()
1398 self.assertEqual(a.foo, 3)
1399 self.assertEqual(a.__class__, C)
1400 class D(C):
1401 pass
1402 b = D()
1403 self.assertEqual(b.foo, 3)
1404 self.assertEqual(b.__class__, D)
1405
1406 def test_altmro(self):
1407 # Testing mro() and overriding it...
1408 class A(object):
1409 def f(self): return "A"
1410 class B(A):
1411 pass
1412 class C(A):
1413 def f(self): return "C"
1414 class D(B, C):
1415 pass
1416 self.assertEqual(D.mro(), [D, B, C, A, object])
1417 self.assertEqual(D.__mro__, (D, B, C, A, object))
1418 self.assertEqual(D().f(), "C")
1419
1420 class PerverseMetaType(type):
1421 def mro(cls):
1422 L = type.mro(cls)
1423 L.reverse()
1424 return L
1425 class X(D,B,C,A, metaclass=PerverseMetaType):
1426 pass
1427 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1428 self.assertEqual(X().f(), "A")
1429
1430 try:
1431 class _metaclass(type):
1432 def mro(self):
1433 return [self, dict, object]
1434 class X(object, metaclass=_metaclass):
1435 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001436 # In CPython, the class creation above already raises
1437 # TypeError, as a protection against the fact that
1438 # instances of X would segfault it. In other Python
1439 # implementations it would be ok to let the class X
1440 # be created, but instead get a clean TypeError on the
1441 # __setitem__ below.
1442 x = object.__new__(X)
1443 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001444 except TypeError:
1445 pass
1446 else:
1447 self.fail("devious mro() return not caught")
1448
1449 try:
1450 class _metaclass(type):
1451 def mro(self):
1452 return [1]
1453 class X(object, metaclass=_metaclass):
1454 pass
1455 except TypeError:
1456 pass
1457 else:
1458 self.fail("non-class mro() return not caught")
1459
1460 try:
1461 class _metaclass(type):
1462 def mro(self):
1463 return 1
1464 class X(object, metaclass=_metaclass):
1465 pass
1466 except TypeError:
1467 pass
1468 else:
1469 self.fail("non-sequence mro() return not caught")
1470
1471 def test_overloading(self):
1472 # Testing operator overloading...
1473
1474 class B(object):
1475 "Intermediate class because object doesn't have a __setattr__"
1476
1477 class C(B):
1478 def __getattr__(self, name):
1479 if name == "foo":
1480 return ("getattr", name)
1481 else:
1482 raise AttributeError
1483 def __setattr__(self, name, value):
1484 if name == "foo":
1485 self.setattr = (name, value)
1486 else:
1487 return B.__setattr__(self, name, value)
1488 def __delattr__(self, name):
1489 if name == "foo":
1490 self.delattr = name
1491 else:
1492 return B.__delattr__(self, name)
1493
1494 def __getitem__(self, key):
1495 return ("getitem", key)
1496 def __setitem__(self, key, value):
1497 self.setitem = (key, value)
1498 def __delitem__(self, key):
1499 self.delitem = key
1500
1501 a = C()
1502 self.assertEqual(a.foo, ("getattr", "foo"))
1503 a.foo = 12
1504 self.assertEqual(a.setattr, ("foo", 12))
1505 del a.foo
1506 self.assertEqual(a.delattr, "foo")
1507
1508 self.assertEqual(a[12], ("getitem", 12))
1509 a[12] = 21
1510 self.assertEqual(a.setitem, (12, 21))
1511 del a[12]
1512 self.assertEqual(a.delitem, 12)
1513
1514 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1515 a[0:10] = "foo"
1516 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1517 del a[0:10]
1518 self.assertEqual(a.delitem, (slice(0, 10)))
1519
1520 def test_methods(self):
1521 # Testing methods...
1522 class C(object):
1523 def __init__(self, x):
1524 self.x = x
1525 def foo(self):
1526 return self.x
1527 c1 = C(1)
1528 self.assertEqual(c1.foo(), 1)
1529 class D(C):
1530 boo = C.foo
1531 goo = c1.foo
1532 d2 = D(2)
1533 self.assertEqual(d2.foo(), 2)
1534 self.assertEqual(d2.boo(), 2)
1535 self.assertEqual(d2.goo(), 1)
1536 class E(object):
1537 foo = C.foo
1538 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1539 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1540
1541 def test_specials(self):
1542 # Testing special operators...
1543 # Test operators like __hash__ for which a built-in default exists
1544
1545 # Test the default behavior for static classes
1546 class C(object):
1547 def __getitem__(self, i):
1548 if 0 <= i < 10: return i
1549 raise IndexError
1550 c1 = C()
1551 c2 = C()
1552 self.assert_(not not c1) # What?
1553 self.assertNotEqual(id(c1), id(c2))
1554 hash(c1)
1555 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001556 self.assertEqual(c1, c1)
1557 self.assert_(c1 != c2)
1558 self.assert_(not c1 != c1)
1559 self.assert_(not c1 == c2)
1560 # Note that the module name appears in str/repr, and that varies
1561 # depending on whether this test is run standalone or from a framework.
1562 self.assert_(str(c1).find('C object at ') >= 0)
1563 self.assertEqual(str(c1), repr(c1))
1564 self.assert_(-1 not in c1)
1565 for i in range(10):
1566 self.assert_(i in c1)
1567 self.assertFalse(10 in c1)
1568 # Test the default behavior for dynamic classes
1569 class D(object):
1570 def __getitem__(self, i):
1571 if 0 <= i < 10: return i
1572 raise IndexError
1573 d1 = D()
1574 d2 = D()
1575 self.assert_(not not d1)
1576 self.assertNotEqual(id(d1), id(d2))
1577 hash(d1)
1578 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001579 self.assertEqual(d1, d1)
1580 self.assertNotEqual(d1, d2)
1581 self.assert_(not d1 != d1)
1582 self.assert_(not d1 == d2)
1583 # Note that the module name appears in str/repr, and that varies
1584 # depending on whether this test is run standalone or from a framework.
1585 self.assert_(str(d1).find('D object at ') >= 0)
1586 self.assertEqual(str(d1), repr(d1))
1587 self.assert_(-1 not in d1)
1588 for i in range(10):
1589 self.assert_(i in d1)
1590 self.assertFalse(10 in d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001591 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001592 class Proxy(object):
1593 def __init__(self, x):
1594 self.x = x
1595 def __bool__(self):
1596 return not not self.x
1597 def __hash__(self):
1598 return hash(self.x)
1599 def __eq__(self, other):
1600 return self.x == other
1601 def __ne__(self, other):
1602 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001603 def __ge__(self, other):
1604 return self.x >= other
1605 def __gt__(self, other):
1606 return self.x > other
1607 def __le__(self, other):
1608 return self.x <= other
1609 def __lt__(self, other):
1610 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001611 def __str__(self):
1612 return "Proxy:%s" % self.x
1613 def __repr__(self):
1614 return "Proxy(%r)" % self.x
1615 def __contains__(self, value):
1616 return value in self.x
1617 p0 = Proxy(0)
1618 p1 = Proxy(1)
1619 p_1 = Proxy(-1)
1620 self.assertFalse(p0)
1621 self.assert_(not not p1)
1622 self.assertEqual(hash(p0), hash(0))
1623 self.assertEqual(p0, p0)
1624 self.assertNotEqual(p0, p1)
1625 self.assert_(not p0 != p0)
1626 self.assertEqual(not p0, p1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001627 self.assert_(p0 < p1)
1628 self.assert_(p0 <= p1)
1629 self.assert_(p1 > p0)
1630 self.assert_(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001631 self.assertEqual(str(p0), "Proxy:0")
1632 self.assertEqual(repr(p0), "Proxy(0)")
1633 p10 = Proxy(range(10))
1634 self.assertFalse(-1 in p10)
1635 for i in range(10):
1636 self.assert_(i in p10)
1637 self.assertFalse(10 in p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001638
Georg Brandl479a7e72008-02-05 18:13:15 +00001639 def test_weakrefs(self):
1640 # Testing weak references...
1641 import weakref
1642 class C(object):
1643 pass
1644 c = C()
1645 r = weakref.ref(c)
1646 self.assertEqual(r(), c)
1647 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001648 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001649 self.assertEqual(r(), None)
1650 del r
1651 class NoWeak(object):
1652 __slots__ = ['foo']
1653 no = NoWeak()
1654 try:
1655 weakref.ref(no)
1656 except TypeError as msg:
1657 self.assert_(str(msg).find("weak reference") >= 0)
1658 else:
1659 self.fail("weakref.ref(no) should be illegal")
1660 class Weak(object):
1661 __slots__ = ['foo', '__weakref__']
1662 yes = Weak()
1663 r = weakref.ref(yes)
1664 self.assertEqual(r(), yes)
1665 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001666 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001667 self.assertEqual(r(), None)
1668 del r
1669
1670 def test_properties(self):
1671 # Testing property...
1672 class C(object):
1673 def getx(self):
1674 return self.__x
1675 def setx(self, value):
1676 self.__x = value
1677 def delx(self):
1678 del self.__x
1679 x = property(getx, setx, delx, doc="I'm the x property.")
1680 a = C()
1681 self.assertFalse(hasattr(a, "x"))
1682 a.x = 42
1683 self.assertEqual(a._C__x, 42)
1684 self.assertEqual(a.x, 42)
1685 del a.x
1686 self.assertFalse(hasattr(a, "x"))
1687 self.assertFalse(hasattr(a, "_C__x"))
1688 C.x.__set__(a, 100)
1689 self.assertEqual(C.x.__get__(a), 100)
1690 C.x.__delete__(a)
1691 self.assertFalse(hasattr(a, "x"))
1692
1693 raw = C.__dict__['x']
1694 self.assert_(isinstance(raw, property))
1695
1696 attrs = dir(raw)
1697 self.assert_("__doc__" in attrs)
1698 self.assert_("fget" in attrs)
1699 self.assert_("fset" in attrs)
1700 self.assert_("fdel" in attrs)
1701
1702 self.assertEqual(raw.__doc__, "I'm the x property.")
1703 self.assert_(raw.fget is C.__dict__['getx'])
1704 self.assert_(raw.fset is C.__dict__['setx'])
1705 self.assert_(raw.fdel is C.__dict__['delx'])
1706
1707 for attr in "__doc__", "fget", "fset", "fdel":
1708 try:
1709 setattr(raw, attr, 42)
1710 except AttributeError as msg:
1711 if str(msg).find('readonly') < 0:
1712 self.fail("when setting readonly attr %r on a property, "
1713 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1714 else:
1715 self.fail("expected AttributeError from trying to set readonly %r "
1716 "attr on a property" % attr)
1717
1718 class D(object):
1719 __getitem__ = property(lambda s: 1/0)
1720
1721 d = D()
1722 try:
1723 for i in d:
1724 str(i)
1725 except ZeroDivisionError:
1726 pass
1727 else:
1728 self.fail("expected ZeroDivisionError from bad property")
1729
1730 class E(object):
1731 def getter(self):
1732 "getter method"
1733 return 0
1734 def setter(self_, value):
1735 "setter method"
1736 pass
1737 prop = property(getter)
1738 self.assertEqual(prop.__doc__, "getter method")
1739 prop2 = property(fset=setter)
1740 self.assertEqual(prop2.__doc__, None)
1741
1742 # this segfaulted in 2.5b2
1743 try:
1744 import _testcapi
1745 except ImportError:
1746 pass
1747 else:
1748 class X(object):
1749 p = property(_testcapi.test_with_docstring)
1750
1751 def test_properties_plus(self):
1752 class C(object):
1753 foo = property(doc="hello")
1754 @foo.getter
1755 def foo(self):
1756 return self._foo
1757 @foo.setter
1758 def foo(self, value):
1759 self._foo = abs(value)
1760 @foo.deleter
1761 def foo(self):
1762 del self._foo
1763 c = C()
1764 self.assertEqual(C.foo.__doc__, "hello")
1765 self.assertFalse(hasattr(c, "foo"))
1766 c.foo = -42
1767 self.assert_(hasattr(c, '_foo'))
1768 self.assertEqual(c._foo, 42)
1769 self.assertEqual(c.foo, 42)
1770 del c.foo
1771 self.assertFalse(hasattr(c, '_foo'))
1772 self.assertFalse(hasattr(c, "foo"))
1773
1774 class D(C):
1775 @C.foo.deleter
1776 def foo(self):
1777 try:
1778 del self._foo
1779 except AttributeError:
1780 pass
1781 d = D()
1782 d.foo = 24
1783 self.assertEqual(d.foo, 24)
1784 del d.foo
1785 del d.foo
1786
1787 class E(object):
1788 @property
1789 def foo(self):
1790 return self._foo
1791 @foo.setter
1792 def foo(self, value):
1793 raise RuntimeError
1794 @foo.setter
1795 def foo(self, value):
1796 self._foo = abs(value)
1797 @foo.deleter
1798 def foo(self, value=None):
1799 del self._foo
1800
1801 e = E()
1802 e.foo = -42
1803 self.assertEqual(e.foo, 42)
1804 del e.foo
1805
1806 class F(E):
1807 @E.foo.deleter
1808 def foo(self):
1809 del self._foo
1810 @foo.setter
1811 def foo(self, value):
1812 self._foo = max(0, value)
1813 f = F()
1814 f.foo = -10
1815 self.assertEqual(f.foo, 0)
1816 del f.foo
1817
1818 def test_dict_constructors(self):
1819 # Testing dict constructor ...
1820 d = dict()
1821 self.assertEqual(d, {})
1822 d = dict({})
1823 self.assertEqual(d, {})
1824 d = dict({1: 2, 'a': 'b'})
1825 self.assertEqual(d, {1: 2, 'a': 'b'})
1826 self.assertEqual(d, dict(list(d.items())))
1827 self.assertEqual(d, dict(iter(d.items())))
1828 d = dict({'one':1, 'two':2})
1829 self.assertEqual(d, dict(one=1, two=2))
1830 self.assertEqual(d, dict(**d))
1831 self.assertEqual(d, dict({"one": 1}, two=2))
1832 self.assertEqual(d, dict([("two", 2)], one=1))
1833 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1834 self.assertEqual(d, dict(**d))
1835
1836 for badarg in 0, 0, 0j, "0", [0], (0,):
1837 try:
1838 dict(badarg)
1839 except TypeError:
1840 pass
1841 except ValueError:
1842 if badarg == "0":
1843 # It's a sequence, and its elements are also sequences (gotta
1844 # love strings <wink>), but they aren't of length 2, so this
1845 # one seemed better as a ValueError than a TypeError.
1846 pass
1847 else:
1848 self.fail("no TypeError from dict(%r)" % badarg)
1849 else:
1850 self.fail("no TypeError from dict(%r)" % badarg)
1851
1852 try:
1853 dict({}, {})
1854 except TypeError:
1855 pass
1856 else:
1857 self.fail("no TypeError from dict({}, {})")
1858
1859 class Mapping:
1860 # Lacks a .keys() method; will be added later.
1861 dict = {1:2, 3:4, 'a':1j}
1862
1863 try:
1864 dict(Mapping())
1865 except TypeError:
1866 pass
1867 else:
1868 self.fail("no TypeError from dict(incomplete mapping)")
1869
1870 Mapping.keys = lambda self: list(self.dict.keys())
1871 Mapping.__getitem__ = lambda self, i: self.dict[i]
1872 d = dict(Mapping())
1873 self.assertEqual(d, Mapping.dict)
1874
1875 # Init from sequence of iterable objects, each producing a 2-sequence.
1876 class AddressBookEntry:
1877 def __init__(self, first, last):
1878 self.first = first
1879 self.last = last
1880 def __iter__(self):
1881 return iter([self.first, self.last])
1882
1883 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1884 AddressBookEntry('Barry', 'Peters'),
1885 AddressBookEntry('Tim', 'Peters'),
1886 AddressBookEntry('Barry', 'Warsaw')])
1887 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1888
1889 d = dict(zip(range(4), range(1, 5)))
1890 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1891
1892 # Bad sequence lengths.
1893 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1894 try:
1895 dict(bad)
1896 except ValueError:
1897 pass
1898 else:
1899 self.fail("no ValueError from dict(%r)" % bad)
1900
1901 def test_dir(self):
1902 # Testing dir() ...
1903 junk = 12
1904 self.assertEqual(dir(), ['junk', 'self'])
1905 del junk
1906
1907 # Just make sure these don't blow up!
1908 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
1909 dir(arg)
1910
1911 # Test dir on new-style classes. Since these have object as a
1912 # base class, a lot more gets sucked in.
1913 def interesting(strings):
1914 return [s for s in strings if not s.startswith('_')]
1915
1916 class C(object):
1917 Cdata = 1
1918 def Cmethod(self): pass
1919
1920 cstuff = ['Cdata', 'Cmethod']
1921 self.assertEqual(interesting(dir(C)), cstuff)
1922
1923 c = C()
1924 self.assertEqual(interesting(dir(c)), cstuff)
1925 ## self.assert_('__self__' in dir(C.Cmethod))
1926
1927 c.cdata = 2
1928 c.cmethod = lambda self: 0
1929 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
1930 ## self.assert_('__self__' in dir(c.Cmethod))
1931
1932 class A(C):
1933 Adata = 1
1934 def Amethod(self): pass
1935
1936 astuff = ['Adata', 'Amethod'] + cstuff
1937 self.assertEqual(interesting(dir(A)), astuff)
1938 ## self.assert_('__self__' in dir(A.Amethod))
1939 a = A()
1940 self.assertEqual(interesting(dir(a)), astuff)
1941 a.adata = 42
1942 a.amethod = lambda self: 3
1943 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
1944 ## self.assert_('__self__' in dir(a.Amethod))
1945
1946 # Try a module subclass.
1947 import sys
1948 class M(type(sys)):
1949 pass
1950 minstance = M("m")
1951 minstance.b = 2
1952 minstance.a = 1
1953 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
1954 self.assertEqual(names, ['a', 'b'])
1955
1956 class M2(M):
1957 def getdict(self):
1958 return "Not a dict!"
1959 __dict__ = property(getdict)
1960
1961 m2instance = M2("m2")
1962 m2instance.b = 2
1963 m2instance.a = 1
1964 self.assertEqual(m2instance.__dict__, "Not a dict!")
1965 try:
1966 dir(m2instance)
1967 except TypeError:
1968 pass
1969
1970 # Two essentially featureless objects, just inheriting stuff from
1971 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00001972 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
1973 if support.check_impl_detail():
1974 # None differs in PyPy: it has a __nonzero__
1975 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00001976
1977 # Nasty test case for proxied objects
1978 class Wrapper(object):
1979 def __init__(self, obj):
1980 self.__obj = obj
1981 def __repr__(self):
1982 return "Wrapper(%s)" % repr(self.__obj)
1983 def __getitem__(self, key):
1984 return Wrapper(self.__obj[key])
1985 def __len__(self):
1986 return len(self.__obj)
1987 def __getattr__(self, name):
1988 return Wrapper(getattr(self.__obj, name))
1989
1990 class C(object):
1991 def __getclass(self):
1992 return Wrapper(type(self))
1993 __class__ = property(__getclass)
1994
1995 dir(C()) # This used to segfault
1996
1997 def test_supers(self):
1998 # Testing super...
1999
2000 class A(object):
2001 def meth(self, a):
2002 return "A(%r)" % a
2003
2004 self.assertEqual(A().meth(1), "A(1)")
2005
2006 class B(A):
2007 def __init__(self):
2008 self.__super = super(B, self)
2009 def meth(self, a):
2010 return "B(%r)" % a + self.__super.meth(a)
2011
2012 self.assertEqual(B().meth(2), "B(2)A(2)")
2013
2014 class C(A):
2015 def meth(self, a):
2016 return "C(%r)" % a + self.__super.meth(a)
2017 C._C__super = super(C)
2018
2019 self.assertEqual(C().meth(3), "C(3)A(3)")
2020
2021 class D(C, B):
2022 def meth(self, a):
2023 return "D(%r)" % a + super(D, self).meth(a)
2024
2025 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2026
2027 # Test for subclassing super
2028
2029 class mysuper(super):
2030 def __init__(self, *args):
2031 return super(mysuper, self).__init__(*args)
2032
2033 class E(D):
2034 def meth(self, a):
2035 return "E(%r)" % a + mysuper(E, self).meth(a)
2036
2037 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2038
2039 class F(E):
2040 def meth(self, a):
2041 s = self.__super # == mysuper(F, self)
2042 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2043 F._F__super = mysuper(F)
2044
2045 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2046
2047 # Make sure certain errors are raised
2048
2049 try:
2050 super(D, 42)
2051 except TypeError:
2052 pass
2053 else:
2054 self.fail("shouldn't allow super(D, 42)")
2055
2056 try:
2057 super(D, C())
2058 except TypeError:
2059 pass
2060 else:
2061 self.fail("shouldn't allow super(D, C())")
2062
2063 try:
2064 super(D).__get__(12)
2065 except TypeError:
2066 pass
2067 else:
2068 self.fail("shouldn't allow super(D).__get__(12)")
2069
2070 try:
2071 super(D).__get__(C())
2072 except TypeError:
2073 pass
2074 else:
2075 self.fail("shouldn't allow super(D).__get__(C())")
2076
2077 # Make sure data descriptors can be overridden and accessed via super
2078 # (new feature in Python 2.3)
2079
2080 class DDbase(object):
2081 def getx(self): return 42
2082 x = property(getx)
2083
2084 class DDsub(DDbase):
2085 def getx(self): return "hello"
2086 x = property(getx)
2087
2088 dd = DDsub()
2089 self.assertEqual(dd.x, "hello")
2090 self.assertEqual(super(DDsub, dd).x, 42)
2091
2092 # Ensure that super() lookup of descriptor from classmethod
2093 # works (SF ID# 743627)
2094
2095 class Base(object):
2096 aProp = property(lambda self: "foo")
2097
2098 class Sub(Base):
2099 @classmethod
2100 def test(klass):
2101 return super(Sub,klass).aProp
2102
2103 self.assertEqual(Sub.test(), Base.aProp)
2104
2105 # Verify that super() doesn't allow keyword args
2106 try:
2107 super(Base, kw=1)
2108 except TypeError:
2109 pass
2110 else:
2111 self.assertEqual("super shouldn't accept keyword args")
2112
2113 def test_basic_inheritance(self):
2114 # Testing inheritance from basic types...
2115
2116 class hexint(int):
2117 def __repr__(self):
2118 return hex(self)
2119 def __add__(self, other):
2120 return hexint(int.__add__(self, other))
2121 # (Note that overriding __radd__ doesn't work,
2122 # because the int type gets first dibs.)
2123 self.assertEqual(repr(hexint(7) + 9), "0x10")
2124 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2125 a = hexint(12345)
2126 self.assertEqual(a, 12345)
2127 self.assertEqual(int(a), 12345)
2128 self.assert_(int(a).__class__ is int)
2129 self.assertEqual(hash(a), hash(12345))
2130 self.assert_((+a).__class__ is int)
2131 self.assert_((a >> 0).__class__ is int)
2132 self.assert_((a << 0).__class__ is int)
2133 self.assert_((hexint(0) << 12).__class__ is int)
2134 self.assert_((hexint(0) >> 12).__class__ is int)
2135
2136 class octlong(int):
2137 __slots__ = []
2138 def __str__(self):
2139 s = oct(self)
2140 if s[-1] == 'L':
2141 s = s[:-1]
2142 return s
2143 def __add__(self, other):
2144 return self.__class__(super(octlong, self).__add__(other))
2145 __radd__ = __add__
2146 self.assertEqual(str(octlong(3) + 5), "0o10")
2147 # (Note that overriding __radd__ here only seems to work
2148 # because the example uses a short int left argument.)
2149 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2150 a = octlong(12345)
2151 self.assertEqual(a, 12345)
2152 self.assertEqual(int(a), 12345)
2153 self.assertEqual(hash(a), hash(12345))
2154 self.assert_(int(a).__class__ is int)
2155 self.assert_((+a).__class__ is int)
2156 self.assert_((-a).__class__ is int)
2157 self.assert_((-octlong(0)).__class__ is int)
2158 self.assert_((a >> 0).__class__ is int)
2159 self.assert_((a << 0).__class__ is int)
2160 self.assert_((a - 0).__class__ is int)
2161 self.assert_((a * 1).__class__ is int)
2162 self.assert_((a ** 1).__class__ is int)
2163 self.assert_((a // 1).__class__ is int)
2164 self.assert_((1 * a).__class__ is int)
2165 self.assert_((a | 0).__class__ is int)
2166 self.assert_((a ^ 0).__class__ is int)
2167 self.assert_((a & -1).__class__ is int)
2168 self.assert_((octlong(0) << 12).__class__ is int)
2169 self.assert_((octlong(0) >> 12).__class__ is int)
2170 self.assert_(abs(octlong(0)).__class__ is int)
2171
2172 # Because octlong overrides __add__, we can't check the absence of +0
2173 # optimizations using octlong.
2174 class longclone(int):
2175 pass
2176 a = longclone(1)
2177 self.assert_((a + 0).__class__ is int)
2178 self.assert_((0 + a).__class__ is int)
2179
2180 # Check that negative clones don't segfault
2181 a = longclone(-1)
2182 self.assertEqual(a.__dict__, {})
2183 self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2184
2185 class precfloat(float):
2186 __slots__ = ['prec']
2187 def __init__(self, value=0.0, prec=12):
2188 self.prec = int(prec)
2189 def __repr__(self):
2190 return "%.*g" % (self.prec, self)
2191 self.assertEqual(repr(precfloat(1.1)), "1.1")
2192 a = precfloat(12345)
2193 self.assertEqual(a, 12345.0)
2194 self.assertEqual(float(a), 12345.0)
2195 self.assert_(float(a).__class__ is float)
2196 self.assertEqual(hash(a), hash(12345.0))
2197 self.assert_((+a).__class__ is float)
2198
2199 class madcomplex(complex):
2200 def __repr__(self):
2201 return "%.17gj%+.17g" % (self.imag, self.real)
2202 a = madcomplex(-3, 4)
2203 self.assertEqual(repr(a), "4j-3")
2204 base = complex(-3, 4)
2205 self.assertEqual(base.__class__, complex)
2206 self.assertEqual(a, base)
2207 self.assertEqual(complex(a), base)
2208 self.assertEqual(complex(a).__class__, complex)
2209 a = madcomplex(a) # just trying another form of the constructor
2210 self.assertEqual(repr(a), "4j-3")
2211 self.assertEqual(a, base)
2212 self.assertEqual(complex(a), base)
2213 self.assertEqual(complex(a).__class__, complex)
2214 self.assertEqual(hash(a), hash(base))
2215 self.assertEqual((+a).__class__, complex)
2216 self.assertEqual((a + 0).__class__, complex)
2217 self.assertEqual(a + 0, base)
2218 self.assertEqual((a - 0).__class__, complex)
2219 self.assertEqual(a - 0, base)
2220 self.assertEqual((a * 1).__class__, complex)
2221 self.assertEqual(a * 1, base)
2222 self.assertEqual((a / 1).__class__, complex)
2223 self.assertEqual(a / 1, base)
2224
2225 class madtuple(tuple):
2226 _rev = None
2227 def rev(self):
2228 if self._rev is not None:
2229 return self._rev
2230 L = list(self)
2231 L.reverse()
2232 self._rev = self.__class__(L)
2233 return self._rev
2234 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2235 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2236 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2237 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2238 for i in range(512):
2239 t = madtuple(range(i))
2240 u = t.rev()
2241 v = u.rev()
2242 self.assertEqual(v, t)
2243 a = madtuple((1,2,3,4,5))
2244 self.assertEqual(tuple(a), (1,2,3,4,5))
2245 self.assert_(tuple(a).__class__ is tuple)
2246 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2247 self.assert_(a[:].__class__ is tuple)
2248 self.assert_((a * 1).__class__ is tuple)
2249 self.assert_((a * 0).__class__ is tuple)
2250 self.assert_((a + ()).__class__ is tuple)
2251 a = madtuple(())
2252 self.assertEqual(tuple(a), ())
2253 self.assert_(tuple(a).__class__ is tuple)
2254 self.assert_((a + a).__class__ is tuple)
2255 self.assert_((a * 0).__class__ is tuple)
2256 self.assert_((a * 1).__class__ is tuple)
2257 self.assert_((a * 2).__class__ is tuple)
2258 self.assert_(a[:].__class__ is tuple)
2259
2260 class madstring(str):
2261 _rev = None
2262 def rev(self):
2263 if self._rev is not None:
2264 return self._rev
2265 L = list(self)
2266 L.reverse()
2267 self._rev = self.__class__("".join(L))
2268 return self._rev
2269 s = madstring("abcdefghijklmnopqrstuvwxyz")
2270 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2271 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2272 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2273 for i in range(256):
2274 s = madstring("".join(map(chr, range(i))))
2275 t = s.rev()
2276 u = t.rev()
2277 self.assertEqual(u, s)
2278 s = madstring("12345")
2279 self.assertEqual(str(s), "12345")
2280 self.assert_(str(s).__class__ is str)
2281
2282 base = "\x00" * 5
2283 s = madstring(base)
2284 self.assertEqual(s, base)
2285 self.assertEqual(str(s), base)
2286 self.assert_(str(s).__class__ is str)
2287 self.assertEqual(hash(s), hash(base))
2288 self.assertEqual({s: 1}[base], 1)
2289 self.assertEqual({base: 1}[s], 1)
2290 self.assert_((s + "").__class__ is str)
2291 self.assertEqual(s + "", base)
2292 self.assert_(("" + s).__class__ is str)
2293 self.assertEqual("" + s, base)
2294 self.assert_((s * 0).__class__ is str)
2295 self.assertEqual(s * 0, "")
2296 self.assert_((s * 1).__class__ is str)
2297 self.assertEqual(s * 1, base)
2298 self.assert_((s * 2).__class__ is str)
2299 self.assertEqual(s * 2, base + base)
2300 self.assert_(s[:].__class__ is str)
2301 self.assertEqual(s[:], base)
2302 self.assert_(s[0:0].__class__ is str)
2303 self.assertEqual(s[0:0], "")
2304 self.assert_(s.strip().__class__ is str)
2305 self.assertEqual(s.strip(), base)
2306 self.assert_(s.lstrip().__class__ is str)
2307 self.assertEqual(s.lstrip(), base)
2308 self.assert_(s.rstrip().__class__ is str)
2309 self.assertEqual(s.rstrip(), base)
2310 identitytab = {}
2311 self.assert_(s.translate(identitytab).__class__ is str)
2312 self.assertEqual(s.translate(identitytab), base)
2313 self.assert_(s.replace("x", "x").__class__ is str)
2314 self.assertEqual(s.replace("x", "x"), base)
2315 self.assert_(s.ljust(len(s)).__class__ is str)
2316 self.assertEqual(s.ljust(len(s)), base)
2317 self.assert_(s.rjust(len(s)).__class__ is str)
2318 self.assertEqual(s.rjust(len(s)), base)
2319 self.assert_(s.center(len(s)).__class__ is str)
2320 self.assertEqual(s.center(len(s)), base)
2321 self.assert_(s.lower().__class__ is str)
2322 self.assertEqual(s.lower(), base)
2323
2324 class madunicode(str):
2325 _rev = None
2326 def rev(self):
2327 if self._rev is not None:
2328 return self._rev
2329 L = list(self)
2330 L.reverse()
2331 self._rev = self.__class__("".join(L))
2332 return self._rev
2333 u = madunicode("ABCDEF")
2334 self.assertEqual(u, "ABCDEF")
2335 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2336 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2337 base = "12345"
2338 u = madunicode(base)
2339 self.assertEqual(str(u), base)
2340 self.assert_(str(u).__class__ is str)
2341 self.assertEqual(hash(u), hash(base))
2342 self.assertEqual({u: 1}[base], 1)
2343 self.assertEqual({base: 1}[u], 1)
2344 self.assert_(u.strip().__class__ is str)
2345 self.assertEqual(u.strip(), base)
2346 self.assert_(u.lstrip().__class__ is str)
2347 self.assertEqual(u.lstrip(), base)
2348 self.assert_(u.rstrip().__class__ is str)
2349 self.assertEqual(u.rstrip(), base)
2350 self.assert_(u.replace("x", "x").__class__ is str)
2351 self.assertEqual(u.replace("x", "x"), base)
2352 self.assert_(u.replace("xy", "xy").__class__ is str)
2353 self.assertEqual(u.replace("xy", "xy"), base)
2354 self.assert_(u.center(len(u)).__class__ is str)
2355 self.assertEqual(u.center(len(u)), base)
2356 self.assert_(u.ljust(len(u)).__class__ is str)
2357 self.assertEqual(u.ljust(len(u)), base)
2358 self.assert_(u.rjust(len(u)).__class__ is str)
2359 self.assertEqual(u.rjust(len(u)), base)
2360 self.assert_(u.lower().__class__ is str)
2361 self.assertEqual(u.lower(), base)
2362 self.assert_(u.upper().__class__ is str)
2363 self.assertEqual(u.upper(), base)
2364 self.assert_(u.capitalize().__class__ is str)
2365 self.assertEqual(u.capitalize(), base)
2366 self.assert_(u.title().__class__ is str)
2367 self.assertEqual(u.title(), base)
2368 self.assert_((u + "").__class__ is str)
2369 self.assertEqual(u + "", base)
2370 self.assert_(("" + u).__class__ is str)
2371 self.assertEqual("" + u, base)
2372 self.assert_((u * 0).__class__ is str)
2373 self.assertEqual(u * 0, "")
2374 self.assert_((u * 1).__class__ is str)
2375 self.assertEqual(u * 1, base)
2376 self.assert_((u * 2).__class__ is str)
2377 self.assertEqual(u * 2, base + base)
2378 self.assert_(u[:].__class__ is str)
2379 self.assertEqual(u[:], base)
2380 self.assert_(u[0:0].__class__ is str)
2381 self.assertEqual(u[0:0], "")
2382
2383 class sublist(list):
2384 pass
2385 a = sublist(range(5))
2386 self.assertEqual(a, list(range(5)))
2387 a.append("hello")
2388 self.assertEqual(a, list(range(5)) + ["hello"])
2389 a[5] = 5
2390 self.assertEqual(a, list(range(6)))
2391 a.extend(range(6, 20))
2392 self.assertEqual(a, list(range(20)))
2393 a[-5:] = []
2394 self.assertEqual(a, list(range(15)))
2395 del a[10:15]
2396 self.assertEqual(len(a), 10)
2397 self.assertEqual(a, list(range(10)))
2398 self.assertEqual(list(a), list(range(10)))
2399 self.assertEqual(a[0], 0)
2400 self.assertEqual(a[9], 9)
2401 self.assertEqual(a[-10], 0)
2402 self.assertEqual(a[-1], 9)
2403 self.assertEqual(a[:5], list(range(5)))
2404
2405 ## class CountedInput(file):
2406 ## """Counts lines read by self.readline().
2407 ##
2408 ## self.lineno is the 0-based ordinal of the last line read, up to
2409 ## a maximum of one greater than the number of lines in the file.
2410 ##
2411 ## self.ateof is true if and only if the final "" line has been read,
2412 ## at which point self.lineno stops incrementing, and further calls
2413 ## to readline() continue to return "".
2414 ## """
2415 ##
2416 ## lineno = 0
2417 ## ateof = 0
2418 ## def readline(self):
2419 ## if self.ateof:
2420 ## return ""
2421 ## s = file.readline(self)
2422 ## # Next line works too.
2423 ## # s = super(CountedInput, self).readline()
2424 ## self.lineno += 1
2425 ## if s == "":
2426 ## self.ateof = 1
2427 ## return s
2428 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002429 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002430 ## lines = ['a\n', 'b\n', 'c\n']
2431 ## try:
2432 ## f.writelines(lines)
2433 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002434 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002435 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2436 ## got = f.readline()
2437 ## self.assertEqual(expected, got)
2438 ## self.assertEqual(f.lineno, i)
2439 ## self.assertEqual(f.ateof, (i > len(lines)))
2440 ## f.close()
2441 ## finally:
2442 ## try:
2443 ## f.close()
2444 ## except:
2445 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002446 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002447
2448 def test_keywords(self):
2449 # Testing keyword args to basic type constructors ...
2450 self.assertEqual(int(x=1), 1)
2451 self.assertEqual(float(x=2), 2.0)
2452 self.assertEqual(int(x=3), 3)
2453 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2454 self.assertEqual(str(object=500), '500')
2455 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2456 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2457 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2458 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2459
2460 for constructor in (int, float, int, complex, str, str,
2461 tuple, list):
2462 try:
2463 constructor(bogus_keyword_arg=1)
2464 except TypeError:
2465 pass
2466 else:
2467 self.fail("expected TypeError from bogus keyword argument to %r"
2468 % constructor)
2469
2470 def test_str_subclass_as_dict_key(self):
2471 # Testing a str subclass used as dict key ..
2472
2473 class cistr(str):
2474 """Sublcass of str that computes __eq__ case-insensitively.
2475
2476 Also computes a hash code of the string in canonical form.
2477 """
2478
2479 def __init__(self, value):
2480 self.canonical = value.lower()
2481 self.hashcode = hash(self.canonical)
2482
2483 def __eq__(self, other):
2484 if not isinstance(other, cistr):
2485 other = cistr(other)
2486 return self.canonical == other.canonical
2487
2488 def __hash__(self):
2489 return self.hashcode
2490
2491 self.assertEqual(cistr('ABC'), 'abc')
2492 self.assertEqual('aBc', cistr('ABC'))
2493 self.assertEqual(str(cistr('ABC')), 'ABC')
2494
2495 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2496 self.assertEqual(d[cistr('one')], 1)
2497 self.assertEqual(d[cistr('tWo')], 2)
2498 self.assertEqual(d[cistr('THrEE')], 3)
2499 self.assert_(cistr('ONe') in d)
2500 self.assertEqual(d.get(cistr('thrEE')), 3)
2501
2502 def test_classic_comparisons(self):
2503 # Testing classic comparisons...
2504 class classic:
2505 pass
2506
2507 for base in (classic, int, object):
2508 class C(base):
2509 def __init__(self, value):
2510 self.value = int(value)
2511 def __eq__(self, other):
2512 if isinstance(other, C):
2513 return self.value == other.value
2514 if isinstance(other, int) or isinstance(other, int):
2515 return self.value == other
2516 return NotImplemented
2517 def __ne__(self, other):
2518 if isinstance(other, C):
2519 return self.value != other.value
2520 if isinstance(other, int) or isinstance(other, int):
2521 return self.value != other
2522 return NotImplemented
2523 def __lt__(self, other):
2524 if isinstance(other, C):
2525 return self.value < other.value
2526 if isinstance(other, int) or isinstance(other, int):
2527 return self.value < other
2528 return NotImplemented
2529 def __le__(self, other):
2530 if isinstance(other, C):
2531 return self.value <= other.value
2532 if isinstance(other, int) or isinstance(other, int):
2533 return self.value <= other
2534 return NotImplemented
2535 def __gt__(self, other):
2536 if isinstance(other, C):
2537 return self.value > other.value
2538 if isinstance(other, int) or isinstance(other, int):
2539 return self.value > other
2540 return NotImplemented
2541 def __ge__(self, other):
2542 if isinstance(other, C):
2543 return self.value >= other.value
2544 if isinstance(other, int) or isinstance(other, int):
2545 return self.value >= other
2546 return NotImplemented
2547
2548 c1 = C(1)
2549 c2 = C(2)
2550 c3 = C(3)
2551 self.assertEqual(c1, 1)
2552 c = {1: c1, 2: c2, 3: c3}
2553 for x in 1, 2, 3:
2554 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002555 for op in "<", "<=", "==", "!=", ">", ">=":
Mark Dickinsona56c4672009-01-27 18:17:45 +00002556 self.assert_(eval("c[x] %s c[y]" % op) ==
2557 eval("x %s y" % op),
2558 "x=%d, y=%d" % (x, y))
2559 self.assert_(eval("c[x] %s y" % op) ==
2560 eval("x %s y" % op),
2561 "x=%d, y=%d" % (x, y))
2562 self.assert_(eval("x %s c[y]" % op) ==
2563 eval("x %s y" % op),
2564 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002565
2566 def test_rich_comparisons(self):
2567 # Testing rich comparisons...
2568 class Z(complex):
2569 pass
2570 z = Z(1)
2571 self.assertEqual(z, 1+0j)
2572 self.assertEqual(1+0j, z)
2573 class ZZ(complex):
2574 def __eq__(self, other):
2575 try:
2576 return abs(self - other) <= 1e-6
2577 except:
2578 return NotImplemented
2579 zz = ZZ(1.0000003)
2580 self.assertEqual(zz, 1+0j)
2581 self.assertEqual(1+0j, zz)
2582
2583 class classic:
2584 pass
2585 for base in (classic, int, object, list):
2586 class C(base):
2587 def __init__(self, value):
2588 self.value = int(value)
2589 def __cmp__(self_, other):
2590 self.fail("shouldn't call __cmp__")
2591 def __eq__(self, other):
2592 if isinstance(other, C):
2593 return self.value == other.value
2594 if isinstance(other, int) or isinstance(other, int):
2595 return self.value == other
2596 return NotImplemented
2597 def __ne__(self, other):
2598 if isinstance(other, C):
2599 return self.value != other.value
2600 if isinstance(other, int) or isinstance(other, int):
2601 return self.value != other
2602 return NotImplemented
2603 def __lt__(self, other):
2604 if isinstance(other, C):
2605 return self.value < other.value
2606 if isinstance(other, int) or isinstance(other, int):
2607 return self.value < other
2608 return NotImplemented
2609 def __le__(self, other):
2610 if isinstance(other, C):
2611 return self.value <= other.value
2612 if isinstance(other, int) or isinstance(other, int):
2613 return self.value <= other
2614 return NotImplemented
2615 def __gt__(self, other):
2616 if isinstance(other, C):
2617 return self.value > other.value
2618 if isinstance(other, int) or isinstance(other, int):
2619 return self.value > other
2620 return NotImplemented
2621 def __ge__(self, other):
2622 if isinstance(other, C):
2623 return self.value >= other.value
2624 if isinstance(other, int) or isinstance(other, int):
2625 return self.value >= other
2626 return NotImplemented
2627 c1 = C(1)
2628 c2 = C(2)
2629 c3 = C(3)
2630 self.assertEqual(c1, 1)
2631 c = {1: c1, 2: c2, 3: c3}
2632 for x in 1, 2, 3:
2633 for y in 1, 2, 3:
2634 for op in "<", "<=", "==", "!=", ">", ">=":
2635 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2636 "x=%d, y=%d" % (x, y))
2637 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2638 "x=%d, y=%d" % (x, y))
2639 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2640 "x=%d, y=%d" % (x, y))
2641
2642 def test_descrdoc(self):
2643 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002644 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002645 def check(descr, what):
2646 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002647 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 check(complex.real, "the real part of a complex number") # member descriptor
2649
2650 def test_doc_descriptor(self):
2651 # Testing __doc__ descriptor...
2652 # SF bug 542984
2653 class DocDescr(object):
2654 def __get__(self, object, otype):
2655 if object:
2656 object = object.__class__.__name__ + ' instance'
2657 if otype:
2658 otype = otype.__name__
2659 return 'object=%s; type=%s' % (object, otype)
2660 class OldClass:
2661 __doc__ = DocDescr()
2662 class NewClass(object):
2663 __doc__ = DocDescr()
2664 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2665 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2666 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2667 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2668
2669 def test_set_class(self):
2670 # Testing __class__ assignment...
2671 class C(object): pass
2672 class D(object): pass
2673 class E(object): pass
2674 class F(D, E): pass
2675 for cls in C, D, E, F:
2676 for cls2 in C, D, E, F:
2677 x = cls()
2678 x.__class__ = cls2
2679 self.assert_(x.__class__ is cls2)
2680 x.__class__ = cls
2681 self.assert_(x.__class__ is cls)
2682 def cant(x, C):
2683 try:
2684 x.__class__ = C
2685 except TypeError:
2686 pass
2687 else:
2688 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2689 try:
2690 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002691 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002692 pass
2693 else:
2694 self.fail("shouldn't allow del %r.__class__" % x)
2695 cant(C(), list)
2696 cant(list(), C)
2697 cant(C(), 1)
2698 cant(C(), object)
2699 cant(object(), list)
2700 cant(list(), object)
2701 class Int(int): __slots__ = []
2702 cant(2, Int)
2703 cant(Int(), int)
2704 cant(True, int)
2705 cant(2, bool)
2706 o = object()
2707 cant(o, type(1))
2708 cant(o, type(None))
2709 del o
2710 class G(object):
2711 __slots__ = ["a", "b"]
2712 class H(object):
2713 __slots__ = ["b", "a"]
2714 class I(object):
2715 __slots__ = ["a", "b"]
2716 class J(object):
2717 __slots__ = ["c", "b"]
2718 class K(object):
2719 __slots__ = ["a", "b", "d"]
2720 class L(H):
2721 __slots__ = ["e"]
2722 class M(I):
2723 __slots__ = ["e"]
2724 class N(J):
2725 __slots__ = ["__weakref__"]
2726 class P(J):
2727 __slots__ = ["__dict__"]
2728 class Q(J):
2729 pass
2730 class R(J):
2731 __slots__ = ["__dict__", "__weakref__"]
2732
2733 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2734 x = cls()
2735 x.a = 1
2736 x.__class__ = cls2
2737 self.assert_(x.__class__ is cls2,
2738 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2739 self.assertEqual(x.a, 1)
2740 x.__class__ = cls
2741 self.assert_(x.__class__ is cls,
2742 "assigning %r as __class__ for %r silently failed" % (cls, x))
2743 self.assertEqual(x.a, 1)
2744 for cls in G, J, K, L, M, N, P, R, list, Int:
2745 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2746 if cls is cls2:
2747 continue
2748 cant(cls(), cls2)
2749
2750 def test_set_dict(self):
2751 # Testing __dict__ assignment...
2752 class C(object): pass
2753 a = C()
2754 a.__dict__ = {'b': 1}
2755 self.assertEqual(a.b, 1)
2756 def cant(x, dict):
2757 try:
2758 x.__dict__ = dict
2759 except (AttributeError, TypeError):
2760 pass
2761 else:
2762 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2763 cant(a, None)
2764 cant(a, [])
2765 cant(a, 1)
2766 del a.__dict__ # Deleting __dict__ is allowed
2767
2768 class Base(object):
2769 pass
2770 def verify_dict_readonly(x):
2771 """
2772 x has to be an instance of a class inheriting from Base.
2773 """
2774 cant(x, {})
2775 try:
2776 del x.__dict__
2777 except (AttributeError, TypeError):
2778 pass
2779 else:
2780 self.fail("shouldn't allow del %r.__dict__" % x)
2781 dict_descr = Base.__dict__["__dict__"]
2782 try:
2783 dict_descr.__set__(x, {})
2784 except (AttributeError, TypeError):
2785 pass
2786 else:
2787 self.fail("dict_descr allowed access to %r's dict" % x)
2788
2789 # Classes don't allow __dict__ assignment and have readonly dicts
2790 class Meta1(type, Base):
2791 pass
2792 class Meta2(Base, type):
2793 pass
2794 class D(object, metaclass=Meta1):
2795 pass
2796 class E(object, metaclass=Meta2):
2797 pass
2798 for cls in C, D, E:
2799 verify_dict_readonly(cls)
2800 class_dict = cls.__dict__
2801 try:
2802 class_dict["spam"] = "eggs"
2803 except TypeError:
2804 pass
2805 else:
2806 self.fail("%r's __dict__ can be modified" % cls)
2807
2808 # Modules also disallow __dict__ assignment
2809 class Module1(types.ModuleType, Base):
2810 pass
2811 class Module2(Base, types.ModuleType):
2812 pass
2813 for ModuleType in Module1, Module2:
2814 mod = ModuleType("spam")
2815 verify_dict_readonly(mod)
2816 mod.__dict__["spam"] = "eggs"
2817
2818 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002819 # (at least not any more than regular exception's __dict__ can
2820 # be deleted; on CPython it is not the case, whereas on PyPy they
2821 # can, just like any other new-style instance's __dict__.)
2822 def can_delete_dict(e):
2823 try:
2824 del e.__dict__
2825 except (TypeError, AttributeError):
2826 return False
2827 else:
2828 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002829 class Exception1(Exception, Base):
2830 pass
2831 class Exception2(Base, Exception):
2832 pass
2833 for ExceptionType in Exception, Exception1, Exception2:
2834 e = ExceptionType()
2835 e.__dict__ = {"a": 1}
2836 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002837 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002838
2839 def test_pickles(self):
2840 # Testing pickling and copying new-style classes and objects...
2841 import pickle
2842
2843 def sorteditems(d):
2844 L = list(d.items())
2845 L.sort()
2846 return L
2847
2848 global C
2849 class C(object):
2850 def __init__(self, a, b):
2851 super(C, self).__init__()
2852 self.a = a
2853 self.b = b
2854 def __repr__(self):
2855 return "C(%r, %r)" % (self.a, self.b)
2856
2857 global C1
2858 class C1(list):
2859 def __new__(cls, a, b):
2860 return super(C1, cls).__new__(cls)
2861 def __getnewargs__(self):
2862 return (self.a, self.b)
2863 def __init__(self, a, b):
2864 self.a = a
2865 self.b = b
2866 def __repr__(self):
2867 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2868
2869 global C2
2870 class C2(int):
2871 def __new__(cls, a, b, val=0):
2872 return super(C2, cls).__new__(cls, val)
2873 def __getnewargs__(self):
2874 return (self.a, self.b, int(self))
2875 def __init__(self, a, b, val=0):
2876 self.a = a
2877 self.b = b
2878 def __repr__(self):
2879 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2880
2881 global C3
2882 class C3(object):
2883 def __init__(self, foo):
2884 self.foo = foo
2885 def __getstate__(self):
2886 return self.foo
2887 def __setstate__(self, foo):
2888 self.foo = foo
2889
2890 global C4classic, C4
2891 class C4classic: # classic
2892 pass
2893 class C4(C4classic, object): # mixed inheritance
2894 pass
2895
Guido van Rossum3926a632001-09-25 16:25:58 +00002896 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00002897 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00002898 s = pickle.dumps(cls, bin)
2899 cls2 = pickle.loads(s)
2900 self.assert_(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00002901
2902 a = C1(1, 2); a.append(42); a.append(24)
2903 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00002904 s = pickle.dumps((a, b), bin)
2905 x, y = pickle.loads(s)
2906 self.assertEqual(x.__class__, a.__class__)
2907 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
2908 self.assertEqual(y.__class__, b.__class__)
2909 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
2910 self.assertEqual(repr(x), repr(a))
2911 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002912 # Test for __getstate__ and __setstate__ on new style class
2913 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 s = pickle.dumps(u, bin)
2915 v = pickle.loads(s)
2916 self.assertEqual(u.__class__, v.__class__)
2917 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00002918 # Test for picklability of hybrid class
2919 u = C4()
2920 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00002921 s = pickle.dumps(u, bin)
2922 v = pickle.loads(s)
2923 self.assertEqual(u.__class__, v.__class__)
2924 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002925
Georg Brandl479a7e72008-02-05 18:13:15 +00002926 # Testing copy.deepcopy()
2927 import copy
2928 for cls in C, C1, C2:
2929 cls2 = copy.deepcopy(cls)
2930 self.assert_(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002931
Georg Brandl479a7e72008-02-05 18:13:15 +00002932 a = C1(1, 2); a.append(42); a.append(24)
2933 b = C2("hello", "world", 42)
2934 x, y = copy.deepcopy((a, b))
2935 self.assertEqual(x.__class__, a.__class__)
2936 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
2937 self.assertEqual(y.__class__, b.__class__)
2938 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
2939 self.assertEqual(repr(x), repr(a))
2940 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002941
Georg Brandl479a7e72008-02-05 18:13:15 +00002942 def test_pickle_slots(self):
2943 # Testing pickling of classes with __slots__ ...
2944 import pickle
2945 # Pickling of classes with __slots__ but without __getstate__ should fail
2946 # (if using protocol 0 or 1)
2947 global B, C, D, E
2948 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00002949 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00002950 for base in [object, B]:
2951 class C(base):
2952 __slots__ = ['a']
2953 class D(C):
2954 pass
2955 try:
2956 pickle.dumps(C(), 0)
2957 except TypeError:
2958 pass
2959 else:
2960 self.fail("should fail: pickle C instance - %s" % base)
2961 try:
2962 pickle.dumps(C(), 0)
2963 except TypeError:
2964 pass
2965 else:
2966 self.fail("should fail: pickle D instance - %s" % base)
2967 # Give C a nice generic __getstate__ and __setstate__
2968 class C(base):
2969 __slots__ = ['a']
2970 def __getstate__(self):
2971 try:
2972 d = self.__dict__.copy()
2973 except AttributeError:
2974 d = {}
2975 for cls in self.__class__.__mro__:
2976 for sn in cls.__dict__.get('__slots__', ()):
2977 try:
2978 d[sn] = getattr(self, sn)
2979 except AttributeError:
2980 pass
2981 return d
2982 def __setstate__(self, d):
2983 for k, v in list(d.items()):
2984 setattr(self, k, v)
2985 class D(C):
2986 pass
2987 # Now it should work
2988 x = C()
2989 y = pickle.loads(pickle.dumps(x))
2990 self.assertEqual(hasattr(y, 'a'), 0)
2991 x.a = 42
2992 y = pickle.loads(pickle.dumps(x))
2993 self.assertEqual(y.a, 42)
2994 x = D()
2995 x.a = 42
2996 x.b = 100
2997 y = pickle.loads(pickle.dumps(x))
2998 self.assertEqual(y.a + y.b, 142)
2999 # A subclass that adds a slot should also work
3000 class E(C):
3001 __slots__ = ['b']
3002 x = E()
3003 x.a = 42
3004 x.b = "foo"
3005 y = pickle.loads(pickle.dumps(x))
3006 self.assertEqual(y.a, x.a)
3007 self.assertEqual(y.b, x.b)
3008
3009 def test_binary_operator_override(self):
3010 # Testing overrides of binary operations...
3011 class I(int):
3012 def __repr__(self):
3013 return "I(%r)" % int(self)
3014 def __add__(self, other):
3015 return I(int(self) + int(other))
3016 __radd__ = __add__
3017 def __pow__(self, other, mod=None):
3018 if mod is None:
3019 return I(pow(int(self), int(other)))
3020 else:
3021 return I(pow(int(self), int(other), int(mod)))
3022 def __rpow__(self, other, mod=None):
3023 if mod is None:
3024 return I(pow(int(other), int(self), mod))
3025 else:
3026 return I(pow(int(other), int(self), int(mod)))
3027
3028 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3029 self.assertEqual(repr(I(1) + 2), "I(3)")
3030 self.assertEqual(repr(1 + I(2)), "I(3)")
3031 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3032 self.assertEqual(repr(2 ** I(3)), "I(8)")
3033 self.assertEqual(repr(I(2) ** 3), "I(8)")
3034 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3035 class S(str):
3036 def __eq__(self, other):
3037 return self.lower() == other.lower()
3038
3039 def test_subclass_propagation(self):
3040 # Testing propagation of slot functions to subclasses...
3041 class A(object):
3042 pass
3043 class B(A):
3044 pass
3045 class C(A):
3046 pass
3047 class D(B, C):
3048 pass
3049 d = D()
3050 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3051 A.__hash__ = lambda self: 42
3052 self.assertEqual(hash(d), 42)
3053 C.__hash__ = lambda self: 314
3054 self.assertEqual(hash(d), 314)
3055 B.__hash__ = lambda self: 144
3056 self.assertEqual(hash(d), 144)
3057 D.__hash__ = lambda self: 100
3058 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003059 D.__hash__ = None
3060 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003061 del D.__hash__
3062 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003063 B.__hash__ = None
3064 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003065 del B.__hash__
3066 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003067 C.__hash__ = None
3068 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003069 del C.__hash__
3070 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003071 A.__hash__ = None
3072 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003073 del A.__hash__
3074 self.assertEqual(hash(d), orig_hash)
3075 d.foo = 42
3076 d.bar = 42
3077 self.assertEqual(d.foo, 42)
3078 self.assertEqual(d.bar, 42)
3079 def __getattribute__(self, name):
3080 if name == "foo":
3081 return 24
3082 return object.__getattribute__(self, name)
3083 A.__getattribute__ = __getattribute__
3084 self.assertEqual(d.foo, 24)
3085 self.assertEqual(d.bar, 42)
3086 def __getattr__(self, name):
3087 if name in ("spam", "foo", "bar"):
3088 return "hello"
3089 raise AttributeError(name)
3090 B.__getattr__ = __getattr__
3091 self.assertEqual(d.spam, "hello")
3092 self.assertEqual(d.foo, 24)
3093 self.assertEqual(d.bar, 42)
3094 del A.__getattribute__
3095 self.assertEqual(d.foo, 42)
3096 del d.foo
3097 self.assertEqual(d.foo, "hello")
3098 self.assertEqual(d.bar, 42)
3099 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003100 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003101 d.foo
3102 except AttributeError:
3103 pass
3104 else:
3105 self.fail("d.foo should be undefined now")
3106
3107 # Test a nasty bug in recurse_down_subclasses()
3108 import gc
3109 class A(object):
3110 pass
3111 class B(A):
3112 pass
3113 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003114 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003115 A.__setitem__ = lambda *a: None # crash
3116
3117 def test_buffer_inheritance(self):
3118 # Testing that buffer interface is inherited ...
3119
3120 import binascii
3121 # SF bug [#470040] ParseTuple t# vs subclasses.
3122
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003123 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003124 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003125 base = b'abc'
3126 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003127 # b2a_hex uses the buffer interface to get its argument's value, via
3128 # PyArg_ParseTuple 't#' code.
3129 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3130
Georg Brandl479a7e72008-02-05 18:13:15 +00003131 class MyInt(int):
3132 pass
3133 m = MyInt(42)
3134 try:
3135 binascii.b2a_hex(m)
3136 self.fail('subclass of int should not have a buffer interface')
3137 except TypeError:
3138 pass
3139
3140 def test_str_of_str_subclass(self):
3141 # Testing __str__ defined in subclass of str ...
3142 import binascii
3143 import io
3144
3145 class octetstring(str):
3146 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003147 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003148 def __repr__(self):
3149 return self + " repr"
3150
3151 o = octetstring('A')
3152 self.assertEqual(type(o), octetstring)
3153 self.assertEqual(type(str(o)), str)
3154 self.assertEqual(type(repr(o)), str)
3155 self.assertEqual(ord(o), 0x41)
3156 self.assertEqual(str(o), '41')
3157 self.assertEqual(repr(o), 'A repr')
3158 self.assertEqual(o.__str__(), '41')
3159 self.assertEqual(o.__repr__(), 'A repr')
3160
3161 capture = io.StringIO()
3162 # Calling str() or not exercises different internal paths.
3163 print(o, file=capture)
3164 print(str(o), file=capture)
3165 self.assertEqual(capture.getvalue(), '41\n41\n')
3166 capture.close()
3167
3168 def test_keyword_arguments(self):
3169 # Testing keyword arguments to __init__, __call__...
3170 def f(a): return a
3171 self.assertEqual(f.__call__(a=42), 42)
3172 a = []
3173 list.__init__(a, sequence=[0, 1, 2])
3174 self.assertEqual(a, [0, 1, 2])
3175
3176 def test_recursive_call(self):
3177 # Testing recursive __call__() by setting to instance of class...
3178 class A(object):
3179 pass
3180
3181 A.__call__ = A()
3182 try:
3183 A()()
3184 except RuntimeError:
3185 pass
3186 else:
3187 self.fail("Recursion limit should have been reached for __call__()")
3188
3189 def test_delete_hook(self):
3190 # Testing __del__ hook...
3191 log = []
3192 class C(object):
3193 def __del__(self):
3194 log.append(1)
3195 c = C()
3196 self.assertEqual(log, [])
3197 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003198 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003199 self.assertEqual(log, [1])
3200
3201 class D(object): pass
3202 d = D()
3203 try: del d[0]
3204 except TypeError: pass
3205 else: self.fail("invalid del() didn't raise TypeError")
3206
3207 def test_hash_inheritance(self):
3208 # Testing hash of mutable subclasses...
3209
3210 class mydict(dict):
3211 pass
3212 d = mydict()
3213 try:
3214 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003215 except TypeError:
3216 pass
3217 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003218 self.fail("hash() of dict subclass should fail")
3219
3220 class mylist(list):
3221 pass
3222 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003223 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003224 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003225 except TypeError:
3226 pass
3227 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 self.fail("hash() of list subclass should fail")
3229
3230 def test_str_operations(self):
3231 try: 'a' + 5
3232 except TypeError: pass
3233 else: self.fail("'' + 5 doesn't raise TypeError")
3234
3235 try: ''.split('')
3236 except ValueError: pass
3237 else: self.fail("''.split('') doesn't raise ValueError")
3238
3239 try: ''.join([0])
3240 except TypeError: pass
3241 else: self.fail("''.join([0]) doesn't raise TypeError")
3242
3243 try: ''.rindex('5')
3244 except ValueError: pass
3245 else: self.fail("''.rindex('5') doesn't raise ValueError")
3246
3247 try: '%(n)s' % None
3248 except TypeError: pass
3249 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3250
3251 try: '%(n' % {}
3252 except ValueError: pass
3253 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3254
3255 try: '%*s' % ('abc')
3256 except TypeError: pass
3257 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3258
3259 try: '%*.*s' % ('abc', 5)
3260 except TypeError: pass
3261 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3262
3263 try: '%s' % (1, 2)
3264 except TypeError: pass
3265 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3266
3267 try: '%' % None
3268 except ValueError: pass
3269 else: self.fail("'%' % None doesn't raise ValueError")
3270
3271 self.assertEqual('534253'.isdigit(), 1)
3272 self.assertEqual('534253x'.isdigit(), 0)
3273 self.assertEqual('%c' % 5, '\x05')
3274 self.assertEqual('%c' % '5', '5')
3275
3276 def test_deepcopy_recursive(self):
3277 # Testing deepcopy of recursive objects...
3278 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003279 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003280 a = Node()
3281 b = Node()
3282 a.b = b
3283 b.a = a
3284 z = deepcopy(a) # This blew up before
3285
3286 def test_unintialized_modules(self):
3287 # Testing uninitialized module objects...
3288 from types import ModuleType as M
3289 m = M.__new__(M)
3290 str(m)
3291 self.assertEqual(hasattr(m, "__name__"), 0)
3292 self.assertEqual(hasattr(m, "__file__"), 0)
3293 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003294 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003295 m.foo = 1
3296 self.assertEqual(m.__dict__, {"foo": 1})
3297
3298 def test_funny_new(self):
3299 # Testing __new__ returning something unexpected...
3300 class C(object):
3301 def __new__(cls, arg):
3302 if isinstance(arg, str): return [1, 2, 3]
3303 elif isinstance(arg, int): return object.__new__(D)
3304 else: return object.__new__(cls)
3305 class D(C):
3306 def __init__(self, arg):
3307 self.foo = arg
3308 self.assertEqual(C("1"), [1, 2, 3])
3309 self.assertEqual(D("1"), [1, 2, 3])
3310 d = D(None)
3311 self.assertEqual(d.foo, None)
3312 d = C(1)
3313 self.assertEqual(isinstance(d, D), True)
3314 self.assertEqual(d.foo, 1)
3315 d = D(1)
3316 self.assertEqual(isinstance(d, D), True)
3317 self.assertEqual(d.foo, 1)
3318
3319 def test_imul_bug(self):
3320 # Testing for __imul__ problems...
3321 # SF bug 544647
3322 class C(object):
3323 def __imul__(self, other):
3324 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003325 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003326 y = x
3327 y *= 1.0
3328 self.assertEqual(y, (x, 1.0))
3329 y = x
3330 y *= 2
3331 self.assertEqual(y, (x, 2))
3332 y = x
3333 y *= 3
3334 self.assertEqual(y, (x, 3))
3335 y = x
3336 y *= 1<<100
3337 self.assertEqual(y, (x, 1<<100))
3338 y = x
3339 y *= None
3340 self.assertEqual(y, (x, None))
3341 y = x
3342 y *= "foo"
3343 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003344
Georg Brandl479a7e72008-02-05 18:13:15 +00003345 def test_copy_setstate(self):
3346 # Testing that copy.*copy() correctly uses __setstate__...
3347 import copy
3348 class C(object):
3349 def __init__(self, foo=None):
3350 self.foo = foo
3351 self.__foo = foo
3352 def setfoo(self, foo=None):
3353 self.foo = foo
3354 def getfoo(self):
3355 return self.__foo
3356 def __getstate__(self):
3357 return [self.foo]
3358 def __setstate__(self_, lst):
3359 self.assertEqual(len(lst), 1)
3360 self_.__foo = self_.foo = lst[0]
3361 a = C(42)
3362 a.setfoo(24)
3363 self.assertEqual(a.foo, 24)
3364 self.assertEqual(a.getfoo(), 42)
3365 b = copy.copy(a)
3366 self.assertEqual(b.foo, 24)
3367 self.assertEqual(b.getfoo(), 24)
3368 b = copy.deepcopy(a)
3369 self.assertEqual(b.foo, 24)
3370 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003371
Georg Brandl479a7e72008-02-05 18:13:15 +00003372 def test_slices(self):
3373 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003374
Georg Brandl479a7e72008-02-05 18:13:15 +00003375 # Strings
3376 self.assertEqual("hello"[:4], "hell")
3377 self.assertEqual("hello"[slice(4)], "hell")
3378 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3379 class S(str):
3380 def __getitem__(self, x):
3381 return str.__getitem__(self, x)
3382 self.assertEqual(S("hello")[:4], "hell")
3383 self.assertEqual(S("hello")[slice(4)], "hell")
3384 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3385 # Tuples
3386 self.assertEqual((1,2,3)[:2], (1,2))
3387 self.assertEqual((1,2,3)[slice(2)], (1,2))
3388 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3389 class T(tuple):
3390 def __getitem__(self, x):
3391 return tuple.__getitem__(self, x)
3392 self.assertEqual(T((1,2,3))[:2], (1,2))
3393 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3394 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3395 # Lists
3396 self.assertEqual([1,2,3][:2], [1,2])
3397 self.assertEqual([1,2,3][slice(2)], [1,2])
3398 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3399 class L(list):
3400 def __getitem__(self, x):
3401 return list.__getitem__(self, x)
3402 self.assertEqual(L([1,2,3])[:2], [1,2])
3403 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3404 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3405 # Now do lists and __setitem__
3406 a = L([1,2,3])
3407 a[slice(1, 3)] = [3,2]
3408 self.assertEqual(a, [1,3,2])
3409 a[slice(0, 2, 1)] = [3,1]
3410 self.assertEqual(a, [3,1,2])
3411 a.__setitem__(slice(1, 3), [2,1])
3412 self.assertEqual(a, [3,2,1])
3413 a.__setitem__(slice(0, 2, 1), [2,3])
3414 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003415
Georg Brandl479a7e72008-02-05 18:13:15 +00003416 def test_subtype_resurrection(self):
3417 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003418
Georg Brandl479a7e72008-02-05 18:13:15 +00003419 class C(object):
3420 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003421
Georg Brandl479a7e72008-02-05 18:13:15 +00003422 def __del__(self):
3423 # resurrect the instance
3424 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003425
Georg Brandl479a7e72008-02-05 18:13:15 +00003426 c = C()
3427 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003428
Benjamin Petersone549ead2009-03-28 21:42:05 +00003429 # The most interesting thing here is whether this blows up, due to
3430 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3431 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003432 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003433
Georg Brandl479a7e72008-02-05 18:13:15 +00003434 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003435 # the last container slot works: that will attempt to delete c again,
3436 # which will cause c to get appended back to the container again
3437 # "during" the del. (On non-CPython implementations, however, __del__
3438 # is typically not called again.)
3439 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003440 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003441 del C.container[-1]
3442 if support.check_impl_detail():
3443 support.gc_collect()
3444 self.assertEqual(len(C.container), 1)
3445 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003446
Georg Brandl479a7e72008-02-05 18:13:15 +00003447 # Make c mortal again, so that the test framework with -l doesn't report
3448 # it as a leak.
3449 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003450
Georg Brandl479a7e72008-02-05 18:13:15 +00003451 def test_slots_trash(self):
3452 # Testing slot trash...
3453 # Deallocating deeply nested slotted trash caused stack overflows
3454 class trash(object):
3455 __slots__ = ['x']
3456 def __init__(self, x):
3457 self.x = x
3458 o = None
3459 for i in range(50000):
3460 o = trash(o)
3461 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003462
Georg Brandl479a7e72008-02-05 18:13:15 +00003463 def test_slots_multiple_inheritance(self):
3464 # SF bug 575229, multiple inheritance w/ slots dumps core
3465 class A(object):
3466 __slots__=()
3467 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003468 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003469 class C(A,B) :
3470 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003471 if support.check_impl_detail():
3472 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl479a7e72008-02-05 18:13:15 +00003473 self.assert_(hasattr(C, '__dict__'))
3474 self.assert_(hasattr(C, '__weakref__'))
3475 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003476
Georg Brandl479a7e72008-02-05 18:13:15 +00003477 def test_rmul(self):
3478 # Testing correct invocation of __rmul__...
3479 # SF patch 592646
3480 class C(object):
3481 def __mul__(self, other):
3482 return "mul"
3483 def __rmul__(self, other):
3484 return "rmul"
3485 a = C()
3486 self.assertEqual(a*2, "mul")
3487 self.assertEqual(a*2.2, "mul")
3488 self.assertEqual(2*a, "rmul")
3489 self.assertEqual(2.2*a, "rmul")
3490
3491 def test_ipow(self):
3492 # Testing correct invocation of __ipow__...
3493 # [SF bug 620179]
3494 class C(object):
3495 def __ipow__(self, other):
3496 pass
3497 a = C()
3498 a **= 2
3499
3500 def test_mutable_bases(self):
3501 # Testing mutable bases...
3502
3503 # stuff that should work:
3504 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003505 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003506 class C2(object):
3507 def __getattribute__(self, attr):
3508 if attr == 'a':
3509 return 2
3510 else:
3511 return super(C2, self).__getattribute__(attr)
3512 def meth(self):
3513 return 1
3514 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003515 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003516 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003517 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003518 d = D()
3519 e = E()
3520 D.__bases__ = (C,)
3521 D.__bases__ = (C2,)
3522 self.assertEqual(d.meth(), 1)
3523 self.assertEqual(e.meth(), 1)
3524 self.assertEqual(d.a, 2)
3525 self.assertEqual(e.a, 2)
3526 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003527
Georg Brandl479a7e72008-02-05 18:13:15 +00003528 # stuff that shouldn't:
3529 class L(list):
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003530 pass
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003531
Georg Brandl479a7e72008-02-05 18:13:15 +00003532 try:
3533 L.__bases__ = (dict,)
3534 except TypeError:
3535 pass
3536 else:
3537 self.fail("shouldn't turn list subclass into dict subclass")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003538
Georg Brandl479a7e72008-02-05 18:13:15 +00003539 try:
3540 list.__bases__ = (dict,)
3541 except TypeError:
3542 pass
3543 else:
3544 self.fail("shouldn't be able to assign to list.__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003545
Georg Brandl479a7e72008-02-05 18:13:15 +00003546 try:
3547 D.__bases__ = (C2, list)
3548 except TypeError:
3549 pass
3550 else:
3551 assert 0, "best_base calculation found wanting"
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003552
Georg Brandl479a7e72008-02-05 18:13:15 +00003553 try:
3554 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003555 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003556 pass
3557 else:
3558 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003559
Georg Brandl479a7e72008-02-05 18:13:15 +00003560 try:
3561 D.__bases__ = ()
3562 except TypeError as msg:
3563 if str(msg) == "a new-style class can't have only classic bases":
3564 self.fail("wrong error message for .__bases__ = ()")
3565 else:
3566 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003567
Georg Brandl479a7e72008-02-05 18:13:15 +00003568 try:
3569 D.__bases__ = (D,)
3570 except TypeError:
3571 pass
3572 else:
3573 # actually, we'll have crashed by here...
3574 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003575
Georg Brandl479a7e72008-02-05 18:13:15 +00003576 try:
3577 D.__bases__ = (C, C)
3578 except TypeError:
3579 pass
3580 else:
3581 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003582
Georg Brandl479a7e72008-02-05 18:13:15 +00003583 try:
3584 D.__bases__ = (E,)
3585 except TypeError:
3586 pass
3587 else:
3588 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003589
Benjamin Petersonae937c02009-04-18 20:54:08 +00003590 def test_builtin_bases(self):
3591 # Make sure all the builtin types can have their base queried without
3592 # segfaulting. See issue #5787.
3593 builtin_types = [tp for tp in builtins.__dict__.values()
3594 if isinstance(tp, type)]
3595 for tp in builtin_types:
3596 object.__getattribute__(tp, "__bases__")
3597 if tp is not object:
3598 self.assertEqual(len(tp.__bases__), 1, tp)
3599
3600
Georg Brandl479a7e72008-02-05 18:13:15 +00003601 def test_mutable_bases_with_failing_mro(self):
3602 # Testing mutable bases with failing mro...
3603 class WorkOnce(type):
3604 def __new__(self, name, bases, ns):
3605 self.flag = 0
3606 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3607 def mro(self):
3608 if self.flag > 0:
3609 raise RuntimeError("bozo")
3610 else:
3611 self.flag += 1
3612 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003613
Georg Brandl479a7e72008-02-05 18:13:15 +00003614 class WorkAlways(type):
3615 def mro(self):
3616 # this is here to make sure that .mro()s aren't called
3617 # with an exception set (which was possible at one point).
3618 # An error message will be printed in a debug build.
3619 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003620 return type.mro(self)
3621
Georg Brandl479a7e72008-02-05 18:13:15 +00003622 class C(object):
3623 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003624
Georg Brandl479a7e72008-02-05 18:13:15 +00003625 class C2(object):
3626 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003627
Georg Brandl479a7e72008-02-05 18:13:15 +00003628 class D(C):
3629 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003630
Georg Brandl479a7e72008-02-05 18:13:15 +00003631 class E(D):
3632 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003633
Georg Brandl479a7e72008-02-05 18:13:15 +00003634 class F(D, metaclass=WorkOnce):
3635 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003636
Georg Brandl479a7e72008-02-05 18:13:15 +00003637 class G(D, metaclass=WorkAlways):
3638 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003639
Georg Brandl479a7e72008-02-05 18:13:15 +00003640 # Immediate subclasses have their mro's adjusted in alphabetical
3641 # order, so E's will get adjusted before adjusting F's fails. We
3642 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003643
Georg Brandl479a7e72008-02-05 18:13:15 +00003644 E_mro_before = E.__mro__
3645 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003646
Armin Rigofd163f92005-12-29 15:59:19 +00003647 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003648 D.__bases__ = (C2,)
3649 except RuntimeError:
3650 self.assertEqual(E.__mro__, E_mro_before)
3651 self.assertEqual(D.__mro__, D_mro_before)
3652 else:
3653 self.fail("exception not propagated")
3654
3655 def test_mutable_bases_catch_mro_conflict(self):
3656 # Testing mutable bases catch mro conflict...
3657 class A(object):
3658 pass
3659
3660 class B(object):
3661 pass
3662
3663 class C(A, B):
3664 pass
3665
3666 class D(A, B):
3667 pass
3668
3669 class E(C, D):
3670 pass
3671
3672 try:
3673 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003674 except TypeError:
3675 pass
3676 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003677 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003678
Georg Brandl479a7e72008-02-05 18:13:15 +00003679 def test_mutable_names(self):
3680 # Testing mutable names...
3681 class C(object):
3682 pass
3683
3684 # C.__module__ could be 'test_descr' or '__main__'
3685 mod = C.__module__
3686
3687 C.__name__ = 'D'
3688 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3689
3690 C.__name__ = 'D.E'
3691 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3692
3693 def test_subclass_right_op(self):
3694 # Testing correct dispatch of subclass overloading __r<op>__...
3695
3696 # This code tests various cases where right-dispatch of a subclass
3697 # should be preferred over left-dispatch of a base class.
3698
3699 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3700
3701 class B(int):
3702 def __floordiv__(self, other):
3703 return "B.__floordiv__"
3704 def __rfloordiv__(self, other):
3705 return "B.__rfloordiv__"
3706
3707 self.assertEqual(B(1) // 1, "B.__floordiv__")
3708 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3709
3710 # Case 2: subclass of object; this is just the baseline for case 3
3711
3712 class C(object):
3713 def __floordiv__(self, other):
3714 return "C.__floordiv__"
3715 def __rfloordiv__(self, other):
3716 return "C.__rfloordiv__"
3717
3718 self.assertEqual(C() // 1, "C.__floordiv__")
3719 self.assertEqual(1 // C(), "C.__rfloordiv__")
3720
3721 # Case 3: subclass of new-style class; here it gets interesting
3722
3723 class D(C):
3724 def __floordiv__(self, other):
3725 return "D.__floordiv__"
3726 def __rfloordiv__(self, other):
3727 return "D.__rfloordiv__"
3728
3729 self.assertEqual(D() // C(), "D.__floordiv__")
3730 self.assertEqual(C() // D(), "D.__rfloordiv__")
3731
3732 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3733
3734 class E(C):
3735 pass
3736
3737 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3738
3739 self.assertEqual(E() // 1, "C.__floordiv__")
3740 self.assertEqual(1 // E(), "C.__rfloordiv__")
3741 self.assertEqual(E() // C(), "C.__floordiv__")
3742 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3743
Benjamin Petersone549ead2009-03-28 21:42:05 +00003744 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003745 def test_meth_class_get(self):
3746 # Testing __get__ method of METH_CLASS C methods...
3747 # Full coverage of descrobject.c::classmethod_get()
3748
3749 # Baseline
3750 arg = [1, 2, 3]
3751 res = {1: None, 2: None, 3: None}
3752 self.assertEqual(dict.fromkeys(arg), res)
3753 self.assertEqual({}.fromkeys(arg), res)
3754
3755 # Now get the descriptor
3756 descr = dict.__dict__["fromkeys"]
3757
3758 # More baseline using the descriptor directly
3759 self.assertEqual(descr.__get__(None, dict)(arg), res)
3760 self.assertEqual(descr.__get__({})(arg), res)
3761
3762 # Now check various error cases
3763 try:
3764 descr.__get__(None, None)
3765 except TypeError:
3766 pass
3767 else:
3768 self.fail("shouldn't have allowed descr.__get__(None, None)")
3769 try:
3770 descr.__get__(42)
3771 except TypeError:
3772 pass
3773 else:
3774 self.fail("shouldn't have allowed descr.__get__(42)")
3775 try:
3776 descr.__get__(None, 42)
3777 except TypeError:
3778 pass
3779 else:
3780 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3781 try:
3782 descr.__get__(None, int)
3783 except TypeError:
3784 pass
3785 else:
3786 self.fail("shouldn't have allowed descr.__get__(None, int)")
3787
3788 def test_isinst_isclass(self):
3789 # Testing proxy isinstance() and isclass()...
3790 class Proxy(object):
3791 def __init__(self, obj):
3792 self.__obj = obj
3793 def __getattribute__(self, name):
3794 if name.startswith("_Proxy__"):
3795 return object.__getattribute__(self, name)
3796 else:
3797 return getattr(self.__obj, name)
3798 # Test with a classic class
3799 class C:
3800 pass
3801 a = C()
3802 pa = Proxy(a)
3803 self.assert_(isinstance(a, C)) # Baseline
3804 self.assert_(isinstance(pa, C)) # Test
3805 # Test with a classic subclass
3806 class D(C):
3807 pass
3808 a = D()
3809 pa = Proxy(a)
3810 self.assert_(isinstance(a, C)) # Baseline
3811 self.assert_(isinstance(pa, C)) # Test
3812 # Test with a new-style class
3813 class C(object):
3814 pass
3815 a = C()
3816 pa = Proxy(a)
3817 self.assert_(isinstance(a, C)) # Baseline
3818 self.assert_(isinstance(pa, C)) # Test
3819 # Test with a new-style subclass
3820 class D(C):
3821 pass
3822 a = D()
3823 pa = Proxy(a)
3824 self.assert_(isinstance(a, C)) # Baseline
3825 self.assert_(isinstance(pa, C)) # Test
3826
3827 def test_proxy_super(self):
3828 # Testing super() for a proxy object...
3829 class Proxy(object):
3830 def __init__(self, obj):
3831 self.__obj = obj
3832 def __getattribute__(self, name):
3833 if name.startswith("_Proxy__"):
3834 return object.__getattribute__(self, name)
3835 else:
3836 return getattr(self.__obj, name)
3837
3838 class B(object):
3839 def f(self):
3840 return "B.f"
3841
3842 class C(B):
3843 def f(self):
3844 return super(C, self).f() + "->C.f"
3845
3846 obj = C()
3847 p = Proxy(obj)
3848 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3849
3850 def test_carloverre(self):
3851 # Testing prohibition of Carlo Verre's hack...
3852 try:
3853 object.__setattr__(str, "foo", 42)
3854 except TypeError:
3855 pass
3856 else:
3857 self.fail("Carlo Verre __setattr__ suceeded!")
3858 try:
3859 object.__delattr__(str, "lower")
3860 except TypeError:
3861 pass
3862 else:
3863 self.fail("Carlo Verre __delattr__ succeeded!")
3864
3865 def test_weakref_segfault(self):
3866 # Testing weakref segfault...
3867 # SF 742911
3868 import weakref
3869
3870 class Provoker:
3871 def __init__(self, referrent):
3872 self.ref = weakref.ref(referrent)
3873
3874 def __del__(self):
3875 x = self.ref()
3876
3877 class Oops(object):
3878 pass
3879
3880 o = Oops()
3881 o.whatever = Provoker(o)
3882 del o
3883
3884 def test_wrapper_segfault(self):
3885 # SF 927248: deeply nested wrappers could cause stack overflow
3886 f = lambda:None
3887 for i in range(1000000):
3888 f = f.__call__
3889 f = None
3890
3891 def test_file_fault(self):
3892 # Testing sys.stdout is changed in getattr...
3893 import sys
3894 class StdoutGuard:
3895 def __getattr__(self, attr):
3896 sys.stdout = sys.__stdout__
3897 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3898 sys.stdout = StdoutGuard()
3899 try:
3900 print("Oops!")
3901 except RuntimeError:
3902 pass
3903
3904 def test_vicious_descriptor_nonsense(self):
3905 # Testing vicious_descriptor_nonsense...
3906
3907 # A potential segfault spotted by Thomas Wouters in mail to
3908 # python-dev 2003-04-17, turned into an example & fixed by Michael
3909 # Hudson just less than four months later...
3910
3911 class Evil(object):
3912 def __hash__(self):
3913 return hash('attr')
3914 def __eq__(self, other):
3915 del C.attr
3916 return 0
3917
3918 class Descr(object):
3919 def __get__(self, ob, type=None):
3920 return 1
3921
3922 class C(object):
3923 attr = Descr()
3924
3925 c = C()
3926 c.__dict__[Evil()] = 0
3927
3928 self.assertEqual(c.attr, 1)
3929 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00003930 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003931 self.assertEqual(hasattr(c, 'attr'), False)
3932
3933 def test_init(self):
3934 # SF 1155938
3935 class Foo(object):
3936 def __init__(self):
3937 return 10
3938 try:
3939 Foo()
3940 except TypeError:
3941 pass
3942 else:
3943 self.fail("did not test __init__() for None return")
3944
3945 def test_method_wrapper(self):
3946 # Testing method-wrapper objects...
3947 # <type 'method-wrapper'> did not support any reflection before 2.5
3948
Mark Dickinson211c6252009-02-01 10:28:51 +00003949 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00003950
3951 l = []
3952 self.assertEqual(l.__add__, l.__add__)
3953 self.assertEqual(l.__add__, [].__add__)
3954 self.assert_(l.__add__ != [5].__add__)
3955 self.assert_(l.__add__ != l.__mul__)
3956 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00003957 if hasattr(l.__add__, '__self__'):
3958 # CPython
3959 self.assert_(l.__add__.__self__ is l)
3960 self.assert_(l.__add__.__objclass__ is list)
3961 else:
3962 # Python implementations where [].__add__ is a normal bound method
3963 self.assert_(l.__add__.im_self is l)
3964 self.assert_(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00003965 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
3966 try:
3967 hash(l.__add__)
3968 except TypeError:
3969 pass
3970 else:
3971 self.fail("no TypeError from hash([].__add__)")
3972
3973 t = ()
3974 t += (7,)
3975 self.assertEqual(t.__add__, (7,).__add__)
3976 self.assertEqual(hash(t.__add__), hash((7,).__add__))
3977
3978 def test_not_implemented(self):
3979 # Testing NotImplemented...
3980 # all binary methods should be able to return a NotImplemented
3981 import sys
3982 import types
3983 import operator
3984
3985 def specialmethod(self, other):
3986 return NotImplemented
3987
3988 def check(expr, x, y):
3989 try:
3990 exec(expr, {'x': x, 'y': y, 'operator': operator})
3991 except TypeError:
3992 pass
3993 else:
3994 self.fail("no TypeError from %r" % (expr,))
3995
3996 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
3997 # TypeErrors
3998 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
3999 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004000 for name, expr, iexpr in [
4001 ('__add__', 'x + y', 'x += y'),
4002 ('__sub__', 'x - y', 'x -= y'),
4003 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004004 ('__truediv__', 'operator.truediv(x, y)', None),
4005 ('__floordiv__', 'operator.floordiv(x, y)', None),
4006 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004007 ('__mod__', 'x % y', 'x %= y'),
4008 ('__divmod__', 'divmod(x, y)', None),
4009 ('__pow__', 'x ** y', 'x **= y'),
4010 ('__lshift__', 'x << y', 'x <<= y'),
4011 ('__rshift__', 'x >> y', 'x >>= y'),
4012 ('__and__', 'x & y', 'x &= y'),
4013 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004014 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004015 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004016 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004017 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004018 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004019 check(expr, a, N1)
4020 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004021 if iexpr:
4022 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004023 check(iexpr, a, N1)
4024 check(iexpr, a, N2)
4025 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004026 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004027 c = C()
4028 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004029 check(iexpr, c, N1)
4030 check(iexpr, c, N2)
4031
Georg Brandl479a7e72008-02-05 18:13:15 +00004032 def test_assign_slice(self):
4033 # ceval.c's assign_slice used to check for
4034 # tp->tp_as_sequence->sq_slice instead of
4035 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004036
Georg Brandl479a7e72008-02-05 18:13:15 +00004037 class C(object):
4038 def __setitem__(self, idx, value):
4039 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004040
Georg Brandl479a7e72008-02-05 18:13:15 +00004041 c = C()
4042 c[1:2] = 3
4043 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004044
Benjamin Peterson9262b842008-11-17 22:45:50 +00004045 def test_getattr_hooks(self):
4046 # issue 4230
4047
4048 class Descriptor(object):
4049 counter = 0
4050 def __get__(self, obj, objtype=None):
4051 def getter(name):
4052 self.counter += 1
4053 raise AttributeError(name)
4054 return getter
4055
4056 descr = Descriptor()
4057 class A(object):
4058 __getattribute__ = descr
4059 class B(object):
4060 __getattr__ = descr
4061 class C(object):
4062 __getattribute__ = descr
4063 __getattr__ = descr
4064
4065 self.assertRaises(AttributeError, getattr, A(), "attr")
4066 self.assertEquals(descr.counter, 1)
4067 self.assertRaises(AttributeError, getattr, B(), "attr")
4068 self.assertEquals(descr.counter, 2)
4069 self.assertRaises(AttributeError, getattr, C(), "attr")
4070 self.assertEquals(descr.counter, 4)
4071
4072 import gc
4073 class EvilGetattribute(object):
4074 # This used to segfault
4075 def __getattr__(self, name):
4076 raise AttributeError(name)
4077 def __getattribute__(self, name):
4078 del EvilGetattribute.__getattr__
4079 for i in range(5):
4080 gc.collect()
4081 raise AttributeError(name)
4082
4083 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4084
Christian Heimesbbffeb62008-01-24 09:42:52 +00004085
Georg Brandl479a7e72008-02-05 18:13:15 +00004086class DictProxyTests(unittest.TestCase):
4087 def setUp(self):
4088 class C(object):
4089 def meth(self):
4090 pass
4091 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004092
Georg Brandl479a7e72008-02-05 18:13:15 +00004093 def test_iter_keys(self):
4094 # Testing dict-proxy iterkeys...
4095 keys = [ key for key in self.C.__dict__.keys() ]
4096 keys.sort()
4097 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4098 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004099
Georg Brandl479a7e72008-02-05 18:13:15 +00004100 def test_iter_values(self):
4101 # Testing dict-proxy itervalues...
4102 values = [ values for values in self.C.__dict__.values() ]
4103 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004104
Georg Brandl479a7e72008-02-05 18:13:15 +00004105 def test_iter_items(self):
4106 # Testing dict-proxy iteritems...
4107 keys = [ key for (key, value) in self.C.__dict__.items() ]
4108 keys.sort()
4109 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4110 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004111
Georg Brandl479a7e72008-02-05 18:13:15 +00004112 def test_dict_type_with_metaclass(self):
4113 # Testing type of __dict__ when metaclass set...
4114 class B(object):
4115 pass
4116 class M(type):
4117 pass
4118 class C(metaclass=M):
4119 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4120 pass
4121 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004122
Christian Heimesbbffeb62008-01-24 09:42:52 +00004123
Georg Brandl479a7e72008-02-05 18:13:15 +00004124class PTypesLongInitTest(unittest.TestCase):
4125 # This is in its own TestCase so that it can be run before any other tests.
4126 def test_pytype_long_ready(self):
4127 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004128
Georg Brandl479a7e72008-02-05 18:13:15 +00004129 # This dumps core when SF bug 551412 isn't fixed --
4130 # but only when test_descr.py is run separately.
4131 # (That can't be helped -- as soon as PyType_Ready()
4132 # is called for PyLong_Type, the bug is gone.)
4133 class UserLong(object):
4134 def __pow__(self, *args):
4135 pass
4136 try:
4137 pow(0, UserLong(), 0)
4138 except:
4139 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004140
Georg Brandl479a7e72008-02-05 18:13:15 +00004141 # Another segfault only when run early
4142 # (before PyType_Ready(tuple) is called)
4143 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004144
4145
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004146def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004147 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004148 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004149 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004151if __name__ == "__main__":
4152 test_main()