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