blob: 10820ab712ed26a20b0041fcb7eadf934db9ad64 [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
Tim Peters4d9b4662002-04-16 01:59:17 +00005
Georg Brandl479a7e72008-02-05 18:13:15 +00006from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00008
Tim Peters6d6c1a32001-08-02 04:15:00 +00009
Georg Brandl479a7e72008-02-05 18:13:15 +000010class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000011
Georg Brandl479a7e72008-02-05 18:13:15 +000012 def __init__(self, *args, **kwargs):
13 unittest.TestCase.__init__(self, *args, **kwargs)
14 self.binops = {
15 'add': '+',
16 'sub': '-',
17 'mul': '*',
18 'div': '/',
19 'divmod': 'divmod',
20 'pow': '**',
21 'lshift': '<<',
22 'rshift': '>>',
23 'and': '&',
24 'xor': '^',
25 'or': '|',
26 'cmp': 'cmp',
27 'lt': '<',
28 'le': '<=',
29 'eq': '==',
30 'ne': '!=',
31 'gt': '>',
32 'ge': '>=',
33 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000034
Georg Brandl479a7e72008-02-05 18:13:15 +000035 for name, expr in list(self.binops.items()):
36 if expr.islower():
37 expr = expr + "(a, b)"
38 else:
39 expr = 'a %s b' % expr
40 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000041
Georg Brandl479a7e72008-02-05 18:13:15 +000042 self.unops = {
43 'pos': '+',
44 'neg': '-',
45 'abs': 'abs',
46 'invert': '~',
47 'int': 'int',
48 'float': 'float',
49 'oct': 'oct',
50 'hex': 'hex',
51 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000052
Georg Brandl479a7e72008-02-05 18:13:15 +000053 for name, expr in list(self.unops.items()):
54 if expr.islower():
55 expr = expr + "(a)"
56 else:
57 expr = '%s a' % expr
58 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000059
Georg Brandl479a7e72008-02-05 18:13:15 +000060 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
61 d = {'a': a}
62 self.assertEqual(eval(expr, d), res)
63 t = type(a)
64 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000065
Georg Brandl479a7e72008-02-05 18:13:15 +000066 # Find method in parent class
67 while meth not in t.__dict__:
68 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000069 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
70 # method object; the getattr() below obtains its underlying function.
71 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000072 self.assertEqual(m(a), res)
73 bm = getattr(a, meth)
74 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000075
Georg Brandl479a7e72008-02-05 18:13:15 +000076 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
77 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000078
Georg Brandl479a7e72008-02-05 18:13:15 +000079 # XXX Hack so this passes before 2.3 when -Qnew is specified.
80 if meth == "__div__" and 1/2 == 0.5:
81 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000082
Georg Brandl479a7e72008-02-05 18:13:15 +000083 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000084
Georg Brandl479a7e72008-02-05 18:13:15 +000085 self.assertEqual(eval(expr, d), res)
86 t = type(a)
87 m = getattr(t, meth)
88 while meth not in t.__dict__:
89 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000090 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
91 # method object; the getattr() below obtains its underlying function.
92 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000093 self.assertEqual(m(a, b), res)
94 bm = getattr(a, meth)
95 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000096
Georg Brandl479a7e72008-02-05 18:13:15 +000097 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
98 d = {'a': a, 'b': b, 'c': c}
99 self.assertEqual(eval(expr, d), res)
100 t = type(a)
101 m = getattr(t, meth)
102 while meth not in t.__dict__:
103 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000104 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
105 # method object; the getattr() below obtains its underlying function.
106 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000107 self.assertEqual(m(a, slice(b, c)), res)
108 bm = getattr(a, meth)
109 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110
Georg Brandl479a7e72008-02-05 18:13:15 +0000111 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
112 d = {'a': deepcopy(a), 'b': b}
113 exec(stmt, d)
114 self.assertEqual(d['a'], res)
115 t = type(a)
116 m = getattr(t, meth)
117 while meth not in t.__dict__:
118 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000119 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
120 # method object; the getattr() below obtains its underlying function.
121 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000122 d['a'] = deepcopy(a)
123 m(d['a'], b)
124 self.assertEqual(d['a'], res)
125 d['a'] = deepcopy(a)
126 bm = getattr(d['a'], meth)
127 bm(b)
128 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000129
Georg Brandl479a7e72008-02-05 18:13:15 +0000130 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
131 d = {'a': deepcopy(a), 'b': b, 'c': c}
132 exec(stmt, d)
133 self.assertEqual(d['a'], res)
134 t = type(a)
135 m = getattr(t, meth)
136 while meth not in t.__dict__:
137 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000138 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
139 # method object; the getattr() below obtains its underlying function.
140 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000141 d['a'] = deepcopy(a)
142 m(d['a'], b, c)
143 self.assertEqual(d['a'], res)
144 d['a'] = deepcopy(a)
145 bm = getattr(d['a'], meth)
146 bm(b, c)
147 self.assertEqual(d['a'], res)
148
149 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
150 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
151 exec(stmt, dictionary)
152 self.assertEqual(dictionary['a'], res)
153 t = type(a)
154 while meth not in t.__dict__:
155 t = t.__bases__[0]
156 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000157 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
158 # method object; the getattr() below obtains its underlying function.
159 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000160 dictionary['a'] = deepcopy(a)
161 m(dictionary['a'], slice(b, c), d)
162 self.assertEqual(dictionary['a'], res)
163 dictionary['a'] = deepcopy(a)
164 bm = getattr(dictionary['a'], meth)
165 bm(slice(b, c), d)
166 self.assertEqual(dictionary['a'], res)
167
168 def test_lists(self):
169 # Testing list operations...
170 # Asserts are within individual test methods
171 self.binop_test([1], [2], [1,2], "a+b", "__add__")
172 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
173 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
174 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
175 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
176 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
177 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
178 self.unop_test([1,2,3], 3, "len(a)", "__len__")
179 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
181 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
182 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
183 "__setitem__")
184
185 def test_dicts(self):
186 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000187 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
188 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
190
191 d = {1:2, 3:4}
192 l1 = []
193 for i in list(d.keys()):
194 l1.append(i)
195 l = []
196 for i in iter(d):
197 l.append(i)
198 self.assertEqual(l, l1)
199 l = []
200 for i in d.__iter__():
201 l.append(i)
202 self.assertEqual(l, l1)
203 l = []
204 for i in dict.__iter__(d):
205 l.append(i)
206 self.assertEqual(l, l1)
207 d = {1:2, 3:4}
208 self.unop_test(d, 2, "len(a)", "__len__")
209 self.assertEqual(eval(repr(d), {}), d)
210 self.assertEqual(eval(d.__repr__(), {}), d)
211 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
212 "__setitem__")
213
214 # Tests for unary and binary operators
215 def number_operators(self, a, b, skip=[]):
216 dict = {'a': a, 'b': b}
217
218 for name, expr in list(self.binops.items()):
219 if name not in skip:
220 name = "__%s__" % name
221 if hasattr(a, name):
222 res = eval(expr, dict)
223 self.binop_test(a, b, res, expr, name)
224
225 for name, expr in list(self.unops.items()):
226 if name not in skip:
227 name = "__%s__" % name
228 if hasattr(a, name):
229 res = eval(expr, dict)
230 self.unop_test(a, res, expr, name)
231
232 def test_ints(self):
233 # Testing int operations...
234 self.number_operators(100, 3)
235 # The following crashes in Python 2.2
236 self.assertEqual((1).__bool__(), 1)
237 self.assertEqual((0).__bool__(), 0)
238 # This returns 'NotImplemented' in Python 2.2
239 class C(int):
240 def __add__(self, other):
241 return NotImplemented
242 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000243 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000244 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000245 except TypeError:
246 pass
247 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000248 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000249
Georg Brandl479a7e72008-02-05 18:13:15 +0000250 def test_floats(self):
251 # Testing float operations...
252 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000253
Georg Brandl479a7e72008-02-05 18:13:15 +0000254 def test_complexes(self):
255 # Testing complex operations...
256 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000257 'int', 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +0000258 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000259
Georg Brandl479a7e72008-02-05 18:13:15 +0000260 class Number(complex):
261 __slots__ = ['prec']
262 def __new__(cls, *args, **kwds):
263 result = complex.__new__(cls, *args)
264 result.prec = kwds.get('prec', 12)
265 return result
266 def __repr__(self):
267 prec = self.prec
268 if self.imag == 0.0:
269 return "%.*g" % (prec, self.real)
270 if self.real == 0.0:
271 return "%.*gj" % (prec, self.imag)
272 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
273 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000274
Georg Brandl479a7e72008-02-05 18:13:15 +0000275 a = Number(3.14, prec=6)
276 self.assertEqual(repr(a), "3.14")
277 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000278
Georg Brandl479a7e72008-02-05 18:13:15 +0000279 a = Number(a, prec=2)
280 self.assertEqual(repr(a), "3.1")
281 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000282
Georg Brandl479a7e72008-02-05 18:13:15 +0000283 a = Number(234.5)
284 self.assertEqual(repr(a), "234.5")
285 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000286
Benjamin Petersone549ead2009-03-28 21:42:05 +0000287 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000288 def test_spam_lists(self):
289 # Testing spamlist operations...
290 import copy, xxsubtype as spam
291
292 def spamlist(l, memo=None):
293 import xxsubtype as spam
294 return spam.spamlist(l)
295
296 # This is an ugly hack:
297 copy._deepcopy_dispatch[spam.spamlist] = spamlist
298
299 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
300 "__add__")
301 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
302 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
303 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
304 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
305 "__getitem__")
306 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
307 "__iadd__")
308 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
309 "__imul__")
310 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
311 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
312 "__mul__")
313 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
314 "__rmul__")
315 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
316 "__setitem__")
317 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
318 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
319 # Test subclassing
320 class C(spam.spamlist):
321 def foo(self): return 1
322 a = C()
323 self.assertEqual(a, [])
324 self.assertEqual(a.foo(), 1)
325 a.append(100)
326 self.assertEqual(a, [100])
327 self.assertEqual(a.getstate(), 0)
328 a.setstate(42)
329 self.assertEqual(a.getstate(), 42)
330
Benjamin Petersone549ead2009-03-28 21:42:05 +0000331 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000332 def test_spam_dicts(self):
333 # Testing spamdict operations...
334 import copy, xxsubtype as spam
335 def spamdict(d, memo=None):
336 import xxsubtype as spam
337 sd = spam.spamdict()
338 for k, v in list(d.items()):
339 sd[k] = v
340 return sd
341 # This is an ugly hack:
342 copy._deepcopy_dispatch[spam.spamdict] = spamdict
343
Georg Brandl479a7e72008-02-05 18:13:15 +0000344 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
345 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
346 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
347 d = spamdict({1:2,3:4})
348 l1 = []
349 for i in list(d.keys()):
350 l1.append(i)
351 l = []
352 for i in iter(d):
353 l.append(i)
354 self.assertEqual(l, l1)
355 l = []
356 for i in d.__iter__():
357 l.append(i)
358 self.assertEqual(l, l1)
359 l = []
360 for i in type(spamdict({})).__iter__(d):
361 l.append(i)
362 self.assertEqual(l, l1)
363 straightd = {1:2, 3:4}
364 spamd = spamdict(straightd)
365 self.unop_test(spamd, 2, "len(a)", "__len__")
366 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
367 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
368 "a[b]=c", "__setitem__")
369 # Test subclassing
370 class C(spam.spamdict):
371 def foo(self): return 1
372 a = C()
373 self.assertEqual(list(a.items()), [])
374 self.assertEqual(a.foo(), 1)
375 a['foo'] = 'bar'
376 self.assertEqual(list(a.items()), [('foo', 'bar')])
377 self.assertEqual(a.getstate(), 0)
378 a.setstate(100)
379 self.assertEqual(a.getstate(), 100)
380
381class ClassPropertiesAndMethods(unittest.TestCase):
382
383 def test_python_dicts(self):
384 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000385 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000386 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000387 d = dict()
388 self.assertEqual(d, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000389 self.assertTrue(d.__class__ is dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000390 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000391 class C(dict):
392 state = -1
393 def __init__(self_local, *a, **kw):
394 if a:
395 self.assertEqual(len(a), 1)
396 self_local.state = a[0]
397 if kw:
398 for k, v in list(kw.items()):
399 self_local[v] = k
400 def __getitem__(self, key):
401 return self.get(key, 0)
402 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000403 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000404 dict.__setitem__(self_local, key, value)
405 def setstate(self, state):
406 self.state = state
407 def getstate(self):
408 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000409 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000410 a1 = C(12)
411 self.assertEqual(a1.state, 12)
412 a2 = C(foo=1, bar=2)
413 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
414 a = C()
415 self.assertEqual(a.state, -1)
416 self.assertEqual(a.getstate(), -1)
417 a.setstate(0)
418 self.assertEqual(a.state, 0)
419 self.assertEqual(a.getstate(), 0)
420 a.setstate(10)
421 self.assertEqual(a.state, 10)
422 self.assertEqual(a.getstate(), 10)
423 self.assertEqual(a[42], 0)
424 a[42] = 24
425 self.assertEqual(a[42], 24)
426 N = 50
427 for i in range(N):
428 a[i] = C()
429 for j in range(N):
430 a[i][j] = i*j
431 for i in range(N):
432 for j in range(N):
433 self.assertEqual(a[i][j], i*j)
434
435 def test_python_lists(self):
436 # Testing Python subclass of list...
437 class C(list):
438 def __getitem__(self, i):
439 if isinstance(i, slice):
440 return i.start, i.stop
441 return list.__getitem__(self, i) + 100
442 a = C()
443 a.extend([0,1,2])
444 self.assertEqual(a[0], 100)
445 self.assertEqual(a[1], 101)
446 self.assertEqual(a[2], 102)
447 self.assertEqual(a[100:200], (100,200))
448
449 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000450 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000451 class C(metaclass=type):
452 def __init__(self):
453 self.__state = 0
454 def getstate(self):
455 return self.__state
456 def setstate(self, state):
457 self.__state = state
458 a = C()
459 self.assertEqual(a.getstate(), 0)
460 a.setstate(10)
461 self.assertEqual(a.getstate(), 10)
462 class _metaclass(type):
463 def myself(cls): return cls
464 class D(metaclass=_metaclass):
465 pass
466 self.assertEqual(D.myself(), D)
467 d = D()
468 self.assertEqual(d.__class__, D)
469 class M1(type):
470 def __new__(cls, name, bases, dict):
471 dict['__spam__'] = 1
472 return type.__new__(cls, name, bases, dict)
473 class C(metaclass=M1):
474 pass
475 self.assertEqual(C.__spam__, 1)
476 c = C()
477 self.assertEqual(c.__spam__, 1)
478
479 class _instance(object):
480 pass
481 class M2(object):
482 @staticmethod
483 def __new__(cls, name, bases, dict):
484 self = object.__new__(cls)
485 self.name = name
486 self.bases = bases
487 self.dict = dict
488 return self
489 def __call__(self):
490 it = _instance()
491 # Early binding of methods
492 for key in self.dict:
493 if key.startswith("__"):
494 continue
495 setattr(it, key, self.dict[key].__get__(it, self))
496 return it
497 class C(metaclass=M2):
498 def spam(self):
499 return 42
500 self.assertEqual(C.name, 'C')
501 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000502 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000503 c = C()
504 self.assertEqual(c.spam(), 42)
505
506 # More metaclass examples
507
508 class autosuper(type):
509 # Automatically add __super to the class
510 # This trick only works for dynamic classes
511 def __new__(metaclass, name, bases, dict):
512 cls = super(autosuper, metaclass).__new__(metaclass,
513 name, bases, dict)
514 # Name mangling for __super removes leading underscores
515 while name[:1] == "_":
516 name = name[1:]
517 if name:
518 name = "_%s__super" % name
519 else:
520 name = "__super"
521 setattr(cls, name, super(cls))
522 return cls
523 class A(metaclass=autosuper):
524 def meth(self):
525 return "A"
526 class B(A):
527 def meth(self):
528 return "B" + self.__super.meth()
529 class C(A):
530 def meth(self):
531 return "C" + self.__super.meth()
532 class D(C, B):
533 def meth(self):
534 return "D" + self.__super.meth()
535 self.assertEqual(D().meth(), "DCBA")
536 class E(B, C):
537 def meth(self):
538 return "E" + self.__super.meth()
539 self.assertEqual(E().meth(), "EBCA")
540
541 class autoproperty(type):
542 # Automatically create property attributes when methods
543 # named _get_x and/or _set_x are found
544 def __new__(metaclass, name, bases, dict):
545 hits = {}
546 for key, val in dict.items():
547 if key.startswith("_get_"):
548 key = key[5:]
549 get, set = hits.get(key, (None, None))
550 get = val
551 hits[key] = get, set
552 elif key.startswith("_set_"):
553 key = key[5:]
554 get, set = hits.get(key, (None, None))
555 set = val
556 hits[key] = get, set
557 for key, (get, set) in hits.items():
558 dict[key] = property(get, set)
559 return super(autoproperty, metaclass).__new__(metaclass,
560 name, bases, dict)
561 class A(metaclass=autoproperty):
562 def _get_x(self):
563 return -self.__x
564 def _set_x(self, x):
565 self.__x = -x
566 a = A()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000567 self.assertTrue(not hasattr(a, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +0000568 a.x = 12
569 self.assertEqual(a.x, 12)
570 self.assertEqual(a._A__x, -12)
571
572 class multimetaclass(autoproperty, autosuper):
573 # Merge of multiple cooperating metaclasses
574 pass
575 class A(metaclass=multimetaclass):
576 def _get_x(self):
577 return "A"
578 class B(A):
579 def _get_x(self):
580 return "B" + self.__super._get_x()
581 class C(A):
582 def _get_x(self):
583 return "C" + self.__super._get_x()
584 class D(C, B):
585 def _get_x(self):
586 return "D" + self.__super._get_x()
587 self.assertEqual(D().x, "DCBA")
588
589 # Make sure type(x) doesn't call x.__class__.__init__
590 class T(type):
591 counter = 0
592 def __init__(self, *args):
593 T.counter += 1
594 class C(metaclass=T):
595 pass
596 self.assertEqual(T.counter, 1)
597 a = C()
598 self.assertEqual(type(a), C)
599 self.assertEqual(T.counter, 1)
600
601 class C(object): pass
602 c = C()
603 try: c()
604 except TypeError: pass
605 else: self.fail("calling object w/o call method should raise "
606 "TypeError")
607
608 # Testing code to find most derived baseclass
609 class A(type):
610 def __new__(*args, **kwargs):
611 return type.__new__(*args, **kwargs)
612
613 class B(object):
614 pass
615
616 class C(object, metaclass=A):
617 pass
618
619 # The most derived metaclass of D is A rather than type.
620 class D(B, C):
621 pass
622
623 def test_module_subclasses(self):
624 # Testing Python subclass of module...
625 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000626 MT = type(sys)
627 class MM(MT):
628 def __init__(self, name):
629 MT.__init__(self, name)
630 def __getattribute__(self, name):
631 log.append(("getattr", name))
632 return MT.__getattribute__(self, name)
633 def __setattr__(self, name, value):
634 log.append(("setattr", name, value))
635 MT.__setattr__(self, name, value)
636 def __delattr__(self, name):
637 log.append(("delattr", name))
638 MT.__delattr__(self, name)
639 a = MM("a")
640 a.foo = 12
641 x = a.foo
642 del a.foo
643 self.assertEqual(log, [("setattr", "foo", 12),
644 ("getattr", "foo"),
645 ("delattr", "foo")])
646
647 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000648 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000649 class Module(types.ModuleType, str):
650 pass
651 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000652 pass
653 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000654 self.fail("inheriting from ModuleType and str at the same time "
655 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000656
Georg Brandl479a7e72008-02-05 18:13:15 +0000657 def test_multiple_inheritance(self):
658 # Testing multiple inheritance...
659 class C(object):
660 def __init__(self):
661 self.__state = 0
662 def getstate(self):
663 return self.__state
664 def setstate(self, state):
665 self.__state = state
666 a = C()
667 self.assertEqual(a.getstate(), 0)
668 a.setstate(10)
669 self.assertEqual(a.getstate(), 10)
670 class D(dict, C):
671 def __init__(self):
672 type({}).__init__(self)
673 C.__init__(self)
674 d = D()
675 self.assertEqual(list(d.keys()), [])
676 d["hello"] = "world"
677 self.assertEqual(list(d.items()), [("hello", "world")])
678 self.assertEqual(d["hello"], "world")
679 self.assertEqual(d.getstate(), 0)
680 d.setstate(10)
681 self.assertEqual(d.getstate(), 10)
682 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000683
Georg Brandl479a7e72008-02-05 18:13:15 +0000684 # SF bug #442833
685 class Node(object):
686 def __int__(self):
687 return int(self.foo())
688 def foo(self):
689 return "23"
690 class Frag(Node, list):
691 def foo(self):
692 return "42"
693 self.assertEqual(Node().__int__(), 23)
694 self.assertEqual(int(Node()), 23)
695 self.assertEqual(Frag().__int__(), 42)
696 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000697
Georg Brandl479a7e72008-02-05 18:13:15 +0000698 def test_diamond_inheritence(self):
699 # Testing multiple inheritance special cases...
700 class A(object):
701 def spam(self): return "A"
702 self.assertEqual(A().spam(), "A")
703 class B(A):
704 def boo(self): return "B"
705 def spam(self): return "B"
706 self.assertEqual(B().spam(), "B")
707 self.assertEqual(B().boo(), "B")
708 class C(A):
709 def boo(self): return "C"
710 self.assertEqual(C().spam(), "A")
711 self.assertEqual(C().boo(), "C")
712 class D(B, C): pass
713 self.assertEqual(D().spam(), "B")
714 self.assertEqual(D().boo(), "B")
715 self.assertEqual(D.__mro__, (D, B, C, A, object))
716 class E(C, B): pass
717 self.assertEqual(E().spam(), "B")
718 self.assertEqual(E().boo(), "C")
719 self.assertEqual(E.__mro__, (E, C, B, A, object))
720 # MRO order disagreement
721 try:
722 class F(D, E): pass
723 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000724 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000725 else:
726 self.fail("expected MRO order disagreement (F)")
727 try:
728 class G(E, D): pass
729 except TypeError:
730 pass
731 else:
732 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000733
Georg Brandl479a7e72008-02-05 18:13:15 +0000734 # see thread python-dev/2002-October/029035.html
735 def test_ex5_from_c3_switch(self):
736 # Testing ex5 from C3 switch discussion...
737 class A(object): pass
738 class B(object): pass
739 class C(object): pass
740 class X(A): pass
741 class Y(A): pass
742 class Z(X,B,Y,C): pass
743 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744
Georg Brandl479a7e72008-02-05 18:13:15 +0000745 # see "A Monotonic Superclass Linearization for Dylan",
746 # by Kim Barrett et al. (OOPSLA 1996)
747 def test_monotonicity(self):
748 # Testing MRO monotonicity...
749 class Boat(object): pass
750 class DayBoat(Boat): pass
751 class WheelBoat(Boat): pass
752 class EngineLess(DayBoat): pass
753 class SmallMultihull(DayBoat): pass
754 class PedalWheelBoat(EngineLess,WheelBoat): pass
755 class SmallCatamaran(SmallMultihull): pass
756 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000757
Georg Brandl479a7e72008-02-05 18:13:15 +0000758 self.assertEqual(PedalWheelBoat.__mro__,
759 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
760 self.assertEqual(SmallCatamaran.__mro__,
761 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
762 self.assertEqual(Pedalo.__mro__,
763 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
764 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000765
Georg Brandl479a7e72008-02-05 18:13:15 +0000766 # see "A Monotonic Superclass Linearization for Dylan",
767 # by Kim Barrett et al. (OOPSLA 1996)
768 def test_consistency_with_epg(self):
769 # Testing consistentcy with EPG...
770 class Pane(object): pass
771 class ScrollingMixin(object): pass
772 class EditingMixin(object): pass
773 class ScrollablePane(Pane,ScrollingMixin): pass
774 class EditablePane(Pane,EditingMixin): pass
775 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000776
Georg Brandl479a7e72008-02-05 18:13:15 +0000777 self.assertEqual(EditableScrollablePane.__mro__,
778 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
779 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000780
Georg Brandl479a7e72008-02-05 18:13:15 +0000781 def test_mro_disagreement(self):
782 # Testing error messages for MRO disagreement...
783 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000784order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000785
Georg Brandl479a7e72008-02-05 18:13:15 +0000786 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000787 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000788 callable(*args)
789 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000790 # the exact msg is generally considered an impl detail
791 if support.check_impl_detail():
792 if not str(msg).startswith(expected):
793 self.fail("Message %r, expected %r" %
794 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000795 else:
796 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000797
Georg Brandl479a7e72008-02-05 18:13:15 +0000798 class A(object): pass
799 class B(A): pass
800 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000801
Georg Brandl479a7e72008-02-05 18:13:15 +0000802 # Test some very simple errors
803 raises(TypeError, "duplicate base class A",
804 type, "X", (A, A), {})
805 raises(TypeError, mro_err_msg,
806 type, "X", (A, B), {})
807 raises(TypeError, mro_err_msg,
808 type, "X", (A, C, B), {})
809 # Test a slightly more complex error
810 class GridLayout(object): pass
811 class HorizontalGrid(GridLayout): pass
812 class VerticalGrid(GridLayout): pass
813 class HVGrid(HorizontalGrid, VerticalGrid): pass
814 class VHGrid(VerticalGrid, HorizontalGrid): pass
815 raises(TypeError, mro_err_msg,
816 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000817
Georg Brandl479a7e72008-02-05 18:13:15 +0000818 def test_object_class(self):
819 # Testing object class...
820 a = object()
821 self.assertEqual(a.__class__, object)
822 self.assertEqual(type(a), object)
823 b = object()
824 self.assertNotEqual(a, b)
825 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +0000826 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000827 a.foo = 12
828 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +0000829 pass
830 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000831 self.fail("object() should not allow setting a foo attribute")
832 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +0000833
Georg Brandl479a7e72008-02-05 18:13:15 +0000834 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000835 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000836 x = Cdict()
837 self.assertEqual(x.__dict__, {})
838 x.foo = 1
839 self.assertEqual(x.foo, 1)
840 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +0000841
Georg Brandl479a7e72008-02-05 18:13:15 +0000842 def test_slots(self):
843 # Testing __slots__...
844 class C0(object):
845 __slots__ = []
846 x = C0()
847 self.assertFalse(hasattr(x, "__dict__"))
848 self.assertFalse(hasattr(x, "foo"))
849
850 class C1(object):
851 __slots__ = ['a']
852 x = C1()
853 self.assertFalse(hasattr(x, "__dict__"))
854 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000855 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +0000856 self.assertEqual(x.a, 1)
857 x.a = None
858 self.assertEqual(x.a, None)
859 del x.a
860 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000861
Georg Brandl479a7e72008-02-05 18:13:15 +0000862 class C3(object):
863 __slots__ = ['a', 'b', 'c']
864 x = C3()
865 self.assertFalse(hasattr(x, "__dict__"))
866 self.assertFalse(hasattr(x, 'a'))
867 self.assertFalse(hasattr(x, 'b'))
868 self.assertFalse(hasattr(x, 'c'))
869 x.a = 1
870 x.b = 2
871 x.c = 3
872 self.assertEqual(x.a, 1)
873 self.assertEqual(x.b, 2)
874 self.assertEqual(x.c, 3)
875
876 class C4(object):
877 """Validate name mangling"""
878 __slots__ = ['__a']
879 def __init__(self, value):
880 self.__a = value
881 def get(self):
882 return self.__a
883 x = C4(5)
884 self.assertFalse(hasattr(x, '__dict__'))
885 self.assertFalse(hasattr(x, '__a'))
886 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000887 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000888 x.__a = 6
889 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +0000890 pass
891 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000892 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000893
Georg Brandl479a7e72008-02-05 18:13:15 +0000894 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +0000895 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000896 class C(object):
897 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +0000898 except TypeError:
899 pass
900 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000901 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000902 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000903 class C(object):
904 __slots__ = ["foo bar"]
905 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000906 pass
907 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000908 self.fail("['foo bar'] slots not caught")
909 try:
910 class C(object):
911 __slots__ = ["foo\0bar"]
912 except TypeError:
913 pass
914 else:
915 self.fail("['foo\\0bar'] slots not caught")
916 try:
917 class C(object):
918 __slots__ = ["1"]
919 except TypeError:
920 pass
921 else:
922 self.fail("['1'] slots not caught")
923 try:
924 class C(object):
925 __slots__ = [""]
926 except TypeError:
927 pass
928 else:
929 self.fail("[''] slots not caught")
930 class C(object):
931 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
932 # XXX(nnorwitz): was there supposed to be something tested
933 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +0000934
Georg Brandl479a7e72008-02-05 18:13:15 +0000935 # Test a single string is not expanded as a sequence.
936 class C(object):
937 __slots__ = "abc"
938 c = C()
939 c.abc = 5
940 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000941
Georg Brandl479a7e72008-02-05 18:13:15 +0000942 # Test unicode slot names
943 # Test a single unicode string is not expanded as a sequence.
944 class C(object):
945 __slots__ = "abc"
946 c = C()
947 c.abc = 5
948 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +0000949
Georg Brandl479a7e72008-02-05 18:13:15 +0000950 # _unicode_to_string used to modify slots in certain circumstances
951 slots = ("foo", "bar")
952 class C(object):
953 __slots__ = slots
954 x = C()
955 x.foo = 5
956 self.assertEqual(x.foo, 5)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000957 self.assertTrue(type(slots[0]) is str)
Georg Brandl479a7e72008-02-05 18:13:15 +0000958 # this used to leak references
959 try:
960 class C(object):
961 __slots__ = [chr(128)]
962 except (TypeError, UnicodeEncodeError):
963 pass
964 else:
965 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +0000966
Georg Brandl479a7e72008-02-05 18:13:15 +0000967 # Test leaks
968 class Counted(object):
969 counter = 0 # counts the number of instances alive
970 def __init__(self):
971 Counted.counter += 1
972 def __del__(self):
973 Counted.counter -= 1
974 class C(object):
975 __slots__ = ['a', 'b', 'c']
976 x = C()
977 x.a = Counted()
978 x.b = Counted()
979 x.c = Counted()
980 self.assertEqual(Counted.counter, 3)
981 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000982 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000983 self.assertEqual(Counted.counter, 0)
984 class D(C):
985 pass
986 x = D()
987 x.a = Counted()
988 x.z = Counted()
989 self.assertEqual(Counted.counter, 2)
990 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000991 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000992 self.assertEqual(Counted.counter, 0)
993 class E(D):
994 __slots__ = ['e']
995 x = E()
996 x.a = Counted()
997 x.z = Counted()
998 x.e = Counted()
999 self.assertEqual(Counted.counter, 3)
1000 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001001 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001002 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001003
Georg Brandl479a7e72008-02-05 18:13:15 +00001004 # Test cyclical leaks [SF bug 519621]
1005 class F(object):
1006 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001007 s = F()
1008 s.a = [Counted(), s]
1009 self.assertEqual(Counted.counter, 1)
1010 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001011 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001012 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001013
Georg Brandl479a7e72008-02-05 18:13:15 +00001014 # Test lookup leaks [SF bug 572567]
Georg Brandl1b37e872010-03-14 10:45:50 +00001015 import gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001016 if hasattr(gc, 'get_objects'):
1017 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001018 def __eq__(self, other):
1019 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001020 g = G()
1021 orig_objects = len(gc.get_objects())
1022 for i in range(10):
1023 g==g
1024 new_objects = len(gc.get_objects())
1025 self.assertEqual(orig_objects, new_objects)
1026
Georg Brandl479a7e72008-02-05 18:13:15 +00001027 class H(object):
1028 __slots__ = ['a', 'b']
1029 def __init__(self):
1030 self.a = 1
1031 self.b = 2
1032 def __del__(self_):
1033 self.assertEqual(self_.a, 1)
1034 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001035 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001036 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001037 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001038 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001039
Benjamin Petersond12362a2009-12-30 19:44:54 +00001040 class X(object):
1041 __slots__ = "a"
1042 with self.assertRaises(AttributeError):
1043 del X().a
1044
Georg Brandl479a7e72008-02-05 18:13:15 +00001045 def test_slots_special(self):
1046 # Testing __dict__ and __weakref__ in __slots__...
1047 class D(object):
1048 __slots__ = ["__dict__"]
1049 a = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001050 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001051 self.assertFalse(hasattr(a, "__weakref__"))
1052 a.foo = 42
1053 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001054
Georg Brandl479a7e72008-02-05 18:13:15 +00001055 class W(object):
1056 __slots__ = ["__weakref__"]
1057 a = W()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001058 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001059 self.assertFalse(hasattr(a, "__dict__"))
1060 try:
1061 a.foo = 42
1062 except AttributeError:
1063 pass
1064 else:
1065 self.fail("shouldn't be allowed to set a.foo")
1066
1067 class C1(W, D):
1068 __slots__ = []
1069 a = C1()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001070 self.assertTrue(hasattr(a, "__dict__"))
1071 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001072 a.foo = 42
1073 self.assertEqual(a.__dict__, {"foo": 42})
1074
1075 class C2(D, W):
1076 __slots__ = []
1077 a = C2()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001078 self.assertTrue(hasattr(a, "__dict__"))
1079 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001080 a.foo = 42
1081 self.assertEqual(a.__dict__, {"foo": 42})
1082
Christian Heimesa156e092008-02-16 07:38:31 +00001083 def test_slots_descriptor(self):
1084 # Issue2115: slot descriptors did not correctly check
1085 # the type of the given object
1086 import abc
1087 class MyABC(metaclass=abc.ABCMeta):
1088 __slots__ = "a"
1089
1090 class Unrelated(object):
1091 pass
1092 MyABC.register(Unrelated)
1093
1094 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001095 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001096
1097 # This used to crash
1098 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1099
Georg Brandl479a7e72008-02-05 18:13:15 +00001100 def test_dynamics(self):
1101 # Testing class attribute propagation...
1102 class D(object):
1103 pass
1104 class E(D):
1105 pass
1106 class F(D):
1107 pass
1108 D.foo = 1
1109 self.assertEqual(D.foo, 1)
1110 # Test that dynamic attributes are inherited
1111 self.assertEqual(E.foo, 1)
1112 self.assertEqual(F.foo, 1)
1113 # Test dynamic instances
1114 class C(object):
1115 pass
1116 a = C()
1117 self.assertFalse(hasattr(a, "foobar"))
1118 C.foobar = 2
1119 self.assertEqual(a.foobar, 2)
1120 C.method = lambda self: 42
1121 self.assertEqual(a.method(), 42)
1122 C.__repr__ = lambda self: "C()"
1123 self.assertEqual(repr(a), "C()")
1124 C.__int__ = lambda self: 100
1125 self.assertEqual(int(a), 100)
1126 self.assertEqual(a.foobar, 2)
1127 self.assertFalse(hasattr(a, "spam"))
1128 def mygetattr(self, name):
1129 if name == "spam":
1130 return "spam"
1131 raise AttributeError
1132 C.__getattr__ = mygetattr
1133 self.assertEqual(a.spam, "spam")
1134 a.new = 12
1135 self.assertEqual(a.new, 12)
1136 def mysetattr(self, name, value):
1137 if name == "spam":
1138 raise AttributeError
1139 return object.__setattr__(self, name, value)
1140 C.__setattr__ = mysetattr
1141 try:
1142 a.spam = "not spam"
1143 except AttributeError:
1144 pass
1145 else:
1146 self.fail("expected AttributeError")
1147 self.assertEqual(a.spam, "spam")
1148 class D(C):
1149 pass
1150 d = D()
1151 d.foo = 1
1152 self.assertEqual(d.foo, 1)
1153
1154 # Test handling of int*seq and seq*int
1155 class I(int):
1156 pass
1157 self.assertEqual("a"*I(2), "aa")
1158 self.assertEqual(I(2)*"a", "aa")
1159 self.assertEqual(2*I(3), 6)
1160 self.assertEqual(I(3)*2, 6)
1161 self.assertEqual(I(3)*I(2), 6)
1162
Georg Brandl479a7e72008-02-05 18:13:15 +00001163 # Test comparison of classes with dynamic metaclasses
1164 class dynamicmetaclass(type):
1165 pass
1166 class someclass(metaclass=dynamicmetaclass):
1167 pass
1168 self.assertNotEqual(someclass, object)
1169
1170 def test_errors(self):
1171 # Testing errors...
1172 try:
1173 class C(list, dict):
1174 pass
1175 except TypeError:
1176 pass
1177 else:
1178 self.fail("inheritance from both list and dict should be illegal")
1179
1180 try:
1181 class C(object, None):
1182 pass
1183 except TypeError:
1184 pass
1185 else:
1186 self.fail("inheritance from non-type should be illegal")
1187 class Classic:
1188 pass
1189
1190 try:
1191 class C(type(len)):
1192 pass
1193 except TypeError:
1194 pass
1195 else:
1196 self.fail("inheritance from CFunction should be illegal")
1197
1198 try:
1199 class C(object):
1200 __slots__ = 1
1201 except TypeError:
1202 pass
1203 else:
1204 self.fail("__slots__ = 1 should be illegal")
1205
1206 try:
1207 class C(object):
1208 __slots__ = [1]
1209 except TypeError:
1210 pass
1211 else:
1212 self.fail("__slots__ = [1] should be illegal")
1213
1214 class M1(type):
1215 pass
1216 class M2(type):
1217 pass
1218 class A1(object, metaclass=M1):
1219 pass
1220 class A2(object, metaclass=M2):
1221 pass
1222 try:
1223 class B(A1, A2):
1224 pass
1225 except TypeError:
1226 pass
1227 else:
1228 self.fail("finding the most derived metaclass should have failed")
1229
1230 def test_classmethods(self):
1231 # Testing class methods...
1232 class C(object):
1233 def foo(*a): return a
1234 goo = classmethod(foo)
1235 c = C()
1236 self.assertEqual(C.goo(1), (C, 1))
1237 self.assertEqual(c.goo(1), (C, 1))
1238 self.assertEqual(c.foo(1), (c, 1))
1239 class D(C):
1240 pass
1241 d = D()
1242 self.assertEqual(D.goo(1), (D, 1))
1243 self.assertEqual(d.goo(1), (D, 1))
1244 self.assertEqual(d.foo(1), (d, 1))
1245 self.assertEqual(D.foo(d, 1), (d, 1))
1246 # Test for a specific crash (SF bug 528132)
1247 def f(cls, arg): return (cls, arg)
1248 ff = classmethod(f)
1249 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1250 self.assertEqual(ff.__get__(0)(42), (int, 42))
1251
1252 # Test super() with classmethods (SF bug 535444)
1253 self.assertEqual(C.goo.__self__, C)
1254 self.assertEqual(D.goo.__self__, D)
1255 self.assertEqual(super(D,D).goo.__self__, D)
1256 self.assertEqual(super(D,d).goo.__self__, D)
1257 self.assertEqual(super(D,D).goo(), (D,))
1258 self.assertEqual(super(D,d).goo(), (D,))
1259
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001260 # Verify that a non-callable will raise
1261 meth = classmethod(1).__get__(1)
1262 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001263
1264 # Verify that classmethod() doesn't allow keyword args
1265 try:
1266 classmethod(f, kw=1)
1267 except TypeError:
1268 pass
1269 else:
1270 self.fail("classmethod shouldn't accept keyword args")
1271
Benjamin Petersone549ead2009-03-28 21:42:05 +00001272 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001273 def test_classmethods_in_c(self):
1274 # Testing C-based class methods...
1275 import xxsubtype as spam
1276 a = (1, 2, 3)
1277 d = {'abc': 123}
1278 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1279 self.assertEqual(x, spam.spamlist)
1280 self.assertEqual(a, a1)
1281 self.assertEqual(d, d1)
1282 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1283 self.assertEqual(x, spam.spamlist)
1284 self.assertEqual(a, a1)
1285 self.assertEqual(d, d1)
1286
1287 def test_staticmethods(self):
1288 # Testing static methods...
1289 class C(object):
1290 def foo(*a): return a
1291 goo = staticmethod(foo)
1292 c = C()
1293 self.assertEqual(C.goo(1), (1,))
1294 self.assertEqual(c.goo(1), (1,))
1295 self.assertEqual(c.foo(1), (c, 1,))
1296 class D(C):
1297 pass
1298 d = D()
1299 self.assertEqual(D.goo(1), (1,))
1300 self.assertEqual(d.goo(1), (1,))
1301 self.assertEqual(d.foo(1), (d, 1))
1302 self.assertEqual(D.foo(d, 1), (d, 1))
1303
Benjamin Petersone549ead2009-03-28 21:42:05 +00001304 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001305 def test_staticmethods_in_c(self):
1306 # Testing C-based static methods...
1307 import xxsubtype as spam
1308 a = (1, 2, 3)
1309 d = {"abc": 123}
1310 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1311 self.assertEqual(x, None)
1312 self.assertEqual(a, a1)
1313 self.assertEqual(d, d1)
1314 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1315 self.assertEqual(x, None)
1316 self.assertEqual(a, a1)
1317 self.assertEqual(d, d1)
1318
1319 def test_classic(self):
1320 # Testing classic classes...
1321 class C:
1322 def foo(*a): return a
1323 goo = classmethod(foo)
1324 c = C()
1325 self.assertEqual(C.goo(1), (C, 1))
1326 self.assertEqual(c.goo(1), (C, 1))
1327 self.assertEqual(c.foo(1), (c, 1))
1328 class D(C):
1329 pass
1330 d = D()
1331 self.assertEqual(D.goo(1), (D, 1))
1332 self.assertEqual(d.goo(1), (D, 1))
1333 self.assertEqual(d.foo(1), (d, 1))
1334 self.assertEqual(D.foo(d, 1), (d, 1))
1335 class E: # *not* subclassing from C
1336 foo = C.foo
1337 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001338 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001339
1340 def test_compattr(self):
1341 # Testing computed attributes...
1342 class C(object):
1343 class computed_attribute(object):
1344 def __init__(self, get, set=None, delete=None):
1345 self.__get = get
1346 self.__set = set
1347 self.__delete = delete
1348 def __get__(self, obj, type=None):
1349 return self.__get(obj)
1350 def __set__(self, obj, value):
1351 return self.__set(obj, value)
1352 def __delete__(self, obj):
1353 return self.__delete(obj)
1354 def __init__(self):
1355 self.__x = 0
1356 def __get_x(self):
1357 x = self.__x
1358 self.__x = x+1
1359 return x
1360 def __set_x(self, x):
1361 self.__x = x
1362 def __delete_x(self):
1363 del self.__x
1364 x = computed_attribute(__get_x, __set_x, __delete_x)
1365 a = C()
1366 self.assertEqual(a.x, 0)
1367 self.assertEqual(a.x, 1)
1368 a.x = 10
1369 self.assertEqual(a.x, 10)
1370 self.assertEqual(a.x, 11)
1371 del a.x
1372 self.assertEqual(hasattr(a, 'x'), 0)
1373
1374 def test_newslots(self):
1375 # Testing __new__ slot override...
1376 class C(list):
1377 def __new__(cls):
1378 self = list.__new__(cls)
1379 self.foo = 1
1380 return self
1381 def __init__(self):
1382 self.foo = self.foo + 2
1383 a = C()
1384 self.assertEqual(a.foo, 3)
1385 self.assertEqual(a.__class__, C)
1386 class D(C):
1387 pass
1388 b = D()
1389 self.assertEqual(b.foo, 3)
1390 self.assertEqual(b.__class__, D)
1391
1392 def test_altmro(self):
1393 # Testing mro() and overriding it...
1394 class A(object):
1395 def f(self): return "A"
1396 class B(A):
1397 pass
1398 class C(A):
1399 def f(self): return "C"
1400 class D(B, C):
1401 pass
1402 self.assertEqual(D.mro(), [D, B, C, A, object])
1403 self.assertEqual(D.__mro__, (D, B, C, A, object))
1404 self.assertEqual(D().f(), "C")
1405
1406 class PerverseMetaType(type):
1407 def mro(cls):
1408 L = type.mro(cls)
1409 L.reverse()
1410 return L
1411 class X(D,B,C,A, metaclass=PerverseMetaType):
1412 pass
1413 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1414 self.assertEqual(X().f(), "A")
1415
1416 try:
1417 class _metaclass(type):
1418 def mro(self):
1419 return [self, dict, object]
1420 class X(object, metaclass=_metaclass):
1421 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001422 # In CPython, the class creation above already raises
1423 # TypeError, as a protection against the fact that
1424 # instances of X would segfault it. In other Python
1425 # implementations it would be ok to let the class X
1426 # be created, but instead get a clean TypeError on the
1427 # __setitem__ below.
1428 x = object.__new__(X)
1429 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001430 except TypeError:
1431 pass
1432 else:
1433 self.fail("devious mro() return not caught")
1434
1435 try:
1436 class _metaclass(type):
1437 def mro(self):
1438 return [1]
1439 class X(object, metaclass=_metaclass):
1440 pass
1441 except TypeError:
1442 pass
1443 else:
1444 self.fail("non-class 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-sequence mro() return not caught")
1456
1457 def test_overloading(self):
1458 # Testing operator overloading...
1459
1460 class B(object):
1461 "Intermediate class because object doesn't have a __setattr__"
1462
1463 class C(B):
1464 def __getattr__(self, name):
1465 if name == "foo":
1466 return ("getattr", name)
1467 else:
1468 raise AttributeError
1469 def __setattr__(self, name, value):
1470 if name == "foo":
1471 self.setattr = (name, value)
1472 else:
1473 return B.__setattr__(self, name, value)
1474 def __delattr__(self, name):
1475 if name == "foo":
1476 self.delattr = name
1477 else:
1478 return B.__delattr__(self, name)
1479
1480 def __getitem__(self, key):
1481 return ("getitem", key)
1482 def __setitem__(self, key, value):
1483 self.setitem = (key, value)
1484 def __delitem__(self, key):
1485 self.delitem = key
1486
1487 a = C()
1488 self.assertEqual(a.foo, ("getattr", "foo"))
1489 a.foo = 12
1490 self.assertEqual(a.setattr, ("foo", 12))
1491 del a.foo
1492 self.assertEqual(a.delattr, "foo")
1493
1494 self.assertEqual(a[12], ("getitem", 12))
1495 a[12] = 21
1496 self.assertEqual(a.setitem, (12, 21))
1497 del a[12]
1498 self.assertEqual(a.delitem, 12)
1499
1500 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1501 a[0:10] = "foo"
1502 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1503 del a[0:10]
1504 self.assertEqual(a.delitem, (slice(0, 10)))
1505
1506 def test_methods(self):
1507 # Testing methods...
1508 class C(object):
1509 def __init__(self, x):
1510 self.x = x
1511 def foo(self):
1512 return self.x
1513 c1 = C(1)
1514 self.assertEqual(c1.foo(), 1)
1515 class D(C):
1516 boo = C.foo
1517 goo = c1.foo
1518 d2 = D(2)
1519 self.assertEqual(d2.foo(), 2)
1520 self.assertEqual(d2.boo(), 2)
1521 self.assertEqual(d2.goo(), 1)
1522 class E(object):
1523 foo = C.foo
1524 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001525 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001526
Benjamin Peterson224205f2009-05-08 03:25:19 +00001527 def test_special_method_lookup(self):
1528 # The lookup of special methods bypasses __getattr__ and
1529 # __getattribute__, but they still can be descriptors.
1530
1531 def run_context(manager):
1532 with manager:
1533 pass
1534 def iden(self):
1535 return self
1536 def hello(self):
1537 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001538 def empty_seq(self):
1539 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001540 def zero(self):
1541 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001542 def complex_num(self):
1543 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001544 def stop(self):
1545 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001546 def return_true(self, thing=None):
1547 return True
1548 def do_isinstance(obj):
1549 return isinstance(int, obj)
1550 def do_issubclass(obj):
1551 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001552 def do_dict_missing(checker):
1553 class DictSub(checker.__class__, dict):
1554 pass
1555 self.assertEqual(DictSub()["hi"], 4)
1556 def some_number(self_, key):
1557 self.assertEqual(key, "hi")
1558 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001559 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001560 def format_impl(self, spec):
1561 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001562
1563 # It would be nice to have every special method tested here, but I'm
1564 # only listing the ones I can remember outside of typeobject.c, since it
1565 # does it right.
1566 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001567 ("__bytes__", bytes, hello, set(), {}),
1568 ("__reversed__", reversed, empty_seq, set(), {}),
1569 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001570 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001571 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1572 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001573 ("__missing__", do_dict_missing, some_number,
1574 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001575 ("__subclasscheck__", do_issubclass, return_true,
1576 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001577 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1578 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001579 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001580 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001581 ]
1582
1583 class Checker(object):
1584 def __getattr__(self, attr, test=self):
1585 test.fail("__getattr__ called with {0}".format(attr))
1586 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001587 if attr not in ok:
1588 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001589 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001590 class SpecialDescr(object):
1591 def __init__(self, impl):
1592 self.impl = impl
1593 def __get__(self, obj, owner):
1594 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001595 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001596 class MyException(Exception):
1597 pass
1598 class ErrDescr(object):
1599 def __get__(self, obj, owner):
1600 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001601
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001602 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001603 class X(Checker):
1604 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001605 for attr, obj in env.items():
1606 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001607 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001608 runner(X())
1609
1610 record = []
1611 class X(Checker):
1612 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001613 for attr, obj in env.items():
1614 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001615 setattr(X, name, SpecialDescr(meth_impl))
1616 runner(X())
1617 self.assertEqual(record, [1], name)
1618
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001619 class X(Checker):
1620 pass
1621 for attr, obj in env.items():
1622 setattr(X, attr, obj)
1623 setattr(X, name, ErrDescr())
1624 try:
1625 runner(X())
1626 except MyException:
1627 pass
1628 else:
1629 self.fail("{0!r} didn't raise".format(name))
1630
Georg Brandl479a7e72008-02-05 18:13:15 +00001631 def test_specials(self):
1632 # Testing special operators...
1633 # Test operators like __hash__ for which a built-in default exists
1634
1635 # Test the default behavior for static classes
1636 class C(object):
1637 def __getitem__(self, i):
1638 if 0 <= i < 10: return i
1639 raise IndexError
1640 c1 = C()
1641 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001642 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001643 self.assertNotEqual(id(c1), id(c2))
1644 hash(c1)
1645 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001646 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001647 self.assertTrue(c1 != c2)
1648 self.assertTrue(not c1 != c1)
1649 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001650 # Note that the module name appears in str/repr, and that varies
1651 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001652 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001653 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001654 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001655 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001656 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001657 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001658 # Test the default behavior for dynamic classes
1659 class D(object):
1660 def __getitem__(self, i):
1661 if 0 <= i < 10: return i
1662 raise IndexError
1663 d1 = D()
1664 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001665 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001666 self.assertNotEqual(id(d1), id(d2))
1667 hash(d1)
1668 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001669 self.assertEqual(d1, d1)
1670 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001671 self.assertTrue(not d1 != d1)
1672 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001673 # Note that the module name appears in str/repr, and that varies
1674 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001675 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001676 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001677 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001678 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001679 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001680 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001681 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001682 class Proxy(object):
1683 def __init__(self, x):
1684 self.x = x
1685 def __bool__(self):
1686 return not not self.x
1687 def __hash__(self):
1688 return hash(self.x)
1689 def __eq__(self, other):
1690 return self.x == other
1691 def __ne__(self, other):
1692 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001693 def __ge__(self, other):
1694 return self.x >= other
1695 def __gt__(self, other):
1696 return self.x > other
1697 def __le__(self, other):
1698 return self.x <= other
1699 def __lt__(self, other):
1700 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001701 def __str__(self):
1702 return "Proxy:%s" % self.x
1703 def __repr__(self):
1704 return "Proxy(%r)" % self.x
1705 def __contains__(self, value):
1706 return value in self.x
1707 p0 = Proxy(0)
1708 p1 = Proxy(1)
1709 p_1 = Proxy(-1)
1710 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001711 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001712 self.assertEqual(hash(p0), hash(0))
1713 self.assertEqual(p0, p0)
1714 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001715 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001716 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001717 self.assertTrue(p0 < p1)
1718 self.assertTrue(p0 <= p1)
1719 self.assertTrue(p1 > p0)
1720 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001721 self.assertEqual(str(p0), "Proxy:0")
1722 self.assertEqual(repr(p0), "Proxy(0)")
1723 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001724 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001725 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001726 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001727 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001728
Georg Brandl479a7e72008-02-05 18:13:15 +00001729 def test_weakrefs(self):
1730 # Testing weak references...
1731 import weakref
1732 class C(object):
1733 pass
1734 c = C()
1735 r = weakref.ref(c)
1736 self.assertEqual(r(), c)
1737 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001738 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001739 self.assertEqual(r(), None)
1740 del r
1741 class NoWeak(object):
1742 __slots__ = ['foo']
1743 no = NoWeak()
1744 try:
1745 weakref.ref(no)
1746 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001747 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001748 else:
1749 self.fail("weakref.ref(no) should be illegal")
1750 class Weak(object):
1751 __slots__ = ['foo', '__weakref__']
1752 yes = Weak()
1753 r = weakref.ref(yes)
1754 self.assertEqual(r(), yes)
1755 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001756 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001757 self.assertEqual(r(), None)
1758 del r
1759
1760 def test_properties(self):
1761 # Testing property...
1762 class C(object):
1763 def getx(self):
1764 return self.__x
1765 def setx(self, value):
1766 self.__x = value
1767 def delx(self):
1768 del self.__x
1769 x = property(getx, setx, delx, doc="I'm the x property.")
1770 a = C()
1771 self.assertFalse(hasattr(a, "x"))
1772 a.x = 42
1773 self.assertEqual(a._C__x, 42)
1774 self.assertEqual(a.x, 42)
1775 del a.x
1776 self.assertFalse(hasattr(a, "x"))
1777 self.assertFalse(hasattr(a, "_C__x"))
1778 C.x.__set__(a, 100)
1779 self.assertEqual(C.x.__get__(a), 100)
1780 C.x.__delete__(a)
1781 self.assertFalse(hasattr(a, "x"))
1782
1783 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001784 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001785
1786 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001787 self.assertIn("__doc__", attrs)
1788 self.assertIn("fget", attrs)
1789 self.assertIn("fset", attrs)
1790 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001791
1792 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001793 self.assertTrue(raw.fget is C.__dict__['getx'])
1794 self.assertTrue(raw.fset is C.__dict__['setx'])
1795 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001796
1797 for attr in "__doc__", "fget", "fset", "fdel":
1798 try:
1799 setattr(raw, attr, 42)
1800 except AttributeError as msg:
1801 if str(msg).find('readonly') < 0:
1802 self.fail("when setting readonly attr %r on a property, "
1803 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1804 else:
1805 self.fail("expected AttributeError from trying to set readonly %r "
1806 "attr on a property" % attr)
1807
1808 class D(object):
1809 __getitem__ = property(lambda s: 1/0)
1810
1811 d = D()
1812 try:
1813 for i in d:
1814 str(i)
1815 except ZeroDivisionError:
1816 pass
1817 else:
1818 self.fail("expected ZeroDivisionError from bad property")
1819
R. David Murray378c0cf2010-02-24 01:46:21 +00001820 @unittest.skipIf(sys.flags.optimize >= 2,
1821 "Docstrings are omitted with -O2 and above")
1822 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00001823 class E(object):
1824 def getter(self):
1825 "getter method"
1826 return 0
1827 def setter(self_, value):
1828 "setter method"
1829 pass
1830 prop = property(getter)
1831 self.assertEqual(prop.__doc__, "getter method")
1832 prop2 = property(fset=setter)
1833 self.assertEqual(prop2.__doc__, None)
1834
R. David Murray378c0cf2010-02-24 01:46:21 +00001835 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00001836 # this segfaulted in 2.5b2
1837 try:
1838 import _testcapi
1839 except ImportError:
1840 pass
1841 else:
1842 class X(object):
1843 p = property(_testcapi.test_with_docstring)
1844
1845 def test_properties_plus(self):
1846 class C(object):
1847 foo = property(doc="hello")
1848 @foo.getter
1849 def foo(self):
1850 return self._foo
1851 @foo.setter
1852 def foo(self, value):
1853 self._foo = abs(value)
1854 @foo.deleter
1855 def foo(self):
1856 del self._foo
1857 c = C()
1858 self.assertEqual(C.foo.__doc__, "hello")
1859 self.assertFalse(hasattr(c, "foo"))
1860 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001861 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00001862 self.assertEqual(c._foo, 42)
1863 self.assertEqual(c.foo, 42)
1864 del c.foo
1865 self.assertFalse(hasattr(c, '_foo'))
1866 self.assertFalse(hasattr(c, "foo"))
1867
1868 class D(C):
1869 @C.foo.deleter
1870 def foo(self):
1871 try:
1872 del self._foo
1873 except AttributeError:
1874 pass
1875 d = D()
1876 d.foo = 24
1877 self.assertEqual(d.foo, 24)
1878 del d.foo
1879 del d.foo
1880
1881 class E(object):
1882 @property
1883 def foo(self):
1884 return self._foo
1885 @foo.setter
1886 def foo(self, value):
1887 raise RuntimeError
1888 @foo.setter
1889 def foo(self, value):
1890 self._foo = abs(value)
1891 @foo.deleter
1892 def foo(self, value=None):
1893 del self._foo
1894
1895 e = E()
1896 e.foo = -42
1897 self.assertEqual(e.foo, 42)
1898 del e.foo
1899
1900 class F(E):
1901 @E.foo.deleter
1902 def foo(self):
1903 del self._foo
1904 @foo.setter
1905 def foo(self, value):
1906 self._foo = max(0, value)
1907 f = F()
1908 f.foo = -10
1909 self.assertEqual(f.foo, 0)
1910 del f.foo
1911
1912 def test_dict_constructors(self):
1913 # Testing dict constructor ...
1914 d = dict()
1915 self.assertEqual(d, {})
1916 d = dict({})
1917 self.assertEqual(d, {})
1918 d = dict({1: 2, 'a': 'b'})
1919 self.assertEqual(d, {1: 2, 'a': 'b'})
1920 self.assertEqual(d, dict(list(d.items())))
1921 self.assertEqual(d, dict(iter(d.items())))
1922 d = dict({'one':1, 'two':2})
1923 self.assertEqual(d, dict(one=1, two=2))
1924 self.assertEqual(d, dict(**d))
1925 self.assertEqual(d, dict({"one": 1}, two=2))
1926 self.assertEqual(d, dict([("two", 2)], one=1))
1927 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1928 self.assertEqual(d, dict(**d))
1929
1930 for badarg in 0, 0, 0j, "0", [0], (0,):
1931 try:
1932 dict(badarg)
1933 except TypeError:
1934 pass
1935 except ValueError:
1936 if badarg == "0":
1937 # It's a sequence, and its elements are also sequences (gotta
1938 # love strings <wink>), but they aren't of length 2, so this
1939 # one seemed better as a ValueError than a TypeError.
1940 pass
1941 else:
1942 self.fail("no TypeError from dict(%r)" % badarg)
1943 else:
1944 self.fail("no TypeError from dict(%r)" % badarg)
1945
1946 try:
1947 dict({}, {})
1948 except TypeError:
1949 pass
1950 else:
1951 self.fail("no TypeError from dict({}, {})")
1952
1953 class Mapping:
1954 # Lacks a .keys() method; will be added later.
1955 dict = {1:2, 3:4, 'a':1j}
1956
1957 try:
1958 dict(Mapping())
1959 except TypeError:
1960 pass
1961 else:
1962 self.fail("no TypeError from dict(incomplete mapping)")
1963
1964 Mapping.keys = lambda self: list(self.dict.keys())
1965 Mapping.__getitem__ = lambda self, i: self.dict[i]
1966 d = dict(Mapping())
1967 self.assertEqual(d, Mapping.dict)
1968
1969 # Init from sequence of iterable objects, each producing a 2-sequence.
1970 class AddressBookEntry:
1971 def __init__(self, first, last):
1972 self.first = first
1973 self.last = last
1974 def __iter__(self):
1975 return iter([self.first, self.last])
1976
1977 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1978 AddressBookEntry('Barry', 'Peters'),
1979 AddressBookEntry('Tim', 'Peters'),
1980 AddressBookEntry('Barry', 'Warsaw')])
1981 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1982
1983 d = dict(zip(range(4), range(1, 5)))
1984 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1985
1986 # Bad sequence lengths.
1987 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1988 try:
1989 dict(bad)
1990 except ValueError:
1991 pass
1992 else:
1993 self.fail("no ValueError from dict(%r)" % bad)
1994
1995 def test_dir(self):
1996 # Testing dir() ...
1997 junk = 12
1998 self.assertEqual(dir(), ['junk', 'self'])
1999 del junk
2000
2001 # Just make sure these don't blow up!
2002 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2003 dir(arg)
2004
2005 # Test dir on new-style classes. Since these have object as a
2006 # base class, a lot more gets sucked in.
2007 def interesting(strings):
2008 return [s for s in strings if not s.startswith('_')]
2009
2010 class C(object):
2011 Cdata = 1
2012 def Cmethod(self): pass
2013
2014 cstuff = ['Cdata', 'Cmethod']
2015 self.assertEqual(interesting(dir(C)), cstuff)
2016
2017 c = C()
2018 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002019 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002020
2021 c.cdata = 2
2022 c.cmethod = lambda self: 0
2023 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002024 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002025
2026 class A(C):
2027 Adata = 1
2028 def Amethod(self): pass
2029
2030 astuff = ['Adata', 'Amethod'] + cstuff
2031 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002032 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002033 a = A()
2034 self.assertEqual(interesting(dir(a)), astuff)
2035 a.adata = 42
2036 a.amethod = lambda self: 3
2037 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002038 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002039
2040 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002041 class M(type(sys)):
2042 pass
2043 minstance = M("m")
2044 minstance.b = 2
2045 minstance.a = 1
2046 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2047 self.assertEqual(names, ['a', 'b'])
2048
2049 class M2(M):
2050 def getdict(self):
2051 return "Not a dict!"
2052 __dict__ = property(getdict)
2053
2054 m2instance = M2("m2")
2055 m2instance.b = 2
2056 m2instance.a = 1
2057 self.assertEqual(m2instance.__dict__, "Not a dict!")
2058 try:
2059 dir(m2instance)
2060 except TypeError:
2061 pass
2062
2063 # Two essentially featureless objects, just inheriting stuff from
2064 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002065 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2066 if support.check_impl_detail():
2067 # None differs in PyPy: it has a __nonzero__
2068 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002069
2070 # Nasty test case for proxied objects
2071 class Wrapper(object):
2072 def __init__(self, obj):
2073 self.__obj = obj
2074 def __repr__(self):
2075 return "Wrapper(%s)" % repr(self.__obj)
2076 def __getitem__(self, key):
2077 return Wrapper(self.__obj[key])
2078 def __len__(self):
2079 return len(self.__obj)
2080 def __getattr__(self, name):
2081 return Wrapper(getattr(self.__obj, name))
2082
2083 class C(object):
2084 def __getclass(self):
2085 return Wrapper(type(self))
2086 __class__ = property(__getclass)
2087
2088 dir(C()) # This used to segfault
2089
2090 def test_supers(self):
2091 # Testing super...
2092
2093 class A(object):
2094 def meth(self, a):
2095 return "A(%r)" % a
2096
2097 self.assertEqual(A().meth(1), "A(1)")
2098
2099 class B(A):
2100 def __init__(self):
2101 self.__super = super(B, self)
2102 def meth(self, a):
2103 return "B(%r)" % a + self.__super.meth(a)
2104
2105 self.assertEqual(B().meth(2), "B(2)A(2)")
2106
2107 class C(A):
2108 def meth(self, a):
2109 return "C(%r)" % a + self.__super.meth(a)
2110 C._C__super = super(C)
2111
2112 self.assertEqual(C().meth(3), "C(3)A(3)")
2113
2114 class D(C, B):
2115 def meth(self, a):
2116 return "D(%r)" % a + super(D, self).meth(a)
2117
2118 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2119
2120 # Test for subclassing super
2121
2122 class mysuper(super):
2123 def __init__(self, *args):
2124 return super(mysuper, self).__init__(*args)
2125
2126 class E(D):
2127 def meth(self, a):
2128 return "E(%r)" % a + mysuper(E, self).meth(a)
2129
2130 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2131
2132 class F(E):
2133 def meth(self, a):
2134 s = self.__super # == mysuper(F, self)
2135 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2136 F._F__super = mysuper(F)
2137
2138 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2139
2140 # Make sure certain errors are raised
2141
2142 try:
2143 super(D, 42)
2144 except TypeError:
2145 pass
2146 else:
2147 self.fail("shouldn't allow super(D, 42)")
2148
2149 try:
2150 super(D, C())
2151 except TypeError:
2152 pass
2153 else:
2154 self.fail("shouldn't allow super(D, C())")
2155
2156 try:
2157 super(D).__get__(12)
2158 except TypeError:
2159 pass
2160 else:
2161 self.fail("shouldn't allow super(D).__get__(12)")
2162
2163 try:
2164 super(D).__get__(C())
2165 except TypeError:
2166 pass
2167 else:
2168 self.fail("shouldn't allow super(D).__get__(C())")
2169
2170 # Make sure data descriptors can be overridden and accessed via super
2171 # (new feature in Python 2.3)
2172
2173 class DDbase(object):
2174 def getx(self): return 42
2175 x = property(getx)
2176
2177 class DDsub(DDbase):
2178 def getx(self): return "hello"
2179 x = property(getx)
2180
2181 dd = DDsub()
2182 self.assertEqual(dd.x, "hello")
2183 self.assertEqual(super(DDsub, dd).x, 42)
2184
2185 # Ensure that super() lookup of descriptor from classmethod
2186 # works (SF ID# 743627)
2187
2188 class Base(object):
2189 aProp = property(lambda self: "foo")
2190
2191 class Sub(Base):
2192 @classmethod
2193 def test(klass):
2194 return super(Sub,klass).aProp
2195
2196 self.assertEqual(Sub.test(), Base.aProp)
2197
2198 # Verify that super() doesn't allow keyword args
2199 try:
2200 super(Base, kw=1)
2201 except TypeError:
2202 pass
2203 else:
2204 self.assertEqual("super shouldn't accept keyword args")
2205
2206 def test_basic_inheritance(self):
2207 # Testing inheritance from basic types...
2208
2209 class hexint(int):
2210 def __repr__(self):
2211 return hex(self)
2212 def __add__(self, other):
2213 return hexint(int.__add__(self, other))
2214 # (Note that overriding __radd__ doesn't work,
2215 # because the int type gets first dibs.)
2216 self.assertEqual(repr(hexint(7) + 9), "0x10")
2217 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2218 a = hexint(12345)
2219 self.assertEqual(a, 12345)
2220 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002221 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002222 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002223 self.assertTrue((+a).__class__ is int)
2224 self.assertTrue((a >> 0).__class__ is int)
2225 self.assertTrue((a << 0).__class__ is int)
2226 self.assertTrue((hexint(0) << 12).__class__ is int)
2227 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002228
2229 class octlong(int):
2230 __slots__ = []
2231 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002232 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002233 def __add__(self, other):
2234 return self.__class__(super(octlong, self).__add__(other))
2235 __radd__ = __add__
2236 self.assertEqual(str(octlong(3) + 5), "0o10")
2237 # (Note that overriding __radd__ here only seems to work
2238 # because the example uses a short int left argument.)
2239 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2240 a = octlong(12345)
2241 self.assertEqual(a, 12345)
2242 self.assertEqual(int(a), 12345)
2243 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002244 self.assertTrue(int(a).__class__ is int)
2245 self.assertTrue((+a).__class__ is int)
2246 self.assertTrue((-a).__class__ is int)
2247 self.assertTrue((-octlong(0)).__class__ is int)
2248 self.assertTrue((a >> 0).__class__ is int)
2249 self.assertTrue((a << 0).__class__ is int)
2250 self.assertTrue((a - 0).__class__ is int)
2251 self.assertTrue((a * 1).__class__ is int)
2252 self.assertTrue((a ** 1).__class__ is int)
2253 self.assertTrue((a // 1).__class__ is int)
2254 self.assertTrue((1 * a).__class__ is int)
2255 self.assertTrue((a | 0).__class__ is int)
2256 self.assertTrue((a ^ 0).__class__ is int)
2257 self.assertTrue((a & -1).__class__ is int)
2258 self.assertTrue((octlong(0) << 12).__class__ is int)
2259 self.assertTrue((octlong(0) >> 12).__class__ is int)
2260 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002261
2262 # Because octlong overrides __add__, we can't check the absence of +0
2263 # optimizations using octlong.
2264 class longclone(int):
2265 pass
2266 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002267 self.assertTrue((a + 0).__class__ is int)
2268 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002269
2270 # Check that negative clones don't segfault
2271 a = longclone(-1)
2272 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002273 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002274
2275 class precfloat(float):
2276 __slots__ = ['prec']
2277 def __init__(self, value=0.0, prec=12):
2278 self.prec = int(prec)
2279 def __repr__(self):
2280 return "%.*g" % (self.prec, self)
2281 self.assertEqual(repr(precfloat(1.1)), "1.1")
2282 a = precfloat(12345)
2283 self.assertEqual(a, 12345.0)
2284 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002285 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002286 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002287 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002288
2289 class madcomplex(complex):
2290 def __repr__(self):
2291 return "%.17gj%+.17g" % (self.imag, self.real)
2292 a = madcomplex(-3, 4)
2293 self.assertEqual(repr(a), "4j-3")
2294 base = complex(-3, 4)
2295 self.assertEqual(base.__class__, complex)
2296 self.assertEqual(a, base)
2297 self.assertEqual(complex(a), base)
2298 self.assertEqual(complex(a).__class__, complex)
2299 a = madcomplex(a) # just trying another form of the constructor
2300 self.assertEqual(repr(a), "4j-3")
2301 self.assertEqual(a, base)
2302 self.assertEqual(complex(a), base)
2303 self.assertEqual(complex(a).__class__, complex)
2304 self.assertEqual(hash(a), hash(base))
2305 self.assertEqual((+a).__class__, complex)
2306 self.assertEqual((a + 0).__class__, complex)
2307 self.assertEqual(a + 0, base)
2308 self.assertEqual((a - 0).__class__, complex)
2309 self.assertEqual(a - 0, base)
2310 self.assertEqual((a * 1).__class__, complex)
2311 self.assertEqual(a * 1, base)
2312 self.assertEqual((a / 1).__class__, complex)
2313 self.assertEqual(a / 1, base)
2314
2315 class madtuple(tuple):
2316 _rev = None
2317 def rev(self):
2318 if self._rev is not None:
2319 return self._rev
2320 L = list(self)
2321 L.reverse()
2322 self._rev = self.__class__(L)
2323 return self._rev
2324 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2325 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2326 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2327 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2328 for i in range(512):
2329 t = madtuple(range(i))
2330 u = t.rev()
2331 v = u.rev()
2332 self.assertEqual(v, t)
2333 a = madtuple((1,2,3,4,5))
2334 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002335 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002336 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002337 self.assertTrue(a[:].__class__ is tuple)
2338 self.assertTrue((a * 1).__class__ is tuple)
2339 self.assertTrue((a * 0).__class__ is tuple)
2340 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002341 a = madtuple(())
2342 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002343 self.assertTrue(tuple(a).__class__ is tuple)
2344 self.assertTrue((a + a).__class__ is tuple)
2345 self.assertTrue((a * 0).__class__ is tuple)
2346 self.assertTrue((a * 1).__class__ is tuple)
2347 self.assertTrue((a * 2).__class__ is tuple)
2348 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002349
2350 class madstring(str):
2351 _rev = None
2352 def rev(self):
2353 if self._rev is not None:
2354 return self._rev
2355 L = list(self)
2356 L.reverse()
2357 self._rev = self.__class__("".join(L))
2358 return self._rev
2359 s = madstring("abcdefghijklmnopqrstuvwxyz")
2360 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2361 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2362 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2363 for i in range(256):
2364 s = madstring("".join(map(chr, range(i))))
2365 t = s.rev()
2366 u = t.rev()
2367 self.assertEqual(u, s)
2368 s = madstring("12345")
2369 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002370 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002371
2372 base = "\x00" * 5
2373 s = madstring(base)
2374 self.assertEqual(s, base)
2375 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002376 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002377 self.assertEqual(hash(s), hash(base))
2378 self.assertEqual({s: 1}[base], 1)
2379 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002380 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002381 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002382 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002383 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002384 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002385 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002386 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002387 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002388 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002389 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002390 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002391 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002392 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002393 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002394 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002395 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002396 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002397 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002398 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002399 self.assertEqual(s.rstrip(), base)
2400 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002401 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002402 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002403 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002404 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002405 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002406 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002407 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002408 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002409 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002410 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002411 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002412 self.assertEqual(s.lower(), base)
2413
2414 class madunicode(str):
2415 _rev = None
2416 def rev(self):
2417 if self._rev is not None:
2418 return self._rev
2419 L = list(self)
2420 L.reverse()
2421 self._rev = self.__class__("".join(L))
2422 return self._rev
2423 u = madunicode("ABCDEF")
2424 self.assertEqual(u, "ABCDEF")
2425 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2426 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2427 base = "12345"
2428 u = madunicode(base)
2429 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002430 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002431 self.assertEqual(hash(u), hash(base))
2432 self.assertEqual({u: 1}[base], 1)
2433 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002434 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002435 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002436 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002437 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002438 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002440 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002441 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002442 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002443 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002444 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002445 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002446 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002447 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002448 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002449 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002450 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002451 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002452 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002453 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002454 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002455 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002456 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002457 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002458 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002459 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002460 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002461 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002462 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002463 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002464 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002465 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002466 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002467 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002468 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002469 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002470 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002471 self.assertEqual(u[0:0], "")
2472
2473 class sublist(list):
2474 pass
2475 a = sublist(range(5))
2476 self.assertEqual(a, list(range(5)))
2477 a.append("hello")
2478 self.assertEqual(a, list(range(5)) + ["hello"])
2479 a[5] = 5
2480 self.assertEqual(a, list(range(6)))
2481 a.extend(range(6, 20))
2482 self.assertEqual(a, list(range(20)))
2483 a[-5:] = []
2484 self.assertEqual(a, list(range(15)))
2485 del a[10:15]
2486 self.assertEqual(len(a), 10)
2487 self.assertEqual(a, list(range(10)))
2488 self.assertEqual(list(a), list(range(10)))
2489 self.assertEqual(a[0], 0)
2490 self.assertEqual(a[9], 9)
2491 self.assertEqual(a[-10], 0)
2492 self.assertEqual(a[-1], 9)
2493 self.assertEqual(a[:5], list(range(5)))
2494
2495 ## class CountedInput(file):
2496 ## """Counts lines read by self.readline().
2497 ##
2498 ## self.lineno is the 0-based ordinal of the last line read, up to
2499 ## a maximum of one greater than the number of lines in the file.
2500 ##
2501 ## self.ateof is true if and only if the final "" line has been read,
2502 ## at which point self.lineno stops incrementing, and further calls
2503 ## to readline() continue to return "".
2504 ## """
2505 ##
2506 ## lineno = 0
2507 ## ateof = 0
2508 ## def readline(self):
2509 ## if self.ateof:
2510 ## return ""
2511 ## s = file.readline(self)
2512 ## # Next line works too.
2513 ## # s = super(CountedInput, self).readline()
2514 ## self.lineno += 1
2515 ## if s == "":
2516 ## self.ateof = 1
2517 ## return s
2518 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002519 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002520 ## lines = ['a\n', 'b\n', 'c\n']
2521 ## try:
2522 ## f.writelines(lines)
2523 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002524 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002525 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2526 ## got = f.readline()
2527 ## self.assertEqual(expected, got)
2528 ## self.assertEqual(f.lineno, i)
2529 ## self.assertEqual(f.ateof, (i > len(lines)))
2530 ## f.close()
2531 ## finally:
2532 ## try:
2533 ## f.close()
2534 ## except:
2535 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002536 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002537
2538 def test_keywords(self):
2539 # Testing keyword args to basic type constructors ...
2540 self.assertEqual(int(x=1), 1)
2541 self.assertEqual(float(x=2), 2.0)
2542 self.assertEqual(int(x=3), 3)
2543 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2544 self.assertEqual(str(object=500), '500')
2545 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2546 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2547 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2548 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2549
2550 for constructor in (int, float, int, complex, str, str,
2551 tuple, list):
2552 try:
2553 constructor(bogus_keyword_arg=1)
2554 except TypeError:
2555 pass
2556 else:
2557 self.fail("expected TypeError from bogus keyword argument to %r"
2558 % constructor)
2559
2560 def test_str_subclass_as_dict_key(self):
2561 # Testing a str subclass used as dict key ..
2562
2563 class cistr(str):
2564 """Sublcass of str that computes __eq__ case-insensitively.
2565
2566 Also computes a hash code of the string in canonical form.
2567 """
2568
2569 def __init__(self, value):
2570 self.canonical = value.lower()
2571 self.hashcode = hash(self.canonical)
2572
2573 def __eq__(self, other):
2574 if not isinstance(other, cistr):
2575 other = cistr(other)
2576 return self.canonical == other.canonical
2577
2578 def __hash__(self):
2579 return self.hashcode
2580
2581 self.assertEqual(cistr('ABC'), 'abc')
2582 self.assertEqual('aBc', cistr('ABC'))
2583 self.assertEqual(str(cistr('ABC')), 'ABC')
2584
2585 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2586 self.assertEqual(d[cistr('one')], 1)
2587 self.assertEqual(d[cistr('tWo')], 2)
2588 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002589 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002590 self.assertEqual(d.get(cistr('thrEE')), 3)
2591
2592 def test_classic_comparisons(self):
2593 # Testing classic comparisons...
2594 class classic:
2595 pass
2596
2597 for base in (classic, int, object):
2598 class C(base):
2599 def __init__(self, value):
2600 self.value = int(value)
2601 def __eq__(self, other):
2602 if isinstance(other, C):
2603 return self.value == other.value
2604 if isinstance(other, int) or isinstance(other, int):
2605 return self.value == other
2606 return NotImplemented
2607 def __ne__(self, other):
2608 if isinstance(other, C):
2609 return self.value != other.value
2610 if isinstance(other, int) or isinstance(other, int):
2611 return self.value != other
2612 return NotImplemented
2613 def __lt__(self, other):
2614 if isinstance(other, C):
2615 return self.value < other.value
2616 if isinstance(other, int) or isinstance(other, int):
2617 return self.value < other
2618 return NotImplemented
2619 def __le__(self, other):
2620 if isinstance(other, C):
2621 return self.value <= other.value
2622 if isinstance(other, int) or isinstance(other, int):
2623 return self.value <= other
2624 return NotImplemented
2625 def __gt__(self, other):
2626 if isinstance(other, C):
2627 return self.value > other.value
2628 if isinstance(other, int) or isinstance(other, int):
2629 return self.value > other
2630 return NotImplemented
2631 def __ge__(self, other):
2632 if isinstance(other, C):
2633 return self.value >= other.value
2634 if isinstance(other, int) or isinstance(other, int):
2635 return self.value >= other
2636 return NotImplemented
2637
2638 c1 = C(1)
2639 c2 = C(2)
2640 c3 = C(3)
2641 self.assertEqual(c1, 1)
2642 c = {1: c1, 2: c2, 3: c3}
2643 for x in 1, 2, 3:
2644 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002645 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002646 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002647 eval("x %s y" % op),
2648 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002649 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002650 eval("x %s y" % op),
2651 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002652 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002653 eval("x %s y" % op),
2654 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002655
2656 def test_rich_comparisons(self):
2657 # Testing rich comparisons...
2658 class Z(complex):
2659 pass
2660 z = Z(1)
2661 self.assertEqual(z, 1+0j)
2662 self.assertEqual(1+0j, z)
2663 class ZZ(complex):
2664 def __eq__(self, other):
2665 try:
2666 return abs(self - other) <= 1e-6
2667 except:
2668 return NotImplemented
2669 zz = ZZ(1.0000003)
2670 self.assertEqual(zz, 1+0j)
2671 self.assertEqual(1+0j, zz)
2672
2673 class classic:
2674 pass
2675 for base in (classic, int, object, list):
2676 class C(base):
2677 def __init__(self, value):
2678 self.value = int(value)
2679 def __cmp__(self_, other):
2680 self.fail("shouldn't call __cmp__")
2681 def __eq__(self, other):
2682 if isinstance(other, C):
2683 return self.value == other.value
2684 if isinstance(other, int) or isinstance(other, int):
2685 return self.value == other
2686 return NotImplemented
2687 def __ne__(self, other):
2688 if isinstance(other, C):
2689 return self.value != other.value
2690 if isinstance(other, int) or isinstance(other, int):
2691 return self.value != other
2692 return NotImplemented
2693 def __lt__(self, other):
2694 if isinstance(other, C):
2695 return self.value < other.value
2696 if isinstance(other, int) or isinstance(other, int):
2697 return self.value < other
2698 return NotImplemented
2699 def __le__(self, other):
2700 if isinstance(other, C):
2701 return self.value <= other.value
2702 if isinstance(other, int) or isinstance(other, int):
2703 return self.value <= other
2704 return NotImplemented
2705 def __gt__(self, other):
2706 if isinstance(other, C):
2707 return self.value > other.value
2708 if isinstance(other, int) or isinstance(other, int):
2709 return self.value > other
2710 return NotImplemented
2711 def __ge__(self, other):
2712 if isinstance(other, C):
2713 return self.value >= other.value
2714 if isinstance(other, int) or isinstance(other, int):
2715 return self.value >= other
2716 return NotImplemented
2717 c1 = C(1)
2718 c2 = C(2)
2719 c3 = C(3)
2720 self.assertEqual(c1, 1)
2721 c = {1: c1, 2: c2, 3: c3}
2722 for x in 1, 2, 3:
2723 for y in 1, 2, 3:
2724 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002725 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002726 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002727 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002728 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002729 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002730 "x=%d, y=%d" % (x, y))
2731
2732 def test_descrdoc(self):
2733 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002734 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002735 def check(descr, what):
2736 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002737 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002738 check(complex.real, "the real part of a complex number") # member descriptor
2739
2740 def test_doc_descriptor(self):
2741 # Testing __doc__ descriptor...
2742 # SF bug 542984
2743 class DocDescr(object):
2744 def __get__(self, object, otype):
2745 if object:
2746 object = object.__class__.__name__ + ' instance'
2747 if otype:
2748 otype = otype.__name__
2749 return 'object=%s; type=%s' % (object, otype)
2750 class OldClass:
2751 __doc__ = DocDescr()
2752 class NewClass(object):
2753 __doc__ = DocDescr()
2754 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2755 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2756 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2757 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2758
2759 def test_set_class(self):
2760 # Testing __class__ assignment...
2761 class C(object): pass
2762 class D(object): pass
2763 class E(object): pass
2764 class F(D, E): pass
2765 for cls in C, D, E, F:
2766 for cls2 in C, D, E, F:
2767 x = cls()
2768 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002769 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002770 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002771 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002772 def cant(x, C):
2773 try:
2774 x.__class__ = C
2775 except TypeError:
2776 pass
2777 else:
2778 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2779 try:
2780 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002781 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002782 pass
2783 else:
2784 self.fail("shouldn't allow del %r.__class__" % x)
2785 cant(C(), list)
2786 cant(list(), C)
2787 cant(C(), 1)
2788 cant(C(), object)
2789 cant(object(), list)
2790 cant(list(), object)
2791 class Int(int): __slots__ = []
2792 cant(2, Int)
2793 cant(Int(), int)
2794 cant(True, int)
2795 cant(2, bool)
2796 o = object()
2797 cant(o, type(1))
2798 cant(o, type(None))
2799 del o
2800 class G(object):
2801 __slots__ = ["a", "b"]
2802 class H(object):
2803 __slots__ = ["b", "a"]
2804 class I(object):
2805 __slots__ = ["a", "b"]
2806 class J(object):
2807 __slots__ = ["c", "b"]
2808 class K(object):
2809 __slots__ = ["a", "b", "d"]
2810 class L(H):
2811 __slots__ = ["e"]
2812 class M(I):
2813 __slots__ = ["e"]
2814 class N(J):
2815 __slots__ = ["__weakref__"]
2816 class P(J):
2817 __slots__ = ["__dict__"]
2818 class Q(J):
2819 pass
2820 class R(J):
2821 __slots__ = ["__dict__", "__weakref__"]
2822
2823 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2824 x = cls()
2825 x.a = 1
2826 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002827 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00002828 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2829 self.assertEqual(x.a, 1)
2830 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002831 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00002832 "assigning %r as __class__ for %r silently failed" % (cls, x))
2833 self.assertEqual(x.a, 1)
2834 for cls in G, J, K, L, M, N, P, R, list, Int:
2835 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2836 if cls is cls2:
2837 continue
2838 cant(cls(), cls2)
2839
Benjamin Peterson193152c2009-04-25 01:08:45 +00002840 # Issue5283: when __class__ changes in __del__, the wrong
2841 # type gets DECREF'd.
2842 class O(object):
2843 pass
2844 class A(object):
2845 def __del__(self):
2846 self.__class__ = O
2847 l = [A() for x in range(100)]
2848 del l
2849
Georg Brandl479a7e72008-02-05 18:13:15 +00002850 def test_set_dict(self):
2851 # Testing __dict__ assignment...
2852 class C(object): pass
2853 a = C()
2854 a.__dict__ = {'b': 1}
2855 self.assertEqual(a.b, 1)
2856 def cant(x, dict):
2857 try:
2858 x.__dict__ = dict
2859 except (AttributeError, TypeError):
2860 pass
2861 else:
2862 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2863 cant(a, None)
2864 cant(a, [])
2865 cant(a, 1)
2866 del a.__dict__ # Deleting __dict__ is allowed
2867
2868 class Base(object):
2869 pass
2870 def verify_dict_readonly(x):
2871 """
2872 x has to be an instance of a class inheriting from Base.
2873 """
2874 cant(x, {})
2875 try:
2876 del x.__dict__
2877 except (AttributeError, TypeError):
2878 pass
2879 else:
2880 self.fail("shouldn't allow del %r.__dict__" % x)
2881 dict_descr = Base.__dict__["__dict__"]
2882 try:
2883 dict_descr.__set__(x, {})
2884 except (AttributeError, TypeError):
2885 pass
2886 else:
2887 self.fail("dict_descr allowed access to %r's dict" % x)
2888
2889 # Classes don't allow __dict__ assignment and have readonly dicts
2890 class Meta1(type, Base):
2891 pass
2892 class Meta2(Base, type):
2893 pass
2894 class D(object, metaclass=Meta1):
2895 pass
2896 class E(object, metaclass=Meta2):
2897 pass
2898 for cls in C, D, E:
2899 verify_dict_readonly(cls)
2900 class_dict = cls.__dict__
2901 try:
2902 class_dict["spam"] = "eggs"
2903 except TypeError:
2904 pass
2905 else:
2906 self.fail("%r's __dict__ can be modified" % cls)
2907
2908 # Modules also disallow __dict__ assignment
2909 class Module1(types.ModuleType, Base):
2910 pass
2911 class Module2(Base, types.ModuleType):
2912 pass
2913 for ModuleType in Module1, Module2:
2914 mod = ModuleType("spam")
2915 verify_dict_readonly(mod)
2916 mod.__dict__["spam"] = "eggs"
2917
2918 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002919 # (at least not any more than regular exception's __dict__ can
2920 # be deleted; on CPython it is not the case, whereas on PyPy they
2921 # can, just like any other new-style instance's __dict__.)
2922 def can_delete_dict(e):
2923 try:
2924 del e.__dict__
2925 except (TypeError, AttributeError):
2926 return False
2927 else:
2928 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002929 class Exception1(Exception, Base):
2930 pass
2931 class Exception2(Base, Exception):
2932 pass
2933 for ExceptionType in Exception, Exception1, Exception2:
2934 e = ExceptionType()
2935 e.__dict__ = {"a": 1}
2936 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002937 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002938
2939 def test_pickles(self):
2940 # Testing pickling and copying new-style classes and objects...
2941 import pickle
2942
2943 def sorteditems(d):
2944 L = list(d.items())
2945 L.sort()
2946 return L
2947
2948 global C
2949 class C(object):
2950 def __init__(self, a, b):
2951 super(C, self).__init__()
2952 self.a = a
2953 self.b = b
2954 def __repr__(self):
2955 return "C(%r, %r)" % (self.a, self.b)
2956
2957 global C1
2958 class C1(list):
2959 def __new__(cls, a, b):
2960 return super(C1, cls).__new__(cls)
2961 def __getnewargs__(self):
2962 return (self.a, self.b)
2963 def __init__(self, a, b):
2964 self.a = a
2965 self.b = b
2966 def __repr__(self):
2967 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2968
2969 global C2
2970 class C2(int):
2971 def __new__(cls, a, b, val=0):
2972 return super(C2, cls).__new__(cls, val)
2973 def __getnewargs__(self):
2974 return (self.a, self.b, int(self))
2975 def __init__(self, a, b, val=0):
2976 self.a = a
2977 self.b = b
2978 def __repr__(self):
2979 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2980
2981 global C3
2982 class C3(object):
2983 def __init__(self, foo):
2984 self.foo = foo
2985 def __getstate__(self):
2986 return self.foo
2987 def __setstate__(self, foo):
2988 self.foo = foo
2989
2990 global C4classic, C4
2991 class C4classic: # classic
2992 pass
2993 class C4(C4classic, object): # mixed inheritance
2994 pass
2995
Guido van Rossum3926a632001-09-25 16:25:58 +00002996 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00002997 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00002998 s = pickle.dumps(cls, bin)
2999 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003000 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003001
3002 a = C1(1, 2); a.append(42); a.append(24)
3003 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003004 s = pickle.dumps((a, b), bin)
3005 x, y = pickle.loads(s)
3006 self.assertEqual(x.__class__, a.__class__)
3007 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3008 self.assertEqual(y.__class__, b.__class__)
3009 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3010 self.assertEqual(repr(x), repr(a))
3011 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003012 # Test for __getstate__ and __setstate__ on new style class
3013 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003014 s = pickle.dumps(u, bin)
3015 v = pickle.loads(s)
3016 self.assertEqual(u.__class__, v.__class__)
3017 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003018 # Test for picklability of hybrid class
3019 u = C4()
3020 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003021 s = pickle.dumps(u, bin)
3022 v = pickle.loads(s)
3023 self.assertEqual(u.__class__, v.__class__)
3024 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003025
Georg Brandl479a7e72008-02-05 18:13:15 +00003026 # Testing copy.deepcopy()
3027 import copy
3028 for cls in C, C1, C2:
3029 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003030 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003031
Georg Brandl479a7e72008-02-05 18:13:15 +00003032 a = C1(1, 2); a.append(42); a.append(24)
3033 b = C2("hello", "world", 42)
3034 x, y = copy.deepcopy((a, b))
3035 self.assertEqual(x.__class__, a.__class__)
3036 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3037 self.assertEqual(y.__class__, b.__class__)
3038 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3039 self.assertEqual(repr(x), repr(a))
3040 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003041
Georg Brandl479a7e72008-02-05 18:13:15 +00003042 def test_pickle_slots(self):
3043 # Testing pickling of classes with __slots__ ...
3044 import pickle
3045 # Pickling of classes with __slots__ but without __getstate__ should fail
3046 # (if using protocol 0 or 1)
3047 global B, C, D, E
3048 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003049 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003050 for base in [object, B]:
3051 class C(base):
3052 __slots__ = ['a']
3053 class D(C):
3054 pass
3055 try:
3056 pickle.dumps(C(), 0)
3057 except TypeError:
3058 pass
3059 else:
3060 self.fail("should fail: pickle C instance - %s" % base)
3061 try:
3062 pickle.dumps(C(), 0)
3063 except TypeError:
3064 pass
3065 else:
3066 self.fail("should fail: pickle D instance - %s" % base)
3067 # Give C a nice generic __getstate__ and __setstate__
3068 class C(base):
3069 __slots__ = ['a']
3070 def __getstate__(self):
3071 try:
3072 d = self.__dict__.copy()
3073 except AttributeError:
3074 d = {}
3075 for cls in self.__class__.__mro__:
3076 for sn in cls.__dict__.get('__slots__', ()):
3077 try:
3078 d[sn] = getattr(self, sn)
3079 except AttributeError:
3080 pass
3081 return d
3082 def __setstate__(self, d):
3083 for k, v in list(d.items()):
3084 setattr(self, k, v)
3085 class D(C):
3086 pass
3087 # Now it should work
3088 x = C()
3089 y = pickle.loads(pickle.dumps(x))
3090 self.assertEqual(hasattr(y, 'a'), 0)
3091 x.a = 42
3092 y = pickle.loads(pickle.dumps(x))
3093 self.assertEqual(y.a, 42)
3094 x = D()
3095 x.a = 42
3096 x.b = 100
3097 y = pickle.loads(pickle.dumps(x))
3098 self.assertEqual(y.a + y.b, 142)
3099 # A subclass that adds a slot should also work
3100 class E(C):
3101 __slots__ = ['b']
3102 x = E()
3103 x.a = 42
3104 x.b = "foo"
3105 y = pickle.loads(pickle.dumps(x))
3106 self.assertEqual(y.a, x.a)
3107 self.assertEqual(y.b, x.b)
3108
3109 def test_binary_operator_override(self):
3110 # Testing overrides of binary operations...
3111 class I(int):
3112 def __repr__(self):
3113 return "I(%r)" % int(self)
3114 def __add__(self, other):
3115 return I(int(self) + int(other))
3116 __radd__ = __add__
3117 def __pow__(self, other, mod=None):
3118 if mod is None:
3119 return I(pow(int(self), int(other)))
3120 else:
3121 return I(pow(int(self), int(other), int(mod)))
3122 def __rpow__(self, other, mod=None):
3123 if mod is None:
3124 return I(pow(int(other), int(self), mod))
3125 else:
3126 return I(pow(int(other), int(self), int(mod)))
3127
3128 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3129 self.assertEqual(repr(I(1) + 2), "I(3)")
3130 self.assertEqual(repr(1 + I(2)), "I(3)")
3131 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3132 self.assertEqual(repr(2 ** I(3)), "I(8)")
3133 self.assertEqual(repr(I(2) ** 3), "I(8)")
3134 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3135 class S(str):
3136 def __eq__(self, other):
3137 return self.lower() == other.lower()
3138
3139 def test_subclass_propagation(self):
3140 # Testing propagation of slot functions to subclasses...
3141 class A(object):
3142 pass
3143 class B(A):
3144 pass
3145 class C(A):
3146 pass
3147 class D(B, C):
3148 pass
3149 d = D()
3150 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3151 A.__hash__ = lambda self: 42
3152 self.assertEqual(hash(d), 42)
3153 C.__hash__ = lambda self: 314
3154 self.assertEqual(hash(d), 314)
3155 B.__hash__ = lambda self: 144
3156 self.assertEqual(hash(d), 144)
3157 D.__hash__ = lambda self: 100
3158 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003159 D.__hash__ = None
3160 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003161 del D.__hash__
3162 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003163 B.__hash__ = None
3164 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003165 del B.__hash__
3166 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003167 C.__hash__ = None
3168 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003169 del C.__hash__
3170 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003171 A.__hash__ = None
3172 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003173 del A.__hash__
3174 self.assertEqual(hash(d), orig_hash)
3175 d.foo = 42
3176 d.bar = 42
3177 self.assertEqual(d.foo, 42)
3178 self.assertEqual(d.bar, 42)
3179 def __getattribute__(self, name):
3180 if name == "foo":
3181 return 24
3182 return object.__getattribute__(self, name)
3183 A.__getattribute__ = __getattribute__
3184 self.assertEqual(d.foo, 24)
3185 self.assertEqual(d.bar, 42)
3186 def __getattr__(self, name):
3187 if name in ("spam", "foo", "bar"):
3188 return "hello"
3189 raise AttributeError(name)
3190 B.__getattr__ = __getattr__
3191 self.assertEqual(d.spam, "hello")
3192 self.assertEqual(d.foo, 24)
3193 self.assertEqual(d.bar, 42)
3194 del A.__getattribute__
3195 self.assertEqual(d.foo, 42)
3196 del d.foo
3197 self.assertEqual(d.foo, "hello")
3198 self.assertEqual(d.bar, 42)
3199 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003200 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003201 d.foo
3202 except AttributeError:
3203 pass
3204 else:
3205 self.fail("d.foo should be undefined now")
3206
3207 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003208 class A(object):
3209 pass
3210 class B(A):
3211 pass
3212 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003213 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003214 A.__setitem__ = lambda *a: None # crash
3215
3216 def test_buffer_inheritance(self):
3217 # Testing that buffer interface is inherited ...
3218
3219 import binascii
3220 # SF bug [#470040] ParseTuple t# vs subclasses.
3221
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003222 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003223 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003224 base = b'abc'
3225 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003226 # b2a_hex uses the buffer interface to get its argument's value, via
3227 # PyArg_ParseTuple 't#' code.
3228 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3229
Georg Brandl479a7e72008-02-05 18:13:15 +00003230 class MyInt(int):
3231 pass
3232 m = MyInt(42)
3233 try:
3234 binascii.b2a_hex(m)
3235 self.fail('subclass of int should not have a buffer interface')
3236 except TypeError:
3237 pass
3238
3239 def test_str_of_str_subclass(self):
3240 # Testing __str__ defined in subclass of str ...
3241 import binascii
3242 import io
3243
3244 class octetstring(str):
3245 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003246 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003247 def __repr__(self):
3248 return self + " repr"
3249
3250 o = octetstring('A')
3251 self.assertEqual(type(o), octetstring)
3252 self.assertEqual(type(str(o)), str)
3253 self.assertEqual(type(repr(o)), str)
3254 self.assertEqual(ord(o), 0x41)
3255 self.assertEqual(str(o), '41')
3256 self.assertEqual(repr(o), 'A repr')
3257 self.assertEqual(o.__str__(), '41')
3258 self.assertEqual(o.__repr__(), 'A repr')
3259
3260 capture = io.StringIO()
3261 # Calling str() or not exercises different internal paths.
3262 print(o, file=capture)
3263 print(str(o), file=capture)
3264 self.assertEqual(capture.getvalue(), '41\n41\n')
3265 capture.close()
3266
3267 def test_keyword_arguments(self):
3268 # Testing keyword arguments to __init__, __call__...
3269 def f(a): return a
3270 self.assertEqual(f.__call__(a=42), 42)
3271 a = []
3272 list.__init__(a, sequence=[0, 1, 2])
3273 self.assertEqual(a, [0, 1, 2])
3274
3275 def test_recursive_call(self):
3276 # Testing recursive __call__() by setting to instance of class...
3277 class A(object):
3278 pass
3279
3280 A.__call__ = A()
3281 try:
3282 A()()
3283 except RuntimeError:
3284 pass
3285 else:
3286 self.fail("Recursion limit should have been reached for __call__()")
3287
3288 def test_delete_hook(self):
3289 # Testing __del__ hook...
3290 log = []
3291 class C(object):
3292 def __del__(self):
3293 log.append(1)
3294 c = C()
3295 self.assertEqual(log, [])
3296 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003297 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003298 self.assertEqual(log, [1])
3299
3300 class D(object): pass
3301 d = D()
3302 try: del d[0]
3303 except TypeError: pass
3304 else: self.fail("invalid del() didn't raise TypeError")
3305
3306 def test_hash_inheritance(self):
3307 # Testing hash of mutable subclasses...
3308
3309 class mydict(dict):
3310 pass
3311 d = mydict()
3312 try:
3313 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003314 except TypeError:
3315 pass
3316 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003317 self.fail("hash() of dict subclass should fail")
3318
3319 class mylist(list):
3320 pass
3321 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003322 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003323 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003324 except TypeError:
3325 pass
3326 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003327 self.fail("hash() of list subclass should fail")
3328
3329 def test_str_operations(self):
3330 try: 'a' + 5
3331 except TypeError: pass
3332 else: self.fail("'' + 5 doesn't raise TypeError")
3333
3334 try: ''.split('')
3335 except ValueError: pass
3336 else: self.fail("''.split('') doesn't raise ValueError")
3337
3338 try: ''.join([0])
3339 except TypeError: pass
3340 else: self.fail("''.join([0]) doesn't raise TypeError")
3341
3342 try: ''.rindex('5')
3343 except ValueError: pass
3344 else: self.fail("''.rindex('5') doesn't raise ValueError")
3345
3346 try: '%(n)s' % None
3347 except TypeError: pass
3348 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3349
3350 try: '%(n' % {}
3351 except ValueError: pass
3352 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3353
3354 try: '%*s' % ('abc')
3355 except TypeError: pass
3356 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3357
3358 try: '%*.*s' % ('abc', 5)
3359 except TypeError: pass
3360 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3361
3362 try: '%s' % (1, 2)
3363 except TypeError: pass
3364 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3365
3366 try: '%' % None
3367 except ValueError: pass
3368 else: self.fail("'%' % None doesn't raise ValueError")
3369
3370 self.assertEqual('534253'.isdigit(), 1)
3371 self.assertEqual('534253x'.isdigit(), 0)
3372 self.assertEqual('%c' % 5, '\x05')
3373 self.assertEqual('%c' % '5', '5')
3374
3375 def test_deepcopy_recursive(self):
3376 # Testing deepcopy of recursive objects...
3377 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003378 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003379 a = Node()
3380 b = Node()
3381 a.b = b
3382 b.a = a
3383 z = deepcopy(a) # This blew up before
3384
3385 def test_unintialized_modules(self):
3386 # Testing uninitialized module objects...
3387 from types import ModuleType as M
3388 m = M.__new__(M)
3389 str(m)
3390 self.assertEqual(hasattr(m, "__name__"), 0)
3391 self.assertEqual(hasattr(m, "__file__"), 0)
3392 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003393 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003394 m.foo = 1
3395 self.assertEqual(m.__dict__, {"foo": 1})
3396
3397 def test_funny_new(self):
3398 # Testing __new__ returning something unexpected...
3399 class C(object):
3400 def __new__(cls, arg):
3401 if isinstance(arg, str): return [1, 2, 3]
3402 elif isinstance(arg, int): return object.__new__(D)
3403 else: return object.__new__(cls)
3404 class D(C):
3405 def __init__(self, arg):
3406 self.foo = arg
3407 self.assertEqual(C("1"), [1, 2, 3])
3408 self.assertEqual(D("1"), [1, 2, 3])
3409 d = D(None)
3410 self.assertEqual(d.foo, None)
3411 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003412 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003413 self.assertEqual(d.foo, 1)
3414 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003415 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003416 self.assertEqual(d.foo, 1)
3417
3418 def test_imul_bug(self):
3419 # Testing for __imul__ problems...
3420 # SF bug 544647
3421 class C(object):
3422 def __imul__(self, other):
3423 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003424 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003425 y = x
3426 y *= 1.0
3427 self.assertEqual(y, (x, 1.0))
3428 y = x
3429 y *= 2
3430 self.assertEqual(y, (x, 2))
3431 y = x
3432 y *= 3
3433 self.assertEqual(y, (x, 3))
3434 y = x
3435 y *= 1<<100
3436 self.assertEqual(y, (x, 1<<100))
3437 y = x
3438 y *= None
3439 self.assertEqual(y, (x, None))
3440 y = x
3441 y *= "foo"
3442 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003443
Georg Brandl479a7e72008-02-05 18:13:15 +00003444 def test_copy_setstate(self):
3445 # Testing that copy.*copy() correctly uses __setstate__...
3446 import copy
3447 class C(object):
3448 def __init__(self, foo=None):
3449 self.foo = foo
3450 self.__foo = foo
3451 def setfoo(self, foo=None):
3452 self.foo = foo
3453 def getfoo(self):
3454 return self.__foo
3455 def __getstate__(self):
3456 return [self.foo]
3457 def __setstate__(self_, lst):
3458 self.assertEqual(len(lst), 1)
3459 self_.__foo = self_.foo = lst[0]
3460 a = C(42)
3461 a.setfoo(24)
3462 self.assertEqual(a.foo, 24)
3463 self.assertEqual(a.getfoo(), 42)
3464 b = copy.copy(a)
3465 self.assertEqual(b.foo, 24)
3466 self.assertEqual(b.getfoo(), 24)
3467 b = copy.deepcopy(a)
3468 self.assertEqual(b.foo, 24)
3469 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003470
Georg Brandl479a7e72008-02-05 18:13:15 +00003471 def test_slices(self):
3472 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003473
Georg Brandl479a7e72008-02-05 18:13:15 +00003474 # Strings
3475 self.assertEqual("hello"[:4], "hell")
3476 self.assertEqual("hello"[slice(4)], "hell")
3477 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3478 class S(str):
3479 def __getitem__(self, x):
3480 return str.__getitem__(self, x)
3481 self.assertEqual(S("hello")[:4], "hell")
3482 self.assertEqual(S("hello")[slice(4)], "hell")
3483 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3484 # Tuples
3485 self.assertEqual((1,2,3)[:2], (1,2))
3486 self.assertEqual((1,2,3)[slice(2)], (1,2))
3487 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3488 class T(tuple):
3489 def __getitem__(self, x):
3490 return tuple.__getitem__(self, x)
3491 self.assertEqual(T((1,2,3))[:2], (1,2))
3492 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3493 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3494 # Lists
3495 self.assertEqual([1,2,3][:2], [1,2])
3496 self.assertEqual([1,2,3][slice(2)], [1,2])
3497 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3498 class L(list):
3499 def __getitem__(self, x):
3500 return list.__getitem__(self, x)
3501 self.assertEqual(L([1,2,3])[:2], [1,2])
3502 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3503 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3504 # Now do lists and __setitem__
3505 a = L([1,2,3])
3506 a[slice(1, 3)] = [3,2]
3507 self.assertEqual(a, [1,3,2])
3508 a[slice(0, 2, 1)] = [3,1]
3509 self.assertEqual(a, [3,1,2])
3510 a.__setitem__(slice(1, 3), [2,1])
3511 self.assertEqual(a, [3,2,1])
3512 a.__setitem__(slice(0, 2, 1), [2,3])
3513 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003514
Georg Brandl479a7e72008-02-05 18:13:15 +00003515 def test_subtype_resurrection(self):
3516 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003517
Georg Brandl479a7e72008-02-05 18:13:15 +00003518 class C(object):
3519 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003520
Georg Brandl479a7e72008-02-05 18:13:15 +00003521 def __del__(self):
3522 # resurrect the instance
3523 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003524
Georg Brandl479a7e72008-02-05 18:13:15 +00003525 c = C()
3526 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003527
Benjamin Petersone549ead2009-03-28 21:42:05 +00003528 # The most interesting thing here is whether this blows up, due to
3529 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3530 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003531 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003532
Georg Brandl479a7e72008-02-05 18:13:15 +00003533 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003534 # the last container slot works: that will attempt to delete c again,
3535 # which will cause c to get appended back to the container again
3536 # "during" the del. (On non-CPython implementations, however, __del__
3537 # is typically not called again.)
3538 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003539 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003540 del C.container[-1]
3541 if support.check_impl_detail():
3542 support.gc_collect()
3543 self.assertEqual(len(C.container), 1)
3544 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003545
Georg Brandl479a7e72008-02-05 18:13:15 +00003546 # Make c mortal again, so that the test framework with -l doesn't report
3547 # it as a leak.
3548 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003549
Georg Brandl479a7e72008-02-05 18:13:15 +00003550 def test_slots_trash(self):
3551 # Testing slot trash...
3552 # Deallocating deeply nested slotted trash caused stack overflows
3553 class trash(object):
3554 __slots__ = ['x']
3555 def __init__(self, x):
3556 self.x = x
3557 o = None
3558 for i in range(50000):
3559 o = trash(o)
3560 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003561
Georg Brandl479a7e72008-02-05 18:13:15 +00003562 def test_slots_multiple_inheritance(self):
3563 # SF bug 575229, multiple inheritance w/ slots dumps core
3564 class A(object):
3565 __slots__=()
3566 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003567 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003568 class C(A,B) :
3569 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003570 if support.check_impl_detail():
3571 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003572 self.assertTrue(hasattr(C, '__dict__'))
3573 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003574 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003575
Georg Brandl479a7e72008-02-05 18:13:15 +00003576 def test_rmul(self):
3577 # Testing correct invocation of __rmul__...
3578 # SF patch 592646
3579 class C(object):
3580 def __mul__(self, other):
3581 return "mul"
3582 def __rmul__(self, other):
3583 return "rmul"
3584 a = C()
3585 self.assertEqual(a*2, "mul")
3586 self.assertEqual(a*2.2, "mul")
3587 self.assertEqual(2*a, "rmul")
3588 self.assertEqual(2.2*a, "rmul")
3589
3590 def test_ipow(self):
3591 # Testing correct invocation of __ipow__...
3592 # [SF bug 620179]
3593 class C(object):
3594 def __ipow__(self, other):
3595 pass
3596 a = C()
3597 a **= 2
3598
3599 def test_mutable_bases(self):
3600 # Testing mutable bases...
3601
3602 # stuff that should work:
3603 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003604 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003605 class C2(object):
3606 def __getattribute__(self, attr):
3607 if attr == 'a':
3608 return 2
3609 else:
3610 return super(C2, self).__getattribute__(attr)
3611 def meth(self):
3612 return 1
3613 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003614 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003615 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003616 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 d = D()
3618 e = E()
3619 D.__bases__ = (C,)
3620 D.__bases__ = (C2,)
3621 self.assertEqual(d.meth(), 1)
3622 self.assertEqual(e.meth(), 1)
3623 self.assertEqual(d.a, 2)
3624 self.assertEqual(e.a, 2)
3625 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003626
Georg Brandl479a7e72008-02-05 18:13:15 +00003627 try:
3628 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003629 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003630 pass
3631 else:
3632 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003633
Georg Brandl479a7e72008-02-05 18:13:15 +00003634 try:
3635 D.__bases__ = ()
3636 except TypeError as msg:
3637 if str(msg) == "a new-style class can't have only classic bases":
3638 self.fail("wrong error message for .__bases__ = ()")
3639 else:
3640 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003641
Georg Brandl479a7e72008-02-05 18:13:15 +00003642 try:
3643 D.__bases__ = (D,)
3644 except TypeError:
3645 pass
3646 else:
3647 # actually, we'll have crashed by here...
3648 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003649
Georg Brandl479a7e72008-02-05 18:13:15 +00003650 try:
3651 D.__bases__ = (C, C)
3652 except TypeError:
3653 pass
3654 else:
3655 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003656
Georg Brandl479a7e72008-02-05 18:13:15 +00003657 try:
3658 D.__bases__ = (E,)
3659 except TypeError:
3660 pass
3661 else:
3662 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003663
Benjamin Petersonae937c02009-04-18 20:54:08 +00003664 def test_builtin_bases(self):
3665 # Make sure all the builtin types can have their base queried without
3666 # segfaulting. See issue #5787.
3667 builtin_types = [tp for tp in builtins.__dict__.values()
3668 if isinstance(tp, type)]
3669 for tp in builtin_types:
3670 object.__getattribute__(tp, "__bases__")
3671 if tp is not object:
3672 self.assertEqual(len(tp.__bases__), 1, tp)
3673
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003674 class L(list):
3675 pass
3676
3677 class C(object):
3678 pass
3679
3680 class D(C):
3681 pass
3682
3683 try:
3684 L.__bases__ = (dict,)
3685 except TypeError:
3686 pass
3687 else:
3688 self.fail("shouldn't turn list subclass into dict subclass")
3689
3690 try:
3691 list.__bases__ = (dict,)
3692 except TypeError:
3693 pass
3694 else:
3695 self.fail("shouldn't be able to assign to list.__bases__")
3696
3697 try:
3698 D.__bases__ = (C, list)
3699 except TypeError:
3700 pass
3701 else:
3702 assert 0, "best_base calculation found wanting"
3703
Benjamin Petersonae937c02009-04-18 20:54:08 +00003704
Georg Brandl479a7e72008-02-05 18:13:15 +00003705 def test_mutable_bases_with_failing_mro(self):
3706 # Testing mutable bases with failing mro...
3707 class WorkOnce(type):
3708 def __new__(self, name, bases, ns):
3709 self.flag = 0
3710 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3711 def mro(self):
3712 if self.flag > 0:
3713 raise RuntimeError("bozo")
3714 else:
3715 self.flag += 1
3716 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003717
Georg Brandl479a7e72008-02-05 18:13:15 +00003718 class WorkAlways(type):
3719 def mro(self):
3720 # this is here to make sure that .mro()s aren't called
3721 # with an exception set (which was possible at one point).
3722 # An error message will be printed in a debug build.
3723 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003724 return type.mro(self)
3725
Georg Brandl479a7e72008-02-05 18:13:15 +00003726 class C(object):
3727 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003728
Georg Brandl479a7e72008-02-05 18:13:15 +00003729 class C2(object):
3730 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003731
Georg Brandl479a7e72008-02-05 18:13:15 +00003732 class D(C):
3733 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003734
Georg Brandl479a7e72008-02-05 18:13:15 +00003735 class E(D):
3736 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003737
Georg Brandl479a7e72008-02-05 18:13:15 +00003738 class F(D, metaclass=WorkOnce):
3739 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003740
Georg Brandl479a7e72008-02-05 18:13:15 +00003741 class G(D, metaclass=WorkAlways):
3742 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003743
Georg Brandl479a7e72008-02-05 18:13:15 +00003744 # Immediate subclasses have their mro's adjusted in alphabetical
3745 # order, so E's will get adjusted before adjusting F's fails. We
3746 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003747
Georg Brandl479a7e72008-02-05 18:13:15 +00003748 E_mro_before = E.__mro__
3749 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003750
Armin Rigofd163f92005-12-29 15:59:19 +00003751 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003752 D.__bases__ = (C2,)
3753 except RuntimeError:
3754 self.assertEqual(E.__mro__, E_mro_before)
3755 self.assertEqual(D.__mro__, D_mro_before)
3756 else:
3757 self.fail("exception not propagated")
3758
3759 def test_mutable_bases_catch_mro_conflict(self):
3760 # Testing mutable bases catch mro conflict...
3761 class A(object):
3762 pass
3763
3764 class B(object):
3765 pass
3766
3767 class C(A, B):
3768 pass
3769
3770 class D(A, B):
3771 pass
3772
3773 class E(C, D):
3774 pass
3775
3776 try:
3777 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003778 except TypeError:
3779 pass
3780 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003781 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003782
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 def test_mutable_names(self):
3784 # Testing mutable names...
3785 class C(object):
3786 pass
3787
3788 # C.__module__ could be 'test_descr' or '__main__'
3789 mod = C.__module__
3790
3791 C.__name__ = 'D'
3792 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3793
3794 C.__name__ = 'D.E'
3795 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3796
3797 def test_subclass_right_op(self):
3798 # Testing correct dispatch of subclass overloading __r<op>__...
3799
3800 # This code tests various cases where right-dispatch of a subclass
3801 # should be preferred over left-dispatch of a base class.
3802
3803 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3804
3805 class B(int):
3806 def __floordiv__(self, other):
3807 return "B.__floordiv__"
3808 def __rfloordiv__(self, other):
3809 return "B.__rfloordiv__"
3810
3811 self.assertEqual(B(1) // 1, "B.__floordiv__")
3812 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3813
3814 # Case 2: subclass of object; this is just the baseline for case 3
3815
3816 class C(object):
3817 def __floordiv__(self, other):
3818 return "C.__floordiv__"
3819 def __rfloordiv__(self, other):
3820 return "C.__rfloordiv__"
3821
3822 self.assertEqual(C() // 1, "C.__floordiv__")
3823 self.assertEqual(1 // C(), "C.__rfloordiv__")
3824
3825 # Case 3: subclass of new-style class; here it gets interesting
3826
3827 class D(C):
3828 def __floordiv__(self, other):
3829 return "D.__floordiv__"
3830 def __rfloordiv__(self, other):
3831 return "D.__rfloordiv__"
3832
3833 self.assertEqual(D() // C(), "D.__floordiv__")
3834 self.assertEqual(C() // D(), "D.__rfloordiv__")
3835
3836 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3837
3838 class E(C):
3839 pass
3840
3841 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3842
3843 self.assertEqual(E() // 1, "C.__floordiv__")
3844 self.assertEqual(1 // E(), "C.__rfloordiv__")
3845 self.assertEqual(E() // C(), "C.__floordiv__")
3846 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3847
Benjamin Petersone549ead2009-03-28 21:42:05 +00003848 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003849 def test_meth_class_get(self):
3850 # Testing __get__ method of METH_CLASS C methods...
3851 # Full coverage of descrobject.c::classmethod_get()
3852
3853 # Baseline
3854 arg = [1, 2, 3]
3855 res = {1: None, 2: None, 3: None}
3856 self.assertEqual(dict.fromkeys(arg), res)
3857 self.assertEqual({}.fromkeys(arg), res)
3858
3859 # Now get the descriptor
3860 descr = dict.__dict__["fromkeys"]
3861
3862 # More baseline using the descriptor directly
3863 self.assertEqual(descr.__get__(None, dict)(arg), res)
3864 self.assertEqual(descr.__get__({})(arg), res)
3865
3866 # Now check various error cases
3867 try:
3868 descr.__get__(None, None)
3869 except TypeError:
3870 pass
3871 else:
3872 self.fail("shouldn't have allowed descr.__get__(None, None)")
3873 try:
3874 descr.__get__(42)
3875 except TypeError:
3876 pass
3877 else:
3878 self.fail("shouldn't have allowed descr.__get__(42)")
3879 try:
3880 descr.__get__(None, 42)
3881 except TypeError:
3882 pass
3883 else:
3884 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3885 try:
3886 descr.__get__(None, int)
3887 except TypeError:
3888 pass
3889 else:
3890 self.fail("shouldn't have allowed descr.__get__(None, int)")
3891
3892 def test_isinst_isclass(self):
3893 # Testing proxy isinstance() and isclass()...
3894 class Proxy(object):
3895 def __init__(self, obj):
3896 self.__obj = obj
3897 def __getattribute__(self, name):
3898 if name.startswith("_Proxy__"):
3899 return object.__getattribute__(self, name)
3900 else:
3901 return getattr(self.__obj, name)
3902 # Test with a classic class
3903 class C:
3904 pass
3905 a = C()
3906 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003907 self.assertIsInstance(a, C) # Baseline
3908 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003909 # Test with a classic subclass
3910 class D(C):
3911 pass
3912 a = D()
3913 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003914 self.assertIsInstance(a, C) # Baseline
3915 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003916 # Test with a new-style class
3917 class C(object):
3918 pass
3919 a = C()
3920 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003921 self.assertIsInstance(a, C) # Baseline
3922 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003923 # Test with a new-style subclass
3924 class D(C):
3925 pass
3926 a = D()
3927 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003928 self.assertIsInstance(a, C) # Baseline
3929 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003930
3931 def test_proxy_super(self):
3932 # Testing super() for a proxy object...
3933 class Proxy(object):
3934 def __init__(self, obj):
3935 self.__obj = obj
3936 def __getattribute__(self, name):
3937 if name.startswith("_Proxy__"):
3938 return object.__getattribute__(self, name)
3939 else:
3940 return getattr(self.__obj, name)
3941
3942 class B(object):
3943 def f(self):
3944 return "B.f"
3945
3946 class C(B):
3947 def f(self):
3948 return super(C, self).f() + "->C.f"
3949
3950 obj = C()
3951 p = Proxy(obj)
3952 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3953
3954 def test_carloverre(self):
3955 # Testing prohibition of Carlo Verre's hack...
3956 try:
3957 object.__setattr__(str, "foo", 42)
3958 except TypeError:
3959 pass
3960 else:
3961 self.fail("Carlo Verre __setattr__ suceeded!")
3962 try:
3963 object.__delattr__(str, "lower")
3964 except TypeError:
3965 pass
3966 else:
3967 self.fail("Carlo Verre __delattr__ succeeded!")
3968
3969 def test_weakref_segfault(self):
3970 # Testing weakref segfault...
3971 # SF 742911
3972 import weakref
3973
3974 class Provoker:
3975 def __init__(self, referrent):
3976 self.ref = weakref.ref(referrent)
3977
3978 def __del__(self):
3979 x = self.ref()
3980
3981 class Oops(object):
3982 pass
3983
3984 o = Oops()
3985 o.whatever = Provoker(o)
3986 del o
3987
3988 def test_wrapper_segfault(self):
3989 # SF 927248: deeply nested wrappers could cause stack overflow
3990 f = lambda:None
3991 for i in range(1000000):
3992 f = f.__call__
3993 f = None
3994
3995 def test_file_fault(self):
3996 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00003997 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00003998 class StdoutGuard:
3999 def __getattr__(self, attr):
4000 sys.stdout = sys.__stdout__
4001 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4002 sys.stdout = StdoutGuard()
4003 try:
4004 print("Oops!")
4005 except RuntimeError:
4006 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004007 finally:
4008 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004009
4010 def test_vicious_descriptor_nonsense(self):
4011 # Testing vicious_descriptor_nonsense...
4012
4013 # A potential segfault spotted by Thomas Wouters in mail to
4014 # python-dev 2003-04-17, turned into an example & fixed by Michael
4015 # Hudson just less than four months later...
4016
4017 class Evil(object):
4018 def __hash__(self):
4019 return hash('attr')
4020 def __eq__(self, other):
4021 del C.attr
4022 return 0
4023
4024 class Descr(object):
4025 def __get__(self, ob, type=None):
4026 return 1
4027
4028 class C(object):
4029 attr = Descr()
4030
4031 c = C()
4032 c.__dict__[Evil()] = 0
4033
4034 self.assertEqual(c.attr, 1)
4035 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004036 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004037 self.assertEqual(hasattr(c, 'attr'), False)
4038
4039 def test_init(self):
4040 # SF 1155938
4041 class Foo(object):
4042 def __init__(self):
4043 return 10
4044 try:
4045 Foo()
4046 except TypeError:
4047 pass
4048 else:
4049 self.fail("did not test __init__() for None return")
4050
4051 def test_method_wrapper(self):
4052 # Testing method-wrapper objects...
4053 # <type 'method-wrapper'> did not support any reflection before 2.5
4054
Mark Dickinson211c6252009-02-01 10:28:51 +00004055 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004056
4057 l = []
4058 self.assertEqual(l.__add__, l.__add__)
4059 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004060 self.assertTrue(l.__add__ != [5].__add__)
4061 self.assertTrue(l.__add__ != l.__mul__)
4062 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004063 if hasattr(l.__add__, '__self__'):
4064 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004065 self.assertTrue(l.__add__.__self__ is l)
4066 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004067 else:
4068 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004069 self.assertTrue(l.__add__.im_self is l)
4070 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004071 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4072 try:
4073 hash(l.__add__)
4074 except TypeError:
4075 pass
4076 else:
4077 self.fail("no TypeError from hash([].__add__)")
4078
4079 t = ()
4080 t += (7,)
4081 self.assertEqual(t.__add__, (7,).__add__)
4082 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4083
4084 def test_not_implemented(self):
4085 # Testing NotImplemented...
4086 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004087 import operator
4088
4089 def specialmethod(self, other):
4090 return NotImplemented
4091
4092 def check(expr, x, y):
4093 try:
4094 exec(expr, {'x': x, 'y': y, 'operator': operator})
4095 except TypeError:
4096 pass
4097 else:
4098 self.fail("no TypeError from %r" % (expr,))
4099
4100 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4101 # TypeErrors
4102 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4103 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004104 for name, expr, iexpr in [
4105 ('__add__', 'x + y', 'x += y'),
4106 ('__sub__', 'x - y', 'x -= y'),
4107 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004108 ('__truediv__', 'operator.truediv(x, y)', None),
4109 ('__floordiv__', 'operator.floordiv(x, y)', None),
4110 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004111 ('__mod__', 'x % y', 'x %= y'),
4112 ('__divmod__', 'divmod(x, y)', None),
4113 ('__pow__', 'x ** y', 'x **= y'),
4114 ('__lshift__', 'x << y', 'x <<= y'),
4115 ('__rshift__', 'x >> y', 'x >>= y'),
4116 ('__and__', 'x & y', 'x &= y'),
4117 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004118 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004119 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004120 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004121 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004122 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004123 check(expr, a, N1)
4124 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004125 if iexpr:
4126 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004127 check(iexpr, a, N1)
4128 check(iexpr, a, N2)
4129 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004130 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004131 c = C()
4132 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004133 check(iexpr, c, N1)
4134 check(iexpr, c, N2)
4135
Georg Brandl479a7e72008-02-05 18:13:15 +00004136 def test_assign_slice(self):
4137 # ceval.c's assign_slice used to check for
4138 # tp->tp_as_sequence->sq_slice instead of
4139 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004140
Georg Brandl479a7e72008-02-05 18:13:15 +00004141 class C(object):
4142 def __setitem__(self, idx, value):
4143 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004144
Georg Brandl479a7e72008-02-05 18:13:15 +00004145 c = C()
4146 c[1:2] = 3
4147 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004148
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004149 def test_set_and_no_get(self):
4150 # See
4151 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4152 class Descr(object):
4153
4154 def __init__(self, name):
4155 self.name = name
4156
4157 def __set__(self, obj, value):
4158 obj.__dict__[self.name] = value
4159 descr = Descr("a")
4160
4161 class X(object):
4162 a = descr
4163
4164 x = X()
4165 self.assertIs(x.a, descr)
4166 x.a = 42
4167 self.assertEqual(x.a, 42)
4168
Benjamin Peterson21896a32010-03-21 22:03:03 +00004169 # Also check type_getattro for correctness.
4170 class Meta(type):
4171 pass
4172 class X(object):
4173 __metaclass__ = Meta
4174 X.a = 42
4175 Meta.a = Descr("a")
4176 self.assertEqual(X.a, 42)
4177
Benjamin Peterson9262b842008-11-17 22:45:50 +00004178 def test_getattr_hooks(self):
4179 # issue 4230
4180
4181 class Descriptor(object):
4182 counter = 0
4183 def __get__(self, obj, objtype=None):
4184 def getter(name):
4185 self.counter += 1
4186 raise AttributeError(name)
4187 return getter
4188
4189 descr = Descriptor()
4190 class A(object):
4191 __getattribute__ = descr
4192 class B(object):
4193 __getattr__ = descr
4194 class C(object):
4195 __getattribute__ = descr
4196 __getattr__ = descr
4197
4198 self.assertRaises(AttributeError, getattr, A(), "attr")
4199 self.assertEquals(descr.counter, 1)
4200 self.assertRaises(AttributeError, getattr, B(), "attr")
4201 self.assertEquals(descr.counter, 2)
4202 self.assertRaises(AttributeError, getattr, C(), "attr")
4203 self.assertEquals(descr.counter, 4)
4204
4205 import gc
4206 class EvilGetattribute(object):
4207 # This used to segfault
4208 def __getattr__(self, name):
4209 raise AttributeError(name)
4210 def __getattribute__(self, name):
4211 del EvilGetattribute.__getattr__
4212 for i in range(5):
4213 gc.collect()
4214 raise AttributeError(name)
4215
4216 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4217
Christian Heimesbbffeb62008-01-24 09:42:52 +00004218
Georg Brandl479a7e72008-02-05 18:13:15 +00004219class DictProxyTests(unittest.TestCase):
4220 def setUp(self):
4221 class C(object):
4222 def meth(self):
4223 pass
4224 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004225
Georg Brandl479a7e72008-02-05 18:13:15 +00004226 def test_iter_keys(self):
4227 # Testing dict-proxy iterkeys...
4228 keys = [ key for key in self.C.__dict__.keys() ]
4229 keys.sort()
4230 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4231 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004232
Georg Brandl479a7e72008-02-05 18:13:15 +00004233 def test_iter_values(self):
4234 # Testing dict-proxy itervalues...
4235 values = [ values for values in self.C.__dict__.values() ]
4236 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004237
Georg Brandl479a7e72008-02-05 18:13:15 +00004238 def test_iter_items(self):
4239 # Testing dict-proxy iteritems...
4240 keys = [ key for (key, value) in self.C.__dict__.items() ]
4241 keys.sort()
4242 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4243 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004244
Georg Brandl479a7e72008-02-05 18:13:15 +00004245 def test_dict_type_with_metaclass(self):
4246 # Testing type of __dict__ when metaclass set...
4247 class B(object):
4248 pass
4249 class M(type):
4250 pass
4251 class C(metaclass=M):
4252 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4253 pass
4254 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004255
Christian Heimesbbffeb62008-01-24 09:42:52 +00004256
Georg Brandl479a7e72008-02-05 18:13:15 +00004257class PTypesLongInitTest(unittest.TestCase):
4258 # This is in its own TestCase so that it can be run before any other tests.
4259 def test_pytype_long_ready(self):
4260 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004261
Georg Brandl479a7e72008-02-05 18:13:15 +00004262 # This dumps core when SF bug 551412 isn't fixed --
4263 # but only when test_descr.py is run separately.
4264 # (That can't be helped -- as soon as PyType_Ready()
4265 # is called for PyLong_Type, the bug is gone.)
4266 class UserLong(object):
4267 def __pow__(self, *args):
4268 pass
4269 try:
4270 pow(0, UserLong(), 0)
4271 except:
4272 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004273
Georg Brandl479a7e72008-02-05 18:13:15 +00004274 # Another segfault only when run early
4275 # (before PyType_Ready(tuple) is called)
4276 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004277
4278
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004279def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004280 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004281 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004282 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004283
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004284if __name__ == "__main__":
4285 test_main()