blob: b6ef06d6ef0e40c21c165ff814ac65a00b4976f8 [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Benjamin Petersona5758c02009-05-09 18:15:04 +00002import sys
Guido van Rossum360e4b82007-05-14 22:51:27 +00003import types
Georg Brandl479a7e72008-02-05 18:13:15 +00004import unittest
5import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00006
Georg Brandl479a7e72008-02-05 18:13:15 +00007from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Georg Brandl479a7e72008-02-05 18:13:15 +000011class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000012
Georg Brandl479a7e72008-02-05 18:13:15 +000013 def __init__(self, *args, **kwargs):
14 unittest.TestCase.__init__(self, *args, **kwargs)
15 self.binops = {
16 'add': '+',
17 'sub': '-',
18 'mul': '*',
19 'div': '/',
20 'divmod': 'divmod',
21 'pow': '**',
22 'lshift': '<<',
23 'rshift': '>>',
24 'and': '&',
25 'xor': '^',
26 'or': '|',
27 'cmp': 'cmp',
28 'lt': '<',
29 'le': '<=',
30 'eq': '==',
31 'ne': '!=',
32 'gt': '>',
33 'ge': '>=',
34 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000035
Georg Brandl479a7e72008-02-05 18:13:15 +000036 for name, expr in list(self.binops.items()):
37 if expr.islower():
38 expr = expr + "(a, b)"
39 else:
40 expr = 'a %s b' % expr
41 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
Georg Brandl479a7e72008-02-05 18:13:15 +000043 self.unops = {
44 'pos': '+',
45 'neg': '-',
46 'abs': 'abs',
47 'invert': '~',
48 'int': 'int',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl479a7e72008-02-05 18:13:15 +000054 for name, expr in list(self.unops.items()):
55 if expr.islower():
56 expr = expr + "(a)"
57 else:
58 expr = '%s a' % expr
59 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000060
Georg Brandl479a7e72008-02-05 18:13:15 +000061 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
62 d = {'a': a}
63 self.assertEqual(eval(expr, d), res)
64 t = type(a)
65 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl479a7e72008-02-05 18:13:15 +000067 # Find method in parent class
68 while meth not in t.__dict__:
69 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000070 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
71 # method object; the getattr() below obtains its underlying function.
72 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000073 self.assertEqual(m(a), res)
74 bm = getattr(a, meth)
75 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000076
Georg Brandl479a7e72008-02-05 18:13:15 +000077 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
78 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000079
Georg Brandl479a7e72008-02-05 18:13:15 +000080 # XXX Hack so this passes before 2.3 when -Qnew is specified.
81 if meth == "__div__" and 1/2 == 0.5:
82 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000083
Georg Brandl479a7e72008-02-05 18:13:15 +000084 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl479a7e72008-02-05 18:13:15 +000086 self.assertEqual(eval(expr, d), res)
87 t = type(a)
88 m = getattr(t, meth)
89 while meth not in t.__dict__:
90 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000091 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000094 self.assertEqual(m(a, b), res)
95 bm = getattr(a, meth)
96 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000097
Georg Brandl479a7e72008-02-05 18:13:15 +000098 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
99 d = {'a': a, 'b': b, 'c': c}
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000108 self.assertEqual(m(a, slice(b, c)), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl479a7e72008-02-05 18:13:15 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec(stmt, d)
115 self.assertEqual(d['a'], res)
116 t = type(a)
117 m = getattr(t, meth)
118 while meth not in t.__dict__:
119 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000123 d['a'] = deepcopy(a)
124 m(d['a'], b)
125 self.assertEqual(d['a'], res)
126 d['a'] = deepcopy(a)
127 bm = getattr(d['a'], meth)
128 bm(b)
129 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130
Georg Brandl479a7e72008-02-05 18:13:15 +0000131 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132 d = {'a': deepcopy(a), 'b': b, 'c': c}
133 exec(stmt, d)
134 self.assertEqual(d['a'], res)
135 t = type(a)
136 m = getattr(t, meth)
137 while meth not in t.__dict__:
138 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000142 d['a'] = deepcopy(a)
143 m(d['a'], b, c)
144 self.assertEqual(d['a'], res)
145 d['a'] = deepcopy(a)
146 bm = getattr(d['a'], meth)
147 bm(b, c)
148 self.assertEqual(d['a'], res)
149
150 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec(stmt, dictionary)
153 self.assertEqual(dictionary['a'], res)
154 t = type(a)
155 while meth not in t.__dict__:
156 t = t.__bases__[0]
157 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], slice(b, c), d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(slice(b, c), d)
167 self.assertEqual(dictionary['a'], res)
168
169 def test_lists(self):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
177 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setitem__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000188 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
190 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
191
192 d = {1:2, 3:4}
193 l1 = []
194 for i in list(d.keys()):
195 l1.append(i)
196 l = []
197 for i in iter(d):
198 l.append(i)
199 self.assertEqual(l, l1)
200 l = []
201 for i in d.__iter__():
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in dict.__iter__(d):
206 l.append(i)
207 self.assertEqual(l, l1)
208 d = {1:2, 3:4}
209 self.unop_test(d, 2, "len(a)", "__len__")
210 self.assertEqual(eval(repr(d), {}), d)
211 self.assertEqual(eval(d.__repr__(), {}), d)
212 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
213 "__setitem__")
214
215 # Tests for unary and binary operators
216 def number_operators(self, a, b, skip=[]):
217 dict = {'a': a, 'b': b}
218
219 for name, expr in list(self.binops.items()):
220 if name not in skip:
221 name = "__%s__" % name
222 if hasattr(a, name):
223 res = eval(expr, dict)
224 self.binop_test(a, b, res, expr, name)
225
226 for name, expr in list(self.unops.items()):
227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.unop_test(a, res, expr, name)
232
233 def test_ints(self):
234 # Testing int operations...
235 self.number_operators(100, 3)
236 # The following crashes in Python 2.2
237 self.assertEqual((1).__bool__(), 1)
238 self.assertEqual((0).__bool__(), 0)
239 # This returns 'NotImplemented' in Python 2.2
240 class C(int):
241 def __add__(self, other):
242 return NotImplemented
243 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000244 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000245 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000246 except TypeError:
247 pass
248 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000249 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000250
Georg Brandl479a7e72008-02-05 18:13:15 +0000251 def test_longs(self):
252 # Testing long operations...
253 self.number_operators(100, 3)
Tim Peters25786c02001-09-02 08:22:48 +0000254
Georg Brandl479a7e72008-02-05 18:13:15 +0000255 def test_floats(self):
256 # Testing float operations...
257 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000258
Georg Brandl479a7e72008-02-05 18:13:15 +0000259 def test_complexes(self):
260 # Testing complex operations...
261 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
262 'int', 'long', 'float',
263 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000264
Georg Brandl479a7e72008-02-05 18:13:15 +0000265 class Number(complex):
266 __slots__ = ['prec']
267 def __new__(cls, *args, **kwds):
268 result = complex.__new__(cls, *args)
269 result.prec = kwds.get('prec', 12)
270 return result
271 def __repr__(self):
272 prec = self.prec
273 if self.imag == 0.0:
274 return "%.*g" % (prec, self.real)
275 if self.real == 0.0:
276 return "%.*gj" % (prec, self.imag)
277 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
278 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000279
Georg Brandl479a7e72008-02-05 18:13:15 +0000280 a = Number(3.14, prec=6)
281 self.assertEqual(repr(a), "3.14")
282 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000283
Georg Brandl479a7e72008-02-05 18:13:15 +0000284 a = Number(a, prec=2)
285 self.assertEqual(repr(a), "3.1")
286 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000287
Georg Brandl479a7e72008-02-05 18:13:15 +0000288 a = Number(234.5)
289 self.assertEqual(repr(a), "234.5")
290 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000291
Benjamin Petersone549ead2009-03-28 21:42:05 +0000292 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000293 def test_spam_lists(self):
294 # Testing spamlist operations...
295 import copy, xxsubtype as spam
296
297 def spamlist(l, memo=None):
298 import xxsubtype as spam
299 return spam.spamlist(l)
300
301 # This is an ugly hack:
302 copy._deepcopy_dispatch[spam.spamlist] = spamlist
303
304 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
305 "__add__")
306 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
307 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
308 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
309 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
310 "__getitem__")
311 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
312 "__iadd__")
313 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
314 "__imul__")
315 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
316 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
317 "__mul__")
318 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
319 "__rmul__")
320 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
321 "__setitem__")
322 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
323 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
324 # Test subclassing
325 class C(spam.spamlist):
326 def foo(self): return 1
327 a = C()
328 self.assertEqual(a, [])
329 self.assertEqual(a.foo(), 1)
330 a.append(100)
331 self.assertEqual(a, [100])
332 self.assertEqual(a.getstate(), 0)
333 a.setstate(42)
334 self.assertEqual(a.getstate(), 42)
335
Benjamin Petersone549ead2009-03-28 21:42:05 +0000336 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000337 def test_spam_dicts(self):
338 # Testing spamdict operations...
339 import copy, xxsubtype as spam
340 def spamdict(d, memo=None):
341 import xxsubtype as spam
342 sd = spam.spamdict()
343 for k, v in list(d.items()):
344 sd[k] = v
345 return sd
346 # This is an ugly hack:
347 copy._deepcopy_dispatch[spam.spamdict] = spamdict
348
Georg Brandl479a7e72008-02-05 18:13:15 +0000349 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
350 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
351 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
352 d = spamdict({1:2,3:4})
353 l1 = []
354 for i in list(d.keys()):
355 l1.append(i)
356 l = []
357 for i in iter(d):
358 l.append(i)
359 self.assertEqual(l, l1)
360 l = []
361 for i in d.__iter__():
362 l.append(i)
363 self.assertEqual(l, l1)
364 l = []
365 for i in type(spamdict({})).__iter__(d):
366 l.append(i)
367 self.assertEqual(l, l1)
368 straightd = {1:2, 3:4}
369 spamd = spamdict(straightd)
370 self.unop_test(spamd, 2, "len(a)", "__len__")
371 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
372 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
373 "a[b]=c", "__setitem__")
374 # Test subclassing
375 class C(spam.spamdict):
376 def foo(self): return 1
377 a = C()
378 self.assertEqual(list(a.items()), [])
379 self.assertEqual(a.foo(), 1)
380 a['foo'] = 'bar'
381 self.assertEqual(list(a.items()), [('foo', 'bar')])
382 self.assertEqual(a.getstate(), 0)
383 a.setstate(100)
384 self.assertEqual(a.getstate(), 100)
385
386class ClassPropertiesAndMethods(unittest.TestCase):
387
388 def test_python_dicts(self):
389 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000390 self.assertTrue(issubclass(dict, dict))
391 self.assertTrue(isinstance({}, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000392 d = dict()
393 self.assertEqual(d, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000394 self.assertTrue(d.__class__ is dict)
395 self.assertTrue(isinstance(d, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000396 class C(dict):
397 state = -1
398 def __init__(self_local, *a, **kw):
399 if a:
400 self.assertEqual(len(a), 1)
401 self_local.state = a[0]
402 if kw:
403 for k, v in list(kw.items()):
404 self_local[v] = k
405 def __getitem__(self, key):
406 return self.get(key, 0)
407 def __setitem__(self_local, key, value):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000408 self.assertTrue(isinstance(key, type(0)))
Georg Brandl479a7e72008-02-05 18:13:15 +0000409 dict.__setitem__(self_local, key, value)
410 def setstate(self, state):
411 self.state = state
412 def getstate(self):
413 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000414 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000415 a1 = C(12)
416 self.assertEqual(a1.state, 12)
417 a2 = C(foo=1, bar=2)
418 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
419 a = C()
420 self.assertEqual(a.state, -1)
421 self.assertEqual(a.getstate(), -1)
422 a.setstate(0)
423 self.assertEqual(a.state, 0)
424 self.assertEqual(a.getstate(), 0)
425 a.setstate(10)
426 self.assertEqual(a.state, 10)
427 self.assertEqual(a.getstate(), 10)
428 self.assertEqual(a[42], 0)
429 a[42] = 24
430 self.assertEqual(a[42], 24)
431 N = 50
432 for i in range(N):
433 a[i] = C()
434 for j in range(N):
435 a[i][j] = i*j
436 for i in range(N):
437 for j in range(N):
438 self.assertEqual(a[i][j], i*j)
439
440 def test_python_lists(self):
441 # Testing Python subclass of list...
442 class C(list):
443 def __getitem__(self, i):
444 if isinstance(i, slice):
445 return i.start, i.stop
446 return list.__getitem__(self, i) + 100
447 a = C()
448 a.extend([0,1,2])
449 self.assertEqual(a[0], 100)
450 self.assertEqual(a[1], 101)
451 self.assertEqual(a[2], 102)
452 self.assertEqual(a[100:200], (100,200))
453
454 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000455 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000456 class C(metaclass=type):
457 def __init__(self):
458 self.__state = 0
459 def getstate(self):
460 return self.__state
461 def setstate(self, state):
462 self.__state = state
463 a = C()
464 self.assertEqual(a.getstate(), 0)
465 a.setstate(10)
466 self.assertEqual(a.getstate(), 10)
467 class _metaclass(type):
468 def myself(cls): return cls
469 class D(metaclass=_metaclass):
470 pass
471 self.assertEqual(D.myself(), D)
472 d = D()
473 self.assertEqual(d.__class__, D)
474 class M1(type):
475 def __new__(cls, name, bases, dict):
476 dict['__spam__'] = 1
477 return type.__new__(cls, name, bases, dict)
478 class C(metaclass=M1):
479 pass
480 self.assertEqual(C.__spam__, 1)
481 c = C()
482 self.assertEqual(c.__spam__, 1)
483
484 class _instance(object):
485 pass
486 class M2(object):
487 @staticmethod
488 def __new__(cls, name, bases, dict):
489 self = object.__new__(cls)
490 self.name = name
491 self.bases = bases
492 self.dict = dict
493 return self
494 def __call__(self):
495 it = _instance()
496 # Early binding of methods
497 for key in self.dict:
498 if key.startswith("__"):
499 continue
500 setattr(it, key, self.dict[key].__get__(it, self))
501 return it
502 class C(metaclass=M2):
503 def spam(self):
504 return 42
505 self.assertEqual(C.name, 'C')
506 self.assertEqual(C.bases, ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000507 self.assertTrue('spam' in C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000508 c = C()
509 self.assertEqual(c.spam(), 42)
510
511 # More metaclass examples
512
513 class autosuper(type):
514 # Automatically add __super to the class
515 # This trick only works for dynamic classes
516 def __new__(metaclass, name, bases, dict):
517 cls = super(autosuper, metaclass).__new__(metaclass,
518 name, bases, dict)
519 # Name mangling for __super removes leading underscores
520 while name[:1] == "_":
521 name = name[1:]
522 if name:
523 name = "_%s__super" % name
524 else:
525 name = "__super"
526 setattr(cls, name, super(cls))
527 return cls
528 class A(metaclass=autosuper):
529 def meth(self):
530 return "A"
531 class B(A):
532 def meth(self):
533 return "B" + self.__super.meth()
534 class C(A):
535 def meth(self):
536 return "C" + self.__super.meth()
537 class D(C, B):
538 def meth(self):
539 return "D" + self.__super.meth()
540 self.assertEqual(D().meth(), "DCBA")
541 class E(B, C):
542 def meth(self):
543 return "E" + self.__super.meth()
544 self.assertEqual(E().meth(), "EBCA")
545
546 class autoproperty(type):
547 # Automatically create property attributes when methods
548 # named _get_x and/or _set_x are found
549 def __new__(metaclass, name, bases, dict):
550 hits = {}
551 for key, val in dict.items():
552 if key.startswith("_get_"):
553 key = key[5:]
554 get, set = hits.get(key, (None, None))
555 get = val
556 hits[key] = get, set
557 elif key.startswith("_set_"):
558 key = key[5:]
559 get, set = hits.get(key, (None, None))
560 set = val
561 hits[key] = get, set
562 for key, (get, set) in hits.items():
563 dict[key] = property(get, set)
564 return super(autoproperty, metaclass).__new__(metaclass,
565 name, bases, dict)
566 class A(metaclass=autoproperty):
567 def _get_x(self):
568 return -self.__x
569 def _set_x(self, x):
570 self.__x = -x
571 a = A()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000572 self.assertTrue(not hasattr(a, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +0000573 a.x = 12
574 self.assertEqual(a.x, 12)
575 self.assertEqual(a._A__x, -12)
576
577 class multimetaclass(autoproperty, autosuper):
578 # Merge of multiple cooperating metaclasses
579 pass
580 class A(metaclass=multimetaclass):
581 def _get_x(self):
582 return "A"
583 class B(A):
584 def _get_x(self):
585 return "B" + self.__super._get_x()
586 class C(A):
587 def _get_x(self):
588 return "C" + self.__super._get_x()
589 class D(C, B):
590 def _get_x(self):
591 return "D" + self.__super._get_x()
592 self.assertEqual(D().x, "DCBA")
593
594 # Make sure type(x) doesn't call x.__class__.__init__
595 class T(type):
596 counter = 0
597 def __init__(self, *args):
598 T.counter += 1
599 class C(metaclass=T):
600 pass
601 self.assertEqual(T.counter, 1)
602 a = C()
603 self.assertEqual(type(a), C)
604 self.assertEqual(T.counter, 1)
605
606 class C(object): pass
607 c = C()
608 try: c()
609 except TypeError: pass
610 else: self.fail("calling object w/o call method should raise "
611 "TypeError")
612
613 # Testing code to find most derived baseclass
614 class A(type):
615 def __new__(*args, **kwargs):
616 return type.__new__(*args, **kwargs)
617
618 class B(object):
619 pass
620
621 class C(object, metaclass=A):
622 pass
623
624 # The most derived metaclass of D is A rather than type.
625 class D(B, C):
626 pass
627
628 def test_module_subclasses(self):
629 # Testing Python subclass of module...
630 log = []
631 import types, sys
632 MT = type(sys)
633 class MM(MT):
634 def __init__(self, name):
635 MT.__init__(self, name)
636 def __getattribute__(self, name):
637 log.append(("getattr", name))
638 return MT.__getattribute__(self, name)
639 def __setattr__(self, name, value):
640 log.append(("setattr", name, value))
641 MT.__setattr__(self, name, value)
642 def __delattr__(self, name):
643 log.append(("delattr", name))
644 MT.__delattr__(self, name)
645 a = MM("a")
646 a.foo = 12
647 x = a.foo
648 del a.foo
649 self.assertEqual(log, [("setattr", "foo", 12),
650 ("getattr", "foo"),
651 ("delattr", "foo")])
652
653 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000654 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000655 class Module(types.ModuleType, str):
656 pass
657 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000658 pass
659 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000660 self.fail("inheriting from ModuleType and str at the same time "
661 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000662
Georg Brandl479a7e72008-02-05 18:13:15 +0000663 def test_multiple_inheritance(self):
664 # Testing multiple inheritance...
665 class C(object):
666 def __init__(self):
667 self.__state = 0
668 def getstate(self):
669 return self.__state
670 def setstate(self, state):
671 self.__state = state
672 a = C()
673 self.assertEqual(a.getstate(), 0)
674 a.setstate(10)
675 self.assertEqual(a.getstate(), 10)
676 class D(dict, C):
677 def __init__(self):
678 type({}).__init__(self)
679 C.__init__(self)
680 d = D()
681 self.assertEqual(list(d.keys()), [])
682 d["hello"] = "world"
683 self.assertEqual(list(d.items()), [("hello", "world")])
684 self.assertEqual(d["hello"], "world")
685 self.assertEqual(d.getstate(), 0)
686 d.setstate(10)
687 self.assertEqual(d.getstate(), 10)
688 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000689
Georg Brandl479a7e72008-02-05 18:13:15 +0000690 # SF bug #442833
691 class Node(object):
692 def __int__(self):
693 return int(self.foo())
694 def foo(self):
695 return "23"
696 class Frag(Node, list):
697 def foo(self):
698 return "42"
699 self.assertEqual(Node().__int__(), 23)
700 self.assertEqual(int(Node()), 23)
701 self.assertEqual(Frag().__int__(), 42)
702 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000703
Georg Brandl479a7e72008-02-05 18:13:15 +0000704 def test_diamond_inheritence(self):
705 # Testing multiple inheritance special cases...
706 class A(object):
707 def spam(self): return "A"
708 self.assertEqual(A().spam(), "A")
709 class B(A):
710 def boo(self): return "B"
711 def spam(self): return "B"
712 self.assertEqual(B().spam(), "B")
713 self.assertEqual(B().boo(), "B")
714 class C(A):
715 def boo(self): return "C"
716 self.assertEqual(C().spam(), "A")
717 self.assertEqual(C().boo(), "C")
718 class D(B, C): pass
719 self.assertEqual(D().spam(), "B")
720 self.assertEqual(D().boo(), "B")
721 self.assertEqual(D.__mro__, (D, B, C, A, object))
722 class E(C, B): pass
723 self.assertEqual(E().spam(), "B")
724 self.assertEqual(E().boo(), "C")
725 self.assertEqual(E.__mro__, (E, C, B, A, object))
726 # MRO order disagreement
727 try:
728 class F(D, E): pass
729 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000730 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000731 else:
732 self.fail("expected MRO order disagreement (F)")
733 try:
734 class G(E, D): pass
735 except TypeError:
736 pass
737 else:
738 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000739
Georg Brandl479a7e72008-02-05 18:13:15 +0000740 # see thread python-dev/2002-October/029035.html
741 def test_ex5_from_c3_switch(self):
742 # Testing ex5 from C3 switch discussion...
743 class A(object): pass
744 class B(object): pass
745 class C(object): pass
746 class X(A): pass
747 class Y(A): pass
748 class Z(X,B,Y,C): pass
749 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750
Georg Brandl479a7e72008-02-05 18:13:15 +0000751 # see "A Monotonic Superclass Linearization for Dylan",
752 # by Kim Barrett et al. (OOPSLA 1996)
753 def test_monotonicity(self):
754 # Testing MRO monotonicity...
755 class Boat(object): pass
756 class DayBoat(Boat): pass
757 class WheelBoat(Boat): pass
758 class EngineLess(DayBoat): pass
759 class SmallMultihull(DayBoat): pass
760 class PedalWheelBoat(EngineLess,WheelBoat): pass
761 class SmallCatamaran(SmallMultihull): pass
762 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000763
Georg Brandl479a7e72008-02-05 18:13:15 +0000764 self.assertEqual(PedalWheelBoat.__mro__,
765 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
766 self.assertEqual(SmallCatamaran.__mro__,
767 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
768 self.assertEqual(Pedalo.__mro__,
769 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
770 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000771
Georg Brandl479a7e72008-02-05 18:13:15 +0000772 # see "A Monotonic Superclass Linearization for Dylan",
773 # by Kim Barrett et al. (OOPSLA 1996)
774 def test_consistency_with_epg(self):
775 # Testing consistentcy with EPG...
776 class Pane(object): pass
777 class ScrollingMixin(object): pass
778 class EditingMixin(object): pass
779 class ScrollablePane(Pane,ScrollingMixin): pass
780 class EditablePane(Pane,EditingMixin): pass
781 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000782
Georg Brandl479a7e72008-02-05 18:13:15 +0000783 self.assertEqual(EditableScrollablePane.__mro__,
784 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
785 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000786
Georg Brandl479a7e72008-02-05 18:13:15 +0000787 def test_mro_disagreement(self):
788 # Testing error messages for MRO disagreement...
789 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000790order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000791
Georg Brandl479a7e72008-02-05 18:13:15 +0000792 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000793 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000794 callable(*args)
795 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000796 # the exact msg is generally considered an impl detail
797 if support.check_impl_detail():
798 if not str(msg).startswith(expected):
799 self.fail("Message %r, expected %r" %
800 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000801 else:
802 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000803
Georg Brandl479a7e72008-02-05 18:13:15 +0000804 class A(object): pass
805 class B(A): pass
806 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000807
Georg Brandl479a7e72008-02-05 18:13:15 +0000808 # Test some very simple errors
809 raises(TypeError, "duplicate base class A",
810 type, "X", (A, A), {})
811 raises(TypeError, mro_err_msg,
812 type, "X", (A, B), {})
813 raises(TypeError, mro_err_msg,
814 type, "X", (A, C, B), {})
815 # Test a slightly more complex error
816 class GridLayout(object): pass
817 class HorizontalGrid(GridLayout): pass
818 class VerticalGrid(GridLayout): pass
819 class HVGrid(HorizontalGrid, VerticalGrid): pass
820 class VHGrid(VerticalGrid, HorizontalGrid): pass
821 raises(TypeError, mro_err_msg,
822 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000823
Georg Brandl479a7e72008-02-05 18:13:15 +0000824 def test_object_class(self):
825 # Testing object class...
826 a = object()
827 self.assertEqual(a.__class__, object)
828 self.assertEqual(type(a), object)
829 b = object()
830 self.assertNotEqual(a, b)
831 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +0000832 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000833 a.foo = 12
834 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +0000835 pass
836 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000837 self.fail("object() should not allow setting a foo attribute")
838 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +0000839
Georg Brandl479a7e72008-02-05 18:13:15 +0000840 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000841 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000842 x = Cdict()
843 self.assertEqual(x.__dict__, {})
844 x.foo = 1
845 self.assertEqual(x.foo, 1)
846 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847
Georg Brandl479a7e72008-02-05 18:13:15 +0000848 def test_slots(self):
849 # Testing __slots__...
850 class C0(object):
851 __slots__ = []
852 x = C0()
853 self.assertFalse(hasattr(x, "__dict__"))
854 self.assertFalse(hasattr(x, "foo"))
855
856 class C1(object):
857 __slots__ = ['a']
858 x = C1()
859 self.assertFalse(hasattr(x, "__dict__"))
860 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000861 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +0000862 self.assertEqual(x.a, 1)
863 x.a = None
864 self.assertEqual(x.a, None)
865 del x.a
866 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000867
Georg Brandl479a7e72008-02-05 18:13:15 +0000868 class C3(object):
869 __slots__ = ['a', 'b', 'c']
870 x = C3()
871 self.assertFalse(hasattr(x, "__dict__"))
872 self.assertFalse(hasattr(x, 'a'))
873 self.assertFalse(hasattr(x, 'b'))
874 self.assertFalse(hasattr(x, 'c'))
875 x.a = 1
876 x.b = 2
877 x.c = 3
878 self.assertEqual(x.a, 1)
879 self.assertEqual(x.b, 2)
880 self.assertEqual(x.c, 3)
881
882 class C4(object):
883 """Validate name mangling"""
884 __slots__ = ['__a']
885 def __init__(self, value):
886 self.__a = value
887 def get(self):
888 return self.__a
889 x = C4(5)
890 self.assertFalse(hasattr(x, '__dict__'))
891 self.assertFalse(hasattr(x, '__a'))
892 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000893 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000894 x.__a = 6
895 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +0000896 pass
897 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000898 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000899
Georg Brandl479a7e72008-02-05 18:13:15 +0000900 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +0000901 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000902 class C(object):
903 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +0000904 except TypeError:
905 pass
906 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000907 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000908 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000909 class C(object):
910 __slots__ = ["foo bar"]
911 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000912 pass
913 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000914 self.fail("['foo bar'] slots not caught")
915 try:
916 class C(object):
917 __slots__ = ["foo\0bar"]
918 except TypeError:
919 pass
920 else:
921 self.fail("['foo\\0bar'] slots not caught")
922 try:
923 class C(object):
924 __slots__ = ["1"]
925 except TypeError:
926 pass
927 else:
928 self.fail("['1'] slots not caught")
929 try:
930 class C(object):
931 __slots__ = [""]
932 except TypeError:
933 pass
934 else:
935 self.fail("[''] slots not caught")
936 class C(object):
937 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
938 # XXX(nnorwitz): was there supposed to be something tested
939 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +0000940
Georg Brandl479a7e72008-02-05 18:13:15 +0000941 # Test a single string is not expanded as a sequence.
942 class C(object):
943 __slots__ = "abc"
944 c = C()
945 c.abc = 5
946 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000947
Georg Brandl479a7e72008-02-05 18:13:15 +0000948 # Test unicode slot names
949 # Test a single unicode string is not expanded as a sequence.
950 class C(object):
951 __slots__ = "abc"
952 c = C()
953 c.abc = 5
954 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +0000955
Georg Brandl479a7e72008-02-05 18:13:15 +0000956 # _unicode_to_string used to modify slots in certain circumstances
957 slots = ("foo", "bar")
958 class C(object):
959 __slots__ = slots
960 x = C()
961 x.foo = 5
962 self.assertEqual(x.foo, 5)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000963 self.assertTrue(type(slots[0]) is str)
Georg Brandl479a7e72008-02-05 18:13:15 +0000964 # this used to leak references
965 try:
966 class C(object):
967 __slots__ = [chr(128)]
968 except (TypeError, UnicodeEncodeError):
969 pass
970 else:
971 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +0000972
Georg Brandl479a7e72008-02-05 18:13:15 +0000973 # Test leaks
974 class Counted(object):
975 counter = 0 # counts the number of instances alive
976 def __init__(self):
977 Counted.counter += 1
978 def __del__(self):
979 Counted.counter -= 1
980 class C(object):
981 __slots__ = ['a', 'b', 'c']
982 x = C()
983 x.a = Counted()
984 x.b = Counted()
985 x.c = Counted()
986 self.assertEqual(Counted.counter, 3)
987 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000988 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 self.assertEqual(Counted.counter, 0)
990 class D(C):
991 pass
992 x = D()
993 x.a = Counted()
994 x.z = Counted()
995 self.assertEqual(Counted.counter, 2)
996 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000997 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000998 self.assertEqual(Counted.counter, 0)
999 class E(D):
1000 __slots__ = ['e']
1001 x = E()
1002 x.a = Counted()
1003 x.z = Counted()
1004 x.e = Counted()
1005 self.assertEqual(Counted.counter, 3)
1006 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001007 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001008 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001009
Georg Brandl479a7e72008-02-05 18:13:15 +00001010 # Test cyclical leaks [SF bug 519621]
1011 class F(object):
1012 __slots__ = ['a', 'b']
1013 log = []
1014 s = F()
1015 s.a = [Counted(), s]
1016 self.assertEqual(Counted.counter, 1)
1017 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001018 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001019 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001020
Georg Brandl479a7e72008-02-05 18:13:15 +00001021 # Test lookup leaks [SF bug 572567]
1022 import sys,gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001023 if hasattr(gc, 'get_objects'):
1024 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001025 def __eq__(self, other):
1026 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001027 g = G()
1028 orig_objects = len(gc.get_objects())
1029 for i in range(10):
1030 g==g
1031 new_objects = len(gc.get_objects())
1032 self.assertEqual(orig_objects, new_objects)
1033
Georg Brandl479a7e72008-02-05 18:13:15 +00001034 class H(object):
1035 __slots__ = ['a', 'b']
1036 def __init__(self):
1037 self.a = 1
1038 self.b = 2
1039 def __del__(self_):
1040 self.assertEqual(self_.a, 1)
1041 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001042 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001043 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001044 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001045 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001046
Georg Brandl479a7e72008-02-05 18:13:15 +00001047 def test_slots_special(self):
1048 # Testing __dict__ and __weakref__ in __slots__...
1049 class D(object):
1050 __slots__ = ["__dict__"]
1051 a = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001052 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001053 self.assertFalse(hasattr(a, "__weakref__"))
1054 a.foo = 42
1055 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001056
Georg Brandl479a7e72008-02-05 18:13:15 +00001057 class W(object):
1058 __slots__ = ["__weakref__"]
1059 a = W()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001060 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001061 self.assertFalse(hasattr(a, "__dict__"))
1062 try:
1063 a.foo = 42
1064 except AttributeError:
1065 pass
1066 else:
1067 self.fail("shouldn't be allowed to set a.foo")
1068
1069 class C1(W, D):
1070 __slots__ = []
1071 a = C1()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001072 self.assertTrue(hasattr(a, "__dict__"))
1073 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001074 a.foo = 42
1075 self.assertEqual(a.__dict__, {"foo": 42})
1076
1077 class C2(D, W):
1078 __slots__ = []
1079 a = C2()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001080 self.assertTrue(hasattr(a, "__dict__"))
1081 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001082 a.foo = 42
1083 self.assertEqual(a.__dict__, {"foo": 42})
1084
Christian Heimesa156e092008-02-16 07:38:31 +00001085 def test_slots_descriptor(self):
1086 # Issue2115: slot descriptors did not correctly check
1087 # the type of the given object
1088 import abc
1089 class MyABC(metaclass=abc.ABCMeta):
1090 __slots__ = "a"
1091
1092 class Unrelated(object):
1093 pass
1094 MyABC.register(Unrelated)
1095
1096 u = Unrelated()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001097 self.assertTrue(isinstance(u, MyABC))
Christian Heimesa156e092008-02-16 07:38:31 +00001098
1099 # This used to crash
1100 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1101
Georg Brandl479a7e72008-02-05 18:13:15 +00001102 def test_dynamics(self):
1103 # Testing class attribute propagation...
1104 class D(object):
1105 pass
1106 class E(D):
1107 pass
1108 class F(D):
1109 pass
1110 D.foo = 1
1111 self.assertEqual(D.foo, 1)
1112 # Test that dynamic attributes are inherited
1113 self.assertEqual(E.foo, 1)
1114 self.assertEqual(F.foo, 1)
1115 # Test dynamic instances
1116 class C(object):
1117 pass
1118 a = C()
1119 self.assertFalse(hasattr(a, "foobar"))
1120 C.foobar = 2
1121 self.assertEqual(a.foobar, 2)
1122 C.method = lambda self: 42
1123 self.assertEqual(a.method(), 42)
1124 C.__repr__ = lambda self: "C()"
1125 self.assertEqual(repr(a), "C()")
1126 C.__int__ = lambda self: 100
1127 self.assertEqual(int(a), 100)
1128 self.assertEqual(a.foobar, 2)
1129 self.assertFalse(hasattr(a, "spam"))
1130 def mygetattr(self, name):
1131 if name == "spam":
1132 return "spam"
1133 raise AttributeError
1134 C.__getattr__ = mygetattr
1135 self.assertEqual(a.spam, "spam")
1136 a.new = 12
1137 self.assertEqual(a.new, 12)
1138 def mysetattr(self, name, value):
1139 if name == "spam":
1140 raise AttributeError
1141 return object.__setattr__(self, name, value)
1142 C.__setattr__ = mysetattr
1143 try:
1144 a.spam = "not spam"
1145 except AttributeError:
1146 pass
1147 else:
1148 self.fail("expected AttributeError")
1149 self.assertEqual(a.spam, "spam")
1150 class D(C):
1151 pass
1152 d = D()
1153 d.foo = 1
1154 self.assertEqual(d.foo, 1)
1155
1156 # Test handling of int*seq and seq*int
1157 class I(int):
1158 pass
1159 self.assertEqual("a"*I(2), "aa")
1160 self.assertEqual(I(2)*"a", "aa")
1161 self.assertEqual(2*I(3), 6)
1162 self.assertEqual(I(3)*2, 6)
1163 self.assertEqual(I(3)*I(2), 6)
1164
1165 # Test handling of long*seq and seq*long
1166 class L(int):
1167 pass
1168 self.assertEqual("a"*L(2), "aa")
1169 self.assertEqual(L(2)*"a", "aa")
1170 self.assertEqual(2*L(3), 6)
1171 self.assertEqual(L(3)*2, 6)
1172 self.assertEqual(L(3)*L(2), 6)
1173
1174 # Test comparison of classes with dynamic metaclasses
1175 class dynamicmetaclass(type):
1176 pass
1177 class someclass(metaclass=dynamicmetaclass):
1178 pass
1179 self.assertNotEqual(someclass, object)
1180
1181 def test_errors(self):
1182 # Testing errors...
1183 try:
1184 class C(list, dict):
1185 pass
1186 except TypeError:
1187 pass
1188 else:
1189 self.fail("inheritance from both list and dict should be illegal")
1190
1191 try:
1192 class C(object, None):
1193 pass
1194 except TypeError:
1195 pass
1196 else:
1197 self.fail("inheritance from non-type should be illegal")
1198 class Classic:
1199 pass
1200
1201 try:
1202 class C(type(len)):
1203 pass
1204 except TypeError:
1205 pass
1206 else:
1207 self.fail("inheritance from CFunction should be illegal")
1208
1209 try:
1210 class C(object):
1211 __slots__ = 1
1212 except TypeError:
1213 pass
1214 else:
1215 self.fail("__slots__ = 1 should be illegal")
1216
1217 try:
1218 class C(object):
1219 __slots__ = [1]
1220 except TypeError:
1221 pass
1222 else:
1223 self.fail("__slots__ = [1] should be illegal")
1224
1225 class M1(type):
1226 pass
1227 class M2(type):
1228 pass
1229 class A1(object, metaclass=M1):
1230 pass
1231 class A2(object, metaclass=M2):
1232 pass
1233 try:
1234 class B(A1, A2):
1235 pass
1236 except TypeError:
1237 pass
1238 else:
1239 self.fail("finding the most derived metaclass should have failed")
1240
1241 def test_classmethods(self):
1242 # Testing class methods...
1243 class C(object):
1244 def foo(*a): return a
1245 goo = classmethod(foo)
1246 c = C()
1247 self.assertEqual(C.goo(1), (C, 1))
1248 self.assertEqual(c.goo(1), (C, 1))
1249 self.assertEqual(c.foo(1), (c, 1))
1250 class D(C):
1251 pass
1252 d = D()
1253 self.assertEqual(D.goo(1), (D, 1))
1254 self.assertEqual(d.goo(1), (D, 1))
1255 self.assertEqual(d.foo(1), (d, 1))
1256 self.assertEqual(D.foo(d, 1), (d, 1))
1257 # Test for a specific crash (SF bug 528132)
1258 def f(cls, arg): return (cls, arg)
1259 ff = classmethod(f)
1260 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1261 self.assertEqual(ff.__get__(0)(42), (int, 42))
1262
1263 # Test super() with classmethods (SF bug 535444)
1264 self.assertEqual(C.goo.__self__, C)
1265 self.assertEqual(D.goo.__self__, D)
1266 self.assertEqual(super(D,D).goo.__self__, D)
1267 self.assertEqual(super(D,d).goo.__self__, D)
1268 self.assertEqual(super(D,D).goo(), (D,))
1269 self.assertEqual(super(D,d).goo(), (D,))
1270
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001271 # Verify that a non-callable will raise
1272 meth = classmethod(1).__get__(1)
1273 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001274
1275 # Verify that classmethod() doesn't allow keyword args
1276 try:
1277 classmethod(f, kw=1)
1278 except TypeError:
1279 pass
1280 else:
1281 self.fail("classmethod shouldn't accept keyword args")
1282
Benjamin Petersone549ead2009-03-28 21:42:05 +00001283 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001284 def test_classmethods_in_c(self):
1285 # Testing C-based class methods...
1286 import xxsubtype as spam
1287 a = (1, 2, 3)
1288 d = {'abc': 123}
1289 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1290 self.assertEqual(x, spam.spamlist)
1291 self.assertEqual(a, a1)
1292 self.assertEqual(d, d1)
1293 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1294 self.assertEqual(x, spam.spamlist)
1295 self.assertEqual(a, a1)
1296 self.assertEqual(d, d1)
1297
1298 def test_staticmethods(self):
1299 # Testing static methods...
1300 class C(object):
1301 def foo(*a): return a
1302 goo = staticmethod(foo)
1303 c = C()
1304 self.assertEqual(C.goo(1), (1,))
1305 self.assertEqual(c.goo(1), (1,))
1306 self.assertEqual(c.foo(1), (c, 1,))
1307 class D(C):
1308 pass
1309 d = D()
1310 self.assertEqual(D.goo(1), (1,))
1311 self.assertEqual(d.goo(1), (1,))
1312 self.assertEqual(d.foo(1), (d, 1))
1313 self.assertEqual(D.foo(d, 1), (d, 1))
1314
Benjamin Petersone549ead2009-03-28 21:42:05 +00001315 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001316 def test_staticmethods_in_c(self):
1317 # Testing C-based static methods...
1318 import xxsubtype as spam
1319 a = (1, 2, 3)
1320 d = {"abc": 123}
1321 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1322 self.assertEqual(x, None)
1323 self.assertEqual(a, a1)
1324 self.assertEqual(d, d1)
1325 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1326 self.assertEqual(x, None)
1327 self.assertEqual(a, a1)
1328 self.assertEqual(d, d1)
1329
1330 def test_classic(self):
1331 # Testing classic classes...
1332 class C:
1333 def foo(*a): return a
1334 goo = classmethod(foo)
1335 c = C()
1336 self.assertEqual(C.goo(1), (C, 1))
1337 self.assertEqual(c.goo(1), (C, 1))
1338 self.assertEqual(c.foo(1), (c, 1))
1339 class D(C):
1340 pass
1341 d = D()
1342 self.assertEqual(D.goo(1), (D, 1))
1343 self.assertEqual(d.goo(1), (D, 1))
1344 self.assertEqual(d.foo(1), (d, 1))
1345 self.assertEqual(D.foo(d, 1), (d, 1))
1346 class E: # *not* subclassing from C
1347 foo = C.foo
1348 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001349 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001350
1351 def test_compattr(self):
1352 # Testing computed attributes...
1353 class C(object):
1354 class computed_attribute(object):
1355 def __init__(self, get, set=None, delete=None):
1356 self.__get = get
1357 self.__set = set
1358 self.__delete = delete
1359 def __get__(self, obj, type=None):
1360 return self.__get(obj)
1361 def __set__(self, obj, value):
1362 return self.__set(obj, value)
1363 def __delete__(self, obj):
1364 return self.__delete(obj)
1365 def __init__(self):
1366 self.__x = 0
1367 def __get_x(self):
1368 x = self.__x
1369 self.__x = x+1
1370 return x
1371 def __set_x(self, x):
1372 self.__x = x
1373 def __delete_x(self):
1374 del self.__x
1375 x = computed_attribute(__get_x, __set_x, __delete_x)
1376 a = C()
1377 self.assertEqual(a.x, 0)
1378 self.assertEqual(a.x, 1)
1379 a.x = 10
1380 self.assertEqual(a.x, 10)
1381 self.assertEqual(a.x, 11)
1382 del a.x
1383 self.assertEqual(hasattr(a, 'x'), 0)
1384
1385 def test_newslots(self):
1386 # Testing __new__ slot override...
1387 class C(list):
1388 def __new__(cls):
1389 self = list.__new__(cls)
1390 self.foo = 1
1391 return self
1392 def __init__(self):
1393 self.foo = self.foo + 2
1394 a = C()
1395 self.assertEqual(a.foo, 3)
1396 self.assertEqual(a.__class__, C)
1397 class D(C):
1398 pass
1399 b = D()
1400 self.assertEqual(b.foo, 3)
1401 self.assertEqual(b.__class__, D)
1402
1403 def test_altmro(self):
1404 # Testing mro() and overriding it...
1405 class A(object):
1406 def f(self): return "A"
1407 class B(A):
1408 pass
1409 class C(A):
1410 def f(self): return "C"
1411 class D(B, C):
1412 pass
1413 self.assertEqual(D.mro(), [D, B, C, A, object])
1414 self.assertEqual(D.__mro__, (D, B, C, A, object))
1415 self.assertEqual(D().f(), "C")
1416
1417 class PerverseMetaType(type):
1418 def mro(cls):
1419 L = type.mro(cls)
1420 L.reverse()
1421 return L
1422 class X(D,B,C,A, metaclass=PerverseMetaType):
1423 pass
1424 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1425 self.assertEqual(X().f(), "A")
1426
1427 try:
1428 class _metaclass(type):
1429 def mro(self):
1430 return [self, dict, object]
1431 class X(object, metaclass=_metaclass):
1432 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001433 # In CPython, the class creation above already raises
1434 # TypeError, as a protection against the fact that
1435 # instances of X would segfault it. In other Python
1436 # implementations it would be ok to let the class X
1437 # be created, but instead get a clean TypeError on the
1438 # __setitem__ below.
1439 x = object.__new__(X)
1440 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001441 except TypeError:
1442 pass
1443 else:
1444 self.fail("devious mro() return not caught")
1445
1446 try:
1447 class _metaclass(type):
1448 def mro(self):
1449 return [1]
1450 class X(object, metaclass=_metaclass):
1451 pass
1452 except TypeError:
1453 pass
1454 else:
1455 self.fail("non-class mro() return not caught")
1456
1457 try:
1458 class _metaclass(type):
1459 def mro(self):
1460 return 1
1461 class X(object, metaclass=_metaclass):
1462 pass
1463 except TypeError:
1464 pass
1465 else:
1466 self.fail("non-sequence mro() return not caught")
1467
1468 def test_overloading(self):
1469 # Testing operator overloading...
1470
1471 class B(object):
1472 "Intermediate class because object doesn't have a __setattr__"
1473
1474 class C(B):
1475 def __getattr__(self, name):
1476 if name == "foo":
1477 return ("getattr", name)
1478 else:
1479 raise AttributeError
1480 def __setattr__(self, name, value):
1481 if name == "foo":
1482 self.setattr = (name, value)
1483 else:
1484 return B.__setattr__(self, name, value)
1485 def __delattr__(self, name):
1486 if name == "foo":
1487 self.delattr = name
1488 else:
1489 return B.__delattr__(self, name)
1490
1491 def __getitem__(self, key):
1492 return ("getitem", key)
1493 def __setitem__(self, key, value):
1494 self.setitem = (key, value)
1495 def __delitem__(self, key):
1496 self.delitem = key
1497
1498 a = C()
1499 self.assertEqual(a.foo, ("getattr", "foo"))
1500 a.foo = 12
1501 self.assertEqual(a.setattr, ("foo", 12))
1502 del a.foo
1503 self.assertEqual(a.delattr, "foo")
1504
1505 self.assertEqual(a[12], ("getitem", 12))
1506 a[12] = 21
1507 self.assertEqual(a.setitem, (12, 21))
1508 del a[12]
1509 self.assertEqual(a.delitem, 12)
1510
1511 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1512 a[0:10] = "foo"
1513 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1514 del a[0:10]
1515 self.assertEqual(a.delitem, (slice(0, 10)))
1516
1517 def test_methods(self):
1518 # Testing methods...
1519 class C(object):
1520 def __init__(self, x):
1521 self.x = x
1522 def foo(self):
1523 return self.x
1524 c1 = C(1)
1525 self.assertEqual(c1.foo(), 1)
1526 class D(C):
1527 boo = C.foo
1528 goo = c1.foo
1529 d2 = D(2)
1530 self.assertEqual(d2.foo(), 2)
1531 self.assertEqual(d2.boo(), 2)
1532 self.assertEqual(d2.goo(), 1)
1533 class E(object):
1534 foo = C.foo
1535 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001536 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001537
Benjamin Peterson224205f2009-05-08 03:25:19 +00001538 def test_special_method_lookup(self):
1539 # The lookup of special methods bypasses __getattr__ and
1540 # __getattribute__, but they still can be descriptors.
1541
1542 def run_context(manager):
1543 with manager:
1544 pass
1545 def iden(self):
1546 return self
1547 def hello(self):
1548 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001549 def empty_seq(self):
1550 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001551 def zero(self):
1552 return 0
1553 def stop(self):
1554 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001555 def return_true(self, thing=None):
1556 return True
1557 def do_isinstance(obj):
1558 return isinstance(int, obj)
1559 def do_issubclass(obj):
1560 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001561 def do_dict_missing(checker):
1562 class DictSub(checker.__class__, dict):
1563 pass
1564 self.assertEqual(DictSub()["hi"], 4)
1565 def some_number(self_, key):
1566 self.assertEqual(key, "hi")
1567 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001568 def swallow(*args): pass
Benjamin Peterson224205f2009-05-08 03:25:19 +00001569
1570 # It would be nice to have every special method tested here, but I'm
1571 # only listing the ones I can remember outside of typeobject.c, since it
1572 # does it right.
1573 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001574 ("__bytes__", bytes, hello, set(), {}),
1575 ("__reversed__", reversed, empty_seq, set(), {}),
1576 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001577 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001578 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1579 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001580 ("__missing__", do_dict_missing, some_number,
1581 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001582 ("__subclasscheck__", do_issubclass, return_true,
1583 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001584 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1585 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001586 ]
1587
1588 class Checker(object):
1589 def __getattr__(self, attr, test=self):
1590 test.fail("__getattr__ called with {0}".format(attr))
1591 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001592 if attr not in ok:
1593 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001594 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001595 class SpecialDescr(object):
1596 def __init__(self, impl):
1597 self.impl = impl
1598 def __get__(self, obj, owner):
1599 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001600 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001601 class MyException(Exception):
1602 pass
1603 class ErrDescr(object):
1604 def __get__(self, obj, owner):
1605 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001606
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001607 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001608 class X(Checker):
1609 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001610 for attr, obj in env.items():
1611 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001612 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001613 runner(X())
1614
1615 record = []
1616 class X(Checker):
1617 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001618 for attr, obj in env.items():
1619 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001620 setattr(X, name, SpecialDescr(meth_impl))
1621 runner(X())
1622 self.assertEqual(record, [1], name)
1623
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001624 class X(Checker):
1625 pass
1626 for attr, obj in env.items():
1627 setattr(X, attr, obj)
1628 setattr(X, name, ErrDescr())
1629 try:
1630 runner(X())
1631 except MyException:
1632 pass
1633 else:
1634 self.fail("{0!r} didn't raise".format(name))
1635
Georg Brandl479a7e72008-02-05 18:13:15 +00001636 def test_specials(self):
1637 # Testing special operators...
1638 # Test operators like __hash__ for which a built-in default exists
1639
1640 # Test the default behavior for static classes
1641 class C(object):
1642 def __getitem__(self, i):
1643 if 0 <= i < 10: return i
1644 raise IndexError
1645 c1 = C()
1646 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001647 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001648 self.assertNotEqual(id(c1), id(c2))
1649 hash(c1)
1650 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001651 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001652 self.assertTrue(c1 != c2)
1653 self.assertTrue(not c1 != c1)
1654 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001655 # Note that the module name appears in str/repr, and that varies
1656 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001657 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001658 self.assertEqual(str(c1), repr(c1))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001659 self.assertTrue(-1 not in c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001660 for i in range(10):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001661 self.assertTrue(i in c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001662 self.assertFalse(10 in c1)
1663 # Test the default behavior for dynamic classes
1664 class D(object):
1665 def __getitem__(self, i):
1666 if 0 <= i < 10: return i
1667 raise IndexError
1668 d1 = D()
1669 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001670 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001671 self.assertNotEqual(id(d1), id(d2))
1672 hash(d1)
1673 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001674 self.assertEqual(d1, d1)
1675 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001676 self.assertTrue(not d1 != d1)
1677 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001678 # Note that the module name appears in str/repr, and that varies
1679 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001680 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001681 self.assertEqual(str(d1), repr(d1))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001682 self.assertTrue(-1 not in d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001683 for i in range(10):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001684 self.assertTrue(i in d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001685 self.assertFalse(10 in d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001686 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001687 class Proxy(object):
1688 def __init__(self, x):
1689 self.x = x
1690 def __bool__(self):
1691 return not not self.x
1692 def __hash__(self):
1693 return hash(self.x)
1694 def __eq__(self, other):
1695 return self.x == other
1696 def __ne__(self, other):
1697 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001698 def __ge__(self, other):
1699 return self.x >= other
1700 def __gt__(self, other):
1701 return self.x > other
1702 def __le__(self, other):
1703 return self.x <= other
1704 def __lt__(self, other):
1705 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001706 def __str__(self):
1707 return "Proxy:%s" % self.x
1708 def __repr__(self):
1709 return "Proxy(%r)" % self.x
1710 def __contains__(self, value):
1711 return value in self.x
1712 p0 = Proxy(0)
1713 p1 = Proxy(1)
1714 p_1 = Proxy(-1)
1715 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001716 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001717 self.assertEqual(hash(p0), hash(0))
1718 self.assertEqual(p0, p0)
1719 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001720 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001721 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001722 self.assertTrue(p0 < p1)
1723 self.assertTrue(p0 <= p1)
1724 self.assertTrue(p1 > p0)
1725 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001726 self.assertEqual(str(p0), "Proxy:0")
1727 self.assertEqual(repr(p0), "Proxy(0)")
1728 p10 = Proxy(range(10))
1729 self.assertFalse(-1 in p10)
1730 for i in range(10):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001731 self.assertTrue(i in p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001732 self.assertFalse(10 in p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001733
Georg Brandl479a7e72008-02-05 18:13:15 +00001734 def test_weakrefs(self):
1735 # Testing weak references...
1736 import weakref
1737 class C(object):
1738 pass
1739 c = C()
1740 r = weakref.ref(c)
1741 self.assertEqual(r(), c)
1742 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001743 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001744 self.assertEqual(r(), None)
1745 del r
1746 class NoWeak(object):
1747 __slots__ = ['foo']
1748 no = NoWeak()
1749 try:
1750 weakref.ref(no)
1751 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001752 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001753 else:
1754 self.fail("weakref.ref(no) should be illegal")
1755 class Weak(object):
1756 __slots__ = ['foo', '__weakref__']
1757 yes = Weak()
1758 r = weakref.ref(yes)
1759 self.assertEqual(r(), yes)
1760 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001761 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001762 self.assertEqual(r(), None)
1763 del r
1764
1765 def test_properties(self):
1766 # Testing property...
1767 class C(object):
1768 def getx(self):
1769 return self.__x
1770 def setx(self, value):
1771 self.__x = value
1772 def delx(self):
1773 del self.__x
1774 x = property(getx, setx, delx, doc="I'm the x property.")
1775 a = C()
1776 self.assertFalse(hasattr(a, "x"))
1777 a.x = 42
1778 self.assertEqual(a._C__x, 42)
1779 self.assertEqual(a.x, 42)
1780 del a.x
1781 self.assertFalse(hasattr(a, "x"))
1782 self.assertFalse(hasattr(a, "_C__x"))
1783 C.x.__set__(a, 100)
1784 self.assertEqual(C.x.__get__(a), 100)
1785 C.x.__delete__(a)
1786 self.assertFalse(hasattr(a, "x"))
1787
1788 raw = C.__dict__['x']
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001789 self.assertTrue(isinstance(raw, property))
Georg Brandl479a7e72008-02-05 18:13:15 +00001790
1791 attrs = dir(raw)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001792 self.assertTrue("__doc__" in attrs)
1793 self.assertTrue("fget" in attrs)
1794 self.assertTrue("fset" in attrs)
1795 self.assertTrue("fdel" in attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001796
1797 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001798 self.assertTrue(raw.fget is C.__dict__['getx'])
1799 self.assertTrue(raw.fset is C.__dict__['setx'])
1800 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001801
1802 for attr in "__doc__", "fget", "fset", "fdel":
1803 try:
1804 setattr(raw, attr, 42)
1805 except AttributeError as msg:
1806 if str(msg).find('readonly') < 0:
1807 self.fail("when setting readonly attr %r on a property, "
1808 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1809 else:
1810 self.fail("expected AttributeError from trying to set readonly %r "
1811 "attr on a property" % attr)
1812
1813 class D(object):
1814 __getitem__ = property(lambda s: 1/0)
1815
1816 d = D()
1817 try:
1818 for i in d:
1819 str(i)
1820 except ZeroDivisionError:
1821 pass
1822 else:
1823 self.fail("expected ZeroDivisionError from bad property")
1824
1825 class E(object):
1826 def getter(self):
1827 "getter method"
1828 return 0
1829 def setter(self_, value):
1830 "setter method"
1831 pass
1832 prop = property(getter)
1833 self.assertEqual(prop.__doc__, "getter method")
1834 prop2 = property(fset=setter)
1835 self.assertEqual(prop2.__doc__, None)
1836
1837 # this segfaulted in 2.5b2
1838 try:
1839 import _testcapi
1840 except ImportError:
1841 pass
1842 else:
1843 class X(object):
1844 p = property(_testcapi.test_with_docstring)
1845
1846 def test_properties_plus(self):
1847 class C(object):
1848 foo = property(doc="hello")
1849 @foo.getter
1850 def foo(self):
1851 return self._foo
1852 @foo.setter
1853 def foo(self, value):
1854 self._foo = abs(value)
1855 @foo.deleter
1856 def foo(self):
1857 del self._foo
1858 c = C()
1859 self.assertEqual(C.foo.__doc__, "hello")
1860 self.assertFalse(hasattr(c, "foo"))
1861 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001862 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00001863 self.assertEqual(c._foo, 42)
1864 self.assertEqual(c.foo, 42)
1865 del c.foo
1866 self.assertFalse(hasattr(c, '_foo'))
1867 self.assertFalse(hasattr(c, "foo"))
1868
1869 class D(C):
1870 @C.foo.deleter
1871 def foo(self):
1872 try:
1873 del self._foo
1874 except AttributeError:
1875 pass
1876 d = D()
1877 d.foo = 24
1878 self.assertEqual(d.foo, 24)
1879 del d.foo
1880 del d.foo
1881
1882 class E(object):
1883 @property
1884 def foo(self):
1885 return self._foo
1886 @foo.setter
1887 def foo(self, value):
1888 raise RuntimeError
1889 @foo.setter
1890 def foo(self, value):
1891 self._foo = abs(value)
1892 @foo.deleter
1893 def foo(self, value=None):
1894 del self._foo
1895
1896 e = E()
1897 e.foo = -42
1898 self.assertEqual(e.foo, 42)
1899 del e.foo
1900
1901 class F(E):
1902 @E.foo.deleter
1903 def foo(self):
1904 del self._foo
1905 @foo.setter
1906 def foo(self, value):
1907 self._foo = max(0, value)
1908 f = F()
1909 f.foo = -10
1910 self.assertEqual(f.foo, 0)
1911 del f.foo
1912
1913 def test_dict_constructors(self):
1914 # Testing dict constructor ...
1915 d = dict()
1916 self.assertEqual(d, {})
1917 d = dict({})
1918 self.assertEqual(d, {})
1919 d = dict({1: 2, 'a': 'b'})
1920 self.assertEqual(d, {1: 2, 'a': 'b'})
1921 self.assertEqual(d, dict(list(d.items())))
1922 self.assertEqual(d, dict(iter(d.items())))
1923 d = dict({'one':1, 'two':2})
1924 self.assertEqual(d, dict(one=1, two=2))
1925 self.assertEqual(d, dict(**d))
1926 self.assertEqual(d, dict({"one": 1}, two=2))
1927 self.assertEqual(d, dict([("two", 2)], one=1))
1928 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1929 self.assertEqual(d, dict(**d))
1930
1931 for badarg in 0, 0, 0j, "0", [0], (0,):
1932 try:
1933 dict(badarg)
1934 except TypeError:
1935 pass
1936 except ValueError:
1937 if badarg == "0":
1938 # It's a sequence, and its elements are also sequences (gotta
1939 # love strings <wink>), but they aren't of length 2, so this
1940 # one seemed better as a ValueError than a TypeError.
1941 pass
1942 else:
1943 self.fail("no TypeError from dict(%r)" % badarg)
1944 else:
1945 self.fail("no TypeError from dict(%r)" % badarg)
1946
1947 try:
1948 dict({}, {})
1949 except TypeError:
1950 pass
1951 else:
1952 self.fail("no TypeError from dict({}, {})")
1953
1954 class Mapping:
1955 # Lacks a .keys() method; will be added later.
1956 dict = {1:2, 3:4, 'a':1j}
1957
1958 try:
1959 dict(Mapping())
1960 except TypeError:
1961 pass
1962 else:
1963 self.fail("no TypeError from dict(incomplete mapping)")
1964
1965 Mapping.keys = lambda self: list(self.dict.keys())
1966 Mapping.__getitem__ = lambda self, i: self.dict[i]
1967 d = dict(Mapping())
1968 self.assertEqual(d, Mapping.dict)
1969
1970 # Init from sequence of iterable objects, each producing a 2-sequence.
1971 class AddressBookEntry:
1972 def __init__(self, first, last):
1973 self.first = first
1974 self.last = last
1975 def __iter__(self):
1976 return iter([self.first, self.last])
1977
1978 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1979 AddressBookEntry('Barry', 'Peters'),
1980 AddressBookEntry('Tim', 'Peters'),
1981 AddressBookEntry('Barry', 'Warsaw')])
1982 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1983
1984 d = dict(zip(range(4), range(1, 5)))
1985 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1986
1987 # Bad sequence lengths.
1988 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1989 try:
1990 dict(bad)
1991 except ValueError:
1992 pass
1993 else:
1994 self.fail("no ValueError from dict(%r)" % bad)
1995
1996 def test_dir(self):
1997 # Testing dir() ...
1998 junk = 12
1999 self.assertEqual(dir(), ['junk', 'self'])
2000 del junk
2001
2002 # Just make sure these don't blow up!
2003 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2004 dir(arg)
2005
2006 # Test dir on new-style classes. Since these have object as a
2007 # base class, a lot more gets sucked in.
2008 def interesting(strings):
2009 return [s for s in strings if not s.startswith('_')]
2010
2011 class C(object):
2012 Cdata = 1
2013 def Cmethod(self): pass
2014
2015 cstuff = ['Cdata', 'Cmethod']
2016 self.assertEqual(interesting(dir(C)), cstuff)
2017
2018 c = C()
2019 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002020 ## self.assertTrue('__self__' in dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002021
2022 c.cdata = 2
2023 c.cmethod = lambda self: 0
2024 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002025 ## self.assertTrue('__self__' in dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002026
2027 class A(C):
2028 Adata = 1
2029 def Amethod(self): pass
2030
2031 astuff = ['Adata', 'Amethod'] + cstuff
2032 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002033 ## self.assertTrue('__self__' in dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002034 a = A()
2035 self.assertEqual(interesting(dir(a)), astuff)
2036 a.adata = 42
2037 a.amethod = lambda self: 3
2038 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002039 ## self.assertTrue('__self__' in dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002040
2041 # Try a module subclass.
2042 import sys
2043 class M(type(sys)):
2044 pass
2045 minstance = M("m")
2046 minstance.b = 2
2047 minstance.a = 1
2048 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2049 self.assertEqual(names, ['a', 'b'])
2050
2051 class M2(M):
2052 def getdict(self):
2053 return "Not a dict!"
2054 __dict__ = property(getdict)
2055
2056 m2instance = M2("m2")
2057 m2instance.b = 2
2058 m2instance.a = 1
2059 self.assertEqual(m2instance.__dict__, "Not a dict!")
2060 try:
2061 dir(m2instance)
2062 except TypeError:
2063 pass
2064
2065 # Two essentially featureless objects, just inheriting stuff from
2066 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002067 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2068 if support.check_impl_detail():
2069 # None differs in PyPy: it has a __nonzero__
2070 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002071
2072 # Nasty test case for proxied objects
2073 class Wrapper(object):
2074 def __init__(self, obj):
2075 self.__obj = obj
2076 def __repr__(self):
2077 return "Wrapper(%s)" % repr(self.__obj)
2078 def __getitem__(self, key):
2079 return Wrapper(self.__obj[key])
2080 def __len__(self):
2081 return len(self.__obj)
2082 def __getattr__(self, name):
2083 return Wrapper(getattr(self.__obj, name))
2084
2085 class C(object):
2086 def __getclass(self):
2087 return Wrapper(type(self))
2088 __class__ = property(__getclass)
2089
2090 dir(C()) # This used to segfault
2091
2092 def test_supers(self):
2093 # Testing super...
2094
2095 class A(object):
2096 def meth(self, a):
2097 return "A(%r)" % a
2098
2099 self.assertEqual(A().meth(1), "A(1)")
2100
2101 class B(A):
2102 def __init__(self):
2103 self.__super = super(B, self)
2104 def meth(self, a):
2105 return "B(%r)" % a + self.__super.meth(a)
2106
2107 self.assertEqual(B().meth(2), "B(2)A(2)")
2108
2109 class C(A):
2110 def meth(self, a):
2111 return "C(%r)" % a + self.__super.meth(a)
2112 C._C__super = super(C)
2113
2114 self.assertEqual(C().meth(3), "C(3)A(3)")
2115
2116 class D(C, B):
2117 def meth(self, a):
2118 return "D(%r)" % a + super(D, self).meth(a)
2119
2120 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2121
2122 # Test for subclassing super
2123
2124 class mysuper(super):
2125 def __init__(self, *args):
2126 return super(mysuper, self).__init__(*args)
2127
2128 class E(D):
2129 def meth(self, a):
2130 return "E(%r)" % a + mysuper(E, self).meth(a)
2131
2132 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2133
2134 class F(E):
2135 def meth(self, a):
2136 s = self.__super # == mysuper(F, self)
2137 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2138 F._F__super = mysuper(F)
2139
2140 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2141
2142 # Make sure certain errors are raised
2143
2144 try:
2145 super(D, 42)
2146 except TypeError:
2147 pass
2148 else:
2149 self.fail("shouldn't allow super(D, 42)")
2150
2151 try:
2152 super(D, C())
2153 except TypeError:
2154 pass
2155 else:
2156 self.fail("shouldn't allow super(D, C())")
2157
2158 try:
2159 super(D).__get__(12)
2160 except TypeError:
2161 pass
2162 else:
2163 self.fail("shouldn't allow super(D).__get__(12)")
2164
2165 try:
2166 super(D).__get__(C())
2167 except TypeError:
2168 pass
2169 else:
2170 self.fail("shouldn't allow super(D).__get__(C())")
2171
2172 # Make sure data descriptors can be overridden and accessed via super
2173 # (new feature in Python 2.3)
2174
2175 class DDbase(object):
2176 def getx(self): return 42
2177 x = property(getx)
2178
2179 class DDsub(DDbase):
2180 def getx(self): return "hello"
2181 x = property(getx)
2182
2183 dd = DDsub()
2184 self.assertEqual(dd.x, "hello")
2185 self.assertEqual(super(DDsub, dd).x, 42)
2186
2187 # Ensure that super() lookup of descriptor from classmethod
2188 # works (SF ID# 743627)
2189
2190 class Base(object):
2191 aProp = property(lambda self: "foo")
2192
2193 class Sub(Base):
2194 @classmethod
2195 def test(klass):
2196 return super(Sub,klass).aProp
2197
2198 self.assertEqual(Sub.test(), Base.aProp)
2199
2200 # Verify that super() doesn't allow keyword args
2201 try:
2202 super(Base, kw=1)
2203 except TypeError:
2204 pass
2205 else:
2206 self.assertEqual("super shouldn't accept keyword args")
2207
2208 def test_basic_inheritance(self):
2209 # Testing inheritance from basic types...
2210
2211 class hexint(int):
2212 def __repr__(self):
2213 return hex(self)
2214 def __add__(self, other):
2215 return hexint(int.__add__(self, other))
2216 # (Note that overriding __radd__ doesn't work,
2217 # because the int type gets first dibs.)
2218 self.assertEqual(repr(hexint(7) + 9), "0x10")
2219 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2220 a = hexint(12345)
2221 self.assertEqual(a, 12345)
2222 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002223 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002224 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002225 self.assertTrue((+a).__class__ is int)
2226 self.assertTrue((a >> 0).__class__ is int)
2227 self.assertTrue((a << 0).__class__ is int)
2228 self.assertTrue((hexint(0) << 12).__class__ is int)
2229 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002230
2231 class octlong(int):
2232 __slots__ = []
2233 def __str__(self):
2234 s = oct(self)
2235 if s[-1] == 'L':
2236 s = s[:-1]
2237 return s
2238 def __add__(self, other):
2239 return self.__class__(super(octlong, self).__add__(other))
2240 __radd__ = __add__
2241 self.assertEqual(str(octlong(3) + 5), "0o10")
2242 # (Note that overriding __radd__ here only seems to work
2243 # because the example uses a short int left argument.)
2244 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2245 a = octlong(12345)
2246 self.assertEqual(a, 12345)
2247 self.assertEqual(int(a), 12345)
2248 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002249 self.assertTrue(int(a).__class__ is int)
2250 self.assertTrue((+a).__class__ is int)
2251 self.assertTrue((-a).__class__ is int)
2252 self.assertTrue((-octlong(0)).__class__ is int)
2253 self.assertTrue((a >> 0).__class__ is int)
2254 self.assertTrue((a << 0).__class__ is int)
2255 self.assertTrue((a - 0).__class__ is int)
2256 self.assertTrue((a * 1).__class__ is int)
2257 self.assertTrue((a ** 1).__class__ is int)
2258 self.assertTrue((a // 1).__class__ is int)
2259 self.assertTrue((1 * a).__class__ is int)
2260 self.assertTrue((a | 0).__class__ is int)
2261 self.assertTrue((a ^ 0).__class__ is int)
2262 self.assertTrue((a & -1).__class__ is int)
2263 self.assertTrue((octlong(0) << 12).__class__ is int)
2264 self.assertTrue((octlong(0) >> 12).__class__ is int)
2265 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002266
2267 # Because octlong overrides __add__, we can't check the absence of +0
2268 # optimizations using octlong.
2269 class longclone(int):
2270 pass
2271 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002272 self.assertTrue((a + 0).__class__ is int)
2273 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002274
2275 # Check that negative clones don't segfault
2276 a = longclone(-1)
2277 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002278 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002279
2280 class precfloat(float):
2281 __slots__ = ['prec']
2282 def __init__(self, value=0.0, prec=12):
2283 self.prec = int(prec)
2284 def __repr__(self):
2285 return "%.*g" % (self.prec, self)
2286 self.assertEqual(repr(precfloat(1.1)), "1.1")
2287 a = precfloat(12345)
2288 self.assertEqual(a, 12345.0)
2289 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002290 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002291 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002292 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002293
2294 class madcomplex(complex):
2295 def __repr__(self):
2296 return "%.17gj%+.17g" % (self.imag, self.real)
2297 a = madcomplex(-3, 4)
2298 self.assertEqual(repr(a), "4j-3")
2299 base = complex(-3, 4)
2300 self.assertEqual(base.__class__, complex)
2301 self.assertEqual(a, base)
2302 self.assertEqual(complex(a), base)
2303 self.assertEqual(complex(a).__class__, complex)
2304 a = madcomplex(a) # just trying another form of the constructor
2305 self.assertEqual(repr(a), "4j-3")
2306 self.assertEqual(a, base)
2307 self.assertEqual(complex(a), base)
2308 self.assertEqual(complex(a).__class__, complex)
2309 self.assertEqual(hash(a), hash(base))
2310 self.assertEqual((+a).__class__, complex)
2311 self.assertEqual((a + 0).__class__, complex)
2312 self.assertEqual(a + 0, base)
2313 self.assertEqual((a - 0).__class__, complex)
2314 self.assertEqual(a - 0, base)
2315 self.assertEqual((a * 1).__class__, complex)
2316 self.assertEqual(a * 1, base)
2317 self.assertEqual((a / 1).__class__, complex)
2318 self.assertEqual(a / 1, base)
2319
2320 class madtuple(tuple):
2321 _rev = None
2322 def rev(self):
2323 if self._rev is not None:
2324 return self._rev
2325 L = list(self)
2326 L.reverse()
2327 self._rev = self.__class__(L)
2328 return self._rev
2329 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2330 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2331 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2332 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2333 for i in range(512):
2334 t = madtuple(range(i))
2335 u = t.rev()
2336 v = u.rev()
2337 self.assertEqual(v, t)
2338 a = madtuple((1,2,3,4,5))
2339 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002340 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002341 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002342 self.assertTrue(a[:].__class__ is tuple)
2343 self.assertTrue((a * 1).__class__ is tuple)
2344 self.assertTrue((a * 0).__class__ is tuple)
2345 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002346 a = madtuple(())
2347 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002348 self.assertTrue(tuple(a).__class__ is tuple)
2349 self.assertTrue((a + a).__class__ is tuple)
2350 self.assertTrue((a * 0).__class__ is tuple)
2351 self.assertTrue((a * 1).__class__ is tuple)
2352 self.assertTrue((a * 2).__class__ is tuple)
2353 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002354
2355 class madstring(str):
2356 _rev = None
2357 def rev(self):
2358 if self._rev is not None:
2359 return self._rev
2360 L = list(self)
2361 L.reverse()
2362 self._rev = self.__class__("".join(L))
2363 return self._rev
2364 s = madstring("abcdefghijklmnopqrstuvwxyz")
2365 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2366 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2367 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2368 for i in range(256):
2369 s = madstring("".join(map(chr, range(i))))
2370 t = s.rev()
2371 u = t.rev()
2372 self.assertEqual(u, s)
2373 s = madstring("12345")
2374 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002375 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002376
2377 base = "\x00" * 5
2378 s = madstring(base)
2379 self.assertEqual(s, base)
2380 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002381 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002382 self.assertEqual(hash(s), hash(base))
2383 self.assertEqual({s: 1}[base], 1)
2384 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002385 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002386 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002387 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002388 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002389 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002390 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002391 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002392 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002393 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002394 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002395 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002396 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002397 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002398 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002399 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002400 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002401 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002402 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002403 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002404 self.assertEqual(s.rstrip(), base)
2405 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002406 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002407 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002408 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002409 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002410 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002411 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002412 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002413 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002414 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002415 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002416 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002417 self.assertEqual(s.lower(), base)
2418
2419 class madunicode(str):
2420 _rev = None
2421 def rev(self):
2422 if self._rev is not None:
2423 return self._rev
2424 L = list(self)
2425 L.reverse()
2426 self._rev = self.__class__("".join(L))
2427 return self._rev
2428 u = madunicode("ABCDEF")
2429 self.assertEqual(u, "ABCDEF")
2430 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2431 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2432 base = "12345"
2433 u = madunicode(base)
2434 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002435 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002436 self.assertEqual(hash(u), hash(base))
2437 self.assertEqual({u: 1}[base], 1)
2438 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002439 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002440 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002441 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002442 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002443 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002444 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002445 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002446 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002447 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002448 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002449 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002450 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002451 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002452 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002453 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002454 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002455 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002456 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002457 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002458 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002459 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002460 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002461 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002462 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002463 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002464 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002465 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002466 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002467 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002468 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002469 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002470 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002471 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002472 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002473 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002474 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002475 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002476 self.assertEqual(u[0:0], "")
2477
2478 class sublist(list):
2479 pass
2480 a = sublist(range(5))
2481 self.assertEqual(a, list(range(5)))
2482 a.append("hello")
2483 self.assertEqual(a, list(range(5)) + ["hello"])
2484 a[5] = 5
2485 self.assertEqual(a, list(range(6)))
2486 a.extend(range(6, 20))
2487 self.assertEqual(a, list(range(20)))
2488 a[-5:] = []
2489 self.assertEqual(a, list(range(15)))
2490 del a[10:15]
2491 self.assertEqual(len(a), 10)
2492 self.assertEqual(a, list(range(10)))
2493 self.assertEqual(list(a), list(range(10)))
2494 self.assertEqual(a[0], 0)
2495 self.assertEqual(a[9], 9)
2496 self.assertEqual(a[-10], 0)
2497 self.assertEqual(a[-1], 9)
2498 self.assertEqual(a[:5], list(range(5)))
2499
2500 ## class CountedInput(file):
2501 ## """Counts lines read by self.readline().
2502 ##
2503 ## self.lineno is the 0-based ordinal of the last line read, up to
2504 ## a maximum of one greater than the number of lines in the file.
2505 ##
2506 ## self.ateof is true if and only if the final "" line has been read,
2507 ## at which point self.lineno stops incrementing, and further calls
2508 ## to readline() continue to return "".
2509 ## """
2510 ##
2511 ## lineno = 0
2512 ## ateof = 0
2513 ## def readline(self):
2514 ## if self.ateof:
2515 ## return ""
2516 ## s = file.readline(self)
2517 ## # Next line works too.
2518 ## # s = super(CountedInput, self).readline()
2519 ## self.lineno += 1
2520 ## if s == "":
2521 ## self.ateof = 1
2522 ## return s
2523 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002524 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002525 ## lines = ['a\n', 'b\n', 'c\n']
2526 ## try:
2527 ## f.writelines(lines)
2528 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002529 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002530 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2531 ## got = f.readline()
2532 ## self.assertEqual(expected, got)
2533 ## self.assertEqual(f.lineno, i)
2534 ## self.assertEqual(f.ateof, (i > len(lines)))
2535 ## f.close()
2536 ## finally:
2537 ## try:
2538 ## f.close()
2539 ## except:
2540 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002541 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002542
2543 def test_keywords(self):
2544 # Testing keyword args to basic type constructors ...
2545 self.assertEqual(int(x=1), 1)
2546 self.assertEqual(float(x=2), 2.0)
2547 self.assertEqual(int(x=3), 3)
2548 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2549 self.assertEqual(str(object=500), '500')
2550 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2551 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2552 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2553 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2554
2555 for constructor in (int, float, int, complex, str, str,
2556 tuple, list):
2557 try:
2558 constructor(bogus_keyword_arg=1)
2559 except TypeError:
2560 pass
2561 else:
2562 self.fail("expected TypeError from bogus keyword argument to %r"
2563 % constructor)
2564
2565 def test_str_subclass_as_dict_key(self):
2566 # Testing a str subclass used as dict key ..
2567
2568 class cistr(str):
2569 """Sublcass of str that computes __eq__ case-insensitively.
2570
2571 Also computes a hash code of the string in canonical form.
2572 """
2573
2574 def __init__(self, value):
2575 self.canonical = value.lower()
2576 self.hashcode = hash(self.canonical)
2577
2578 def __eq__(self, other):
2579 if not isinstance(other, cistr):
2580 other = cistr(other)
2581 return self.canonical == other.canonical
2582
2583 def __hash__(self):
2584 return self.hashcode
2585
2586 self.assertEqual(cistr('ABC'), 'abc')
2587 self.assertEqual('aBc', cistr('ABC'))
2588 self.assertEqual(str(cistr('ABC')), 'ABC')
2589
2590 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2591 self.assertEqual(d[cistr('one')], 1)
2592 self.assertEqual(d[cistr('tWo')], 2)
2593 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002594 self.assertTrue(cistr('ONe') in d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002595 self.assertEqual(d.get(cistr('thrEE')), 3)
2596
2597 def test_classic_comparisons(self):
2598 # Testing classic comparisons...
2599 class classic:
2600 pass
2601
2602 for base in (classic, int, object):
2603 class C(base):
2604 def __init__(self, value):
2605 self.value = int(value)
2606 def __eq__(self, other):
2607 if isinstance(other, C):
2608 return self.value == other.value
2609 if isinstance(other, int) or isinstance(other, int):
2610 return self.value == other
2611 return NotImplemented
2612 def __ne__(self, other):
2613 if isinstance(other, C):
2614 return self.value != other.value
2615 if isinstance(other, int) or isinstance(other, int):
2616 return self.value != other
2617 return NotImplemented
2618 def __lt__(self, other):
2619 if isinstance(other, C):
2620 return self.value < other.value
2621 if isinstance(other, int) or isinstance(other, int):
2622 return self.value < other
2623 return NotImplemented
2624 def __le__(self, other):
2625 if isinstance(other, C):
2626 return self.value <= other.value
2627 if isinstance(other, int) or isinstance(other, int):
2628 return self.value <= other
2629 return NotImplemented
2630 def __gt__(self, other):
2631 if isinstance(other, C):
2632 return self.value > other.value
2633 if isinstance(other, int) or isinstance(other, int):
2634 return self.value > other
2635 return NotImplemented
2636 def __ge__(self, other):
2637 if isinstance(other, C):
2638 return self.value >= other.value
2639 if isinstance(other, int) or isinstance(other, int):
2640 return self.value >= other
2641 return NotImplemented
2642
2643 c1 = C(1)
2644 c2 = C(2)
2645 c3 = C(3)
2646 self.assertEqual(c1, 1)
2647 c = {1: c1, 2: c2, 3: c3}
2648 for x in 1, 2, 3:
2649 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002651 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002652 eval("x %s y" % op),
2653 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002654 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002655 eval("x %s y" % op),
2656 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002657 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002658 eval("x %s y" % op),
2659 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002660
2661 def test_rich_comparisons(self):
2662 # Testing rich comparisons...
2663 class Z(complex):
2664 pass
2665 z = Z(1)
2666 self.assertEqual(z, 1+0j)
2667 self.assertEqual(1+0j, z)
2668 class ZZ(complex):
2669 def __eq__(self, other):
2670 try:
2671 return abs(self - other) <= 1e-6
2672 except:
2673 return NotImplemented
2674 zz = ZZ(1.0000003)
2675 self.assertEqual(zz, 1+0j)
2676 self.assertEqual(1+0j, zz)
2677
2678 class classic:
2679 pass
2680 for base in (classic, int, object, list):
2681 class C(base):
2682 def __init__(self, value):
2683 self.value = int(value)
2684 def __cmp__(self_, other):
2685 self.fail("shouldn't call __cmp__")
2686 def __eq__(self, other):
2687 if isinstance(other, C):
2688 return self.value == other.value
2689 if isinstance(other, int) or isinstance(other, int):
2690 return self.value == other
2691 return NotImplemented
2692 def __ne__(self, other):
2693 if isinstance(other, C):
2694 return self.value != other.value
2695 if isinstance(other, int) or isinstance(other, int):
2696 return self.value != other
2697 return NotImplemented
2698 def __lt__(self, other):
2699 if isinstance(other, C):
2700 return self.value < other.value
2701 if isinstance(other, int) or isinstance(other, int):
2702 return self.value < other
2703 return NotImplemented
2704 def __le__(self, other):
2705 if isinstance(other, C):
2706 return self.value <= other.value
2707 if isinstance(other, int) or isinstance(other, int):
2708 return self.value <= other
2709 return NotImplemented
2710 def __gt__(self, other):
2711 if isinstance(other, C):
2712 return self.value > other.value
2713 if isinstance(other, int) or isinstance(other, int):
2714 return self.value > other
2715 return NotImplemented
2716 def __ge__(self, other):
2717 if isinstance(other, C):
2718 return self.value >= other.value
2719 if isinstance(other, int) or isinstance(other, int):
2720 return self.value >= other
2721 return NotImplemented
2722 c1 = C(1)
2723 c2 = C(2)
2724 c3 = C(3)
2725 self.assertEqual(c1, 1)
2726 c = {1: c1, 2: c2, 3: c3}
2727 for x in 1, 2, 3:
2728 for y in 1, 2, 3:
2729 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002730 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002731 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002732 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002733 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002734 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002735 "x=%d, y=%d" % (x, y))
2736
2737 def test_descrdoc(self):
2738 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002739 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002740 def check(descr, what):
2741 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002742 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002743 check(complex.real, "the real part of a complex number") # member descriptor
2744
2745 def test_doc_descriptor(self):
2746 # Testing __doc__ descriptor...
2747 # SF bug 542984
2748 class DocDescr(object):
2749 def __get__(self, object, otype):
2750 if object:
2751 object = object.__class__.__name__ + ' instance'
2752 if otype:
2753 otype = otype.__name__
2754 return 'object=%s; type=%s' % (object, otype)
2755 class OldClass:
2756 __doc__ = DocDescr()
2757 class NewClass(object):
2758 __doc__ = DocDescr()
2759 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2760 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2761 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2762 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2763
2764 def test_set_class(self):
2765 # Testing __class__ assignment...
2766 class C(object): pass
2767 class D(object): pass
2768 class E(object): pass
2769 class F(D, E): pass
2770 for cls in C, D, E, F:
2771 for cls2 in C, D, E, F:
2772 x = cls()
2773 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002774 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002775 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002776 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002777 def cant(x, C):
2778 try:
2779 x.__class__ = C
2780 except TypeError:
2781 pass
2782 else:
2783 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2784 try:
2785 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002786 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002787 pass
2788 else:
2789 self.fail("shouldn't allow del %r.__class__" % x)
2790 cant(C(), list)
2791 cant(list(), C)
2792 cant(C(), 1)
2793 cant(C(), object)
2794 cant(object(), list)
2795 cant(list(), object)
2796 class Int(int): __slots__ = []
2797 cant(2, Int)
2798 cant(Int(), int)
2799 cant(True, int)
2800 cant(2, bool)
2801 o = object()
2802 cant(o, type(1))
2803 cant(o, type(None))
2804 del o
2805 class G(object):
2806 __slots__ = ["a", "b"]
2807 class H(object):
2808 __slots__ = ["b", "a"]
2809 class I(object):
2810 __slots__ = ["a", "b"]
2811 class J(object):
2812 __slots__ = ["c", "b"]
2813 class K(object):
2814 __slots__ = ["a", "b", "d"]
2815 class L(H):
2816 __slots__ = ["e"]
2817 class M(I):
2818 __slots__ = ["e"]
2819 class N(J):
2820 __slots__ = ["__weakref__"]
2821 class P(J):
2822 __slots__ = ["__dict__"]
2823 class Q(J):
2824 pass
2825 class R(J):
2826 __slots__ = ["__dict__", "__weakref__"]
2827
2828 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2829 x = cls()
2830 x.a = 1
2831 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002832 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00002833 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2834 self.assertEqual(x.a, 1)
2835 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002836 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00002837 "assigning %r as __class__ for %r silently failed" % (cls, x))
2838 self.assertEqual(x.a, 1)
2839 for cls in G, J, K, L, M, N, P, R, list, Int:
2840 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2841 if cls is cls2:
2842 continue
2843 cant(cls(), cls2)
2844
Benjamin Peterson193152c2009-04-25 01:08:45 +00002845 # Issue5283: when __class__ changes in __del__, the wrong
2846 # type gets DECREF'd.
2847 class O(object):
2848 pass
2849 class A(object):
2850 def __del__(self):
2851 self.__class__ = O
2852 l = [A() for x in range(100)]
2853 del l
2854
Georg Brandl479a7e72008-02-05 18:13:15 +00002855 def test_set_dict(self):
2856 # Testing __dict__ assignment...
2857 class C(object): pass
2858 a = C()
2859 a.__dict__ = {'b': 1}
2860 self.assertEqual(a.b, 1)
2861 def cant(x, dict):
2862 try:
2863 x.__dict__ = dict
2864 except (AttributeError, TypeError):
2865 pass
2866 else:
2867 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2868 cant(a, None)
2869 cant(a, [])
2870 cant(a, 1)
2871 del a.__dict__ # Deleting __dict__ is allowed
2872
2873 class Base(object):
2874 pass
2875 def verify_dict_readonly(x):
2876 """
2877 x has to be an instance of a class inheriting from Base.
2878 """
2879 cant(x, {})
2880 try:
2881 del x.__dict__
2882 except (AttributeError, TypeError):
2883 pass
2884 else:
2885 self.fail("shouldn't allow del %r.__dict__" % x)
2886 dict_descr = Base.__dict__["__dict__"]
2887 try:
2888 dict_descr.__set__(x, {})
2889 except (AttributeError, TypeError):
2890 pass
2891 else:
2892 self.fail("dict_descr allowed access to %r's dict" % x)
2893
2894 # Classes don't allow __dict__ assignment and have readonly dicts
2895 class Meta1(type, Base):
2896 pass
2897 class Meta2(Base, type):
2898 pass
2899 class D(object, metaclass=Meta1):
2900 pass
2901 class E(object, metaclass=Meta2):
2902 pass
2903 for cls in C, D, E:
2904 verify_dict_readonly(cls)
2905 class_dict = cls.__dict__
2906 try:
2907 class_dict["spam"] = "eggs"
2908 except TypeError:
2909 pass
2910 else:
2911 self.fail("%r's __dict__ can be modified" % cls)
2912
2913 # Modules also disallow __dict__ assignment
2914 class Module1(types.ModuleType, Base):
2915 pass
2916 class Module2(Base, types.ModuleType):
2917 pass
2918 for ModuleType in Module1, Module2:
2919 mod = ModuleType("spam")
2920 verify_dict_readonly(mod)
2921 mod.__dict__["spam"] = "eggs"
2922
2923 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002924 # (at least not any more than regular exception's __dict__ can
2925 # be deleted; on CPython it is not the case, whereas on PyPy they
2926 # can, just like any other new-style instance's __dict__.)
2927 def can_delete_dict(e):
2928 try:
2929 del e.__dict__
2930 except (TypeError, AttributeError):
2931 return False
2932 else:
2933 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002934 class Exception1(Exception, Base):
2935 pass
2936 class Exception2(Base, Exception):
2937 pass
2938 for ExceptionType in Exception, Exception1, Exception2:
2939 e = ExceptionType()
2940 e.__dict__ = {"a": 1}
2941 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002942 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002943
2944 def test_pickles(self):
2945 # Testing pickling and copying new-style classes and objects...
2946 import pickle
2947
2948 def sorteditems(d):
2949 L = list(d.items())
2950 L.sort()
2951 return L
2952
2953 global C
2954 class C(object):
2955 def __init__(self, a, b):
2956 super(C, self).__init__()
2957 self.a = a
2958 self.b = b
2959 def __repr__(self):
2960 return "C(%r, %r)" % (self.a, self.b)
2961
2962 global C1
2963 class C1(list):
2964 def __new__(cls, a, b):
2965 return super(C1, cls).__new__(cls)
2966 def __getnewargs__(self):
2967 return (self.a, self.b)
2968 def __init__(self, a, b):
2969 self.a = a
2970 self.b = b
2971 def __repr__(self):
2972 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2973
2974 global C2
2975 class C2(int):
2976 def __new__(cls, a, b, val=0):
2977 return super(C2, cls).__new__(cls, val)
2978 def __getnewargs__(self):
2979 return (self.a, self.b, int(self))
2980 def __init__(self, a, b, val=0):
2981 self.a = a
2982 self.b = b
2983 def __repr__(self):
2984 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2985
2986 global C3
2987 class C3(object):
2988 def __init__(self, foo):
2989 self.foo = foo
2990 def __getstate__(self):
2991 return self.foo
2992 def __setstate__(self, foo):
2993 self.foo = foo
2994
2995 global C4classic, C4
2996 class C4classic: # classic
2997 pass
2998 class C4(C4classic, object): # mixed inheritance
2999 pass
3000
Guido van Rossum3926a632001-09-25 16:25:58 +00003001 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003002 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003003 s = pickle.dumps(cls, bin)
3004 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003005 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003006
3007 a = C1(1, 2); a.append(42); a.append(24)
3008 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003009 s = pickle.dumps((a, b), bin)
3010 x, y = pickle.loads(s)
3011 self.assertEqual(x.__class__, a.__class__)
3012 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3013 self.assertEqual(y.__class__, b.__class__)
3014 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3015 self.assertEqual(repr(x), repr(a))
3016 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003017 # Test for __getstate__ and __setstate__ on new style class
3018 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003019 s = pickle.dumps(u, bin)
3020 v = pickle.loads(s)
3021 self.assertEqual(u.__class__, v.__class__)
3022 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003023 # Test for picklability of hybrid class
3024 u = C4()
3025 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003026 s = pickle.dumps(u, bin)
3027 v = pickle.loads(s)
3028 self.assertEqual(u.__class__, v.__class__)
3029 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003030
Georg Brandl479a7e72008-02-05 18:13:15 +00003031 # Testing copy.deepcopy()
3032 import copy
3033 for cls in C, C1, C2:
3034 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003035 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003036
Georg Brandl479a7e72008-02-05 18:13:15 +00003037 a = C1(1, 2); a.append(42); a.append(24)
3038 b = C2("hello", "world", 42)
3039 x, y = copy.deepcopy((a, b))
3040 self.assertEqual(x.__class__, a.__class__)
3041 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3042 self.assertEqual(y.__class__, b.__class__)
3043 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3044 self.assertEqual(repr(x), repr(a))
3045 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003046
Georg Brandl479a7e72008-02-05 18:13:15 +00003047 def test_pickle_slots(self):
3048 # Testing pickling of classes with __slots__ ...
3049 import pickle
3050 # Pickling of classes with __slots__ but without __getstate__ should fail
3051 # (if using protocol 0 or 1)
3052 global B, C, D, E
3053 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003054 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003055 for base in [object, B]:
3056 class C(base):
3057 __slots__ = ['a']
3058 class D(C):
3059 pass
3060 try:
3061 pickle.dumps(C(), 0)
3062 except TypeError:
3063 pass
3064 else:
3065 self.fail("should fail: pickle C instance - %s" % base)
3066 try:
3067 pickle.dumps(C(), 0)
3068 except TypeError:
3069 pass
3070 else:
3071 self.fail("should fail: pickle D instance - %s" % base)
3072 # Give C a nice generic __getstate__ and __setstate__
3073 class C(base):
3074 __slots__ = ['a']
3075 def __getstate__(self):
3076 try:
3077 d = self.__dict__.copy()
3078 except AttributeError:
3079 d = {}
3080 for cls in self.__class__.__mro__:
3081 for sn in cls.__dict__.get('__slots__', ()):
3082 try:
3083 d[sn] = getattr(self, sn)
3084 except AttributeError:
3085 pass
3086 return d
3087 def __setstate__(self, d):
3088 for k, v in list(d.items()):
3089 setattr(self, k, v)
3090 class D(C):
3091 pass
3092 # Now it should work
3093 x = C()
3094 y = pickle.loads(pickle.dumps(x))
3095 self.assertEqual(hasattr(y, 'a'), 0)
3096 x.a = 42
3097 y = pickle.loads(pickle.dumps(x))
3098 self.assertEqual(y.a, 42)
3099 x = D()
3100 x.a = 42
3101 x.b = 100
3102 y = pickle.loads(pickle.dumps(x))
3103 self.assertEqual(y.a + y.b, 142)
3104 # A subclass that adds a slot should also work
3105 class E(C):
3106 __slots__ = ['b']
3107 x = E()
3108 x.a = 42
3109 x.b = "foo"
3110 y = pickle.loads(pickle.dumps(x))
3111 self.assertEqual(y.a, x.a)
3112 self.assertEqual(y.b, x.b)
3113
3114 def test_binary_operator_override(self):
3115 # Testing overrides of binary operations...
3116 class I(int):
3117 def __repr__(self):
3118 return "I(%r)" % int(self)
3119 def __add__(self, other):
3120 return I(int(self) + int(other))
3121 __radd__ = __add__
3122 def __pow__(self, other, mod=None):
3123 if mod is None:
3124 return I(pow(int(self), int(other)))
3125 else:
3126 return I(pow(int(self), int(other), int(mod)))
3127 def __rpow__(self, other, mod=None):
3128 if mod is None:
3129 return I(pow(int(other), int(self), mod))
3130 else:
3131 return I(pow(int(other), int(self), int(mod)))
3132
3133 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3134 self.assertEqual(repr(I(1) + 2), "I(3)")
3135 self.assertEqual(repr(1 + I(2)), "I(3)")
3136 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3137 self.assertEqual(repr(2 ** I(3)), "I(8)")
3138 self.assertEqual(repr(I(2) ** 3), "I(8)")
3139 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3140 class S(str):
3141 def __eq__(self, other):
3142 return self.lower() == other.lower()
3143
3144 def test_subclass_propagation(self):
3145 # Testing propagation of slot functions to subclasses...
3146 class A(object):
3147 pass
3148 class B(A):
3149 pass
3150 class C(A):
3151 pass
3152 class D(B, C):
3153 pass
3154 d = D()
3155 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3156 A.__hash__ = lambda self: 42
3157 self.assertEqual(hash(d), 42)
3158 C.__hash__ = lambda self: 314
3159 self.assertEqual(hash(d), 314)
3160 B.__hash__ = lambda self: 144
3161 self.assertEqual(hash(d), 144)
3162 D.__hash__ = lambda self: 100
3163 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003164 D.__hash__ = None
3165 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003166 del D.__hash__
3167 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003168 B.__hash__ = None
3169 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003170 del B.__hash__
3171 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003172 C.__hash__ = None
3173 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003174 del C.__hash__
3175 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003176 A.__hash__ = None
3177 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003178 del A.__hash__
3179 self.assertEqual(hash(d), orig_hash)
3180 d.foo = 42
3181 d.bar = 42
3182 self.assertEqual(d.foo, 42)
3183 self.assertEqual(d.bar, 42)
3184 def __getattribute__(self, name):
3185 if name == "foo":
3186 return 24
3187 return object.__getattribute__(self, name)
3188 A.__getattribute__ = __getattribute__
3189 self.assertEqual(d.foo, 24)
3190 self.assertEqual(d.bar, 42)
3191 def __getattr__(self, name):
3192 if name in ("spam", "foo", "bar"):
3193 return "hello"
3194 raise AttributeError(name)
3195 B.__getattr__ = __getattr__
3196 self.assertEqual(d.spam, "hello")
3197 self.assertEqual(d.foo, 24)
3198 self.assertEqual(d.bar, 42)
3199 del A.__getattribute__
3200 self.assertEqual(d.foo, 42)
3201 del d.foo
3202 self.assertEqual(d.foo, "hello")
3203 self.assertEqual(d.bar, 42)
3204 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003205 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003206 d.foo
3207 except AttributeError:
3208 pass
3209 else:
3210 self.fail("d.foo should be undefined now")
3211
3212 # Test a nasty bug in recurse_down_subclasses()
3213 import gc
3214 class A(object):
3215 pass
3216 class B(A):
3217 pass
3218 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003219 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003220 A.__setitem__ = lambda *a: None # crash
3221
3222 def test_buffer_inheritance(self):
3223 # Testing that buffer interface is inherited ...
3224
3225 import binascii
3226 # SF bug [#470040] ParseTuple t# vs subclasses.
3227
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003228 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003229 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003230 base = b'abc'
3231 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003232 # b2a_hex uses the buffer interface to get its argument's value, via
3233 # PyArg_ParseTuple 't#' code.
3234 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3235
Georg Brandl479a7e72008-02-05 18:13:15 +00003236 class MyInt(int):
3237 pass
3238 m = MyInt(42)
3239 try:
3240 binascii.b2a_hex(m)
3241 self.fail('subclass of int should not have a buffer interface')
3242 except TypeError:
3243 pass
3244
3245 def test_str_of_str_subclass(self):
3246 # Testing __str__ defined in subclass of str ...
3247 import binascii
3248 import io
3249
3250 class octetstring(str):
3251 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003252 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003253 def __repr__(self):
3254 return self + " repr"
3255
3256 o = octetstring('A')
3257 self.assertEqual(type(o), octetstring)
3258 self.assertEqual(type(str(o)), str)
3259 self.assertEqual(type(repr(o)), str)
3260 self.assertEqual(ord(o), 0x41)
3261 self.assertEqual(str(o), '41')
3262 self.assertEqual(repr(o), 'A repr')
3263 self.assertEqual(o.__str__(), '41')
3264 self.assertEqual(o.__repr__(), 'A repr')
3265
3266 capture = io.StringIO()
3267 # Calling str() or not exercises different internal paths.
3268 print(o, file=capture)
3269 print(str(o), file=capture)
3270 self.assertEqual(capture.getvalue(), '41\n41\n')
3271 capture.close()
3272
3273 def test_keyword_arguments(self):
3274 # Testing keyword arguments to __init__, __call__...
3275 def f(a): return a
3276 self.assertEqual(f.__call__(a=42), 42)
3277 a = []
3278 list.__init__(a, sequence=[0, 1, 2])
3279 self.assertEqual(a, [0, 1, 2])
3280
3281 def test_recursive_call(self):
3282 # Testing recursive __call__() by setting to instance of class...
3283 class A(object):
3284 pass
3285
3286 A.__call__ = A()
3287 try:
3288 A()()
3289 except RuntimeError:
3290 pass
3291 else:
3292 self.fail("Recursion limit should have been reached for __call__()")
3293
3294 def test_delete_hook(self):
3295 # Testing __del__ hook...
3296 log = []
3297 class C(object):
3298 def __del__(self):
3299 log.append(1)
3300 c = C()
3301 self.assertEqual(log, [])
3302 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003303 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003304 self.assertEqual(log, [1])
3305
3306 class D(object): pass
3307 d = D()
3308 try: del d[0]
3309 except TypeError: pass
3310 else: self.fail("invalid del() didn't raise TypeError")
3311
3312 def test_hash_inheritance(self):
3313 # Testing hash of mutable subclasses...
3314
3315 class mydict(dict):
3316 pass
3317 d = mydict()
3318 try:
3319 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003320 except TypeError:
3321 pass
3322 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003323 self.fail("hash() of dict subclass should fail")
3324
3325 class mylist(list):
3326 pass
3327 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003328 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003329 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003330 except TypeError:
3331 pass
3332 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003333 self.fail("hash() of list subclass should fail")
3334
3335 def test_str_operations(self):
3336 try: 'a' + 5
3337 except TypeError: pass
3338 else: self.fail("'' + 5 doesn't raise TypeError")
3339
3340 try: ''.split('')
3341 except ValueError: pass
3342 else: self.fail("''.split('') doesn't raise ValueError")
3343
3344 try: ''.join([0])
3345 except TypeError: pass
3346 else: self.fail("''.join([0]) doesn't raise TypeError")
3347
3348 try: ''.rindex('5')
3349 except ValueError: pass
3350 else: self.fail("''.rindex('5') doesn't raise ValueError")
3351
3352 try: '%(n)s' % None
3353 except TypeError: pass
3354 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3355
3356 try: '%(n' % {}
3357 except ValueError: pass
3358 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3359
3360 try: '%*s' % ('abc')
3361 except TypeError: pass
3362 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3363
3364 try: '%*.*s' % ('abc', 5)
3365 except TypeError: pass
3366 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3367
3368 try: '%s' % (1, 2)
3369 except TypeError: pass
3370 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3371
3372 try: '%' % None
3373 except ValueError: pass
3374 else: self.fail("'%' % None doesn't raise ValueError")
3375
3376 self.assertEqual('534253'.isdigit(), 1)
3377 self.assertEqual('534253x'.isdigit(), 0)
3378 self.assertEqual('%c' % 5, '\x05')
3379 self.assertEqual('%c' % '5', '5')
3380
3381 def test_deepcopy_recursive(self):
3382 # Testing deepcopy of recursive objects...
3383 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003384 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003385 a = Node()
3386 b = Node()
3387 a.b = b
3388 b.a = a
3389 z = deepcopy(a) # This blew up before
3390
3391 def test_unintialized_modules(self):
3392 # Testing uninitialized module objects...
3393 from types import ModuleType as M
3394 m = M.__new__(M)
3395 str(m)
3396 self.assertEqual(hasattr(m, "__name__"), 0)
3397 self.assertEqual(hasattr(m, "__file__"), 0)
3398 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003399 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003400 m.foo = 1
3401 self.assertEqual(m.__dict__, {"foo": 1})
3402
3403 def test_funny_new(self):
3404 # Testing __new__ returning something unexpected...
3405 class C(object):
3406 def __new__(cls, arg):
3407 if isinstance(arg, str): return [1, 2, 3]
3408 elif isinstance(arg, int): return object.__new__(D)
3409 else: return object.__new__(cls)
3410 class D(C):
3411 def __init__(self, arg):
3412 self.foo = arg
3413 self.assertEqual(C("1"), [1, 2, 3])
3414 self.assertEqual(D("1"), [1, 2, 3])
3415 d = D(None)
3416 self.assertEqual(d.foo, None)
3417 d = C(1)
3418 self.assertEqual(isinstance(d, D), True)
3419 self.assertEqual(d.foo, 1)
3420 d = D(1)
3421 self.assertEqual(isinstance(d, D), True)
3422 self.assertEqual(d.foo, 1)
3423
3424 def test_imul_bug(self):
3425 # Testing for __imul__ problems...
3426 # SF bug 544647
3427 class C(object):
3428 def __imul__(self, other):
3429 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003430 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003431 y = x
3432 y *= 1.0
3433 self.assertEqual(y, (x, 1.0))
3434 y = x
3435 y *= 2
3436 self.assertEqual(y, (x, 2))
3437 y = x
3438 y *= 3
3439 self.assertEqual(y, (x, 3))
3440 y = x
3441 y *= 1<<100
3442 self.assertEqual(y, (x, 1<<100))
3443 y = x
3444 y *= None
3445 self.assertEqual(y, (x, None))
3446 y = x
3447 y *= "foo"
3448 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003449
Georg Brandl479a7e72008-02-05 18:13:15 +00003450 def test_copy_setstate(self):
3451 # Testing that copy.*copy() correctly uses __setstate__...
3452 import copy
3453 class C(object):
3454 def __init__(self, foo=None):
3455 self.foo = foo
3456 self.__foo = foo
3457 def setfoo(self, foo=None):
3458 self.foo = foo
3459 def getfoo(self):
3460 return self.__foo
3461 def __getstate__(self):
3462 return [self.foo]
3463 def __setstate__(self_, lst):
3464 self.assertEqual(len(lst), 1)
3465 self_.__foo = self_.foo = lst[0]
3466 a = C(42)
3467 a.setfoo(24)
3468 self.assertEqual(a.foo, 24)
3469 self.assertEqual(a.getfoo(), 42)
3470 b = copy.copy(a)
3471 self.assertEqual(b.foo, 24)
3472 self.assertEqual(b.getfoo(), 24)
3473 b = copy.deepcopy(a)
3474 self.assertEqual(b.foo, 24)
3475 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003476
Georg Brandl479a7e72008-02-05 18:13:15 +00003477 def test_slices(self):
3478 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003479
Georg Brandl479a7e72008-02-05 18:13:15 +00003480 # Strings
3481 self.assertEqual("hello"[:4], "hell")
3482 self.assertEqual("hello"[slice(4)], "hell")
3483 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3484 class S(str):
3485 def __getitem__(self, x):
3486 return str.__getitem__(self, x)
3487 self.assertEqual(S("hello")[:4], "hell")
3488 self.assertEqual(S("hello")[slice(4)], "hell")
3489 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3490 # Tuples
3491 self.assertEqual((1,2,3)[:2], (1,2))
3492 self.assertEqual((1,2,3)[slice(2)], (1,2))
3493 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3494 class T(tuple):
3495 def __getitem__(self, x):
3496 return tuple.__getitem__(self, x)
3497 self.assertEqual(T((1,2,3))[:2], (1,2))
3498 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3499 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3500 # Lists
3501 self.assertEqual([1,2,3][:2], [1,2])
3502 self.assertEqual([1,2,3][slice(2)], [1,2])
3503 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3504 class L(list):
3505 def __getitem__(self, x):
3506 return list.__getitem__(self, x)
3507 self.assertEqual(L([1,2,3])[:2], [1,2])
3508 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3509 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3510 # Now do lists and __setitem__
3511 a = L([1,2,3])
3512 a[slice(1, 3)] = [3,2]
3513 self.assertEqual(a, [1,3,2])
3514 a[slice(0, 2, 1)] = [3,1]
3515 self.assertEqual(a, [3,1,2])
3516 a.__setitem__(slice(1, 3), [2,1])
3517 self.assertEqual(a, [3,2,1])
3518 a.__setitem__(slice(0, 2, 1), [2,3])
3519 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003520
Georg Brandl479a7e72008-02-05 18:13:15 +00003521 def test_subtype_resurrection(self):
3522 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003523
Georg Brandl479a7e72008-02-05 18:13:15 +00003524 class C(object):
3525 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003526
Georg Brandl479a7e72008-02-05 18:13:15 +00003527 def __del__(self):
3528 # resurrect the instance
3529 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003530
Georg Brandl479a7e72008-02-05 18:13:15 +00003531 c = C()
3532 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003533
Benjamin Petersone549ead2009-03-28 21:42:05 +00003534 # The most interesting thing here is whether this blows up, due to
3535 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3536 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003537 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003538
Georg Brandl479a7e72008-02-05 18:13:15 +00003539 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003540 # the last container slot works: that will attempt to delete c again,
3541 # which will cause c to get appended back to the container again
3542 # "during" the del. (On non-CPython implementations, however, __del__
3543 # is typically not called again.)
3544 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003545 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003546 del C.container[-1]
3547 if support.check_impl_detail():
3548 support.gc_collect()
3549 self.assertEqual(len(C.container), 1)
3550 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003551
Georg Brandl479a7e72008-02-05 18:13:15 +00003552 # Make c mortal again, so that the test framework with -l doesn't report
3553 # it as a leak.
3554 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003555
Georg Brandl479a7e72008-02-05 18:13:15 +00003556 def test_slots_trash(self):
3557 # Testing slot trash...
3558 # Deallocating deeply nested slotted trash caused stack overflows
3559 class trash(object):
3560 __slots__ = ['x']
3561 def __init__(self, x):
3562 self.x = x
3563 o = None
3564 for i in range(50000):
3565 o = trash(o)
3566 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003567
Georg Brandl479a7e72008-02-05 18:13:15 +00003568 def test_slots_multiple_inheritance(self):
3569 # SF bug 575229, multiple inheritance w/ slots dumps core
3570 class A(object):
3571 __slots__=()
3572 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003573 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003574 class C(A,B) :
3575 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003576 if support.check_impl_detail():
3577 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003578 self.assertTrue(hasattr(C, '__dict__'))
3579 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003581
Georg Brandl479a7e72008-02-05 18:13:15 +00003582 def test_rmul(self):
3583 # Testing correct invocation of __rmul__...
3584 # SF patch 592646
3585 class C(object):
3586 def __mul__(self, other):
3587 return "mul"
3588 def __rmul__(self, other):
3589 return "rmul"
3590 a = C()
3591 self.assertEqual(a*2, "mul")
3592 self.assertEqual(a*2.2, "mul")
3593 self.assertEqual(2*a, "rmul")
3594 self.assertEqual(2.2*a, "rmul")
3595
3596 def test_ipow(self):
3597 # Testing correct invocation of __ipow__...
3598 # [SF bug 620179]
3599 class C(object):
3600 def __ipow__(self, other):
3601 pass
3602 a = C()
3603 a **= 2
3604
3605 def test_mutable_bases(self):
3606 # Testing mutable bases...
3607
3608 # stuff that should work:
3609 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003610 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003611 class C2(object):
3612 def __getattribute__(self, attr):
3613 if attr == 'a':
3614 return 2
3615 else:
3616 return super(C2, self).__getattribute__(attr)
3617 def meth(self):
3618 return 1
3619 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003620 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003621 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003622 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003623 d = D()
3624 e = E()
3625 D.__bases__ = (C,)
3626 D.__bases__ = (C2,)
3627 self.assertEqual(d.meth(), 1)
3628 self.assertEqual(e.meth(), 1)
3629 self.assertEqual(d.a, 2)
3630 self.assertEqual(e.a, 2)
3631 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003632
Georg Brandl479a7e72008-02-05 18:13:15 +00003633 try:
3634 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003635 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003636 pass
3637 else:
3638 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003639
Georg Brandl479a7e72008-02-05 18:13:15 +00003640 try:
3641 D.__bases__ = ()
3642 except TypeError as msg:
3643 if str(msg) == "a new-style class can't have only classic bases":
3644 self.fail("wrong error message for .__bases__ = ()")
3645 else:
3646 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003647
Georg Brandl479a7e72008-02-05 18:13:15 +00003648 try:
3649 D.__bases__ = (D,)
3650 except TypeError:
3651 pass
3652 else:
3653 # actually, we'll have crashed by here...
3654 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003655
Georg Brandl479a7e72008-02-05 18:13:15 +00003656 try:
3657 D.__bases__ = (C, C)
3658 except TypeError:
3659 pass
3660 else:
3661 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003662
Georg Brandl479a7e72008-02-05 18:13:15 +00003663 try:
3664 D.__bases__ = (E,)
3665 except TypeError:
3666 pass
3667 else:
3668 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003669
Benjamin Petersonae937c02009-04-18 20:54:08 +00003670 def test_builtin_bases(self):
3671 # Make sure all the builtin types can have their base queried without
3672 # segfaulting. See issue #5787.
3673 builtin_types = [tp for tp in builtins.__dict__.values()
3674 if isinstance(tp, type)]
3675 for tp in builtin_types:
3676 object.__getattribute__(tp, "__bases__")
3677 if tp is not object:
3678 self.assertEqual(len(tp.__bases__), 1, tp)
3679
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003680 class L(list):
3681 pass
3682
3683 class C(object):
3684 pass
3685
3686 class D(C):
3687 pass
3688
3689 try:
3690 L.__bases__ = (dict,)
3691 except TypeError:
3692 pass
3693 else:
3694 self.fail("shouldn't turn list subclass into dict subclass")
3695
3696 try:
3697 list.__bases__ = (dict,)
3698 except TypeError:
3699 pass
3700 else:
3701 self.fail("shouldn't be able to assign to list.__bases__")
3702
3703 try:
3704 D.__bases__ = (C, list)
3705 except TypeError:
3706 pass
3707 else:
3708 assert 0, "best_base calculation found wanting"
3709
Benjamin Petersonae937c02009-04-18 20:54:08 +00003710
Georg Brandl479a7e72008-02-05 18:13:15 +00003711 def test_mutable_bases_with_failing_mro(self):
3712 # Testing mutable bases with failing mro...
3713 class WorkOnce(type):
3714 def __new__(self, name, bases, ns):
3715 self.flag = 0
3716 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3717 def mro(self):
3718 if self.flag > 0:
3719 raise RuntimeError("bozo")
3720 else:
3721 self.flag += 1
3722 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003723
Georg Brandl479a7e72008-02-05 18:13:15 +00003724 class WorkAlways(type):
3725 def mro(self):
3726 # this is here to make sure that .mro()s aren't called
3727 # with an exception set (which was possible at one point).
3728 # An error message will be printed in a debug build.
3729 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003730 return type.mro(self)
3731
Georg Brandl479a7e72008-02-05 18:13:15 +00003732 class C(object):
3733 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003734
Georg Brandl479a7e72008-02-05 18:13:15 +00003735 class C2(object):
3736 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003737
Georg Brandl479a7e72008-02-05 18:13:15 +00003738 class D(C):
3739 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003740
Georg Brandl479a7e72008-02-05 18:13:15 +00003741 class E(D):
3742 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003743
Georg Brandl479a7e72008-02-05 18:13:15 +00003744 class F(D, metaclass=WorkOnce):
3745 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003746
Georg Brandl479a7e72008-02-05 18:13:15 +00003747 class G(D, metaclass=WorkAlways):
3748 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003749
Georg Brandl479a7e72008-02-05 18:13:15 +00003750 # Immediate subclasses have their mro's adjusted in alphabetical
3751 # order, so E's will get adjusted before adjusting F's fails. We
3752 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003753
Georg Brandl479a7e72008-02-05 18:13:15 +00003754 E_mro_before = E.__mro__
3755 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003756
Armin Rigofd163f92005-12-29 15:59:19 +00003757 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003758 D.__bases__ = (C2,)
3759 except RuntimeError:
3760 self.assertEqual(E.__mro__, E_mro_before)
3761 self.assertEqual(D.__mro__, D_mro_before)
3762 else:
3763 self.fail("exception not propagated")
3764
3765 def test_mutable_bases_catch_mro_conflict(self):
3766 # Testing mutable bases catch mro conflict...
3767 class A(object):
3768 pass
3769
3770 class B(object):
3771 pass
3772
3773 class C(A, B):
3774 pass
3775
3776 class D(A, B):
3777 pass
3778
3779 class E(C, D):
3780 pass
3781
3782 try:
3783 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003784 except TypeError:
3785 pass
3786 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003787 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003788
Georg Brandl479a7e72008-02-05 18:13:15 +00003789 def test_mutable_names(self):
3790 # Testing mutable names...
3791 class C(object):
3792 pass
3793
3794 # C.__module__ could be 'test_descr' or '__main__'
3795 mod = C.__module__
3796
3797 C.__name__ = 'D'
3798 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3799
3800 C.__name__ = 'D.E'
3801 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3802
3803 def test_subclass_right_op(self):
3804 # Testing correct dispatch of subclass overloading __r<op>__...
3805
3806 # This code tests various cases where right-dispatch of a subclass
3807 # should be preferred over left-dispatch of a base class.
3808
3809 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3810
3811 class B(int):
3812 def __floordiv__(self, other):
3813 return "B.__floordiv__"
3814 def __rfloordiv__(self, other):
3815 return "B.__rfloordiv__"
3816
3817 self.assertEqual(B(1) // 1, "B.__floordiv__")
3818 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3819
3820 # Case 2: subclass of object; this is just the baseline for case 3
3821
3822 class C(object):
3823 def __floordiv__(self, other):
3824 return "C.__floordiv__"
3825 def __rfloordiv__(self, other):
3826 return "C.__rfloordiv__"
3827
3828 self.assertEqual(C() // 1, "C.__floordiv__")
3829 self.assertEqual(1 // C(), "C.__rfloordiv__")
3830
3831 # Case 3: subclass of new-style class; here it gets interesting
3832
3833 class D(C):
3834 def __floordiv__(self, other):
3835 return "D.__floordiv__"
3836 def __rfloordiv__(self, other):
3837 return "D.__rfloordiv__"
3838
3839 self.assertEqual(D() // C(), "D.__floordiv__")
3840 self.assertEqual(C() // D(), "D.__rfloordiv__")
3841
3842 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3843
3844 class E(C):
3845 pass
3846
3847 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3848
3849 self.assertEqual(E() // 1, "C.__floordiv__")
3850 self.assertEqual(1 // E(), "C.__rfloordiv__")
3851 self.assertEqual(E() // C(), "C.__floordiv__")
3852 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3853
Benjamin Petersone549ead2009-03-28 21:42:05 +00003854 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003855 def test_meth_class_get(self):
3856 # Testing __get__ method of METH_CLASS C methods...
3857 # Full coverage of descrobject.c::classmethod_get()
3858
3859 # Baseline
3860 arg = [1, 2, 3]
3861 res = {1: None, 2: None, 3: None}
3862 self.assertEqual(dict.fromkeys(arg), res)
3863 self.assertEqual({}.fromkeys(arg), res)
3864
3865 # Now get the descriptor
3866 descr = dict.__dict__["fromkeys"]
3867
3868 # More baseline using the descriptor directly
3869 self.assertEqual(descr.__get__(None, dict)(arg), res)
3870 self.assertEqual(descr.__get__({})(arg), res)
3871
3872 # Now check various error cases
3873 try:
3874 descr.__get__(None, None)
3875 except TypeError:
3876 pass
3877 else:
3878 self.fail("shouldn't have allowed descr.__get__(None, None)")
3879 try:
3880 descr.__get__(42)
3881 except TypeError:
3882 pass
3883 else:
3884 self.fail("shouldn't have allowed descr.__get__(42)")
3885 try:
3886 descr.__get__(None, 42)
3887 except TypeError:
3888 pass
3889 else:
3890 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3891 try:
3892 descr.__get__(None, int)
3893 except TypeError:
3894 pass
3895 else:
3896 self.fail("shouldn't have allowed descr.__get__(None, int)")
3897
3898 def test_isinst_isclass(self):
3899 # Testing proxy isinstance() and isclass()...
3900 class Proxy(object):
3901 def __init__(self, obj):
3902 self.__obj = obj
3903 def __getattribute__(self, name):
3904 if name.startswith("_Proxy__"):
3905 return object.__getattribute__(self, name)
3906 else:
3907 return getattr(self.__obj, name)
3908 # Test with a classic class
3909 class C:
3910 pass
3911 a = C()
3912 pa = Proxy(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003913 self.assertTrue(isinstance(a, C)) # Baseline
3914 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003915 # Test with a classic subclass
3916 class D(C):
3917 pass
3918 a = D()
3919 pa = Proxy(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003920 self.assertTrue(isinstance(a, C)) # Baseline
3921 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003922 # Test with a new-style class
3923 class C(object):
3924 pass
3925 a = C()
3926 pa = Proxy(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003927 self.assertTrue(isinstance(a, C)) # Baseline
3928 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003929 # Test with a new-style subclass
3930 class D(C):
3931 pass
3932 a = D()
3933 pa = Proxy(a)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003934 self.assertTrue(isinstance(a, C)) # Baseline
3935 self.assertTrue(isinstance(pa, C)) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003936
3937 def test_proxy_super(self):
3938 # Testing super() for a proxy object...
3939 class Proxy(object):
3940 def __init__(self, obj):
3941 self.__obj = obj
3942 def __getattribute__(self, name):
3943 if name.startswith("_Proxy__"):
3944 return object.__getattribute__(self, name)
3945 else:
3946 return getattr(self.__obj, name)
3947
3948 class B(object):
3949 def f(self):
3950 return "B.f"
3951
3952 class C(B):
3953 def f(self):
3954 return super(C, self).f() + "->C.f"
3955
3956 obj = C()
3957 p = Proxy(obj)
3958 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3959
3960 def test_carloverre(self):
3961 # Testing prohibition of Carlo Verre's hack...
3962 try:
3963 object.__setattr__(str, "foo", 42)
3964 except TypeError:
3965 pass
3966 else:
3967 self.fail("Carlo Verre __setattr__ suceeded!")
3968 try:
3969 object.__delattr__(str, "lower")
3970 except TypeError:
3971 pass
3972 else:
3973 self.fail("Carlo Verre __delattr__ succeeded!")
3974
3975 def test_weakref_segfault(self):
3976 # Testing weakref segfault...
3977 # SF 742911
3978 import weakref
3979
3980 class Provoker:
3981 def __init__(self, referrent):
3982 self.ref = weakref.ref(referrent)
3983
3984 def __del__(self):
3985 x = self.ref()
3986
3987 class Oops(object):
3988 pass
3989
3990 o = Oops()
3991 o.whatever = Provoker(o)
3992 del o
3993
3994 def test_wrapper_segfault(self):
3995 # SF 927248: deeply nested wrappers could cause stack overflow
3996 f = lambda:None
3997 for i in range(1000000):
3998 f = f.__call__
3999 f = None
4000
4001 def test_file_fault(self):
4002 # Testing sys.stdout is changed in getattr...
4003 import sys
4004 class StdoutGuard:
4005 def __getattr__(self, attr):
4006 sys.stdout = sys.__stdout__
4007 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4008 sys.stdout = StdoutGuard()
4009 try:
4010 print("Oops!")
4011 except RuntimeError:
4012 pass
4013
4014 def test_vicious_descriptor_nonsense(self):
4015 # Testing vicious_descriptor_nonsense...
4016
4017 # A potential segfault spotted by Thomas Wouters in mail to
4018 # python-dev 2003-04-17, turned into an example & fixed by Michael
4019 # Hudson just less than four months later...
4020
4021 class Evil(object):
4022 def __hash__(self):
4023 return hash('attr')
4024 def __eq__(self, other):
4025 del C.attr
4026 return 0
4027
4028 class Descr(object):
4029 def __get__(self, ob, type=None):
4030 return 1
4031
4032 class C(object):
4033 attr = Descr()
4034
4035 c = C()
4036 c.__dict__[Evil()] = 0
4037
4038 self.assertEqual(c.attr, 1)
4039 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004040 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004041 self.assertEqual(hasattr(c, 'attr'), False)
4042
4043 def test_init(self):
4044 # SF 1155938
4045 class Foo(object):
4046 def __init__(self):
4047 return 10
4048 try:
4049 Foo()
4050 except TypeError:
4051 pass
4052 else:
4053 self.fail("did not test __init__() for None return")
4054
4055 def test_method_wrapper(self):
4056 # Testing method-wrapper objects...
4057 # <type 'method-wrapper'> did not support any reflection before 2.5
4058
Mark Dickinson211c6252009-02-01 10:28:51 +00004059 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004060
4061 l = []
4062 self.assertEqual(l.__add__, l.__add__)
4063 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004064 self.assertTrue(l.__add__ != [5].__add__)
4065 self.assertTrue(l.__add__ != l.__mul__)
4066 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004067 if hasattr(l.__add__, '__self__'):
4068 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004069 self.assertTrue(l.__add__.__self__ is l)
4070 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004071 else:
4072 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004073 self.assertTrue(l.__add__.im_self is l)
4074 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004075 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4076 try:
4077 hash(l.__add__)
4078 except TypeError:
4079 pass
4080 else:
4081 self.fail("no TypeError from hash([].__add__)")
4082
4083 t = ()
4084 t += (7,)
4085 self.assertEqual(t.__add__, (7,).__add__)
4086 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4087
4088 def test_not_implemented(self):
4089 # Testing NotImplemented...
4090 # all binary methods should be able to return a NotImplemented
4091 import sys
4092 import types
4093 import operator
4094
4095 def specialmethod(self, other):
4096 return NotImplemented
4097
4098 def check(expr, x, y):
4099 try:
4100 exec(expr, {'x': x, 'y': y, 'operator': operator})
4101 except TypeError:
4102 pass
4103 else:
4104 self.fail("no TypeError from %r" % (expr,))
4105
4106 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4107 # TypeErrors
4108 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4109 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004110 for name, expr, iexpr in [
4111 ('__add__', 'x + y', 'x += y'),
4112 ('__sub__', 'x - y', 'x -= y'),
4113 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004114 ('__truediv__', 'operator.truediv(x, y)', None),
4115 ('__floordiv__', 'operator.floordiv(x, y)', None),
4116 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004117 ('__mod__', 'x % y', 'x %= y'),
4118 ('__divmod__', 'divmod(x, y)', None),
4119 ('__pow__', 'x ** y', 'x **= y'),
4120 ('__lshift__', 'x << y', 'x <<= y'),
4121 ('__rshift__', 'x >> y', 'x >>= y'),
4122 ('__and__', 'x & y', 'x &= y'),
4123 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004124 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004125 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004126 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004127 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004128 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004129 check(expr, a, N1)
4130 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004131 if iexpr:
4132 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004133 check(iexpr, a, N1)
4134 check(iexpr, a, N2)
4135 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004136 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004137 c = C()
4138 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004139 check(iexpr, c, N1)
4140 check(iexpr, c, N2)
4141
Georg Brandl479a7e72008-02-05 18:13:15 +00004142 def test_assign_slice(self):
4143 # ceval.c's assign_slice used to check for
4144 # tp->tp_as_sequence->sq_slice instead of
4145 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004146
Georg Brandl479a7e72008-02-05 18:13:15 +00004147 class C(object):
4148 def __setitem__(self, idx, value):
4149 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004150
Georg Brandl479a7e72008-02-05 18:13:15 +00004151 c = C()
4152 c[1:2] = 3
4153 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004154
Benjamin Peterson9262b842008-11-17 22:45:50 +00004155 def test_getattr_hooks(self):
4156 # issue 4230
4157
4158 class Descriptor(object):
4159 counter = 0
4160 def __get__(self, obj, objtype=None):
4161 def getter(name):
4162 self.counter += 1
4163 raise AttributeError(name)
4164 return getter
4165
4166 descr = Descriptor()
4167 class A(object):
4168 __getattribute__ = descr
4169 class B(object):
4170 __getattr__ = descr
4171 class C(object):
4172 __getattribute__ = descr
4173 __getattr__ = descr
4174
4175 self.assertRaises(AttributeError, getattr, A(), "attr")
4176 self.assertEquals(descr.counter, 1)
4177 self.assertRaises(AttributeError, getattr, B(), "attr")
4178 self.assertEquals(descr.counter, 2)
4179 self.assertRaises(AttributeError, getattr, C(), "attr")
4180 self.assertEquals(descr.counter, 4)
4181
4182 import gc
4183 class EvilGetattribute(object):
4184 # This used to segfault
4185 def __getattr__(self, name):
4186 raise AttributeError(name)
4187 def __getattribute__(self, name):
4188 del EvilGetattribute.__getattr__
4189 for i in range(5):
4190 gc.collect()
4191 raise AttributeError(name)
4192
4193 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4194
Christian Heimesbbffeb62008-01-24 09:42:52 +00004195
Georg Brandl479a7e72008-02-05 18:13:15 +00004196class DictProxyTests(unittest.TestCase):
4197 def setUp(self):
4198 class C(object):
4199 def meth(self):
4200 pass
4201 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004202
Georg Brandl479a7e72008-02-05 18:13:15 +00004203 def test_iter_keys(self):
4204 # Testing dict-proxy iterkeys...
4205 keys = [ key for key in self.C.__dict__.keys() ]
4206 keys.sort()
4207 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4208 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004209
Georg Brandl479a7e72008-02-05 18:13:15 +00004210 def test_iter_values(self):
4211 # Testing dict-proxy itervalues...
4212 values = [ values for values in self.C.__dict__.values() ]
4213 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004214
Georg Brandl479a7e72008-02-05 18:13:15 +00004215 def test_iter_items(self):
4216 # Testing dict-proxy iteritems...
4217 keys = [ key for (key, value) in self.C.__dict__.items() ]
4218 keys.sort()
4219 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4220 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004221
Georg Brandl479a7e72008-02-05 18:13:15 +00004222 def test_dict_type_with_metaclass(self):
4223 # Testing type of __dict__ when metaclass set...
4224 class B(object):
4225 pass
4226 class M(type):
4227 pass
4228 class C(metaclass=M):
4229 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4230 pass
4231 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004232
Christian Heimesbbffeb62008-01-24 09:42:52 +00004233
Georg Brandl479a7e72008-02-05 18:13:15 +00004234class PTypesLongInitTest(unittest.TestCase):
4235 # This is in its own TestCase so that it can be run before any other tests.
4236 def test_pytype_long_ready(self):
4237 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004238
Georg Brandl479a7e72008-02-05 18:13:15 +00004239 # This dumps core when SF bug 551412 isn't fixed --
4240 # but only when test_descr.py is run separately.
4241 # (That can't be helped -- as soon as PyType_Ready()
4242 # is called for PyLong_Type, the bug is gone.)
4243 class UserLong(object):
4244 def __pow__(self, *args):
4245 pass
4246 try:
4247 pow(0, UserLong(), 0)
4248 except:
4249 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004250
Georg Brandl479a7e72008-02-05 18:13:15 +00004251 # Another segfault only when run early
4252 # (before PyType_Ready(tuple) is called)
4253 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004254
4255
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004256def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004257 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004258 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004259 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004261if __name__ == "__main__":
4262 test_main()