blob: 22277798f6dd29208784bb67de42cd29567ad5c8 [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
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00004import math
Georg Brandl479a7e72008-02-05 18:13:15 +00005import unittest
Tim Peters4d9b4662002-04-16 01:59:17 +00006
Georg Brandl479a7e72008-02-05 18:13:15 +00007from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Georg Brandl479a7e72008-02-05 18:13:15 +000011class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000012
Georg Brandl479a7e72008-02-05 18:13:15 +000013 def __init__(self, *args, **kwargs):
14 unittest.TestCase.__init__(self, *args, **kwargs)
15 self.binops = {
16 'add': '+',
17 'sub': '-',
18 'mul': '*',
19 'div': '/',
20 'divmod': 'divmod',
21 'pow': '**',
22 'lshift': '<<',
23 'rshift': '>>',
24 'and': '&',
25 'xor': '^',
26 'or': '|',
27 'cmp': 'cmp',
28 'lt': '<',
29 'le': '<=',
30 'eq': '==',
31 'ne': '!=',
32 'gt': '>',
33 'ge': '>=',
34 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000035
Georg Brandl479a7e72008-02-05 18:13:15 +000036 for name, expr in list(self.binops.items()):
37 if expr.islower():
38 expr = expr + "(a, b)"
39 else:
40 expr = 'a %s b' % expr
41 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
Georg Brandl479a7e72008-02-05 18:13:15 +000043 self.unops = {
44 'pos': '+',
45 'neg': '-',
46 'abs': 'abs',
47 'invert': '~',
48 'int': 'int',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl479a7e72008-02-05 18:13:15 +000054 for name, expr in list(self.unops.items()):
55 if expr.islower():
56 expr = expr + "(a)"
57 else:
58 expr = '%s a' % expr
59 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000060
Georg Brandl479a7e72008-02-05 18:13:15 +000061 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
62 d = {'a': a}
63 self.assertEqual(eval(expr, d), res)
64 t = type(a)
65 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl479a7e72008-02-05 18:13:15 +000067 # Find method in parent class
68 while meth not in t.__dict__:
69 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000070 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
71 # method object; the getattr() below obtains its underlying function.
72 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000073 self.assertEqual(m(a), res)
74 bm = getattr(a, meth)
75 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000076
Georg Brandl479a7e72008-02-05 18:13:15 +000077 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
78 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000079
Georg Brandl479a7e72008-02-05 18:13:15 +000080 # XXX Hack so this passes before 2.3 when -Qnew is specified.
81 if meth == "__div__" and 1/2 == 0.5:
82 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000083
Georg Brandl479a7e72008-02-05 18:13:15 +000084 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl479a7e72008-02-05 18:13:15 +000086 self.assertEqual(eval(expr, d), res)
87 t = type(a)
88 m = getattr(t, meth)
89 while meth not in t.__dict__:
90 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000091 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000094 self.assertEqual(m(a, b), res)
95 bm = getattr(a, meth)
96 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000097
Georg Brandl479a7e72008-02-05 18:13:15 +000098 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
99 d = {'a': a, 'b': b, 'c': c}
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000108 self.assertEqual(m(a, slice(b, c)), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl479a7e72008-02-05 18:13:15 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec(stmt, d)
115 self.assertEqual(d['a'], res)
116 t = type(a)
117 m = getattr(t, meth)
118 while meth not in t.__dict__:
119 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000123 d['a'] = deepcopy(a)
124 m(d['a'], b)
125 self.assertEqual(d['a'], res)
126 d['a'] = deepcopy(a)
127 bm = getattr(d['a'], meth)
128 bm(b)
129 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130
Georg Brandl479a7e72008-02-05 18:13:15 +0000131 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132 d = {'a': deepcopy(a), 'b': b, 'c': c}
133 exec(stmt, d)
134 self.assertEqual(d['a'], res)
135 t = type(a)
136 m = getattr(t, meth)
137 while meth not in t.__dict__:
138 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000142 d['a'] = deepcopy(a)
143 m(d['a'], b, c)
144 self.assertEqual(d['a'], res)
145 d['a'] = deepcopy(a)
146 bm = getattr(d['a'], meth)
147 bm(b, c)
148 self.assertEqual(d['a'], res)
149
150 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec(stmt, dictionary)
153 self.assertEqual(dictionary['a'], res)
154 t = type(a)
155 while meth not in t.__dict__:
156 t = t.__bases__[0]
157 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], slice(b, c), d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(slice(b, c), d)
167 self.assertEqual(dictionary['a'], res)
168
169 def test_lists(self):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
177 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setitem__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000188 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
190 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
191
192 d = {1:2, 3:4}
193 l1 = []
194 for i in list(d.keys()):
195 l1.append(i)
196 l = []
197 for i in iter(d):
198 l.append(i)
199 self.assertEqual(l, l1)
200 l = []
201 for i in d.__iter__():
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in dict.__iter__(d):
206 l.append(i)
207 self.assertEqual(l, l1)
208 d = {1:2, 3:4}
209 self.unop_test(d, 2, "len(a)", "__len__")
210 self.assertEqual(eval(repr(d), {}), d)
211 self.assertEqual(eval(d.__repr__(), {}), d)
212 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
213 "__setitem__")
214
215 # Tests for unary and binary operators
216 def number_operators(self, a, b, skip=[]):
217 dict = {'a': a, 'b': b}
218
219 for name, expr in list(self.binops.items()):
220 if name not in skip:
221 name = "__%s__" % name
222 if hasattr(a, name):
223 res = eval(expr, dict)
224 self.binop_test(a, b, res, expr, name)
225
226 for name, expr in list(self.unops.items()):
227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.unop_test(a, res, expr, name)
232
233 def test_ints(self):
234 # Testing int operations...
235 self.number_operators(100, 3)
236 # The following crashes in Python 2.2
237 self.assertEqual((1).__bool__(), 1)
238 self.assertEqual((0).__bool__(), 0)
239 # This returns 'NotImplemented' in Python 2.2
240 class C(int):
241 def __add__(self, other):
242 return NotImplemented
243 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000244 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000245 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000246 except TypeError:
247 pass
248 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000249 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000250
Georg Brandl479a7e72008-02-05 18:13:15 +0000251 def test_floats(self):
252 # Testing float operations...
253 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000254
Georg Brandl479a7e72008-02-05 18:13:15 +0000255 def test_complexes(self):
256 # Testing complex operations...
257 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000258 'int', 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +0000259 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000260
Georg Brandl479a7e72008-02-05 18:13:15 +0000261 class Number(complex):
262 __slots__ = ['prec']
263 def __new__(cls, *args, **kwds):
264 result = complex.__new__(cls, *args)
265 result.prec = kwds.get('prec', 12)
266 return result
267 def __repr__(self):
268 prec = self.prec
269 if self.imag == 0.0:
270 return "%.*g" % (prec, self.real)
271 if self.real == 0.0:
272 return "%.*gj" % (prec, self.imag)
273 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
274 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000275
Georg Brandl479a7e72008-02-05 18:13:15 +0000276 a = Number(3.14, prec=6)
277 self.assertEqual(repr(a), "3.14")
278 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000279
Georg Brandl479a7e72008-02-05 18:13:15 +0000280 a = Number(a, prec=2)
281 self.assertEqual(repr(a), "3.1")
282 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000283
Georg Brandl479a7e72008-02-05 18:13:15 +0000284 a = Number(234.5)
285 self.assertEqual(repr(a), "234.5")
286 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000287
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000288 def test_explicit_reverse_methods(self):
289 # see issue 9930
290 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
291 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
292
Benjamin Petersone549ead2009-03-28 21:42:05 +0000293 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000294 def test_spam_lists(self):
295 # Testing spamlist operations...
296 import copy, xxsubtype as spam
297
298 def spamlist(l, memo=None):
299 import xxsubtype as spam
300 return spam.spamlist(l)
301
302 # This is an ugly hack:
303 copy._deepcopy_dispatch[spam.spamlist] = spamlist
304
305 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
306 "__add__")
307 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
308 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
309 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
310 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
311 "__getitem__")
312 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
313 "__iadd__")
314 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
315 "__imul__")
316 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
317 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
318 "__mul__")
319 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
320 "__rmul__")
321 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
322 "__setitem__")
323 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
324 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
325 # Test subclassing
326 class C(spam.spamlist):
327 def foo(self): return 1
328 a = C()
329 self.assertEqual(a, [])
330 self.assertEqual(a.foo(), 1)
331 a.append(100)
332 self.assertEqual(a, [100])
333 self.assertEqual(a.getstate(), 0)
334 a.setstate(42)
335 self.assertEqual(a.getstate(), 42)
336
Benjamin Petersone549ead2009-03-28 21:42:05 +0000337 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000338 def test_spam_dicts(self):
339 # Testing spamdict operations...
340 import copy, xxsubtype as spam
341 def spamdict(d, memo=None):
342 import xxsubtype as spam
343 sd = spam.spamdict()
344 for k, v in list(d.items()):
345 sd[k] = v
346 return sd
347 # This is an ugly hack:
348 copy._deepcopy_dispatch[spam.spamdict] = spamdict
349
Georg Brandl479a7e72008-02-05 18:13:15 +0000350 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
351 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
352 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
353 d = spamdict({1:2,3:4})
354 l1 = []
355 for i in list(d.keys()):
356 l1.append(i)
357 l = []
358 for i in iter(d):
359 l.append(i)
360 self.assertEqual(l, l1)
361 l = []
362 for i in d.__iter__():
363 l.append(i)
364 self.assertEqual(l, l1)
365 l = []
366 for i in type(spamdict({})).__iter__(d):
367 l.append(i)
368 self.assertEqual(l, l1)
369 straightd = {1:2, 3:4}
370 spamd = spamdict(straightd)
371 self.unop_test(spamd, 2, "len(a)", "__len__")
372 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
373 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
374 "a[b]=c", "__setitem__")
375 # Test subclassing
376 class C(spam.spamdict):
377 def foo(self): return 1
378 a = C()
379 self.assertEqual(list(a.items()), [])
380 self.assertEqual(a.foo(), 1)
381 a['foo'] = 'bar'
382 self.assertEqual(list(a.items()), [('foo', 'bar')])
383 self.assertEqual(a.getstate(), 0)
384 a.setstate(100)
385 self.assertEqual(a.getstate(), 100)
386
387class ClassPropertiesAndMethods(unittest.TestCase):
388
389 def test_python_dicts(self):
390 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000391 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000392 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000393 d = dict()
394 self.assertEqual(d, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000395 self.assertTrue(d.__class__ is dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000396 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000397 class C(dict):
398 state = -1
399 def __init__(self_local, *a, **kw):
400 if a:
401 self.assertEqual(len(a), 1)
402 self_local.state = a[0]
403 if kw:
404 for k, v in list(kw.items()):
405 self_local[v] = k
406 def __getitem__(self, key):
407 return self.get(key, 0)
408 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000409 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000410 dict.__setitem__(self_local, key, value)
411 def setstate(self, state):
412 self.state = state
413 def getstate(self):
414 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000415 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000416 a1 = C(12)
417 self.assertEqual(a1.state, 12)
418 a2 = C(foo=1, bar=2)
419 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
420 a = C()
421 self.assertEqual(a.state, -1)
422 self.assertEqual(a.getstate(), -1)
423 a.setstate(0)
424 self.assertEqual(a.state, 0)
425 self.assertEqual(a.getstate(), 0)
426 a.setstate(10)
427 self.assertEqual(a.state, 10)
428 self.assertEqual(a.getstate(), 10)
429 self.assertEqual(a[42], 0)
430 a[42] = 24
431 self.assertEqual(a[42], 24)
432 N = 50
433 for i in range(N):
434 a[i] = C()
435 for j in range(N):
436 a[i][j] = i*j
437 for i in range(N):
438 for j in range(N):
439 self.assertEqual(a[i][j], i*j)
440
441 def test_python_lists(self):
442 # Testing Python subclass of list...
443 class C(list):
444 def __getitem__(self, i):
445 if isinstance(i, slice):
446 return i.start, i.stop
447 return list.__getitem__(self, i) + 100
448 a = C()
449 a.extend([0,1,2])
450 self.assertEqual(a[0], 100)
451 self.assertEqual(a[1], 101)
452 self.assertEqual(a[2], 102)
453 self.assertEqual(a[100:200], (100,200))
454
455 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000456 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000457 class C(metaclass=type):
458 def __init__(self):
459 self.__state = 0
460 def getstate(self):
461 return self.__state
462 def setstate(self, state):
463 self.__state = state
464 a = C()
465 self.assertEqual(a.getstate(), 0)
466 a.setstate(10)
467 self.assertEqual(a.getstate(), 10)
468 class _metaclass(type):
469 def myself(cls): return cls
470 class D(metaclass=_metaclass):
471 pass
472 self.assertEqual(D.myself(), D)
473 d = D()
474 self.assertEqual(d.__class__, D)
475 class M1(type):
476 def __new__(cls, name, bases, dict):
477 dict['__spam__'] = 1
478 return type.__new__(cls, name, bases, dict)
479 class C(metaclass=M1):
480 pass
481 self.assertEqual(C.__spam__, 1)
482 c = C()
483 self.assertEqual(c.__spam__, 1)
484
485 class _instance(object):
486 pass
487 class M2(object):
488 @staticmethod
489 def __new__(cls, name, bases, dict):
490 self = object.__new__(cls)
491 self.name = name
492 self.bases = bases
493 self.dict = dict
494 return self
495 def __call__(self):
496 it = _instance()
497 # Early binding of methods
498 for key in self.dict:
499 if key.startswith("__"):
500 continue
501 setattr(it, key, self.dict[key].__get__(it, self))
502 return it
503 class C(metaclass=M2):
504 def spam(self):
505 return 42
506 self.assertEqual(C.name, 'C')
507 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000508 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000509 c = C()
510 self.assertEqual(c.spam(), 42)
511
512 # More metaclass examples
513
514 class autosuper(type):
515 # Automatically add __super to the class
516 # This trick only works for dynamic classes
517 def __new__(metaclass, name, bases, dict):
518 cls = super(autosuper, metaclass).__new__(metaclass,
519 name, bases, dict)
520 # Name mangling for __super removes leading underscores
521 while name[:1] == "_":
522 name = name[1:]
523 if name:
524 name = "_%s__super" % name
525 else:
526 name = "__super"
527 setattr(cls, name, super(cls))
528 return cls
529 class A(metaclass=autosuper):
530 def meth(self):
531 return "A"
532 class B(A):
533 def meth(self):
534 return "B" + self.__super.meth()
535 class C(A):
536 def meth(self):
537 return "C" + self.__super.meth()
538 class D(C, B):
539 def meth(self):
540 return "D" + self.__super.meth()
541 self.assertEqual(D().meth(), "DCBA")
542 class E(B, C):
543 def meth(self):
544 return "E" + self.__super.meth()
545 self.assertEqual(E().meth(), "EBCA")
546
547 class autoproperty(type):
548 # Automatically create property attributes when methods
549 # named _get_x and/or _set_x are found
550 def __new__(metaclass, name, bases, dict):
551 hits = {}
552 for key, val in dict.items():
553 if key.startswith("_get_"):
554 key = key[5:]
555 get, set = hits.get(key, (None, None))
556 get = val
557 hits[key] = get, set
558 elif key.startswith("_set_"):
559 key = key[5:]
560 get, set = hits.get(key, (None, None))
561 set = val
562 hits[key] = get, set
563 for key, (get, set) in hits.items():
564 dict[key] = property(get, set)
565 return super(autoproperty, metaclass).__new__(metaclass,
566 name, bases, dict)
567 class A(metaclass=autoproperty):
568 def _get_x(self):
569 return -self.__x
570 def _set_x(self, x):
571 self.__x = -x
572 a = A()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000573 self.assertTrue(not hasattr(a, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +0000574 a.x = 12
575 self.assertEqual(a.x, 12)
576 self.assertEqual(a._A__x, -12)
577
578 class multimetaclass(autoproperty, autosuper):
579 # Merge of multiple cooperating metaclasses
580 pass
581 class A(metaclass=multimetaclass):
582 def _get_x(self):
583 return "A"
584 class B(A):
585 def _get_x(self):
586 return "B" + self.__super._get_x()
587 class C(A):
588 def _get_x(self):
589 return "C" + self.__super._get_x()
590 class D(C, B):
591 def _get_x(self):
592 return "D" + self.__super._get_x()
593 self.assertEqual(D().x, "DCBA")
594
595 # Make sure type(x) doesn't call x.__class__.__init__
596 class T(type):
597 counter = 0
598 def __init__(self, *args):
599 T.counter += 1
600 class C(metaclass=T):
601 pass
602 self.assertEqual(T.counter, 1)
603 a = C()
604 self.assertEqual(type(a), C)
605 self.assertEqual(T.counter, 1)
606
607 class C(object): pass
608 c = C()
609 try: c()
610 except TypeError: pass
611 else: self.fail("calling object w/o call method should raise "
612 "TypeError")
613
614 # Testing code to find most derived baseclass
615 class A(type):
616 def __new__(*args, **kwargs):
617 return type.__new__(*args, **kwargs)
618
619 class B(object):
620 pass
621
622 class C(object, metaclass=A):
623 pass
624
625 # The most derived metaclass of D is A rather than type.
626 class D(B, C):
627 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000628 self.assertIs(A, type(D))
629
630 # issue1294232: correct metaclass calculation
631 new_calls = [] # to check the order of __new__ calls
632 class AMeta(type):
633 @staticmethod
634 def __new__(mcls, name, bases, ns):
635 new_calls.append('AMeta')
636 return super().__new__(mcls, name, bases, ns)
637 @classmethod
638 def __prepare__(mcls, name, bases):
639 return {}
640
641 class BMeta(AMeta):
642 @staticmethod
643 def __new__(mcls, name, bases, ns):
644 new_calls.append('BMeta')
645 return super().__new__(mcls, name, bases, ns)
646 @classmethod
647 def __prepare__(mcls, name, bases):
648 ns = super().__prepare__(name, bases)
649 ns['BMeta_was_here'] = True
650 return ns
651
652 class A(metaclass=AMeta):
653 pass
654 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000655 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000656
657 class B(metaclass=BMeta):
658 pass
659 # BMeta.__new__ calls AMeta.__new__ with super:
660 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000661 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000662
663 class C(A, B):
664 pass
665 # The most derived metaclass is BMeta:
666 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000667 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000668 # BMeta.__prepare__ should've been called:
669 self.assertIn('BMeta_was_here', C.__dict__)
670
671 # The order of the bases shouldn't matter:
672 class C2(B, A):
673 pass
674 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000675 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000676 self.assertIn('BMeta_was_here', C2.__dict__)
677
678 # Check correct metaclass calculation when a metaclass is declared:
679 class D(C, metaclass=type):
680 pass
681 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000682 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000683 self.assertIn('BMeta_was_here', D.__dict__)
684
685 class E(C, metaclass=AMeta):
686 pass
687 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000688 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000689 self.assertIn('BMeta_was_here', E.__dict__)
690
691 # Special case: the given metaclass isn't a class,
692 # so there is no metaclass calculation.
693 marker = object()
694 def func(*args, **kwargs):
695 return marker
696 class X(metaclass=func):
697 pass
698 class Y(object, metaclass=func):
699 pass
700 class Z(D, metaclass=func):
701 pass
702 self.assertIs(marker, X)
703 self.assertIs(marker, Y)
704 self.assertIs(marker, Z)
705
706 # The given metaclass is a class,
707 # but not a descendant of type.
708 prepare_calls = [] # to track __prepare__ calls
709 class ANotMeta:
710 def __new__(mcls, *args, **kwargs):
711 new_calls.append('ANotMeta')
712 return super().__new__(mcls)
713 @classmethod
714 def __prepare__(mcls, name, bases):
715 prepare_calls.append('ANotMeta')
716 return {}
717 class BNotMeta(ANotMeta):
718 def __new__(mcls, *args, **kwargs):
719 new_calls.append('BNotMeta')
720 return super().__new__(mcls)
721 @classmethod
722 def __prepare__(mcls, name, bases):
723 prepare_calls.append('BNotMeta')
724 return super().__prepare__(name, bases)
725
726 class A(metaclass=ANotMeta):
727 pass
728 self.assertIs(ANotMeta, type(A))
729 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000730 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000731 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000732 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000733
734 class B(metaclass=BNotMeta):
735 pass
736 self.assertIs(BNotMeta, type(B))
737 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000738 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000739 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000740 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000741
742 class C(A, B):
743 pass
744 self.assertIs(BNotMeta, type(C))
745 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000746 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000747 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000748 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000749
750 class C2(B, A):
751 pass
752 self.assertIs(BNotMeta, type(C2))
753 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000754 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000755 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000756 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000757
758 # This is a TypeError, because of a metaclass conflict:
759 # BNotMeta is neither a subclass, nor a superclass of type
760 with self.assertRaises(TypeError):
761 class D(C, metaclass=type):
762 pass
763
764 class E(C, metaclass=ANotMeta):
765 pass
766 self.assertIs(BNotMeta, type(E))
767 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000768 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000769 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000770 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000771
772 class F(object(), C):
773 pass
774 self.assertIs(BNotMeta, type(F))
775 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000776 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000777 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000778 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000779
780 class F2(C, object()):
781 pass
782 self.assertIs(BNotMeta, type(F2))
783 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000784 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000785 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000786 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000787
788 # TypeError: BNotMeta is neither a
789 # subclass, nor a superclass of int
790 with self.assertRaises(TypeError):
791 class X(C, int()):
792 pass
793 with self.assertRaises(TypeError):
794 class X(int(), C):
795 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000796
797 def test_module_subclasses(self):
798 # Testing Python subclass of module...
799 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000800 MT = type(sys)
801 class MM(MT):
802 def __init__(self, name):
803 MT.__init__(self, name)
804 def __getattribute__(self, name):
805 log.append(("getattr", name))
806 return MT.__getattribute__(self, name)
807 def __setattr__(self, name, value):
808 log.append(("setattr", name, value))
809 MT.__setattr__(self, name, value)
810 def __delattr__(self, name):
811 log.append(("delattr", name))
812 MT.__delattr__(self, name)
813 a = MM("a")
814 a.foo = 12
815 x = a.foo
816 del a.foo
817 self.assertEqual(log, [("setattr", "foo", 12),
818 ("getattr", "foo"),
819 ("delattr", "foo")])
820
821 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000822 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000823 class Module(types.ModuleType, str):
824 pass
825 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000826 pass
827 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000828 self.fail("inheriting from ModuleType and str at the same time "
829 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000830
Georg Brandl479a7e72008-02-05 18:13:15 +0000831 def test_multiple_inheritance(self):
832 # Testing multiple inheritance...
833 class C(object):
834 def __init__(self):
835 self.__state = 0
836 def getstate(self):
837 return self.__state
838 def setstate(self, state):
839 self.__state = state
840 a = C()
841 self.assertEqual(a.getstate(), 0)
842 a.setstate(10)
843 self.assertEqual(a.getstate(), 10)
844 class D(dict, C):
845 def __init__(self):
846 type({}).__init__(self)
847 C.__init__(self)
848 d = D()
849 self.assertEqual(list(d.keys()), [])
850 d["hello"] = "world"
851 self.assertEqual(list(d.items()), [("hello", "world")])
852 self.assertEqual(d["hello"], "world")
853 self.assertEqual(d.getstate(), 0)
854 d.setstate(10)
855 self.assertEqual(d.getstate(), 10)
856 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000857
Georg Brandl479a7e72008-02-05 18:13:15 +0000858 # SF bug #442833
859 class Node(object):
860 def __int__(self):
861 return int(self.foo())
862 def foo(self):
863 return "23"
864 class Frag(Node, list):
865 def foo(self):
866 return "42"
867 self.assertEqual(Node().__int__(), 23)
868 self.assertEqual(int(Node()), 23)
869 self.assertEqual(Frag().__int__(), 42)
870 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000871
Georg Brandl479a7e72008-02-05 18:13:15 +0000872 def test_diamond_inheritence(self):
873 # Testing multiple inheritance special cases...
874 class A(object):
875 def spam(self): return "A"
876 self.assertEqual(A().spam(), "A")
877 class B(A):
878 def boo(self): return "B"
879 def spam(self): return "B"
880 self.assertEqual(B().spam(), "B")
881 self.assertEqual(B().boo(), "B")
882 class C(A):
883 def boo(self): return "C"
884 self.assertEqual(C().spam(), "A")
885 self.assertEqual(C().boo(), "C")
886 class D(B, C): pass
887 self.assertEqual(D().spam(), "B")
888 self.assertEqual(D().boo(), "B")
889 self.assertEqual(D.__mro__, (D, B, C, A, object))
890 class E(C, B): pass
891 self.assertEqual(E().spam(), "B")
892 self.assertEqual(E().boo(), "C")
893 self.assertEqual(E.__mro__, (E, C, B, A, object))
894 # MRO order disagreement
895 try:
896 class F(D, E): pass
897 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000898 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000899 else:
900 self.fail("expected MRO order disagreement (F)")
901 try:
902 class G(E, D): pass
903 except TypeError:
904 pass
905 else:
906 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000907
Georg Brandl479a7e72008-02-05 18:13:15 +0000908 # see thread python-dev/2002-October/029035.html
909 def test_ex5_from_c3_switch(self):
910 # Testing ex5 from C3 switch discussion...
911 class A(object): pass
912 class B(object): pass
913 class C(object): pass
914 class X(A): pass
915 class Y(A): pass
916 class Z(X,B,Y,C): pass
917 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000918
Georg Brandl479a7e72008-02-05 18:13:15 +0000919 # see "A Monotonic Superclass Linearization for Dylan",
920 # by Kim Barrett et al. (OOPSLA 1996)
921 def test_monotonicity(self):
922 # Testing MRO monotonicity...
923 class Boat(object): pass
924 class DayBoat(Boat): pass
925 class WheelBoat(Boat): pass
926 class EngineLess(DayBoat): pass
927 class SmallMultihull(DayBoat): pass
928 class PedalWheelBoat(EngineLess,WheelBoat): pass
929 class SmallCatamaran(SmallMultihull): pass
930 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000931
Georg Brandl479a7e72008-02-05 18:13:15 +0000932 self.assertEqual(PedalWheelBoat.__mro__,
933 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
934 self.assertEqual(SmallCatamaran.__mro__,
935 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
936 self.assertEqual(Pedalo.__mro__,
937 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
938 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000939
Georg Brandl479a7e72008-02-05 18:13:15 +0000940 # see "A Monotonic Superclass Linearization for Dylan",
941 # by Kim Barrett et al. (OOPSLA 1996)
942 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200943 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000944 class Pane(object): pass
945 class ScrollingMixin(object): pass
946 class EditingMixin(object): pass
947 class ScrollablePane(Pane,ScrollingMixin): pass
948 class EditablePane(Pane,EditingMixin): pass
949 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000950
Georg Brandl479a7e72008-02-05 18:13:15 +0000951 self.assertEqual(EditableScrollablePane.__mro__,
952 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
953 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000954
Georg Brandl479a7e72008-02-05 18:13:15 +0000955 def test_mro_disagreement(self):
956 # Testing error messages for MRO disagreement...
957 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000958order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000959
Georg Brandl479a7e72008-02-05 18:13:15 +0000960 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000961 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000962 callable(*args)
963 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000964 # the exact msg is generally considered an impl detail
965 if support.check_impl_detail():
966 if not str(msg).startswith(expected):
967 self.fail("Message %r, expected %r" %
968 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000969 else:
970 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000971
Georg Brandl479a7e72008-02-05 18:13:15 +0000972 class A(object): pass
973 class B(A): pass
974 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000975
Georg Brandl479a7e72008-02-05 18:13:15 +0000976 # Test some very simple errors
977 raises(TypeError, "duplicate base class A",
978 type, "X", (A, A), {})
979 raises(TypeError, mro_err_msg,
980 type, "X", (A, B), {})
981 raises(TypeError, mro_err_msg,
982 type, "X", (A, C, B), {})
983 # Test a slightly more complex error
984 class GridLayout(object): pass
985 class HorizontalGrid(GridLayout): pass
986 class VerticalGrid(GridLayout): pass
987 class HVGrid(HorizontalGrid, VerticalGrid): pass
988 class VHGrid(VerticalGrid, HorizontalGrid): pass
989 raises(TypeError, mro_err_msg,
990 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000991
Georg Brandl479a7e72008-02-05 18:13:15 +0000992 def test_object_class(self):
993 # Testing object class...
994 a = object()
995 self.assertEqual(a.__class__, object)
996 self.assertEqual(type(a), object)
997 b = object()
998 self.assertNotEqual(a, b)
999 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +00001000 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001001 a.foo = 12
1002 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001003 pass
1004 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001005 self.fail("object() should not allow setting a foo attribute")
1006 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +00001007
Georg Brandl479a7e72008-02-05 18:13:15 +00001008 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001009 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001010 x = Cdict()
1011 self.assertEqual(x.__dict__, {})
1012 x.foo = 1
1013 self.assertEqual(x.foo, 1)
1014 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015
Georg Brandl479a7e72008-02-05 18:13:15 +00001016 def test_slots(self):
1017 # Testing __slots__...
1018 class C0(object):
1019 __slots__ = []
1020 x = C0()
1021 self.assertFalse(hasattr(x, "__dict__"))
1022 self.assertFalse(hasattr(x, "foo"))
1023
1024 class C1(object):
1025 __slots__ = ['a']
1026 x = C1()
1027 self.assertFalse(hasattr(x, "__dict__"))
1028 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001030 self.assertEqual(x.a, 1)
1031 x.a = None
1032 self.assertEqual(x.a, None)
1033 del x.a
1034 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001035
Georg Brandl479a7e72008-02-05 18:13:15 +00001036 class C3(object):
1037 __slots__ = ['a', 'b', 'c']
1038 x = C3()
1039 self.assertFalse(hasattr(x, "__dict__"))
1040 self.assertFalse(hasattr(x, 'a'))
1041 self.assertFalse(hasattr(x, 'b'))
1042 self.assertFalse(hasattr(x, 'c'))
1043 x.a = 1
1044 x.b = 2
1045 x.c = 3
1046 self.assertEqual(x.a, 1)
1047 self.assertEqual(x.b, 2)
1048 self.assertEqual(x.c, 3)
1049
1050 class C4(object):
1051 """Validate name mangling"""
1052 __slots__ = ['__a']
1053 def __init__(self, value):
1054 self.__a = value
1055 def get(self):
1056 return self.__a
1057 x = C4(5)
1058 self.assertFalse(hasattr(x, '__dict__'))
1059 self.assertFalse(hasattr(x, '__a'))
1060 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001061 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001062 x.__a = 6
1063 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001064 pass
1065 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001066 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001067
Georg Brandl479a7e72008-02-05 18:13:15 +00001068 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001069 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001070 class C(object):
1071 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001072 except TypeError:
1073 pass
1074 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001075 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001076 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001077 class C(object):
1078 __slots__ = ["foo bar"]
1079 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001080 pass
1081 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001082 self.fail("['foo bar'] slots not caught")
1083 try:
1084 class C(object):
1085 __slots__ = ["foo\0bar"]
1086 except TypeError:
1087 pass
1088 else:
1089 self.fail("['foo\\0bar'] slots not caught")
1090 try:
1091 class C(object):
1092 __slots__ = ["1"]
1093 except TypeError:
1094 pass
1095 else:
1096 self.fail("['1'] slots not caught")
1097 try:
1098 class C(object):
1099 __slots__ = [""]
1100 except TypeError:
1101 pass
1102 else:
1103 self.fail("[''] slots not caught")
1104 class C(object):
1105 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1106 # XXX(nnorwitz): was there supposed to be something tested
1107 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001108
Georg Brandl479a7e72008-02-05 18:13:15 +00001109 # Test a single string is not expanded as a sequence.
1110 class C(object):
1111 __slots__ = "abc"
1112 c = C()
1113 c.abc = 5
1114 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001115
Georg Brandl479a7e72008-02-05 18:13:15 +00001116 # Test unicode slot names
1117 # Test a single unicode string is not expanded as a sequence.
1118 class C(object):
1119 __slots__ = "abc"
1120 c = C()
1121 c.abc = 5
1122 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001123
Georg Brandl479a7e72008-02-05 18:13:15 +00001124 # _unicode_to_string used to modify slots in certain circumstances
1125 slots = ("foo", "bar")
1126 class C(object):
1127 __slots__ = slots
1128 x = C()
1129 x.foo = 5
1130 self.assertEqual(x.foo, 5)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001131 self.assertTrue(type(slots[0]) is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001132 # this used to leak references
1133 try:
1134 class C(object):
1135 __slots__ = [chr(128)]
1136 except (TypeError, UnicodeEncodeError):
1137 pass
1138 else:
1139 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001140
Georg Brandl479a7e72008-02-05 18:13:15 +00001141 # Test leaks
1142 class Counted(object):
1143 counter = 0 # counts the number of instances alive
1144 def __init__(self):
1145 Counted.counter += 1
1146 def __del__(self):
1147 Counted.counter -= 1
1148 class C(object):
1149 __slots__ = ['a', 'b', 'c']
1150 x = C()
1151 x.a = Counted()
1152 x.b = Counted()
1153 x.c = Counted()
1154 self.assertEqual(Counted.counter, 3)
1155 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001156 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001157 self.assertEqual(Counted.counter, 0)
1158 class D(C):
1159 pass
1160 x = D()
1161 x.a = Counted()
1162 x.z = Counted()
1163 self.assertEqual(Counted.counter, 2)
1164 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001165 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001166 self.assertEqual(Counted.counter, 0)
1167 class E(D):
1168 __slots__ = ['e']
1169 x = E()
1170 x.a = Counted()
1171 x.z = Counted()
1172 x.e = Counted()
1173 self.assertEqual(Counted.counter, 3)
1174 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001175 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001176 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001177
Georg Brandl479a7e72008-02-05 18:13:15 +00001178 # Test cyclical leaks [SF bug 519621]
1179 class F(object):
1180 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001181 s = F()
1182 s.a = [Counted(), s]
1183 self.assertEqual(Counted.counter, 1)
1184 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001185 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001186 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001187
Georg Brandl479a7e72008-02-05 18:13:15 +00001188 # Test lookup leaks [SF bug 572567]
Georg Brandl1b37e872010-03-14 10:45:50 +00001189 import gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001190 if hasattr(gc, 'get_objects'):
1191 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001192 def __eq__(self, other):
1193 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001194 g = G()
1195 orig_objects = len(gc.get_objects())
1196 for i in range(10):
1197 g==g
1198 new_objects = len(gc.get_objects())
1199 self.assertEqual(orig_objects, new_objects)
1200
Georg Brandl479a7e72008-02-05 18:13:15 +00001201 class H(object):
1202 __slots__ = ['a', 'b']
1203 def __init__(self):
1204 self.a = 1
1205 self.b = 2
1206 def __del__(self_):
1207 self.assertEqual(self_.a, 1)
1208 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001209 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001210 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001211 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001212 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001213
Benjamin Petersond12362a2009-12-30 19:44:54 +00001214 class X(object):
1215 __slots__ = "a"
1216 with self.assertRaises(AttributeError):
1217 del X().a
1218
Georg Brandl479a7e72008-02-05 18:13:15 +00001219 def test_slots_special(self):
1220 # Testing __dict__ and __weakref__ in __slots__...
1221 class D(object):
1222 __slots__ = ["__dict__"]
1223 a = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001224 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001225 self.assertFalse(hasattr(a, "__weakref__"))
1226 a.foo = 42
1227 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001228
Georg Brandl479a7e72008-02-05 18:13:15 +00001229 class W(object):
1230 __slots__ = ["__weakref__"]
1231 a = W()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001232 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001233 self.assertFalse(hasattr(a, "__dict__"))
1234 try:
1235 a.foo = 42
1236 except AttributeError:
1237 pass
1238 else:
1239 self.fail("shouldn't be allowed to set a.foo")
1240
1241 class C1(W, D):
1242 __slots__ = []
1243 a = C1()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001244 self.assertTrue(hasattr(a, "__dict__"))
1245 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001246 a.foo = 42
1247 self.assertEqual(a.__dict__, {"foo": 42})
1248
1249 class C2(D, W):
1250 __slots__ = []
1251 a = C2()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001252 self.assertTrue(hasattr(a, "__dict__"))
1253 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001254 a.foo = 42
1255 self.assertEqual(a.__dict__, {"foo": 42})
1256
Christian Heimesa156e092008-02-16 07:38:31 +00001257 def test_slots_descriptor(self):
1258 # Issue2115: slot descriptors did not correctly check
1259 # the type of the given object
1260 import abc
1261 class MyABC(metaclass=abc.ABCMeta):
1262 __slots__ = "a"
1263
1264 class Unrelated(object):
1265 pass
1266 MyABC.register(Unrelated)
1267
1268 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001269 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001270
1271 # This used to crash
1272 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1273
Georg Brandl479a7e72008-02-05 18:13:15 +00001274 def test_dynamics(self):
1275 # Testing class attribute propagation...
1276 class D(object):
1277 pass
1278 class E(D):
1279 pass
1280 class F(D):
1281 pass
1282 D.foo = 1
1283 self.assertEqual(D.foo, 1)
1284 # Test that dynamic attributes are inherited
1285 self.assertEqual(E.foo, 1)
1286 self.assertEqual(F.foo, 1)
1287 # Test dynamic instances
1288 class C(object):
1289 pass
1290 a = C()
1291 self.assertFalse(hasattr(a, "foobar"))
1292 C.foobar = 2
1293 self.assertEqual(a.foobar, 2)
1294 C.method = lambda self: 42
1295 self.assertEqual(a.method(), 42)
1296 C.__repr__ = lambda self: "C()"
1297 self.assertEqual(repr(a), "C()")
1298 C.__int__ = lambda self: 100
1299 self.assertEqual(int(a), 100)
1300 self.assertEqual(a.foobar, 2)
1301 self.assertFalse(hasattr(a, "spam"))
1302 def mygetattr(self, name):
1303 if name == "spam":
1304 return "spam"
1305 raise AttributeError
1306 C.__getattr__ = mygetattr
1307 self.assertEqual(a.spam, "spam")
1308 a.new = 12
1309 self.assertEqual(a.new, 12)
1310 def mysetattr(self, name, value):
1311 if name == "spam":
1312 raise AttributeError
1313 return object.__setattr__(self, name, value)
1314 C.__setattr__ = mysetattr
1315 try:
1316 a.spam = "not spam"
1317 except AttributeError:
1318 pass
1319 else:
1320 self.fail("expected AttributeError")
1321 self.assertEqual(a.spam, "spam")
1322 class D(C):
1323 pass
1324 d = D()
1325 d.foo = 1
1326 self.assertEqual(d.foo, 1)
1327
1328 # Test handling of int*seq and seq*int
1329 class I(int):
1330 pass
1331 self.assertEqual("a"*I(2), "aa")
1332 self.assertEqual(I(2)*"a", "aa")
1333 self.assertEqual(2*I(3), 6)
1334 self.assertEqual(I(3)*2, 6)
1335 self.assertEqual(I(3)*I(2), 6)
1336
Georg Brandl479a7e72008-02-05 18:13:15 +00001337 # Test comparison of classes with dynamic metaclasses
1338 class dynamicmetaclass(type):
1339 pass
1340 class someclass(metaclass=dynamicmetaclass):
1341 pass
1342 self.assertNotEqual(someclass, object)
1343
1344 def test_errors(self):
1345 # Testing errors...
1346 try:
1347 class C(list, dict):
1348 pass
1349 except TypeError:
1350 pass
1351 else:
1352 self.fail("inheritance from both list and dict should be illegal")
1353
1354 try:
1355 class C(object, None):
1356 pass
1357 except TypeError:
1358 pass
1359 else:
1360 self.fail("inheritance from non-type should be illegal")
1361 class Classic:
1362 pass
1363
1364 try:
1365 class C(type(len)):
1366 pass
1367 except TypeError:
1368 pass
1369 else:
1370 self.fail("inheritance from CFunction should be illegal")
1371
1372 try:
1373 class C(object):
1374 __slots__ = 1
1375 except TypeError:
1376 pass
1377 else:
1378 self.fail("__slots__ = 1 should be illegal")
1379
1380 try:
1381 class C(object):
1382 __slots__ = [1]
1383 except TypeError:
1384 pass
1385 else:
1386 self.fail("__slots__ = [1] should be illegal")
1387
1388 class M1(type):
1389 pass
1390 class M2(type):
1391 pass
1392 class A1(object, metaclass=M1):
1393 pass
1394 class A2(object, metaclass=M2):
1395 pass
1396 try:
1397 class B(A1, A2):
1398 pass
1399 except TypeError:
1400 pass
1401 else:
1402 self.fail("finding the most derived metaclass should have failed")
1403
1404 def test_classmethods(self):
1405 # Testing class methods...
1406 class C(object):
1407 def foo(*a): return a
1408 goo = classmethod(foo)
1409 c = C()
1410 self.assertEqual(C.goo(1), (C, 1))
1411 self.assertEqual(c.goo(1), (C, 1))
1412 self.assertEqual(c.foo(1), (c, 1))
1413 class D(C):
1414 pass
1415 d = D()
1416 self.assertEqual(D.goo(1), (D, 1))
1417 self.assertEqual(d.goo(1), (D, 1))
1418 self.assertEqual(d.foo(1), (d, 1))
1419 self.assertEqual(D.foo(d, 1), (d, 1))
1420 # Test for a specific crash (SF bug 528132)
1421 def f(cls, arg): return (cls, arg)
1422 ff = classmethod(f)
1423 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1424 self.assertEqual(ff.__get__(0)(42), (int, 42))
1425
1426 # Test super() with classmethods (SF bug 535444)
1427 self.assertEqual(C.goo.__self__, C)
1428 self.assertEqual(D.goo.__self__, D)
1429 self.assertEqual(super(D,D).goo.__self__, D)
1430 self.assertEqual(super(D,d).goo.__self__, D)
1431 self.assertEqual(super(D,D).goo(), (D,))
1432 self.assertEqual(super(D,d).goo(), (D,))
1433
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001434 # Verify that a non-callable will raise
1435 meth = classmethod(1).__get__(1)
1436 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001437
1438 # Verify that classmethod() doesn't allow keyword args
1439 try:
1440 classmethod(f, kw=1)
1441 except TypeError:
1442 pass
1443 else:
1444 self.fail("classmethod shouldn't accept keyword args")
1445
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001446 cm = classmethod(f)
1447 cm.x = 42
1448 self.assertEqual(cm.x, 42)
1449 self.assertEqual(cm.__dict__, {"x" : 42})
1450 del cm.x
1451 self.assertFalse(hasattr(cm, "x"))
1452
Benjamin Petersone549ead2009-03-28 21:42:05 +00001453 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001454 def test_classmethods_in_c(self):
1455 # Testing C-based class methods...
1456 import xxsubtype as spam
1457 a = (1, 2, 3)
1458 d = {'abc': 123}
1459 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1460 self.assertEqual(x, spam.spamlist)
1461 self.assertEqual(a, a1)
1462 self.assertEqual(d, d1)
1463 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1464 self.assertEqual(x, spam.spamlist)
1465 self.assertEqual(a, a1)
1466 self.assertEqual(d, d1)
1467
1468 def test_staticmethods(self):
1469 # Testing static methods...
1470 class C(object):
1471 def foo(*a): return a
1472 goo = staticmethod(foo)
1473 c = C()
1474 self.assertEqual(C.goo(1), (1,))
1475 self.assertEqual(c.goo(1), (1,))
1476 self.assertEqual(c.foo(1), (c, 1,))
1477 class D(C):
1478 pass
1479 d = D()
1480 self.assertEqual(D.goo(1), (1,))
1481 self.assertEqual(d.goo(1), (1,))
1482 self.assertEqual(d.foo(1), (d, 1))
1483 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001484 sm = staticmethod(None)
1485 sm.x = 42
1486 self.assertEqual(sm.x, 42)
1487 self.assertEqual(sm.__dict__, {"x" : 42})
1488 del sm.x
1489 self.assertFalse(hasattr(sm, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001490
Benjamin Petersone549ead2009-03-28 21:42:05 +00001491 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001492 def test_staticmethods_in_c(self):
1493 # Testing C-based static methods...
1494 import xxsubtype as spam
1495 a = (1, 2, 3)
1496 d = {"abc": 123}
1497 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1498 self.assertEqual(x, None)
1499 self.assertEqual(a, a1)
1500 self.assertEqual(d, d1)
1501 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1502 self.assertEqual(x, None)
1503 self.assertEqual(a, a1)
1504 self.assertEqual(d, d1)
1505
1506 def test_classic(self):
1507 # Testing classic classes...
1508 class C:
1509 def foo(*a): return a
1510 goo = classmethod(foo)
1511 c = C()
1512 self.assertEqual(C.goo(1), (C, 1))
1513 self.assertEqual(c.goo(1), (C, 1))
1514 self.assertEqual(c.foo(1), (c, 1))
1515 class D(C):
1516 pass
1517 d = D()
1518 self.assertEqual(D.goo(1), (D, 1))
1519 self.assertEqual(d.goo(1), (D, 1))
1520 self.assertEqual(d.foo(1), (d, 1))
1521 self.assertEqual(D.foo(d, 1), (d, 1))
1522 class E: # *not* subclassing from C
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())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001526
1527 def test_compattr(self):
1528 # Testing computed attributes...
1529 class C(object):
1530 class computed_attribute(object):
1531 def __init__(self, get, set=None, delete=None):
1532 self.__get = get
1533 self.__set = set
1534 self.__delete = delete
1535 def __get__(self, obj, type=None):
1536 return self.__get(obj)
1537 def __set__(self, obj, value):
1538 return self.__set(obj, value)
1539 def __delete__(self, obj):
1540 return self.__delete(obj)
1541 def __init__(self):
1542 self.__x = 0
1543 def __get_x(self):
1544 x = self.__x
1545 self.__x = x+1
1546 return x
1547 def __set_x(self, x):
1548 self.__x = x
1549 def __delete_x(self):
1550 del self.__x
1551 x = computed_attribute(__get_x, __set_x, __delete_x)
1552 a = C()
1553 self.assertEqual(a.x, 0)
1554 self.assertEqual(a.x, 1)
1555 a.x = 10
1556 self.assertEqual(a.x, 10)
1557 self.assertEqual(a.x, 11)
1558 del a.x
1559 self.assertEqual(hasattr(a, 'x'), 0)
1560
1561 def test_newslots(self):
1562 # Testing __new__ slot override...
1563 class C(list):
1564 def __new__(cls):
1565 self = list.__new__(cls)
1566 self.foo = 1
1567 return self
1568 def __init__(self):
1569 self.foo = self.foo + 2
1570 a = C()
1571 self.assertEqual(a.foo, 3)
1572 self.assertEqual(a.__class__, C)
1573 class D(C):
1574 pass
1575 b = D()
1576 self.assertEqual(b.foo, 3)
1577 self.assertEqual(b.__class__, D)
1578
1579 def test_altmro(self):
1580 # Testing mro() and overriding it...
1581 class A(object):
1582 def f(self): return "A"
1583 class B(A):
1584 pass
1585 class C(A):
1586 def f(self): return "C"
1587 class D(B, C):
1588 pass
1589 self.assertEqual(D.mro(), [D, B, C, A, object])
1590 self.assertEqual(D.__mro__, (D, B, C, A, object))
1591 self.assertEqual(D().f(), "C")
1592
1593 class PerverseMetaType(type):
1594 def mro(cls):
1595 L = type.mro(cls)
1596 L.reverse()
1597 return L
1598 class X(D,B,C,A, metaclass=PerverseMetaType):
1599 pass
1600 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1601 self.assertEqual(X().f(), "A")
1602
1603 try:
1604 class _metaclass(type):
1605 def mro(self):
1606 return [self, dict, object]
1607 class X(object, metaclass=_metaclass):
1608 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001609 # In CPython, the class creation above already raises
1610 # TypeError, as a protection against the fact that
1611 # instances of X would segfault it. In other Python
1612 # implementations it would be ok to let the class X
1613 # be created, but instead get a clean TypeError on the
1614 # __setitem__ below.
1615 x = object.__new__(X)
1616 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001617 except TypeError:
1618 pass
1619 else:
1620 self.fail("devious mro() return not caught")
1621
1622 try:
1623 class _metaclass(type):
1624 def mro(self):
1625 return [1]
1626 class X(object, metaclass=_metaclass):
1627 pass
1628 except TypeError:
1629 pass
1630 else:
1631 self.fail("non-class mro() return not caught")
1632
1633 try:
1634 class _metaclass(type):
1635 def mro(self):
1636 return 1
1637 class X(object, metaclass=_metaclass):
1638 pass
1639 except TypeError:
1640 pass
1641 else:
1642 self.fail("non-sequence mro() return not caught")
1643
1644 def test_overloading(self):
1645 # Testing operator overloading...
1646
1647 class B(object):
1648 "Intermediate class because object doesn't have a __setattr__"
1649
1650 class C(B):
1651 def __getattr__(self, name):
1652 if name == "foo":
1653 return ("getattr", name)
1654 else:
1655 raise AttributeError
1656 def __setattr__(self, name, value):
1657 if name == "foo":
1658 self.setattr = (name, value)
1659 else:
1660 return B.__setattr__(self, name, value)
1661 def __delattr__(self, name):
1662 if name == "foo":
1663 self.delattr = name
1664 else:
1665 return B.__delattr__(self, name)
1666
1667 def __getitem__(self, key):
1668 return ("getitem", key)
1669 def __setitem__(self, key, value):
1670 self.setitem = (key, value)
1671 def __delitem__(self, key):
1672 self.delitem = key
1673
1674 a = C()
1675 self.assertEqual(a.foo, ("getattr", "foo"))
1676 a.foo = 12
1677 self.assertEqual(a.setattr, ("foo", 12))
1678 del a.foo
1679 self.assertEqual(a.delattr, "foo")
1680
1681 self.assertEqual(a[12], ("getitem", 12))
1682 a[12] = 21
1683 self.assertEqual(a.setitem, (12, 21))
1684 del a[12]
1685 self.assertEqual(a.delitem, 12)
1686
1687 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1688 a[0:10] = "foo"
1689 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1690 del a[0:10]
1691 self.assertEqual(a.delitem, (slice(0, 10)))
1692
1693 def test_methods(self):
1694 # Testing methods...
1695 class C(object):
1696 def __init__(self, x):
1697 self.x = x
1698 def foo(self):
1699 return self.x
1700 c1 = C(1)
1701 self.assertEqual(c1.foo(), 1)
1702 class D(C):
1703 boo = C.foo
1704 goo = c1.foo
1705 d2 = D(2)
1706 self.assertEqual(d2.foo(), 2)
1707 self.assertEqual(d2.boo(), 2)
1708 self.assertEqual(d2.goo(), 1)
1709 class E(object):
1710 foo = C.foo
1711 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001712 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001713
Benjamin Peterson224205f2009-05-08 03:25:19 +00001714 def test_special_method_lookup(self):
1715 # The lookup of special methods bypasses __getattr__ and
1716 # __getattribute__, but they still can be descriptors.
1717
1718 def run_context(manager):
1719 with manager:
1720 pass
1721 def iden(self):
1722 return self
1723 def hello(self):
1724 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001725 def empty_seq(self):
1726 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001727 def zero(self):
1728 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001729 def complex_num(self):
1730 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001731 def stop(self):
1732 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001733 def return_true(self, thing=None):
1734 return True
1735 def do_isinstance(obj):
1736 return isinstance(int, obj)
1737 def do_issubclass(obj):
1738 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001739 def do_dict_missing(checker):
1740 class DictSub(checker.__class__, dict):
1741 pass
1742 self.assertEqual(DictSub()["hi"], 4)
1743 def some_number(self_, key):
1744 self.assertEqual(key, "hi")
1745 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001746 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001747 def format_impl(self, spec):
1748 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001749
1750 # It would be nice to have every special method tested here, but I'm
1751 # only listing the ones I can remember outside of typeobject.c, since it
1752 # does it right.
1753 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001754 ("__bytes__", bytes, hello, set(), {}),
1755 ("__reversed__", reversed, empty_seq, set(), {}),
1756 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001757 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001758 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1759 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001760 ("__missing__", do_dict_missing, some_number,
1761 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001762 ("__subclasscheck__", do_issubclass, return_true,
1763 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001764 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1765 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001766 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001767 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001768 ("__floor__", math.floor, zero, set(), {}),
1769 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001770 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001771 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001772 ]
1773
1774 class Checker(object):
1775 def __getattr__(self, attr, test=self):
1776 test.fail("__getattr__ called with {0}".format(attr))
1777 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001778 if attr not in ok:
1779 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001780 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001781 class SpecialDescr(object):
1782 def __init__(self, impl):
1783 self.impl = impl
1784 def __get__(self, obj, owner):
1785 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001786 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001787 class MyException(Exception):
1788 pass
1789 class ErrDescr(object):
1790 def __get__(self, obj, owner):
1791 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001792
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001793 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001794 class X(Checker):
1795 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001796 for attr, obj in env.items():
1797 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001798 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001799 runner(X())
1800
1801 record = []
1802 class X(Checker):
1803 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001804 for attr, obj in env.items():
1805 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001806 setattr(X, name, SpecialDescr(meth_impl))
1807 runner(X())
1808 self.assertEqual(record, [1], name)
1809
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001810 class X(Checker):
1811 pass
1812 for attr, obj in env.items():
1813 setattr(X, attr, obj)
1814 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001815 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001816
Georg Brandl479a7e72008-02-05 18:13:15 +00001817 def test_specials(self):
1818 # Testing special operators...
1819 # Test operators like __hash__ for which a built-in default exists
1820
1821 # Test the default behavior for static classes
1822 class C(object):
1823 def __getitem__(self, i):
1824 if 0 <= i < 10: return i
1825 raise IndexError
1826 c1 = C()
1827 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001828 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001829 self.assertNotEqual(id(c1), id(c2))
1830 hash(c1)
1831 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001832 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001833 self.assertTrue(c1 != c2)
1834 self.assertTrue(not c1 != c1)
1835 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001836 # Note that the module name appears in str/repr, and that varies
1837 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001838 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001839 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001840 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001841 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001842 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001843 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001844 # Test the default behavior for dynamic classes
1845 class D(object):
1846 def __getitem__(self, i):
1847 if 0 <= i < 10: return i
1848 raise IndexError
1849 d1 = D()
1850 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001851 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001852 self.assertNotEqual(id(d1), id(d2))
1853 hash(d1)
1854 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001855 self.assertEqual(d1, d1)
1856 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001857 self.assertTrue(not d1 != d1)
1858 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001859 # Note that the module name appears in str/repr, and that varies
1860 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001861 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001862 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001863 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001864 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001865 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001866 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001867 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001868 class Proxy(object):
1869 def __init__(self, x):
1870 self.x = x
1871 def __bool__(self):
1872 return not not self.x
1873 def __hash__(self):
1874 return hash(self.x)
1875 def __eq__(self, other):
1876 return self.x == other
1877 def __ne__(self, other):
1878 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001879 def __ge__(self, other):
1880 return self.x >= other
1881 def __gt__(self, other):
1882 return self.x > other
1883 def __le__(self, other):
1884 return self.x <= other
1885 def __lt__(self, other):
1886 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001887 def __str__(self):
1888 return "Proxy:%s" % self.x
1889 def __repr__(self):
1890 return "Proxy(%r)" % self.x
1891 def __contains__(self, value):
1892 return value in self.x
1893 p0 = Proxy(0)
1894 p1 = Proxy(1)
1895 p_1 = Proxy(-1)
1896 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001897 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001898 self.assertEqual(hash(p0), hash(0))
1899 self.assertEqual(p0, p0)
1900 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001901 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001902 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001903 self.assertTrue(p0 < p1)
1904 self.assertTrue(p0 <= p1)
1905 self.assertTrue(p1 > p0)
1906 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001907 self.assertEqual(str(p0), "Proxy:0")
1908 self.assertEqual(repr(p0), "Proxy(0)")
1909 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001910 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001911 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001912 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001913 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001914
Georg Brandl479a7e72008-02-05 18:13:15 +00001915 def test_weakrefs(self):
1916 # Testing weak references...
1917 import weakref
1918 class C(object):
1919 pass
1920 c = C()
1921 r = weakref.ref(c)
1922 self.assertEqual(r(), c)
1923 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001924 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001925 self.assertEqual(r(), None)
1926 del r
1927 class NoWeak(object):
1928 __slots__ = ['foo']
1929 no = NoWeak()
1930 try:
1931 weakref.ref(no)
1932 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001933 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001934 else:
1935 self.fail("weakref.ref(no) should be illegal")
1936 class Weak(object):
1937 __slots__ = ['foo', '__weakref__']
1938 yes = Weak()
1939 r = weakref.ref(yes)
1940 self.assertEqual(r(), yes)
1941 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001942 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001943 self.assertEqual(r(), None)
1944 del r
1945
1946 def test_properties(self):
1947 # Testing property...
1948 class C(object):
1949 def getx(self):
1950 return self.__x
1951 def setx(self, value):
1952 self.__x = value
1953 def delx(self):
1954 del self.__x
1955 x = property(getx, setx, delx, doc="I'm the x property.")
1956 a = C()
1957 self.assertFalse(hasattr(a, "x"))
1958 a.x = 42
1959 self.assertEqual(a._C__x, 42)
1960 self.assertEqual(a.x, 42)
1961 del a.x
1962 self.assertFalse(hasattr(a, "x"))
1963 self.assertFalse(hasattr(a, "_C__x"))
1964 C.x.__set__(a, 100)
1965 self.assertEqual(C.x.__get__(a), 100)
1966 C.x.__delete__(a)
1967 self.assertFalse(hasattr(a, "x"))
1968
1969 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001970 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001971
1972 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001973 self.assertIn("__doc__", attrs)
1974 self.assertIn("fget", attrs)
1975 self.assertIn("fset", attrs)
1976 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001977
1978 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001979 self.assertTrue(raw.fget is C.__dict__['getx'])
1980 self.assertTrue(raw.fset is C.__dict__['setx'])
1981 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001982
1983 for attr in "__doc__", "fget", "fset", "fdel":
1984 try:
1985 setattr(raw, attr, 42)
1986 except AttributeError as msg:
1987 if str(msg).find('readonly') < 0:
1988 self.fail("when setting readonly attr %r on a property, "
1989 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1990 else:
1991 self.fail("expected AttributeError from trying to set readonly %r "
1992 "attr on a property" % attr)
1993
1994 class D(object):
1995 __getitem__ = property(lambda s: 1/0)
1996
1997 d = D()
1998 try:
1999 for i in d:
2000 str(i)
2001 except ZeroDivisionError:
2002 pass
2003 else:
2004 self.fail("expected ZeroDivisionError from bad property")
2005
R. David Murray378c0cf2010-02-24 01:46:21 +00002006 @unittest.skipIf(sys.flags.optimize >= 2,
2007 "Docstrings are omitted with -O2 and above")
2008 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002009 class E(object):
2010 def getter(self):
2011 "getter method"
2012 return 0
2013 def setter(self_, value):
2014 "setter method"
2015 pass
2016 prop = property(getter)
2017 self.assertEqual(prop.__doc__, "getter method")
2018 prop2 = property(fset=setter)
2019 self.assertEqual(prop2.__doc__, None)
2020
R. David Murray378c0cf2010-02-24 01:46:21 +00002021 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002022 # this segfaulted in 2.5b2
2023 try:
2024 import _testcapi
2025 except ImportError:
2026 pass
2027 else:
2028 class X(object):
2029 p = property(_testcapi.test_with_docstring)
2030
2031 def test_properties_plus(self):
2032 class C(object):
2033 foo = property(doc="hello")
2034 @foo.getter
2035 def foo(self):
2036 return self._foo
2037 @foo.setter
2038 def foo(self, value):
2039 self._foo = abs(value)
2040 @foo.deleter
2041 def foo(self):
2042 del self._foo
2043 c = C()
2044 self.assertEqual(C.foo.__doc__, "hello")
2045 self.assertFalse(hasattr(c, "foo"))
2046 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002047 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00002048 self.assertEqual(c._foo, 42)
2049 self.assertEqual(c.foo, 42)
2050 del c.foo
2051 self.assertFalse(hasattr(c, '_foo'))
2052 self.assertFalse(hasattr(c, "foo"))
2053
2054 class D(C):
2055 @C.foo.deleter
2056 def foo(self):
2057 try:
2058 del self._foo
2059 except AttributeError:
2060 pass
2061 d = D()
2062 d.foo = 24
2063 self.assertEqual(d.foo, 24)
2064 del d.foo
2065 del d.foo
2066
2067 class E(object):
2068 @property
2069 def foo(self):
2070 return self._foo
2071 @foo.setter
2072 def foo(self, value):
2073 raise RuntimeError
2074 @foo.setter
2075 def foo(self, value):
2076 self._foo = abs(value)
2077 @foo.deleter
2078 def foo(self, value=None):
2079 del self._foo
2080
2081 e = E()
2082 e.foo = -42
2083 self.assertEqual(e.foo, 42)
2084 del e.foo
2085
2086 class F(E):
2087 @E.foo.deleter
2088 def foo(self):
2089 del self._foo
2090 @foo.setter
2091 def foo(self, value):
2092 self._foo = max(0, value)
2093 f = F()
2094 f.foo = -10
2095 self.assertEqual(f.foo, 0)
2096 del f.foo
2097
2098 def test_dict_constructors(self):
2099 # Testing dict constructor ...
2100 d = dict()
2101 self.assertEqual(d, {})
2102 d = dict({})
2103 self.assertEqual(d, {})
2104 d = dict({1: 2, 'a': 'b'})
2105 self.assertEqual(d, {1: 2, 'a': 'b'})
2106 self.assertEqual(d, dict(list(d.items())))
2107 self.assertEqual(d, dict(iter(d.items())))
2108 d = dict({'one':1, 'two':2})
2109 self.assertEqual(d, dict(one=1, two=2))
2110 self.assertEqual(d, dict(**d))
2111 self.assertEqual(d, dict({"one": 1}, two=2))
2112 self.assertEqual(d, dict([("two", 2)], one=1))
2113 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2114 self.assertEqual(d, dict(**d))
2115
2116 for badarg in 0, 0, 0j, "0", [0], (0,):
2117 try:
2118 dict(badarg)
2119 except TypeError:
2120 pass
2121 except ValueError:
2122 if badarg == "0":
2123 # It's a sequence, and its elements are also sequences (gotta
2124 # love strings <wink>), but they aren't of length 2, so this
2125 # one seemed better as a ValueError than a TypeError.
2126 pass
2127 else:
2128 self.fail("no TypeError from dict(%r)" % badarg)
2129 else:
2130 self.fail("no TypeError from dict(%r)" % badarg)
2131
2132 try:
2133 dict({}, {})
2134 except TypeError:
2135 pass
2136 else:
2137 self.fail("no TypeError from dict({}, {})")
2138
2139 class Mapping:
2140 # Lacks a .keys() method; will be added later.
2141 dict = {1:2, 3:4, 'a':1j}
2142
2143 try:
2144 dict(Mapping())
2145 except TypeError:
2146 pass
2147 else:
2148 self.fail("no TypeError from dict(incomplete mapping)")
2149
2150 Mapping.keys = lambda self: list(self.dict.keys())
2151 Mapping.__getitem__ = lambda self, i: self.dict[i]
2152 d = dict(Mapping())
2153 self.assertEqual(d, Mapping.dict)
2154
2155 # Init from sequence of iterable objects, each producing a 2-sequence.
2156 class AddressBookEntry:
2157 def __init__(self, first, last):
2158 self.first = first
2159 self.last = last
2160 def __iter__(self):
2161 return iter([self.first, self.last])
2162
2163 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2164 AddressBookEntry('Barry', 'Peters'),
2165 AddressBookEntry('Tim', 'Peters'),
2166 AddressBookEntry('Barry', 'Warsaw')])
2167 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2168
2169 d = dict(zip(range(4), range(1, 5)))
2170 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2171
2172 # Bad sequence lengths.
2173 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2174 try:
2175 dict(bad)
2176 except ValueError:
2177 pass
2178 else:
2179 self.fail("no ValueError from dict(%r)" % bad)
2180
2181 def test_dir(self):
2182 # Testing dir() ...
2183 junk = 12
2184 self.assertEqual(dir(), ['junk', 'self'])
2185 del junk
2186
2187 # Just make sure these don't blow up!
2188 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2189 dir(arg)
2190
2191 # Test dir on new-style classes. Since these have object as a
2192 # base class, a lot more gets sucked in.
2193 def interesting(strings):
2194 return [s for s in strings if not s.startswith('_')]
2195
2196 class C(object):
2197 Cdata = 1
2198 def Cmethod(self): pass
2199
2200 cstuff = ['Cdata', 'Cmethod']
2201 self.assertEqual(interesting(dir(C)), cstuff)
2202
2203 c = C()
2204 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002205 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002206
2207 c.cdata = 2
2208 c.cmethod = lambda self: 0
2209 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002210 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002211
2212 class A(C):
2213 Adata = 1
2214 def Amethod(self): pass
2215
2216 astuff = ['Adata', 'Amethod'] + cstuff
2217 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002218 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002219 a = A()
2220 self.assertEqual(interesting(dir(a)), astuff)
2221 a.adata = 42
2222 a.amethod = lambda self: 3
2223 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002224 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002225
2226 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002227 class M(type(sys)):
2228 pass
2229 minstance = M("m")
2230 minstance.b = 2
2231 minstance.a = 1
2232 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2233 self.assertEqual(names, ['a', 'b'])
2234
2235 class M2(M):
2236 def getdict(self):
2237 return "Not a dict!"
2238 __dict__ = property(getdict)
2239
2240 m2instance = M2("m2")
2241 m2instance.b = 2
2242 m2instance.a = 1
2243 self.assertEqual(m2instance.__dict__, "Not a dict!")
2244 try:
2245 dir(m2instance)
2246 except TypeError:
2247 pass
2248
2249 # Two essentially featureless objects, just inheriting stuff from
2250 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002251 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002252
2253 # Nasty test case for proxied objects
2254 class Wrapper(object):
2255 def __init__(self, obj):
2256 self.__obj = obj
2257 def __repr__(self):
2258 return "Wrapper(%s)" % repr(self.__obj)
2259 def __getitem__(self, key):
2260 return Wrapper(self.__obj[key])
2261 def __len__(self):
2262 return len(self.__obj)
2263 def __getattr__(self, name):
2264 return Wrapper(getattr(self.__obj, name))
2265
2266 class C(object):
2267 def __getclass(self):
2268 return Wrapper(type(self))
2269 __class__ = property(__getclass)
2270
2271 dir(C()) # This used to segfault
2272
2273 def test_supers(self):
2274 # Testing super...
2275
2276 class A(object):
2277 def meth(self, a):
2278 return "A(%r)" % a
2279
2280 self.assertEqual(A().meth(1), "A(1)")
2281
2282 class B(A):
2283 def __init__(self):
2284 self.__super = super(B, self)
2285 def meth(self, a):
2286 return "B(%r)" % a + self.__super.meth(a)
2287
2288 self.assertEqual(B().meth(2), "B(2)A(2)")
2289
2290 class C(A):
2291 def meth(self, a):
2292 return "C(%r)" % a + self.__super.meth(a)
2293 C._C__super = super(C)
2294
2295 self.assertEqual(C().meth(3), "C(3)A(3)")
2296
2297 class D(C, B):
2298 def meth(self, a):
2299 return "D(%r)" % a + super(D, self).meth(a)
2300
2301 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2302
2303 # Test for subclassing super
2304
2305 class mysuper(super):
2306 def __init__(self, *args):
2307 return super(mysuper, self).__init__(*args)
2308
2309 class E(D):
2310 def meth(self, a):
2311 return "E(%r)" % a + mysuper(E, self).meth(a)
2312
2313 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2314
2315 class F(E):
2316 def meth(self, a):
2317 s = self.__super # == mysuper(F, self)
2318 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2319 F._F__super = mysuper(F)
2320
2321 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2322
2323 # Make sure certain errors are raised
2324
2325 try:
2326 super(D, 42)
2327 except TypeError:
2328 pass
2329 else:
2330 self.fail("shouldn't allow super(D, 42)")
2331
2332 try:
2333 super(D, C())
2334 except TypeError:
2335 pass
2336 else:
2337 self.fail("shouldn't allow super(D, C())")
2338
2339 try:
2340 super(D).__get__(12)
2341 except TypeError:
2342 pass
2343 else:
2344 self.fail("shouldn't allow super(D).__get__(12)")
2345
2346 try:
2347 super(D).__get__(C())
2348 except TypeError:
2349 pass
2350 else:
2351 self.fail("shouldn't allow super(D).__get__(C())")
2352
2353 # Make sure data descriptors can be overridden and accessed via super
2354 # (new feature in Python 2.3)
2355
2356 class DDbase(object):
2357 def getx(self): return 42
2358 x = property(getx)
2359
2360 class DDsub(DDbase):
2361 def getx(self): return "hello"
2362 x = property(getx)
2363
2364 dd = DDsub()
2365 self.assertEqual(dd.x, "hello")
2366 self.assertEqual(super(DDsub, dd).x, 42)
2367
2368 # Ensure that super() lookup of descriptor from classmethod
2369 # works (SF ID# 743627)
2370
2371 class Base(object):
2372 aProp = property(lambda self: "foo")
2373
2374 class Sub(Base):
2375 @classmethod
2376 def test(klass):
2377 return super(Sub,klass).aProp
2378
2379 self.assertEqual(Sub.test(), Base.aProp)
2380
2381 # Verify that super() doesn't allow keyword args
2382 try:
2383 super(Base, kw=1)
2384 except TypeError:
2385 pass
2386 else:
2387 self.assertEqual("super shouldn't accept keyword args")
2388
2389 def test_basic_inheritance(self):
2390 # Testing inheritance from basic types...
2391
2392 class hexint(int):
2393 def __repr__(self):
2394 return hex(self)
2395 def __add__(self, other):
2396 return hexint(int.__add__(self, other))
2397 # (Note that overriding __radd__ doesn't work,
2398 # because the int type gets first dibs.)
2399 self.assertEqual(repr(hexint(7) + 9), "0x10")
2400 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2401 a = hexint(12345)
2402 self.assertEqual(a, 12345)
2403 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002404 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002405 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002406 self.assertTrue((+a).__class__ is int)
2407 self.assertTrue((a >> 0).__class__ is int)
2408 self.assertTrue((a << 0).__class__ is int)
2409 self.assertTrue((hexint(0) << 12).__class__ is int)
2410 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002411
2412 class octlong(int):
2413 __slots__ = []
2414 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002415 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002416 def __add__(self, other):
2417 return self.__class__(super(octlong, self).__add__(other))
2418 __radd__ = __add__
2419 self.assertEqual(str(octlong(3) + 5), "0o10")
2420 # (Note that overriding __radd__ here only seems to work
2421 # because the example uses a short int left argument.)
2422 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2423 a = octlong(12345)
2424 self.assertEqual(a, 12345)
2425 self.assertEqual(int(a), 12345)
2426 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002427 self.assertTrue(int(a).__class__ is int)
2428 self.assertTrue((+a).__class__ is int)
2429 self.assertTrue((-a).__class__ is int)
2430 self.assertTrue((-octlong(0)).__class__ is int)
2431 self.assertTrue((a >> 0).__class__ is int)
2432 self.assertTrue((a << 0).__class__ is int)
2433 self.assertTrue((a - 0).__class__ is int)
2434 self.assertTrue((a * 1).__class__ is int)
2435 self.assertTrue((a ** 1).__class__ is int)
2436 self.assertTrue((a // 1).__class__ is int)
2437 self.assertTrue((1 * a).__class__ is int)
2438 self.assertTrue((a | 0).__class__ is int)
2439 self.assertTrue((a ^ 0).__class__ is int)
2440 self.assertTrue((a & -1).__class__ is int)
2441 self.assertTrue((octlong(0) << 12).__class__ is int)
2442 self.assertTrue((octlong(0) >> 12).__class__ is int)
2443 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002444
2445 # Because octlong overrides __add__, we can't check the absence of +0
2446 # optimizations using octlong.
2447 class longclone(int):
2448 pass
2449 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002450 self.assertTrue((a + 0).__class__ is int)
2451 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002452
2453 # Check that negative clones don't segfault
2454 a = longclone(-1)
2455 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002456 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002457
2458 class precfloat(float):
2459 __slots__ = ['prec']
2460 def __init__(self, value=0.0, prec=12):
2461 self.prec = int(prec)
2462 def __repr__(self):
2463 return "%.*g" % (self.prec, self)
2464 self.assertEqual(repr(precfloat(1.1)), "1.1")
2465 a = precfloat(12345)
2466 self.assertEqual(a, 12345.0)
2467 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002468 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002469 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002470 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002471
2472 class madcomplex(complex):
2473 def __repr__(self):
2474 return "%.17gj%+.17g" % (self.imag, self.real)
2475 a = madcomplex(-3, 4)
2476 self.assertEqual(repr(a), "4j-3")
2477 base = complex(-3, 4)
2478 self.assertEqual(base.__class__, complex)
2479 self.assertEqual(a, base)
2480 self.assertEqual(complex(a), base)
2481 self.assertEqual(complex(a).__class__, complex)
2482 a = madcomplex(a) # just trying another form of the constructor
2483 self.assertEqual(repr(a), "4j-3")
2484 self.assertEqual(a, base)
2485 self.assertEqual(complex(a), base)
2486 self.assertEqual(complex(a).__class__, complex)
2487 self.assertEqual(hash(a), hash(base))
2488 self.assertEqual((+a).__class__, complex)
2489 self.assertEqual((a + 0).__class__, complex)
2490 self.assertEqual(a + 0, base)
2491 self.assertEqual((a - 0).__class__, complex)
2492 self.assertEqual(a - 0, base)
2493 self.assertEqual((a * 1).__class__, complex)
2494 self.assertEqual(a * 1, base)
2495 self.assertEqual((a / 1).__class__, complex)
2496 self.assertEqual(a / 1, base)
2497
2498 class madtuple(tuple):
2499 _rev = None
2500 def rev(self):
2501 if self._rev is not None:
2502 return self._rev
2503 L = list(self)
2504 L.reverse()
2505 self._rev = self.__class__(L)
2506 return self._rev
2507 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2508 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2509 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2510 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2511 for i in range(512):
2512 t = madtuple(range(i))
2513 u = t.rev()
2514 v = u.rev()
2515 self.assertEqual(v, t)
2516 a = madtuple((1,2,3,4,5))
2517 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002518 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002519 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002520 self.assertTrue(a[:].__class__ is tuple)
2521 self.assertTrue((a * 1).__class__ is tuple)
2522 self.assertTrue((a * 0).__class__ is tuple)
2523 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002524 a = madtuple(())
2525 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002526 self.assertTrue(tuple(a).__class__ is tuple)
2527 self.assertTrue((a + a).__class__ is tuple)
2528 self.assertTrue((a * 0).__class__ is tuple)
2529 self.assertTrue((a * 1).__class__ is tuple)
2530 self.assertTrue((a * 2).__class__ is tuple)
2531 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002532
2533 class madstring(str):
2534 _rev = None
2535 def rev(self):
2536 if self._rev is not None:
2537 return self._rev
2538 L = list(self)
2539 L.reverse()
2540 self._rev = self.__class__("".join(L))
2541 return self._rev
2542 s = madstring("abcdefghijklmnopqrstuvwxyz")
2543 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2544 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2545 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2546 for i in range(256):
2547 s = madstring("".join(map(chr, range(i))))
2548 t = s.rev()
2549 u = t.rev()
2550 self.assertEqual(u, s)
2551 s = madstring("12345")
2552 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002553 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002554
2555 base = "\x00" * 5
2556 s = madstring(base)
2557 self.assertEqual(s, base)
2558 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002559 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002560 self.assertEqual(hash(s), hash(base))
2561 self.assertEqual({s: 1}[base], 1)
2562 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002563 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002564 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002565 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002566 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002567 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002568 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002569 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002570 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002571 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002572 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002573 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002574 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002575 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002576 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002577 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002578 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002579 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002580 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002581 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582 self.assertEqual(s.rstrip(), base)
2583 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002584 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002585 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002586 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002587 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002588 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002589 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002590 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002591 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002592 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002593 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002594 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002595 self.assertEqual(s.lower(), base)
2596
2597 class madunicode(str):
2598 _rev = None
2599 def rev(self):
2600 if self._rev is not None:
2601 return self._rev
2602 L = list(self)
2603 L.reverse()
2604 self._rev = self.__class__("".join(L))
2605 return self._rev
2606 u = madunicode("ABCDEF")
2607 self.assertEqual(u, "ABCDEF")
2608 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2609 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2610 base = "12345"
2611 u = madunicode(base)
2612 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002613 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002614 self.assertEqual(hash(u), hash(base))
2615 self.assertEqual({u: 1}[base], 1)
2616 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002617 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002618 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002619 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002620 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002621 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002622 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002623 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002624 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002625 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002626 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002627 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002628 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002629 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002630 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002631 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002632 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002633 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002634 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002635 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002636 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002637 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002638 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002639 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002640 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002641 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002642 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002643 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002644 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002645 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002646 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002647 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002649 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002651 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002652 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002653 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002654 self.assertEqual(u[0:0], "")
2655
2656 class sublist(list):
2657 pass
2658 a = sublist(range(5))
2659 self.assertEqual(a, list(range(5)))
2660 a.append("hello")
2661 self.assertEqual(a, list(range(5)) + ["hello"])
2662 a[5] = 5
2663 self.assertEqual(a, list(range(6)))
2664 a.extend(range(6, 20))
2665 self.assertEqual(a, list(range(20)))
2666 a[-5:] = []
2667 self.assertEqual(a, list(range(15)))
2668 del a[10:15]
2669 self.assertEqual(len(a), 10)
2670 self.assertEqual(a, list(range(10)))
2671 self.assertEqual(list(a), list(range(10)))
2672 self.assertEqual(a[0], 0)
2673 self.assertEqual(a[9], 9)
2674 self.assertEqual(a[-10], 0)
2675 self.assertEqual(a[-1], 9)
2676 self.assertEqual(a[:5], list(range(5)))
2677
2678 ## class CountedInput(file):
2679 ## """Counts lines read by self.readline().
2680 ##
2681 ## self.lineno is the 0-based ordinal of the last line read, up to
2682 ## a maximum of one greater than the number of lines in the file.
2683 ##
2684 ## self.ateof is true if and only if the final "" line has been read,
2685 ## at which point self.lineno stops incrementing, and further calls
2686 ## to readline() continue to return "".
2687 ## """
2688 ##
2689 ## lineno = 0
2690 ## ateof = 0
2691 ## def readline(self):
2692 ## if self.ateof:
2693 ## return ""
2694 ## s = file.readline(self)
2695 ## # Next line works too.
2696 ## # s = super(CountedInput, self).readline()
2697 ## self.lineno += 1
2698 ## if s == "":
2699 ## self.ateof = 1
2700 ## return s
2701 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002702 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002703 ## lines = ['a\n', 'b\n', 'c\n']
2704 ## try:
2705 ## f.writelines(lines)
2706 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002707 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002708 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2709 ## got = f.readline()
2710 ## self.assertEqual(expected, got)
2711 ## self.assertEqual(f.lineno, i)
2712 ## self.assertEqual(f.ateof, (i > len(lines)))
2713 ## f.close()
2714 ## finally:
2715 ## try:
2716 ## f.close()
2717 ## except:
2718 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002719 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002720
2721 def test_keywords(self):
2722 # Testing keyword args to basic type constructors ...
2723 self.assertEqual(int(x=1), 1)
2724 self.assertEqual(float(x=2), 2.0)
2725 self.assertEqual(int(x=3), 3)
2726 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2727 self.assertEqual(str(object=500), '500')
2728 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2729 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2730 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2731 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2732
2733 for constructor in (int, float, int, complex, str, str,
2734 tuple, list):
2735 try:
2736 constructor(bogus_keyword_arg=1)
2737 except TypeError:
2738 pass
2739 else:
2740 self.fail("expected TypeError from bogus keyword argument to %r"
2741 % constructor)
2742
2743 def test_str_subclass_as_dict_key(self):
2744 # Testing a str subclass used as dict key ..
2745
2746 class cistr(str):
2747 """Sublcass of str that computes __eq__ case-insensitively.
2748
2749 Also computes a hash code of the string in canonical form.
2750 """
2751
2752 def __init__(self, value):
2753 self.canonical = value.lower()
2754 self.hashcode = hash(self.canonical)
2755
2756 def __eq__(self, other):
2757 if not isinstance(other, cistr):
2758 other = cistr(other)
2759 return self.canonical == other.canonical
2760
2761 def __hash__(self):
2762 return self.hashcode
2763
2764 self.assertEqual(cistr('ABC'), 'abc')
2765 self.assertEqual('aBc', cistr('ABC'))
2766 self.assertEqual(str(cistr('ABC')), 'ABC')
2767
2768 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2769 self.assertEqual(d[cistr('one')], 1)
2770 self.assertEqual(d[cistr('tWo')], 2)
2771 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002772 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002773 self.assertEqual(d.get(cistr('thrEE')), 3)
2774
2775 def test_classic_comparisons(self):
2776 # Testing classic comparisons...
2777 class classic:
2778 pass
2779
2780 for base in (classic, int, object):
2781 class C(base):
2782 def __init__(self, value):
2783 self.value = int(value)
2784 def __eq__(self, other):
2785 if isinstance(other, C):
2786 return self.value == other.value
2787 if isinstance(other, int) or isinstance(other, int):
2788 return self.value == other
2789 return NotImplemented
2790 def __ne__(self, other):
2791 if isinstance(other, C):
2792 return self.value != other.value
2793 if isinstance(other, int) or isinstance(other, int):
2794 return self.value != other
2795 return NotImplemented
2796 def __lt__(self, other):
2797 if isinstance(other, C):
2798 return self.value < other.value
2799 if isinstance(other, int) or isinstance(other, int):
2800 return self.value < other
2801 return NotImplemented
2802 def __le__(self, other):
2803 if isinstance(other, C):
2804 return self.value <= other.value
2805 if isinstance(other, int) or isinstance(other, int):
2806 return self.value <= other
2807 return NotImplemented
2808 def __gt__(self, other):
2809 if isinstance(other, C):
2810 return self.value > other.value
2811 if isinstance(other, int) or isinstance(other, int):
2812 return self.value > other
2813 return NotImplemented
2814 def __ge__(self, other):
2815 if isinstance(other, C):
2816 return self.value >= other.value
2817 if isinstance(other, int) or isinstance(other, int):
2818 return self.value >= other
2819 return NotImplemented
2820
2821 c1 = C(1)
2822 c2 = C(2)
2823 c3 = C(3)
2824 self.assertEqual(c1, 1)
2825 c = {1: c1, 2: c2, 3: c3}
2826 for x in 1, 2, 3:
2827 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002828 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002829 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002830 eval("x %s y" % op),
2831 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002832 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002833 eval("x %s y" % op),
2834 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002835 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002836 eval("x %s y" % op),
2837 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002838
2839 def test_rich_comparisons(self):
2840 # Testing rich comparisons...
2841 class Z(complex):
2842 pass
2843 z = Z(1)
2844 self.assertEqual(z, 1+0j)
2845 self.assertEqual(1+0j, z)
2846 class ZZ(complex):
2847 def __eq__(self, other):
2848 try:
2849 return abs(self - other) <= 1e-6
2850 except:
2851 return NotImplemented
2852 zz = ZZ(1.0000003)
2853 self.assertEqual(zz, 1+0j)
2854 self.assertEqual(1+0j, zz)
2855
2856 class classic:
2857 pass
2858 for base in (classic, int, object, list):
2859 class C(base):
2860 def __init__(self, value):
2861 self.value = int(value)
2862 def __cmp__(self_, other):
2863 self.fail("shouldn't call __cmp__")
2864 def __eq__(self, other):
2865 if isinstance(other, C):
2866 return self.value == other.value
2867 if isinstance(other, int) or isinstance(other, int):
2868 return self.value == other
2869 return NotImplemented
2870 def __ne__(self, other):
2871 if isinstance(other, C):
2872 return self.value != other.value
2873 if isinstance(other, int) or isinstance(other, int):
2874 return self.value != other
2875 return NotImplemented
2876 def __lt__(self, other):
2877 if isinstance(other, C):
2878 return self.value < other.value
2879 if isinstance(other, int) or isinstance(other, int):
2880 return self.value < other
2881 return NotImplemented
2882 def __le__(self, other):
2883 if isinstance(other, C):
2884 return self.value <= other.value
2885 if isinstance(other, int) or isinstance(other, int):
2886 return self.value <= other
2887 return NotImplemented
2888 def __gt__(self, other):
2889 if isinstance(other, C):
2890 return self.value > other.value
2891 if isinstance(other, int) or isinstance(other, int):
2892 return self.value > other
2893 return NotImplemented
2894 def __ge__(self, other):
2895 if isinstance(other, C):
2896 return self.value >= other.value
2897 if isinstance(other, int) or isinstance(other, int):
2898 return self.value >= other
2899 return NotImplemented
2900 c1 = C(1)
2901 c2 = C(2)
2902 c3 = C(3)
2903 self.assertEqual(c1, 1)
2904 c = {1: c1, 2: c2, 3: c3}
2905 for x in 1, 2, 3:
2906 for y in 1, 2, 3:
2907 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002908 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002909 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002910 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002911 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002912 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002913 "x=%d, y=%d" % (x, y))
2914
2915 def test_descrdoc(self):
2916 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002917 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002918 def check(descr, what):
2919 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002920 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002921 check(complex.real, "the real part of a complex number") # member descriptor
2922
2923 def test_doc_descriptor(self):
2924 # Testing __doc__ descriptor...
2925 # SF bug 542984
2926 class DocDescr(object):
2927 def __get__(self, object, otype):
2928 if object:
2929 object = object.__class__.__name__ + ' instance'
2930 if otype:
2931 otype = otype.__name__
2932 return 'object=%s; type=%s' % (object, otype)
2933 class OldClass:
2934 __doc__ = DocDescr()
2935 class NewClass(object):
2936 __doc__ = DocDescr()
2937 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2938 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2939 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2940 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2941
2942 def test_set_class(self):
2943 # Testing __class__ assignment...
2944 class C(object): pass
2945 class D(object): pass
2946 class E(object): pass
2947 class F(D, E): pass
2948 for cls in C, D, E, F:
2949 for cls2 in C, D, E, F:
2950 x = cls()
2951 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002952 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002953 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002954 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002955 def cant(x, C):
2956 try:
2957 x.__class__ = C
2958 except TypeError:
2959 pass
2960 else:
2961 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2962 try:
2963 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002964 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002965 pass
2966 else:
2967 self.fail("shouldn't allow del %r.__class__" % x)
2968 cant(C(), list)
2969 cant(list(), C)
2970 cant(C(), 1)
2971 cant(C(), object)
2972 cant(object(), list)
2973 cant(list(), object)
2974 class Int(int): __slots__ = []
2975 cant(2, Int)
2976 cant(Int(), int)
2977 cant(True, int)
2978 cant(2, bool)
2979 o = object()
2980 cant(o, type(1))
2981 cant(o, type(None))
2982 del o
2983 class G(object):
2984 __slots__ = ["a", "b"]
2985 class H(object):
2986 __slots__ = ["b", "a"]
2987 class I(object):
2988 __slots__ = ["a", "b"]
2989 class J(object):
2990 __slots__ = ["c", "b"]
2991 class K(object):
2992 __slots__ = ["a", "b", "d"]
2993 class L(H):
2994 __slots__ = ["e"]
2995 class M(I):
2996 __slots__ = ["e"]
2997 class N(J):
2998 __slots__ = ["__weakref__"]
2999 class P(J):
3000 __slots__ = ["__dict__"]
3001 class Q(J):
3002 pass
3003 class R(J):
3004 __slots__ = ["__dict__", "__weakref__"]
3005
3006 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3007 x = cls()
3008 x.a = 1
3009 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003010 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003011 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3012 self.assertEqual(x.a, 1)
3013 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003014 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003015 "assigning %r as __class__ for %r silently failed" % (cls, x))
3016 self.assertEqual(x.a, 1)
3017 for cls in G, J, K, L, M, N, P, R, list, Int:
3018 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3019 if cls is cls2:
3020 continue
3021 cant(cls(), cls2)
3022
Benjamin Peterson193152c2009-04-25 01:08:45 +00003023 # Issue5283: when __class__ changes in __del__, the wrong
3024 # type gets DECREF'd.
3025 class O(object):
3026 pass
3027 class A(object):
3028 def __del__(self):
3029 self.__class__ = O
3030 l = [A() for x in range(100)]
3031 del l
3032
Georg Brandl479a7e72008-02-05 18:13:15 +00003033 def test_set_dict(self):
3034 # Testing __dict__ assignment...
3035 class C(object): pass
3036 a = C()
3037 a.__dict__ = {'b': 1}
3038 self.assertEqual(a.b, 1)
3039 def cant(x, dict):
3040 try:
3041 x.__dict__ = dict
3042 except (AttributeError, TypeError):
3043 pass
3044 else:
3045 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3046 cant(a, None)
3047 cant(a, [])
3048 cant(a, 1)
3049 del a.__dict__ # Deleting __dict__ is allowed
3050
3051 class Base(object):
3052 pass
3053 def verify_dict_readonly(x):
3054 """
3055 x has to be an instance of a class inheriting from Base.
3056 """
3057 cant(x, {})
3058 try:
3059 del x.__dict__
3060 except (AttributeError, TypeError):
3061 pass
3062 else:
3063 self.fail("shouldn't allow del %r.__dict__" % x)
3064 dict_descr = Base.__dict__["__dict__"]
3065 try:
3066 dict_descr.__set__(x, {})
3067 except (AttributeError, TypeError):
3068 pass
3069 else:
3070 self.fail("dict_descr allowed access to %r's dict" % x)
3071
3072 # Classes don't allow __dict__ assignment and have readonly dicts
3073 class Meta1(type, Base):
3074 pass
3075 class Meta2(Base, type):
3076 pass
3077 class D(object, metaclass=Meta1):
3078 pass
3079 class E(object, metaclass=Meta2):
3080 pass
3081 for cls in C, D, E:
3082 verify_dict_readonly(cls)
3083 class_dict = cls.__dict__
3084 try:
3085 class_dict["spam"] = "eggs"
3086 except TypeError:
3087 pass
3088 else:
3089 self.fail("%r's __dict__ can be modified" % cls)
3090
3091 # Modules also disallow __dict__ assignment
3092 class Module1(types.ModuleType, Base):
3093 pass
3094 class Module2(Base, types.ModuleType):
3095 pass
3096 for ModuleType in Module1, Module2:
3097 mod = ModuleType("spam")
3098 verify_dict_readonly(mod)
3099 mod.__dict__["spam"] = "eggs"
3100
3101 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003102 # (at least not any more than regular exception's __dict__ can
3103 # be deleted; on CPython it is not the case, whereas on PyPy they
3104 # can, just like any other new-style instance's __dict__.)
3105 def can_delete_dict(e):
3106 try:
3107 del e.__dict__
3108 except (TypeError, AttributeError):
3109 return False
3110 else:
3111 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003112 class Exception1(Exception, Base):
3113 pass
3114 class Exception2(Base, Exception):
3115 pass
3116 for ExceptionType in Exception, Exception1, Exception2:
3117 e = ExceptionType()
3118 e.__dict__ = {"a": 1}
3119 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003120 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003121
3122 def test_pickles(self):
3123 # Testing pickling and copying new-style classes and objects...
3124 import pickle
3125
3126 def sorteditems(d):
3127 L = list(d.items())
3128 L.sort()
3129 return L
3130
3131 global C
3132 class C(object):
3133 def __init__(self, a, b):
3134 super(C, self).__init__()
3135 self.a = a
3136 self.b = b
3137 def __repr__(self):
3138 return "C(%r, %r)" % (self.a, self.b)
3139
3140 global C1
3141 class C1(list):
3142 def __new__(cls, a, b):
3143 return super(C1, cls).__new__(cls)
3144 def __getnewargs__(self):
3145 return (self.a, self.b)
3146 def __init__(self, a, b):
3147 self.a = a
3148 self.b = b
3149 def __repr__(self):
3150 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3151
3152 global C2
3153 class C2(int):
3154 def __new__(cls, a, b, val=0):
3155 return super(C2, cls).__new__(cls, val)
3156 def __getnewargs__(self):
3157 return (self.a, self.b, int(self))
3158 def __init__(self, a, b, val=0):
3159 self.a = a
3160 self.b = b
3161 def __repr__(self):
3162 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3163
3164 global C3
3165 class C3(object):
3166 def __init__(self, foo):
3167 self.foo = foo
3168 def __getstate__(self):
3169 return self.foo
3170 def __setstate__(self, foo):
3171 self.foo = foo
3172
3173 global C4classic, C4
3174 class C4classic: # classic
3175 pass
3176 class C4(C4classic, object): # mixed inheritance
3177 pass
3178
Guido van Rossum3926a632001-09-25 16:25:58 +00003179 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003180 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003181 s = pickle.dumps(cls, bin)
3182 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003183 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003184
3185 a = C1(1, 2); a.append(42); a.append(24)
3186 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003187 s = pickle.dumps((a, b), bin)
3188 x, y = pickle.loads(s)
3189 self.assertEqual(x.__class__, a.__class__)
3190 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3191 self.assertEqual(y.__class__, b.__class__)
3192 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3193 self.assertEqual(repr(x), repr(a))
3194 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003195 # Test for __getstate__ and __setstate__ on new style class
3196 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003197 s = pickle.dumps(u, bin)
3198 v = pickle.loads(s)
3199 self.assertEqual(u.__class__, v.__class__)
3200 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003201 # Test for picklability of hybrid class
3202 u = C4()
3203 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003204 s = pickle.dumps(u, bin)
3205 v = pickle.loads(s)
3206 self.assertEqual(u.__class__, v.__class__)
3207 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003208
Georg Brandl479a7e72008-02-05 18:13:15 +00003209 # Testing copy.deepcopy()
3210 import copy
3211 for cls in C, C1, C2:
3212 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003213 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003214
Georg Brandl479a7e72008-02-05 18:13:15 +00003215 a = C1(1, 2); a.append(42); a.append(24)
3216 b = C2("hello", "world", 42)
3217 x, y = copy.deepcopy((a, b))
3218 self.assertEqual(x.__class__, a.__class__)
3219 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3220 self.assertEqual(y.__class__, b.__class__)
3221 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3222 self.assertEqual(repr(x), repr(a))
3223 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003224
Georg Brandl479a7e72008-02-05 18:13:15 +00003225 def test_pickle_slots(self):
3226 # Testing pickling of classes with __slots__ ...
3227 import pickle
3228 # Pickling of classes with __slots__ but without __getstate__ should fail
3229 # (if using protocol 0 or 1)
3230 global B, C, D, E
3231 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003232 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003233 for base in [object, B]:
3234 class C(base):
3235 __slots__ = ['a']
3236 class D(C):
3237 pass
3238 try:
3239 pickle.dumps(C(), 0)
3240 except TypeError:
3241 pass
3242 else:
3243 self.fail("should fail: pickle C instance - %s" % base)
3244 try:
3245 pickle.dumps(C(), 0)
3246 except TypeError:
3247 pass
3248 else:
3249 self.fail("should fail: pickle D instance - %s" % base)
3250 # Give C a nice generic __getstate__ and __setstate__
3251 class C(base):
3252 __slots__ = ['a']
3253 def __getstate__(self):
3254 try:
3255 d = self.__dict__.copy()
3256 except AttributeError:
3257 d = {}
3258 for cls in self.__class__.__mro__:
3259 for sn in cls.__dict__.get('__slots__', ()):
3260 try:
3261 d[sn] = getattr(self, sn)
3262 except AttributeError:
3263 pass
3264 return d
3265 def __setstate__(self, d):
3266 for k, v in list(d.items()):
3267 setattr(self, k, v)
3268 class D(C):
3269 pass
3270 # Now it should work
3271 x = C()
3272 y = pickle.loads(pickle.dumps(x))
3273 self.assertEqual(hasattr(y, 'a'), 0)
3274 x.a = 42
3275 y = pickle.loads(pickle.dumps(x))
3276 self.assertEqual(y.a, 42)
3277 x = D()
3278 x.a = 42
3279 x.b = 100
3280 y = pickle.loads(pickle.dumps(x))
3281 self.assertEqual(y.a + y.b, 142)
3282 # A subclass that adds a slot should also work
3283 class E(C):
3284 __slots__ = ['b']
3285 x = E()
3286 x.a = 42
3287 x.b = "foo"
3288 y = pickle.loads(pickle.dumps(x))
3289 self.assertEqual(y.a, x.a)
3290 self.assertEqual(y.b, x.b)
3291
3292 def test_binary_operator_override(self):
3293 # Testing overrides of binary operations...
3294 class I(int):
3295 def __repr__(self):
3296 return "I(%r)" % int(self)
3297 def __add__(self, other):
3298 return I(int(self) + int(other))
3299 __radd__ = __add__
3300 def __pow__(self, other, mod=None):
3301 if mod is None:
3302 return I(pow(int(self), int(other)))
3303 else:
3304 return I(pow(int(self), int(other), int(mod)))
3305 def __rpow__(self, other, mod=None):
3306 if mod is None:
3307 return I(pow(int(other), int(self), mod))
3308 else:
3309 return I(pow(int(other), int(self), int(mod)))
3310
3311 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3312 self.assertEqual(repr(I(1) + 2), "I(3)")
3313 self.assertEqual(repr(1 + I(2)), "I(3)")
3314 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3315 self.assertEqual(repr(2 ** I(3)), "I(8)")
3316 self.assertEqual(repr(I(2) ** 3), "I(8)")
3317 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3318 class S(str):
3319 def __eq__(self, other):
3320 return self.lower() == other.lower()
3321
3322 def test_subclass_propagation(self):
3323 # Testing propagation of slot functions to subclasses...
3324 class A(object):
3325 pass
3326 class B(A):
3327 pass
3328 class C(A):
3329 pass
3330 class D(B, C):
3331 pass
3332 d = D()
3333 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3334 A.__hash__ = lambda self: 42
3335 self.assertEqual(hash(d), 42)
3336 C.__hash__ = lambda self: 314
3337 self.assertEqual(hash(d), 314)
3338 B.__hash__ = lambda self: 144
3339 self.assertEqual(hash(d), 144)
3340 D.__hash__ = lambda self: 100
3341 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003342 D.__hash__ = None
3343 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003344 del D.__hash__
3345 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003346 B.__hash__ = None
3347 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003348 del B.__hash__
3349 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003350 C.__hash__ = None
3351 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003352 del C.__hash__
3353 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003354 A.__hash__ = None
3355 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003356 del A.__hash__
3357 self.assertEqual(hash(d), orig_hash)
3358 d.foo = 42
3359 d.bar = 42
3360 self.assertEqual(d.foo, 42)
3361 self.assertEqual(d.bar, 42)
3362 def __getattribute__(self, name):
3363 if name == "foo":
3364 return 24
3365 return object.__getattribute__(self, name)
3366 A.__getattribute__ = __getattribute__
3367 self.assertEqual(d.foo, 24)
3368 self.assertEqual(d.bar, 42)
3369 def __getattr__(self, name):
3370 if name in ("spam", "foo", "bar"):
3371 return "hello"
3372 raise AttributeError(name)
3373 B.__getattr__ = __getattr__
3374 self.assertEqual(d.spam, "hello")
3375 self.assertEqual(d.foo, 24)
3376 self.assertEqual(d.bar, 42)
3377 del A.__getattribute__
3378 self.assertEqual(d.foo, 42)
3379 del d.foo
3380 self.assertEqual(d.foo, "hello")
3381 self.assertEqual(d.bar, 42)
3382 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003383 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003384 d.foo
3385 except AttributeError:
3386 pass
3387 else:
3388 self.fail("d.foo should be undefined now")
3389
3390 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003391 class A(object):
3392 pass
3393 class B(A):
3394 pass
3395 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003396 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003397 A.__setitem__ = lambda *a: None # crash
3398
3399 def test_buffer_inheritance(self):
3400 # Testing that buffer interface is inherited ...
3401
3402 import binascii
3403 # SF bug [#470040] ParseTuple t# vs subclasses.
3404
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003405 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003406 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003407 base = b'abc'
3408 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003409 # b2a_hex uses the buffer interface to get its argument's value, via
3410 # PyArg_ParseTuple 't#' code.
3411 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3412
Georg Brandl479a7e72008-02-05 18:13:15 +00003413 class MyInt(int):
3414 pass
3415 m = MyInt(42)
3416 try:
3417 binascii.b2a_hex(m)
3418 self.fail('subclass of int should not have a buffer interface')
3419 except TypeError:
3420 pass
3421
3422 def test_str_of_str_subclass(self):
3423 # Testing __str__ defined in subclass of str ...
3424 import binascii
3425 import io
3426
3427 class octetstring(str):
3428 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003429 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003430 def __repr__(self):
3431 return self + " repr"
3432
3433 o = octetstring('A')
3434 self.assertEqual(type(o), octetstring)
3435 self.assertEqual(type(str(o)), str)
3436 self.assertEqual(type(repr(o)), str)
3437 self.assertEqual(ord(o), 0x41)
3438 self.assertEqual(str(o), '41')
3439 self.assertEqual(repr(o), 'A repr')
3440 self.assertEqual(o.__str__(), '41')
3441 self.assertEqual(o.__repr__(), 'A repr')
3442
3443 capture = io.StringIO()
3444 # Calling str() or not exercises different internal paths.
3445 print(o, file=capture)
3446 print(str(o), file=capture)
3447 self.assertEqual(capture.getvalue(), '41\n41\n')
3448 capture.close()
3449
3450 def test_keyword_arguments(self):
3451 # Testing keyword arguments to __init__, __call__...
3452 def f(a): return a
3453 self.assertEqual(f.__call__(a=42), 42)
3454 a = []
3455 list.__init__(a, sequence=[0, 1, 2])
3456 self.assertEqual(a, [0, 1, 2])
3457
3458 def test_recursive_call(self):
3459 # Testing recursive __call__() by setting to instance of class...
3460 class A(object):
3461 pass
3462
3463 A.__call__ = A()
3464 try:
3465 A()()
3466 except RuntimeError:
3467 pass
3468 else:
3469 self.fail("Recursion limit should have been reached for __call__()")
3470
3471 def test_delete_hook(self):
3472 # Testing __del__ hook...
3473 log = []
3474 class C(object):
3475 def __del__(self):
3476 log.append(1)
3477 c = C()
3478 self.assertEqual(log, [])
3479 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003480 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003481 self.assertEqual(log, [1])
3482
3483 class D(object): pass
3484 d = D()
3485 try: del d[0]
3486 except TypeError: pass
3487 else: self.fail("invalid del() didn't raise TypeError")
3488
3489 def test_hash_inheritance(self):
3490 # Testing hash of mutable subclasses...
3491
3492 class mydict(dict):
3493 pass
3494 d = mydict()
3495 try:
3496 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003497 except TypeError:
3498 pass
3499 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003500 self.fail("hash() of dict subclass should fail")
3501
3502 class mylist(list):
3503 pass
3504 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003505 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003506 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003507 except TypeError:
3508 pass
3509 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003510 self.fail("hash() of list subclass should fail")
3511
3512 def test_str_operations(self):
3513 try: 'a' + 5
3514 except TypeError: pass
3515 else: self.fail("'' + 5 doesn't raise TypeError")
3516
3517 try: ''.split('')
3518 except ValueError: pass
3519 else: self.fail("''.split('') doesn't raise ValueError")
3520
3521 try: ''.join([0])
3522 except TypeError: pass
3523 else: self.fail("''.join([0]) doesn't raise TypeError")
3524
3525 try: ''.rindex('5')
3526 except ValueError: pass
3527 else: self.fail("''.rindex('5') doesn't raise ValueError")
3528
3529 try: '%(n)s' % None
3530 except TypeError: pass
3531 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3532
3533 try: '%(n' % {}
3534 except ValueError: pass
3535 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3536
3537 try: '%*s' % ('abc')
3538 except TypeError: pass
3539 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3540
3541 try: '%*.*s' % ('abc', 5)
3542 except TypeError: pass
3543 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3544
3545 try: '%s' % (1, 2)
3546 except TypeError: pass
3547 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3548
3549 try: '%' % None
3550 except ValueError: pass
3551 else: self.fail("'%' % None doesn't raise ValueError")
3552
3553 self.assertEqual('534253'.isdigit(), 1)
3554 self.assertEqual('534253x'.isdigit(), 0)
3555 self.assertEqual('%c' % 5, '\x05')
3556 self.assertEqual('%c' % '5', '5')
3557
3558 def test_deepcopy_recursive(self):
3559 # Testing deepcopy of recursive objects...
3560 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003561 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003562 a = Node()
3563 b = Node()
3564 a.b = b
3565 b.a = a
3566 z = deepcopy(a) # This blew up before
3567
3568 def test_unintialized_modules(self):
3569 # Testing uninitialized module objects...
3570 from types import ModuleType as M
3571 m = M.__new__(M)
3572 str(m)
3573 self.assertEqual(hasattr(m, "__name__"), 0)
3574 self.assertEqual(hasattr(m, "__file__"), 0)
3575 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003576 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003577 m.foo = 1
3578 self.assertEqual(m.__dict__, {"foo": 1})
3579
3580 def test_funny_new(self):
3581 # Testing __new__ returning something unexpected...
3582 class C(object):
3583 def __new__(cls, arg):
3584 if isinstance(arg, str): return [1, 2, 3]
3585 elif isinstance(arg, int): return object.__new__(D)
3586 else: return object.__new__(cls)
3587 class D(C):
3588 def __init__(self, arg):
3589 self.foo = arg
3590 self.assertEqual(C("1"), [1, 2, 3])
3591 self.assertEqual(D("1"), [1, 2, 3])
3592 d = D(None)
3593 self.assertEqual(d.foo, None)
3594 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003595 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003596 self.assertEqual(d.foo, 1)
3597 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003598 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003599 self.assertEqual(d.foo, 1)
3600
3601 def test_imul_bug(self):
3602 # Testing for __imul__ problems...
3603 # SF bug 544647
3604 class C(object):
3605 def __imul__(self, other):
3606 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003607 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003608 y = x
3609 y *= 1.0
3610 self.assertEqual(y, (x, 1.0))
3611 y = x
3612 y *= 2
3613 self.assertEqual(y, (x, 2))
3614 y = x
3615 y *= 3
3616 self.assertEqual(y, (x, 3))
3617 y = x
3618 y *= 1<<100
3619 self.assertEqual(y, (x, 1<<100))
3620 y = x
3621 y *= None
3622 self.assertEqual(y, (x, None))
3623 y = x
3624 y *= "foo"
3625 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003626
Georg Brandl479a7e72008-02-05 18:13:15 +00003627 def test_copy_setstate(self):
3628 # Testing that copy.*copy() correctly uses __setstate__...
3629 import copy
3630 class C(object):
3631 def __init__(self, foo=None):
3632 self.foo = foo
3633 self.__foo = foo
3634 def setfoo(self, foo=None):
3635 self.foo = foo
3636 def getfoo(self):
3637 return self.__foo
3638 def __getstate__(self):
3639 return [self.foo]
3640 def __setstate__(self_, lst):
3641 self.assertEqual(len(lst), 1)
3642 self_.__foo = self_.foo = lst[0]
3643 a = C(42)
3644 a.setfoo(24)
3645 self.assertEqual(a.foo, 24)
3646 self.assertEqual(a.getfoo(), 42)
3647 b = copy.copy(a)
3648 self.assertEqual(b.foo, 24)
3649 self.assertEqual(b.getfoo(), 24)
3650 b = copy.deepcopy(a)
3651 self.assertEqual(b.foo, 24)
3652 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003653
Georg Brandl479a7e72008-02-05 18:13:15 +00003654 def test_slices(self):
3655 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003656
Georg Brandl479a7e72008-02-05 18:13:15 +00003657 # Strings
3658 self.assertEqual("hello"[:4], "hell")
3659 self.assertEqual("hello"[slice(4)], "hell")
3660 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3661 class S(str):
3662 def __getitem__(self, x):
3663 return str.__getitem__(self, x)
3664 self.assertEqual(S("hello")[:4], "hell")
3665 self.assertEqual(S("hello")[slice(4)], "hell")
3666 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3667 # Tuples
3668 self.assertEqual((1,2,3)[:2], (1,2))
3669 self.assertEqual((1,2,3)[slice(2)], (1,2))
3670 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3671 class T(tuple):
3672 def __getitem__(self, x):
3673 return tuple.__getitem__(self, x)
3674 self.assertEqual(T((1,2,3))[:2], (1,2))
3675 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3676 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3677 # Lists
3678 self.assertEqual([1,2,3][:2], [1,2])
3679 self.assertEqual([1,2,3][slice(2)], [1,2])
3680 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3681 class L(list):
3682 def __getitem__(self, x):
3683 return list.__getitem__(self, x)
3684 self.assertEqual(L([1,2,3])[:2], [1,2])
3685 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3686 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3687 # Now do lists and __setitem__
3688 a = L([1,2,3])
3689 a[slice(1, 3)] = [3,2]
3690 self.assertEqual(a, [1,3,2])
3691 a[slice(0, 2, 1)] = [3,1]
3692 self.assertEqual(a, [3,1,2])
3693 a.__setitem__(slice(1, 3), [2,1])
3694 self.assertEqual(a, [3,2,1])
3695 a.__setitem__(slice(0, 2, 1), [2,3])
3696 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003697
Georg Brandl479a7e72008-02-05 18:13:15 +00003698 def test_subtype_resurrection(self):
3699 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003700
Georg Brandl479a7e72008-02-05 18:13:15 +00003701 class C(object):
3702 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003703
Georg Brandl479a7e72008-02-05 18:13:15 +00003704 def __del__(self):
3705 # resurrect the instance
3706 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003707
Georg Brandl479a7e72008-02-05 18:13:15 +00003708 c = C()
3709 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003710
Benjamin Petersone549ead2009-03-28 21:42:05 +00003711 # The most interesting thing here is whether this blows up, due to
3712 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3713 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003714 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003715
Georg Brandl479a7e72008-02-05 18:13:15 +00003716 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003717 # the last container slot works: that will attempt to delete c again,
3718 # which will cause c to get appended back to the container again
3719 # "during" the del. (On non-CPython implementations, however, __del__
3720 # is typically not called again.)
3721 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003722 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003723 del C.container[-1]
3724 if support.check_impl_detail():
3725 support.gc_collect()
3726 self.assertEqual(len(C.container), 1)
3727 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003728
Georg Brandl479a7e72008-02-05 18:13:15 +00003729 # Make c mortal again, so that the test framework with -l doesn't report
3730 # it as a leak.
3731 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003732
Georg Brandl479a7e72008-02-05 18:13:15 +00003733 def test_slots_trash(self):
3734 # Testing slot trash...
3735 # Deallocating deeply nested slotted trash caused stack overflows
3736 class trash(object):
3737 __slots__ = ['x']
3738 def __init__(self, x):
3739 self.x = x
3740 o = None
3741 for i in range(50000):
3742 o = trash(o)
3743 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003744
Georg Brandl479a7e72008-02-05 18:13:15 +00003745 def test_slots_multiple_inheritance(self):
3746 # SF bug 575229, multiple inheritance w/ slots dumps core
3747 class A(object):
3748 __slots__=()
3749 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003750 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003751 class C(A,B) :
3752 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003753 if support.check_impl_detail():
3754 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003755 self.assertTrue(hasattr(C, '__dict__'))
3756 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003757 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003758
Georg Brandl479a7e72008-02-05 18:13:15 +00003759 def test_rmul(self):
3760 # Testing correct invocation of __rmul__...
3761 # SF patch 592646
3762 class C(object):
3763 def __mul__(self, other):
3764 return "mul"
3765 def __rmul__(self, other):
3766 return "rmul"
3767 a = C()
3768 self.assertEqual(a*2, "mul")
3769 self.assertEqual(a*2.2, "mul")
3770 self.assertEqual(2*a, "rmul")
3771 self.assertEqual(2.2*a, "rmul")
3772
3773 def test_ipow(self):
3774 # Testing correct invocation of __ipow__...
3775 # [SF bug 620179]
3776 class C(object):
3777 def __ipow__(self, other):
3778 pass
3779 a = C()
3780 a **= 2
3781
3782 def test_mutable_bases(self):
3783 # Testing mutable bases...
3784
3785 # stuff that should work:
3786 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003787 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003788 class C2(object):
3789 def __getattribute__(self, attr):
3790 if attr == 'a':
3791 return 2
3792 else:
3793 return super(C2, self).__getattribute__(attr)
3794 def meth(self):
3795 return 1
3796 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003797 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003798 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003799 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 d = D()
3801 e = E()
3802 D.__bases__ = (C,)
3803 D.__bases__ = (C2,)
3804 self.assertEqual(d.meth(), 1)
3805 self.assertEqual(e.meth(), 1)
3806 self.assertEqual(d.a, 2)
3807 self.assertEqual(e.a, 2)
3808 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003809
Georg Brandl479a7e72008-02-05 18:13:15 +00003810 try:
3811 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003812 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003813 pass
3814 else:
3815 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003816
Georg Brandl479a7e72008-02-05 18:13:15 +00003817 try:
3818 D.__bases__ = ()
3819 except TypeError as msg:
3820 if str(msg) == "a new-style class can't have only classic bases":
3821 self.fail("wrong error message for .__bases__ = ()")
3822 else:
3823 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003824
Georg Brandl479a7e72008-02-05 18:13:15 +00003825 try:
3826 D.__bases__ = (D,)
3827 except TypeError:
3828 pass
3829 else:
3830 # actually, we'll have crashed by here...
3831 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003832
Georg Brandl479a7e72008-02-05 18:13:15 +00003833 try:
3834 D.__bases__ = (C, C)
3835 except TypeError:
3836 pass
3837 else:
3838 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003839
Georg Brandl479a7e72008-02-05 18:13:15 +00003840 try:
3841 D.__bases__ = (E,)
3842 except TypeError:
3843 pass
3844 else:
3845 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003846
Benjamin Petersonae937c02009-04-18 20:54:08 +00003847 def test_builtin_bases(self):
3848 # Make sure all the builtin types can have their base queried without
3849 # segfaulting. See issue #5787.
3850 builtin_types = [tp for tp in builtins.__dict__.values()
3851 if isinstance(tp, type)]
3852 for tp in builtin_types:
3853 object.__getattribute__(tp, "__bases__")
3854 if tp is not object:
3855 self.assertEqual(len(tp.__bases__), 1, tp)
3856
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003857 class L(list):
3858 pass
3859
3860 class C(object):
3861 pass
3862
3863 class D(C):
3864 pass
3865
3866 try:
3867 L.__bases__ = (dict,)
3868 except TypeError:
3869 pass
3870 else:
3871 self.fail("shouldn't turn list subclass into dict subclass")
3872
3873 try:
3874 list.__bases__ = (dict,)
3875 except TypeError:
3876 pass
3877 else:
3878 self.fail("shouldn't be able to assign to list.__bases__")
3879
3880 try:
3881 D.__bases__ = (C, list)
3882 except TypeError:
3883 pass
3884 else:
3885 assert 0, "best_base calculation found wanting"
3886
Benjamin Petersonae937c02009-04-18 20:54:08 +00003887
Georg Brandl479a7e72008-02-05 18:13:15 +00003888 def test_mutable_bases_with_failing_mro(self):
3889 # Testing mutable bases with failing mro...
3890 class WorkOnce(type):
3891 def __new__(self, name, bases, ns):
3892 self.flag = 0
3893 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3894 def mro(self):
3895 if self.flag > 0:
3896 raise RuntimeError("bozo")
3897 else:
3898 self.flag += 1
3899 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003900
Georg Brandl479a7e72008-02-05 18:13:15 +00003901 class WorkAlways(type):
3902 def mro(self):
3903 # this is here to make sure that .mro()s aren't called
3904 # with an exception set (which was possible at one point).
3905 # An error message will be printed in a debug build.
3906 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003907 return type.mro(self)
3908
Georg Brandl479a7e72008-02-05 18:13:15 +00003909 class C(object):
3910 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003911
Georg Brandl479a7e72008-02-05 18:13:15 +00003912 class C2(object):
3913 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003914
Georg Brandl479a7e72008-02-05 18:13:15 +00003915 class D(C):
3916 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003917
Georg Brandl479a7e72008-02-05 18:13:15 +00003918 class E(D):
3919 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003920
Georg Brandl479a7e72008-02-05 18:13:15 +00003921 class F(D, metaclass=WorkOnce):
3922 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003923
Georg Brandl479a7e72008-02-05 18:13:15 +00003924 class G(D, metaclass=WorkAlways):
3925 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003926
Georg Brandl479a7e72008-02-05 18:13:15 +00003927 # Immediate subclasses have their mro's adjusted in alphabetical
3928 # order, so E's will get adjusted before adjusting F's fails. We
3929 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003930
Georg Brandl479a7e72008-02-05 18:13:15 +00003931 E_mro_before = E.__mro__
3932 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003933
Armin Rigofd163f92005-12-29 15:59:19 +00003934 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003935 D.__bases__ = (C2,)
3936 except RuntimeError:
3937 self.assertEqual(E.__mro__, E_mro_before)
3938 self.assertEqual(D.__mro__, D_mro_before)
3939 else:
3940 self.fail("exception not propagated")
3941
3942 def test_mutable_bases_catch_mro_conflict(self):
3943 # Testing mutable bases catch mro conflict...
3944 class A(object):
3945 pass
3946
3947 class B(object):
3948 pass
3949
3950 class C(A, B):
3951 pass
3952
3953 class D(A, B):
3954 pass
3955
3956 class E(C, D):
3957 pass
3958
3959 try:
3960 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003961 except TypeError:
3962 pass
3963 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003964 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003965
Georg Brandl479a7e72008-02-05 18:13:15 +00003966 def test_mutable_names(self):
3967 # Testing mutable names...
3968 class C(object):
3969 pass
3970
3971 # C.__module__ could be 'test_descr' or '__main__'
3972 mod = C.__module__
3973
3974 C.__name__ = 'D'
3975 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3976
3977 C.__name__ = 'D.E'
3978 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3979
3980 def test_subclass_right_op(self):
3981 # Testing correct dispatch of subclass overloading __r<op>__...
3982
3983 # This code tests various cases where right-dispatch of a subclass
3984 # should be preferred over left-dispatch of a base class.
3985
3986 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3987
3988 class B(int):
3989 def __floordiv__(self, other):
3990 return "B.__floordiv__"
3991 def __rfloordiv__(self, other):
3992 return "B.__rfloordiv__"
3993
3994 self.assertEqual(B(1) // 1, "B.__floordiv__")
3995 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3996
3997 # Case 2: subclass of object; this is just the baseline for case 3
3998
3999 class C(object):
4000 def __floordiv__(self, other):
4001 return "C.__floordiv__"
4002 def __rfloordiv__(self, other):
4003 return "C.__rfloordiv__"
4004
4005 self.assertEqual(C() // 1, "C.__floordiv__")
4006 self.assertEqual(1 // C(), "C.__rfloordiv__")
4007
4008 # Case 3: subclass of new-style class; here it gets interesting
4009
4010 class D(C):
4011 def __floordiv__(self, other):
4012 return "D.__floordiv__"
4013 def __rfloordiv__(self, other):
4014 return "D.__rfloordiv__"
4015
4016 self.assertEqual(D() // C(), "D.__floordiv__")
4017 self.assertEqual(C() // D(), "D.__rfloordiv__")
4018
4019 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4020
4021 class E(C):
4022 pass
4023
4024 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4025
4026 self.assertEqual(E() // 1, "C.__floordiv__")
4027 self.assertEqual(1 // E(), "C.__rfloordiv__")
4028 self.assertEqual(E() // C(), "C.__floordiv__")
4029 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4030
Benjamin Petersone549ead2009-03-28 21:42:05 +00004031 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004032 def test_meth_class_get(self):
4033 # Testing __get__ method of METH_CLASS C methods...
4034 # Full coverage of descrobject.c::classmethod_get()
4035
4036 # Baseline
4037 arg = [1, 2, 3]
4038 res = {1: None, 2: None, 3: None}
4039 self.assertEqual(dict.fromkeys(arg), res)
4040 self.assertEqual({}.fromkeys(arg), res)
4041
4042 # Now get the descriptor
4043 descr = dict.__dict__["fromkeys"]
4044
4045 # More baseline using the descriptor directly
4046 self.assertEqual(descr.__get__(None, dict)(arg), res)
4047 self.assertEqual(descr.__get__({})(arg), res)
4048
4049 # Now check various error cases
4050 try:
4051 descr.__get__(None, None)
4052 except TypeError:
4053 pass
4054 else:
4055 self.fail("shouldn't have allowed descr.__get__(None, None)")
4056 try:
4057 descr.__get__(42)
4058 except TypeError:
4059 pass
4060 else:
4061 self.fail("shouldn't have allowed descr.__get__(42)")
4062 try:
4063 descr.__get__(None, 42)
4064 except TypeError:
4065 pass
4066 else:
4067 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4068 try:
4069 descr.__get__(None, int)
4070 except TypeError:
4071 pass
4072 else:
4073 self.fail("shouldn't have allowed descr.__get__(None, int)")
4074
4075 def test_isinst_isclass(self):
4076 # Testing proxy isinstance() and isclass()...
4077 class Proxy(object):
4078 def __init__(self, obj):
4079 self.__obj = obj
4080 def __getattribute__(self, name):
4081 if name.startswith("_Proxy__"):
4082 return object.__getattribute__(self, name)
4083 else:
4084 return getattr(self.__obj, name)
4085 # Test with a classic class
4086 class C:
4087 pass
4088 a = C()
4089 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004090 self.assertIsInstance(a, C) # Baseline
4091 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004092 # Test with a classic subclass
4093 class D(C):
4094 pass
4095 a = D()
4096 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004097 self.assertIsInstance(a, C) # Baseline
4098 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004099 # Test with a new-style class
4100 class C(object):
4101 pass
4102 a = C()
4103 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004104 self.assertIsInstance(a, C) # Baseline
4105 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004106 # Test with a new-style subclass
4107 class D(C):
4108 pass
4109 a = D()
4110 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004111 self.assertIsInstance(a, C) # Baseline
4112 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004113
4114 def test_proxy_super(self):
4115 # Testing super() for a proxy object...
4116 class Proxy(object):
4117 def __init__(self, obj):
4118 self.__obj = obj
4119 def __getattribute__(self, name):
4120 if name.startswith("_Proxy__"):
4121 return object.__getattribute__(self, name)
4122 else:
4123 return getattr(self.__obj, name)
4124
4125 class B(object):
4126 def f(self):
4127 return "B.f"
4128
4129 class C(B):
4130 def f(self):
4131 return super(C, self).f() + "->C.f"
4132
4133 obj = C()
4134 p = Proxy(obj)
4135 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4136
4137 def test_carloverre(self):
4138 # Testing prohibition of Carlo Verre's hack...
4139 try:
4140 object.__setattr__(str, "foo", 42)
4141 except TypeError:
4142 pass
4143 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004144 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004145 try:
4146 object.__delattr__(str, "lower")
4147 except TypeError:
4148 pass
4149 else:
4150 self.fail("Carlo Verre __delattr__ succeeded!")
4151
4152 def test_weakref_segfault(self):
4153 # Testing weakref segfault...
4154 # SF 742911
4155 import weakref
4156
4157 class Provoker:
4158 def __init__(self, referrent):
4159 self.ref = weakref.ref(referrent)
4160
4161 def __del__(self):
4162 x = self.ref()
4163
4164 class Oops(object):
4165 pass
4166
4167 o = Oops()
4168 o.whatever = Provoker(o)
4169 del o
4170
4171 def test_wrapper_segfault(self):
4172 # SF 927248: deeply nested wrappers could cause stack overflow
4173 f = lambda:None
4174 for i in range(1000000):
4175 f = f.__call__
4176 f = None
4177
4178 def test_file_fault(self):
4179 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004180 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004181 class StdoutGuard:
4182 def __getattr__(self, attr):
4183 sys.stdout = sys.__stdout__
4184 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4185 sys.stdout = StdoutGuard()
4186 try:
4187 print("Oops!")
4188 except RuntimeError:
4189 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004190 finally:
4191 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004192
4193 def test_vicious_descriptor_nonsense(self):
4194 # Testing vicious_descriptor_nonsense...
4195
4196 # A potential segfault spotted by Thomas Wouters in mail to
4197 # python-dev 2003-04-17, turned into an example & fixed by Michael
4198 # Hudson just less than four months later...
4199
4200 class Evil(object):
4201 def __hash__(self):
4202 return hash('attr')
4203 def __eq__(self, other):
4204 del C.attr
4205 return 0
4206
4207 class Descr(object):
4208 def __get__(self, ob, type=None):
4209 return 1
4210
4211 class C(object):
4212 attr = Descr()
4213
4214 c = C()
4215 c.__dict__[Evil()] = 0
4216
4217 self.assertEqual(c.attr, 1)
4218 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004219 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004220 self.assertEqual(hasattr(c, 'attr'), False)
4221
4222 def test_init(self):
4223 # SF 1155938
4224 class Foo(object):
4225 def __init__(self):
4226 return 10
4227 try:
4228 Foo()
4229 except TypeError:
4230 pass
4231 else:
4232 self.fail("did not test __init__() for None return")
4233
4234 def test_method_wrapper(self):
4235 # Testing method-wrapper objects...
4236 # <type 'method-wrapper'> did not support any reflection before 2.5
4237
Mark Dickinson211c6252009-02-01 10:28:51 +00004238 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004239
4240 l = []
4241 self.assertEqual(l.__add__, l.__add__)
4242 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004243 self.assertTrue(l.__add__ != [5].__add__)
4244 self.assertTrue(l.__add__ != l.__mul__)
4245 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004246 if hasattr(l.__add__, '__self__'):
4247 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004248 self.assertTrue(l.__add__.__self__ is l)
4249 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004250 else:
4251 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004252 self.assertTrue(l.__add__.im_self is l)
4253 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004254 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4255 try:
4256 hash(l.__add__)
4257 except TypeError:
4258 pass
4259 else:
4260 self.fail("no TypeError from hash([].__add__)")
4261
4262 t = ()
4263 t += (7,)
4264 self.assertEqual(t.__add__, (7,).__add__)
4265 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4266
4267 def test_not_implemented(self):
4268 # Testing NotImplemented...
4269 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004270 import operator
4271
4272 def specialmethod(self, other):
4273 return NotImplemented
4274
4275 def check(expr, x, y):
4276 try:
4277 exec(expr, {'x': x, 'y': y, 'operator': operator})
4278 except TypeError:
4279 pass
4280 else:
4281 self.fail("no TypeError from %r" % (expr,))
4282
4283 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4284 # TypeErrors
4285 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4286 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004287 for name, expr, iexpr in [
4288 ('__add__', 'x + y', 'x += y'),
4289 ('__sub__', 'x - y', 'x -= y'),
4290 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004291 ('__truediv__', 'operator.truediv(x, y)', None),
4292 ('__floordiv__', 'operator.floordiv(x, y)', None),
4293 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004294 ('__mod__', 'x % y', 'x %= y'),
4295 ('__divmod__', 'divmod(x, y)', None),
4296 ('__pow__', 'x ** y', 'x **= y'),
4297 ('__lshift__', 'x << y', 'x <<= y'),
4298 ('__rshift__', 'x >> y', 'x >>= y'),
4299 ('__and__', 'x & y', 'x &= y'),
4300 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004301 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004302 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004303 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004304 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004305 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004306 check(expr, a, N1)
4307 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004308 if iexpr:
4309 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004310 check(iexpr, a, N1)
4311 check(iexpr, a, N2)
4312 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004313 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004314 c = C()
4315 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004316 check(iexpr, c, N1)
4317 check(iexpr, c, N2)
4318
Georg Brandl479a7e72008-02-05 18:13:15 +00004319 def test_assign_slice(self):
4320 # ceval.c's assign_slice used to check for
4321 # tp->tp_as_sequence->sq_slice instead of
4322 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004323
Georg Brandl479a7e72008-02-05 18:13:15 +00004324 class C(object):
4325 def __setitem__(self, idx, value):
4326 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004327
Georg Brandl479a7e72008-02-05 18:13:15 +00004328 c = C()
4329 c[1:2] = 3
4330 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004331
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004332 def test_set_and_no_get(self):
4333 # See
4334 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4335 class Descr(object):
4336
4337 def __init__(self, name):
4338 self.name = name
4339
4340 def __set__(self, obj, value):
4341 obj.__dict__[self.name] = value
4342 descr = Descr("a")
4343
4344 class X(object):
4345 a = descr
4346
4347 x = X()
4348 self.assertIs(x.a, descr)
4349 x.a = 42
4350 self.assertEqual(x.a, 42)
4351
Benjamin Peterson21896a32010-03-21 22:03:03 +00004352 # Also check type_getattro for correctness.
4353 class Meta(type):
4354 pass
4355 class X(object):
4356 __metaclass__ = Meta
4357 X.a = 42
4358 Meta.a = Descr("a")
4359 self.assertEqual(X.a, 42)
4360
Benjamin Peterson9262b842008-11-17 22:45:50 +00004361 def test_getattr_hooks(self):
4362 # issue 4230
4363
4364 class Descriptor(object):
4365 counter = 0
4366 def __get__(self, obj, objtype=None):
4367 def getter(name):
4368 self.counter += 1
4369 raise AttributeError(name)
4370 return getter
4371
4372 descr = Descriptor()
4373 class A(object):
4374 __getattribute__ = descr
4375 class B(object):
4376 __getattr__ = descr
4377 class C(object):
4378 __getattribute__ = descr
4379 __getattr__ = descr
4380
4381 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004382 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004383 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004384 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004385 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004386 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004387
4388 import gc
4389 class EvilGetattribute(object):
4390 # This used to segfault
4391 def __getattr__(self, name):
4392 raise AttributeError(name)
4393 def __getattribute__(self, name):
4394 del EvilGetattribute.__getattr__
4395 for i in range(5):
4396 gc.collect()
4397 raise AttributeError(name)
4398
4399 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4400
Benjamin Peterson477ba912011-01-12 15:34:01 +00004401 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004402 # type pretends not to have __abstractmethods__.
4403 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4404 class meta(type):
4405 pass
4406 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004407 class X(object):
4408 pass
4409 with self.assertRaises(AttributeError):
4410 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004411
Victor Stinner3249dec2011-05-01 23:19:15 +02004412 def test_proxy_call(self):
4413 class FakeStr:
4414 __class__ = str
4415
4416 fake_str = FakeStr()
4417 # isinstance() reads __class__
4418 self.assertTrue(isinstance(fake_str, str))
4419
4420 # call a method descriptor
4421 with self.assertRaises(TypeError):
4422 str.split(fake_str)
4423
4424 # call a slot wrapper descriptor
4425 with self.assertRaises(TypeError):
4426 str.__add__(fake_str, "abc")
4427
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004428 def test_repr_as_str(self):
4429 # Issue #11603: crash or infinite loop when rebinding __str__ as
4430 # __repr__.
4431 class Foo:
4432 pass
4433 Foo.__repr__ = Foo.__str__
4434 foo = Foo()
4435 str(foo)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004436
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004437 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004438 with self.assertRaises(ValueError) as cm:
4439 class X:
4440 __slots__ = ["foo"]
4441 foo = None
4442 m = str(cm.exception)
4443 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4444
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004445 def test_set_doc(self):
4446 class X:
4447 "elephant"
4448 X.__doc__ = "banana"
4449 self.assertEqual(X.__doc__, "banana")
4450 with self.assertRaises(TypeError) as cm:
4451 type(list).__dict__["__doc__"].__set__(list, "blah")
4452 self.assertIn("can't set list.__doc__", str(cm.exception))
4453 with self.assertRaises(TypeError) as cm:
4454 type(X).__dict__["__doc__"].__delete__(X)
4455 self.assertIn("can't delete X.__doc__", str(cm.exception))
4456 self.assertEqual(X.__doc__, "banana")
4457
Antoine Pitrou9d574812011-12-12 13:47:25 +01004458 def test_qualname(self):
4459 descriptors = [str.lower, complex.real, float.real, int.__add__]
4460 types = ['method', 'member', 'getset', 'wrapper']
4461
4462 # make sure we have an example of each type of descriptor
4463 for d, n in zip(descriptors, types):
4464 self.assertEqual(type(d).__name__, n + '_descriptor')
4465
4466 for d in descriptors:
4467 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4468 self.assertEqual(d.__qualname__, qualname)
4469
4470 self.assertEqual(str.lower.__qualname__, 'str.lower')
4471 self.assertEqual(complex.real.__qualname__, 'complex.real')
4472 self.assertEqual(float.real.__qualname__, 'float.real')
4473 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4474
4475
Georg Brandl479a7e72008-02-05 18:13:15 +00004476class DictProxyTests(unittest.TestCase):
4477 def setUp(self):
4478 class C(object):
4479 def meth(self):
4480 pass
4481 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004482
Brett Cannon7a540732011-02-22 03:04:06 +00004483 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4484 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004485 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004486 # Testing dict-proxy keys...
4487 it = self.C.__dict__.keys()
4488 self.assertNotIsInstance(it, list)
4489 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004490 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004491 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl479a7e72008-02-05 18:13:15 +00004492 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004493
Brett Cannon7a540732011-02-22 03:04:06 +00004494 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4495 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004496 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004497 # Testing dict-proxy values...
4498 it = self.C.__dict__.values()
4499 self.assertNotIsInstance(it, list)
4500 values = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004501 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004502
Brett Cannon7a540732011-02-22 03:04:06 +00004503 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4504 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004505 def test_iter_items(self):
4506 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004507 it = self.C.__dict__.items()
4508 self.assertNotIsInstance(it, list)
4509 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004510 keys.sort()
4511 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4512 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004513
Georg Brandl479a7e72008-02-05 18:13:15 +00004514 def test_dict_type_with_metaclass(self):
4515 # Testing type of __dict__ when metaclass set...
4516 class B(object):
4517 pass
4518 class M(type):
4519 pass
4520 class C(metaclass=M):
4521 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4522 pass
4523 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004524
Ezio Melottiac53ab62010-12-18 14:59:43 +00004525 def test_repr(self):
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004526 # Testing dict_proxy.__repr__.
4527 # We can't blindly compare with the repr of another dict as ordering
4528 # of keys and values is arbitrary and may differ.
4529 r = repr(self.C.__dict__)
4530 self.assertTrue(r.startswith('dict_proxy('), r)
4531 self.assertTrue(r.endswith(')'), r)
4532 for k, v in self.C.__dict__.items():
4533 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004534
Christian Heimesbbffeb62008-01-24 09:42:52 +00004535
Georg Brandl479a7e72008-02-05 18:13:15 +00004536class PTypesLongInitTest(unittest.TestCase):
4537 # This is in its own TestCase so that it can be run before any other tests.
4538 def test_pytype_long_ready(self):
4539 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004540
Georg Brandl479a7e72008-02-05 18:13:15 +00004541 # This dumps core when SF bug 551412 isn't fixed --
4542 # but only when test_descr.py is run separately.
4543 # (That can't be helped -- as soon as PyType_Ready()
4544 # is called for PyLong_Type, the bug is gone.)
4545 class UserLong(object):
4546 def __pow__(self, *args):
4547 pass
4548 try:
4549 pow(0, UserLong(), 0)
4550 except:
4551 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004552
Georg Brandl479a7e72008-02-05 18:13:15 +00004553 # Another segfault only when run early
4554 # (before PyType_Ready(tuple) is called)
4555 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004556
4557
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004558def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004559 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004560 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004561 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004563if __name__ == "__main__":
4564 test_main()